diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 224e7f0..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.pc/ diff --git a/CHANGES.txt b/CHANGES.txt index 5e6abb6..5c776a7 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,26 @@ +Changes in V4.0.0 since V3.1.0 + +* XMLBEANS-548: XmlDocumentProperties.setStandalone is ignored when saving +* XMLBEANS-542: SAX Parsing should not fail if parser does not allow the setting of declaration-handler +* XMLBEANS-541, XMLBEANS-544, XMLBEANS-545: Fixes to ant build scripts +* XMLBEANS-540: Prevent trim of elements when pretty print is used +* XMLBEANS-539: Support Saxon-HE 10 as an XPath engine + +Changes in V3.1.0 since V3.0.2 + +* update build and deployment artifacts to standardize naming and remove unused items +* XMLBEANS-502: Allow to clear all ThreadLocals from the current thread +* XMLBEANS-503: Allow to specify -nowarn in the Ant task +* XMLBEANS-537: Add missing StscState.end() to avoid memory leaks +* XMLBEANS-532: Streamline build.xml and update tests to Junit4 +* XMLBEANS-531: Fix schema gen of attributes +* XMLBEANS-530: Allow namespaces of XmlOptions to be passed to the XQuery engine +* XMLBEANS-529: Format xmlobjects to the correct string representation on XPath access +* XMLBEANS-528: Allow document locator to be set after initialization +* XMLBEANS-527: Rename shell script directory, to align on typical directory layout +* XMLBEANS-526: Fix issue with loading META-INF/services files +* XMLBEANS-538: fix issue with parsing DOM with DTD + Changes in V3.0.2 since V3.0.1 * XMLBEANS-520: wrong name for source(s) artifact diff --git a/KEYS b/KEYS index bb73098..6f0a569 100644 --- a/KEYS +++ b/KEYS @@ -2749,4 +2749,98 @@ pNpL7MDQGAmGLh41XWy7CmT+haoS2zhxAXWwXgUZOE0umsMfil+XVE9oZWjeg1Dm egfcIxtZ0AuggFN6ijBJqATbj0DlomeKrnHLVloD6lEDgB/j0SoYsGbv9kpYPqvU lSeSg2C31/20JYI= =/nGR +-----END PGP PUBLIC KEY BLOCK----- +pub 2048R/1556F3A4 2016-10-04 +uid Greg Woolsey +uid Greg Woolsey (personal) +sub 2048R/8CF53C56 2016-10-04 +sub 4096R/D5718BA4 2017-01-09 + +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQENBFfz7TQBCAC8O+eiVCz76SgBDty51fYXvp9IfIBNyVSCa5tOQiasICmXAZjn +L0EZqLtoZheR1z7qYV2zgDX0goGYx2NukWB4X1nrbVRQgmTOIoyNZ36L6BTV32Is +0v1gcPrFshenQoGna+VlUl5W/W13CdvmqeP2CUwOcPD2Wk+ySD4sBa4V3/hmLvjw +3ARek8c8/E7ctdMJ29iMPlnf9lIHzeCg2p9Gv+SUO9codZs7+n5cZHLA32mgek6P +eh7fuyh/2U34EnILeXgkiv80afn9udPYDNAjDZhOD3b72YcjSrBFN4GbShF71jkw +VX30E2t/lGGXpa3yhK7Qcjy+f7RFyvUdTipbABEBAAG0MEdyZWcgV29vbHNleSAo +cGVyc29uYWwpIDxncmVnLndvb2xzZXlAZ21haWwuY29tPokBOAQTAQIAIgUCV/Pt +NAIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQLRXlShVW86SRXgf/QvbE +HWBOILgbysKjDcy34r9S5sf8fgawxTSTXoQaEQoANebz/ooR1wDgc+yvOvcAtDaO +y5ukO73oE6pIT7x9FGoELQtbvSSSIornG6IK93xidbLwYRK4oPDmiOyIeTsfEUVX +Lp0HgbDhadWZwQaSgP4kQPROZcP34u9YozqEFIdvVO4G0VZGK/GakwC21tL8t1e6 +DaialULlCTMma42nxHuKxpDpPlJuAr3JtUM+Q9153P9xLIhdh2cmQ4XrHI6eWo6j +PLatowbPDzYdevr5OYH6bjO/q47TzNZQakLThxE4fA84zpBqcrnhWreCT+umme6s +g3NXyen1z9cDjyV994kCHAQTAQIABgUCWHch5gAKCRDmZ3rGi6vdbMorD/sHmSER +4I3nW6VWaIihcaaqzzA+kPwlMc1aP5y7hfGpic/gUa8I2VX69tPnryfjD22Xvtzw +mX0FuNWDyvDczlgXl+xCeRdykAhQYqRHH+To65mMHVTN4m0wsz3zhuY4C6Tx79D8 +BJtzk14gfmkn4mzMP+vTF0rlGVccN84Ysrnf9AhEyatNvyPrejnrOmYQziN1nLPf +K7L3tox6a7sciOxM3jfTd5t4pUO+ZcWLGnmtssBGC5mZ3SSuxFLMVLvQ/vYRHBSc +J/FGP2bSZ/e3e9k4UAB51GZnwjhR6JbGx6K2qTYh1Lnr6BffLmDEkV+XfUI9Y5xg +mNmq8NEC8EisA5eLYeMXnqDUgp+/pCwfk4+bX8OZ1MGDOx6Q2kI6JqEXtFYMXgcb +EYNyoZygIunNJAPzuPy2DjLO79PhZlV97UTJ9mup/UlQPHMEy+WbsnCIkf5Dh5T/ +1EdhBkWrUAMDcbQI/8i0Cxnyqdu+gnL0zxmyMut+gzVSzaAEEUlxOs7oZLz/SUsd +MQeyCGsuU/4L/j4DxWOkHuC65TIdb6wf6chGa72Q9zZzrPbG2j8+B4EGPAs6c8L4 +UzTFtMTL6iL5B8BkkBhaf10EBuNKQWpu85dFcJfLNi4JTRc5oe7apbWIefLoI+k1 +Rl6DdZ0088+B1bc2kA0QSYZ3kIkAvKcaIX54DrQiR3JlZyBXb29sc2V5IDxnd29v +bHNleUBhcGFjaGUub3JnPokBOAQTAQIAIgUCWHPLIAIbAwYLCQgHAwIGFQgCCQoL +BBYCAwECHgECF4AACgkQLRXlShVW86Tk2gf+LDN1vEw7SIdes+3XaYalaDPaSWnA +HpLwpFTRHjy7knNL006ttx3yrH2+kuKSTy+D/XCty2U8gPFV8KbPSXWUgkwzJgbA +VzzbwvpXgN7Dlt5oLFajF56F4Ba5ZS0rOUvrz43cbb7t1SodUfNl0rvlWdEBmGbJ +smTzDCuzX8D0zTGI2x4bgBRbtzTtrZ866EEE5NT0LGClAl+HElTyzRCmabzFSnaV +TwLZTMI0Z1ZXZ/HIE/fFraddjM1SllDrRMGrKzmFtH3ryQlhJBX1m5/6WsOyn7xE +FRXc8IJmkli0yu5gg3HS6apLR0NglDwFrS0gkEIcoipv8/hSz6hCymZnRIkCHAQT +AQIABgUCWHch2gAKCRDmZ3rGi6vdbJ1nD/9Q/v+TomMOSS/dm1EklT1p8YkCMVYA +ToPYi7mkBFdjfrRMozYEVaUZKEo2Cc/xwWkvqfyls4afSZ+2k+1jpp8DQCA69KXx +htltTXdHAOnAQ/MrFZ0h833XKNYxHEw5nIwiq2RDUBLA5vHJ7HLxUQW3wHNXwACm +HaAXq3a78gfv52YRqUvHJL2X0MhJ6mxtok6f0m0yqXXbdk6lPXxCkjiWbbia4jZY +aoCdTLam+8lvDFC0m4NF3NOw9b8aIZmy/ZHgU3KyWgItG2FjKLdHGQcxgEg8Mgkj +WT24KuURIf+cMM4zClmFwQIzWBnCmzlIJMo96LogywkTYQ1+QxqTAQXbSwlawGHH +yXE+8Daa3q4svJCaOuP3TjTTTo17Ef554JTTIQDsPfd9DdtKvKfb1BLVZhcyMRCH +0cl/tXMt62frgDgK2Fm9+s8wJhDmURAPSyMcLUH0L4g15huTOGgQkJscuueD9PLD +SXjsrJ5vYbGr/sf+KPBNMh8Ajms7VlWlAzyrGU7TWCrQfr6DIkKVXWjm8g9NclkG +gg3E2Y8dA4ZNlLSm7Cq3mmv1Y+KvXmVgJYOE0oHQhsVSAQTdgJ3+ZKp2OnpNACfn +BUhHZw5VBPoHmEKKxVisxvhj8zYGu3eC3KpOFuF6WGlKlnL+vmsUNlHC52Q167tn +zgxnEbre0TAbp7kBDQRX8+00AQgAo4qasXoWEZkjgWqsNLSecysZ3o+7BYRxv4xu +I07x5sGjTKEqbNEW8jiBgur25nnLEWILYH2HMPdbOD21wBkJyCJ8qxfyxWy79bv/ +HUkwOWwLe7BPV912kmzk8DTLHJpQlhvQ1okXdUw6U66/OA69JgA1xwSIq3OiVTD/ +hgdHiKbmbXzjETeLK/lAYxuWL7PpRkuDlTCFvD+Tnns1j9B3C3ybkj3r7oRXQ/sr +NVG8R53AGmiihmkRtViE6D+/wjJ8OKm73XYGECYuIuQuKjpJufy/eCyImZ6APHcu +M3LQfzBJmvI8MvOSPBNvjyO1v/OYX7/lM2ChvDsoXv7KsLqH1wARAQABiQEfBBgB +AgAJBQJX8+00AhsMAAoJEC0V5UoVVvOkfDkIAITaVfsvNc5BUHoDKaEvHGihLqKm +NrzcLuQuvYttAVm8mCfSLsf1VvDTwOh2zMswF6OOVN8IlehGPyeByDiV60+zYAk5 +9a/UL3iVvlAnYMDYweOVIC+pfvjXOEbJRh6PIuDKDH77xotmlMsLF4ZTDQt5VLzY +tn9yB5aCdaQYOfdIQbxZbVzBnGc9Qb89u9d1pzPN3GJo9aCVNs5cB+EsDtbAltK0 +Bx2diGvuXtNGUY4AtnyDcOyWPF8e/Tf/Yl9qWJ8DN9CiFwWDSpMAUxveZSuC9CbB +LxsUrhzlD5FFuE13hjDe3Wy+fG+2OghF9VehA7xdEhbyGW15MTB9kHNXy/u5Ag0E +WHPICAEQANLw5I8gBGTvt5WRb3Xja325LY6DkPj1GexZO3NiAT4BoAuK+Pub2eII +iws0kF1UT13LKOvruzeKza1mJylNGzwwcV/NW5q3i398RWcAw3cF0Zz9E6+GSx9+ +r35CylciO72ACQzINbDvxwvN4DVRKNitpjeAnzDRm7gdISkFjSgFgey4hLxBR3BE +3J0BB2l1A/xn2RwVs+/4YG37Dc1tJBKI33KR3dtmjTtb9v5A5YktdDOAK0Oo617B +WS6VioP5DpKOL1LkvKpA5yPs3JCx3FZ2PD/4UMX66WLkierPq7vZ9rMk6BFqpVI+ +OfLrDobITzOVlqsYFuJcxW5DVohoiVrQi94vvV25m1KZ92DY80z7NoJL3tQiJ48j +bskgxWPi8w3M+/AebnfjEaRjSomUlMzxr5+/slTueNZGADUBIoOCY3N/yCqe3X36 +JvJC7tmpi3ckpTxy1YrUepeJUmLsTX7MY0Ta/Gj3mbq3iP5Ofp1R4isjWgj0tmi6 +Md5K5MBayy4ZzNNIFphGGXTqgP6U8WpjV3vAdq8Ll5aPKlqpiJf4ALaIjNWGiJRb +xocXqEC4iN5gbL15jwh0VM+CY6zy+XffF1pN6fFJMX80csxirhYzNbDPQeAsp8TH ++gopEP7t3ezpUMnEatcChXyErIwXuxgysbV+syCIZuGuKPzCxtuxABEBAAGJAz4E +GAECAAkFAlhzyAgCGwICKQkQLRXlShVW86TBXSAEGQECAAYFAlhzyAgACgkQ2Ydr +uNVxi6Tdug//bNCLnSQDSPuVTP5IBggeSMniSfVbwDiQiDxtmdlLtVF9fnofGjEa +NadzxhKyz8QZXnsJgbpQ47WKeJcuJlCi6COR2gAs6gpCk4i8tjJpGnP34D5mDEnb +7MxM78+GPLIOGktnByXv1xxxixpZBRAthmGVI1kHo5NtzCUvKIeQLlDtmquPCThI +ZYpSBf9FFh8iJDXsnnoomeYp4YOcN4x0JRdfAU4NowFRxf6JV8VDts3VPL75lq9z +he+ICdGxRVWPfJ+9UTeeUmYSxdYnTVVcnNYCIeS6VjwzXLjFTnAZUAhnShAly6pi +F+mpg7FRDHxdulxQuIuCmpNWp6PHEeI2ynHX/5NyJ+90HeuDi+UC4kUc2PB2NNzt +79GprNnWiR8J7Zz00lisX5oD82IXKl1RnbgDMK1GafeLJwsfGEt3cUXyIyp+F5xW +Qp4nxSlGenEpi0ZIPUNoHMB7QTPG/mqVDHqNFvXRY6JiwXUZRvW88h45vNJ+V6np +Aa4eaNDQIKkawEcKMnpdL3okF8yWTT/7YTvpFMWGbC6zjFFemqxjc/y+eRMu9m+U +r9BHs8a6DtfGHlP55bx4+PA4nrRIj367wshLZQIj0i/vMue5sSxLKN8iM6rvaOaZ +XgwcGHx6+g33c9v+BwzH/OVdNKypvluhm5DU+LXL1bb9QH0DMFWL0T26ZAf/RtvQ +SiyzKFTrb0uFZs6ZOsgTzpI50LlM4Jkq4ejD7Bay5ZokH3rNM66JjDtnrzE2qpCp +LrvphHvbH5G2uOiirM5GjHwyXV1oYIIkXP3DMtc8biqZoGR22SLDsFORvUCYRHfk +MQbJRK/Bz9lZLhVWNUIIbq5WCBGQeeqsWu5E8XkOnaKnjamJ2LbvuSOHgDv4Vslf +cOgiy5G0KyQ1Nnm7tKWDFw6rtY2DuVu78ql0mgAh7VXXu0/QiKBC3xUenr3HOg1S +3w1duYfKrRYa7dLqI607wiz03pgmicV7JfWZH5ythHnOImQGnlzWGpyBElYTpUyg +NTeD7OEx91V/30fH3Q== +=Jrt1 -----END PGP PUBLIC KEY BLOCK----- \ No newline at end of file diff --git a/README.txt b/README.txt index 445390b..1cfd6a9 100644 --- a/README.txt +++ b/README.txt @@ -18,13 +18,13 @@ Welcome to XMLBeans! Layout of the tree: - README.txt this file - build.xml ant build file for building XmlBeans code and utilities -- testbuild.xml ant build file for building and running tests - STATUS essential info about the project - xbeanenv.cmd sets the XMLBEANS_HOME environment variable on Windows - xbeanenv.sh sets the XMLBEANS_HOME environment variable on Unix - bin contains useful command-line scripts for Win and Unix - docs contains several documentation files -- external contains external jars upon which XmlBeans depends +- javadocs API documentation +- maven-plugin source and documentation on using the xmlbeans2 Maven plugin - samples contains ... samples - src the source code for XmlBeans, organized by area - test contains test cases and infrastructure @@ -54,4 +54,4 @@ XmlBeans depends on the following external libraries: (O) means that the library is optional For licensing information, see ./src/license/LICENSE.txt -Updated: 11/25/09. +Updated: 3/22/2019. diff --git a/STATUS b/STATUS index 41d2cdf..689736b 100644 --- a/STATUS +++ b/STATUS @@ -10,6 +10,7 @@ Radu Preotiuc-Pietro radu.preotiuc-pietro at oracle dot com Jacob Danner jacob dot danner at gmail.com Wing Yew Poon wing.yew.poon at oracle dot com +Apache POI team FAQ: diff --git a/bin/_setlib.cmd b/bin/_setlib.cmd deleted file mode 100644 index 6344731..0000000 --- a/bin/_setlib.cmd +++ /dev/null @@ -1,28 +0,0 @@ -@REM -@REM Copyright 2004 The Apache Software Foundation -@REM -@REM Licensed under the Apache License, Version 2.0 (the "License"); -@REM you may not use this file except in compliance with the License. -@REM You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, software -@REM distributed under the License is distributed on an "AS IS" BASIS, -@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@REM See the License for the specific language governing permissions and -@REM limitations under the License. -@REM - -@rem Common script to set the XMLBEANS_LIB variable -@rem to the directory containing xbean.jar -@echo off - -if "%XMLBEANS_HOME%" EQU "" (set XMLBEANS_HOME=%~dp0..) - -set XMLBEANS_LIB= - -if exist "%XMLBEANS_HOME%\build\lib\xbean.jar" set XMLBEANS_LIB=%XMLBEANS_HOME%\build\lib -if exist "%XMLBEANS_HOME%\lib\xbean.jar" set XMLBEANS_LIB=%XMLBEANS_HOME%\lib - -if "%XMLBEANS_LIB%" EQU "" echo "ERROR: Could not find xbean.jar, try setting XMLBEANS_LIB to the directory containing xbean.jar" diff --git a/build.xml b/build.xml index 74c33fd..fd17c46 100644 --- a/build.xml +++ b/build.xml @@ -13,1133 +13,712 @@ See the License for the specific language governing permissions and limitations under the License. --> - + - - - + + + - + - - - - - + - + + - - - - - + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - - - + + + + @{artifact} + + + + + + + + + @{artifact} + + + + + + + + @{artifact} + + + + + + + + @{artifact} + + + + + + + + + + + + + + @{usage} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + + - - - - - - - - - - - - - - - - - + + - + + + - - - + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + - - - - - - - - - + + + + - - + + - - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + - - - - - - - - - - + + - - - - - - + + + + + + + - + + + + - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
-
-
-
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - + + + - - - - + - - - - - - - - - - - - - - + - - - - - - - - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
-
-
-
+ + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
-
-
-
- - - - + + + + + - + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - + - - - - - - -
- - - - - -
-
-
+ +
- + + + - - - - - - - - + + + - - - - - - - - - - - + + + + + - - - - - - - - - - - - + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+
+
- + + + + +
+ + + + + +
+
+
- - - + + + + + + + + + + + + + - - - - - - + +
+ + + + + +
+
+
- - - - - - + + + - - - - - - + - - - - + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + @@ -1148,10 +727,17 @@ classpath="${rat.jar}" /> + - + + + + + + + @@ -1172,43 +758,31 @@ - - - - - + + + - - - - - - - - - - - - - - - - - - - + + + + + + + + @@ -1217,26 +791,149 @@ - - - - - - - - - - - - - - - - + + + + + + + + + Maven ant tasks not found. + Please make sure the maven-ant-tasks jar is in ANT_HOME/lib, or made + available to Ant using other mechanisms like -lib or CLASSPATH. + + You can download the Maven Ant Tasks from https://maven.apache.org/ant-tasks/download.html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ]]> + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/debian/ant.properties b/debian/ant.properties index 9d81bae..7e3f4b0 100644 --- a/debian/ant.properties +++ b/debian/ant.properties @@ -1,7 +1,4 @@ -saxon_jar=/usr/share/java/Saxon-HE.jar -saxon_dom_jar=/usr/share/java/Saxon-HE.jar -jsr173-bundle.exists=true -jsr173_1.0.jars.exist=true -saxon9.jar.exists=true -xcresolver.zip.exists=true -resolver.jar.exists=true +ant.jar=/usr/share/java/ant.jar +javaparser.core.jar=/usr/share/java/javaparser-core.jar +old.xmlbeans.jar=/usr/share/java/xmlbeans.jar +saxon.jar=/usr/share/java/Saxon-HE.jar diff --git a/debian/changelog b/debian/changelog index c308f28..9ed0e73 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,25 @@ +xmlbeans (4.0.0-2) unstable; urgency=medium + + * Team upload. + * Remove dangling symlink to xmlbeans_xpath.jar (Closes: #1012448) + + -- tony mancill Wed, 29 Jun 2022 21:36:02 -0700 + +xmlbeans (4.0.0-1) unstable; urgency=medium + + * New upstream release (Closes: #981936) + - No longer build the xpath jar + - Refreshed the patches + - Updated the Maven poms + - Depend on libjavaparser-java (>= 3.16) + - Restored the javasource option to preserve the backward compatibility + * Standards-Version updated to 4.5.1 + * Switch to debhelper level 13 + * Updated the watch file + * Standards-Version updated to 4.6.1 + + -- Emmanuel Bourg Mon, 16 May 2022 11:34:47 +0200 + xmlbeans (3.0.2-1) unstable; urgency=medium * New upstream release diff --git a/debian/compat b/debian/compat deleted file mode 100644 index b4de394..0000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -11 diff --git a/debian/control b/debian/control index f09ba23..32c3a45 100644 --- a/debian/control +++ b/debian/control @@ -6,12 +6,13 @@ Uploaders: Emmanuel Bourg Build-Depends: ant, ant-optional, - debhelper (>= 11), + debhelper-compat (= 13), default-jdk, + libjavaparser-java (>= 3.16), libsaxonhe-java, libxmlbeans-java, maven-repo-helper -Standards-Version: 4.3.0 +Standards-Version: 4.6.1 Vcs-Git: https://salsa.debian.org/java-team/xmlbeans.git Vcs-Browser: https://salsa.debian.org/java-team/xmlbeans Homepage: http://xmlbeans.apache.org @@ -19,6 +20,7 @@ Homepage: http://xmlbeans.apache.org Package: libxmlbeans-java Architecture: all Depends: + libjavaparser-java (>= 3.16), libsaxonhe-java, libxml-commons-resolver1.1-java, ${misc:Depends} diff --git a/debian/copyright b/debian/copyright index 5ed53be..764520d 100644 --- a/debian/copyright +++ b/debian/copyright @@ -1,8 +1,7 @@ Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: Apache XMLBeans Source: http://www.apache.org/dist/xmlbeans/source/ -Files-Excluded: external/lib/junit* - external/lib/oldxbean.jar +Files-Excluded: lib/oldxbean.jar samples/vxsdb/external/* test/lib/*.jar test/tools/lib/*.jar diff --git a/debian/libxmlbeans-java.links b/debian/libxmlbeans-java.links deleted file mode 100644 index 0023989..0000000 --- a/debian/libxmlbeans-java.links +++ /dev/null @@ -1 +0,0 @@ -/usr/share/java/xmlbeans-xpath.jar /usr/share/java/xmlbeans_xpath.jar diff --git a/debian/libxmlbeans-java.poms b/debian/libxmlbeans-java.poms index e91eb9a..761cc72 100644 --- a/debian/libxmlbeans-java.poms +++ b/debian/libxmlbeans-java.poms @@ -1,2 +1 @@ -debian/poms/xmlbeans.xml --java-lib --artifact=build/lib/xbean.jar -debian/poms/xpath.xml --java-lib --artifact=build/lib/xbean_xpath.jar +debian/poms/xmlbeans.xml --java-lib --artifact=build/xmlbeans-4.0.0.jar diff --git a/debian/patches/javasource-option.patch b/debian/patches/javasource-option.patch new file mode 100644 index 0000000..4f0baac --- /dev/null +++ b/debian/patches/javasource-option.patch @@ -0,0 +1,37 @@ +Description: Restores the javasource option to preserve the backward compatibility +Author: Emmanuel Bourg +Forwarded: not-needed +--- a/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java ++++ b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java +@@ -111,6 +111,7 @@ + opts.add("extensionParms"); + opts.add("allowmdef"); + opts.add("catalog"); ++ opts.add("javasource"); + CommandLine cl = new CommandLine(args, flags, opts); + + if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) { +@@ -632,6 +633,10 @@ + public void setEntityResolver(EntityResolver entityResolver) { + this.entityResolver = entityResolver; + } ++ ++ @Deprecated ++ public void setJavaSource(String version) { ++ } + } + + private static SchemaTypeSystem loadTypeSystem(String name, File[] xsdFiles, File[] wsdlFiles, URL[] urlFiles, File[] configFiles, +--- a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java ++++ b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java +@@ -764,6 +764,10 @@ + this.repackage = repackage; + } + ++ @Deprecated ++ public void setJavaSource(String version) { ++ } ++ + private static URI uriFromFile(File f) { + if (f == null) { + return null; diff --git a/debian/patches/saxon-compatibility.patch b/debian/patches/saxon-compatibility.patch new file mode 100644 index 0000000..222d4a3 --- /dev/null +++ b/debian/patches/saxon-compatibility.patch @@ -0,0 +1,11 @@ +--- a/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPath.java ++++ b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPath.java +@@ -111,7 +111,7 @@ + dc.setContextItem(contextItem); + dc.setVariable(thisVar, contextItem); + +- List saxonNodes = xpath.evaluate(dc); ++ List saxonNodes = (List) xpath.evaluate(dc); + List retNodes = new ArrayList<>(saxonNodes.size()); + for (Item o : saxonNodes) { + if (o instanceof DOMNodeWrapper) { diff --git a/debian/patches/saxon_9.7.patch b/debian/patches/saxon_9.7.patch deleted file mode 100644 index 22acc28..0000000 --- a/debian/patches/saxon_9.7.patch +++ /dev/null @@ -1,306 +0,0 @@ -Description: Build with Saxon-HE 9.7.0.10 - ---- a/src/xpath_xquery/org/apache/xmlbeans/impl/xpath/saxon/XBeansXPath.java -+++ /dev/null -@@ -1,173 +0,0 @@ --/* Copyright 2004 The Apache Software Foundation -- * -- * Licensed under the Apache License, Version 2.0 (the "License"); -- * you may not use this file except in compliance with the License. -- * You may obtain a copy of the License at -- * -- * http://www.apache.org/licenses/LICENSE-2.0 -- * -- * Unless required by applicable law or agreed to in writing, software -- * distributed under the License is distributed on an "AS IS" BASIS, -- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- * See the License for the specific language governing permissions and -- * limitations under the License. -- */ -- --package org.apache.xmlbeans.impl.xpath.saxon; -- --import java.util.List; --import java.util.Map; --import java.util.ListIterator; -- --import javax.xml.transform.dom.DOMSource; --import javax.xml.transform.TransformerException; -- --import org.w3c.dom.Node; -- --import net.sf.saxon.Configuration; --import net.sf.saxon.dom.NodeWrapper; --import net.sf.saxon.om.NodeInfo; --import net.sf.saxon.om.VirtualNode; --import net.sf.saxon.om.Item; --import net.sf.saxon.value.Value; --import net.sf.saxon.sxpath.XPathEvaluator; --import net.sf.saxon.sxpath.XPathExpression; --import net.sf.saxon.sxpath.IndependentContext; --import net.sf.saxon.sxpath.XPathDynamicContext; --import net.sf.saxon.sxpath.XPathVariable; -- --import org.apache.xmlbeans.impl.store.PathDelegate; -- --public class XBeansXPath -- implements PathDelegate.SelectPathInterface --{ -- private Object[] namespaceMap; -- private String path; -- private String contextVar; -- private String defaultNS; -- -- /** -- * Construct given an XPath expression string. -- * @param path The XPath expression -- * @param contextVar The name of the context variable -- * @param namespaceMap a map of prefix/uri bindings for NS support -- * @param defaultNS the uri for the default element NS, if any -- */ -- public XBeansXPath(String path, String contextVar, -- Map namespaceMap, String defaultNS) -- { -- this.path = path; -- this.contextVar = contextVar; -- this.defaultNS = defaultNS; -- this.namespaceMap = namespaceMap.entrySet().toArray(); -- } -- -- /** -- * Select all nodes that are selectable by this XPath -- * expression. If multiple nodes match, multiple nodes -- * will be returned. -- *

-- *

-- * NOTE: In most cases, nodes will be returned -- * in document-order, as defined by the XML Canonicalization -- * specification. The exception occurs when using XPath -- * expressions involving the union operator -- * (denoted with the pipe '|' character). -- *

-- *

-- *

-- * NOTE: Param node must be a DOM node which will be used -- * during the xpath execution and iteration through the results. -- * A call of node.dispose() must be done after reading all results. -- *

-- * -- * @param node The node, nodeset or Context object for evaluation. -- * This value can be null. -- * @return The List of all items selected -- * by this XPath expression. -- */ -- public List selectNodes(Object node) -- { -- try -- { -- Node contextNode = (Node)node; -- XPathEvaluator xpe = new XPathEvaluator(); -- Configuration config = new Configuration(); -- config.setDOMLevel(2); -- config.setTreeModel(net.sf.saxon.event.Builder.STANDARD_TREE); -- IndependentContext sc = new IndependentContext(config); -- // Declare ns bindings -- if (defaultNS != null) -- sc.setDefaultElementNamespace(defaultNS); -- -- for (int i = 0; i < namespaceMap.length; i++) -- { -- Map.Entry entry = (Map.Entry) namespaceMap[i]; -- sc.declareNamespace((String) entry.getKey(), -- (String) entry.getValue()); -- } -- xpe.setStaticContext(sc); -- XPathVariable thisVar = xpe.declareVariable("", contextVar); -- XPathExpression xpath = xpe.createExpression(path); -- NodeInfo contextItem = -- //config.buildDocument(new DOMSource(contextNode)); -- config.unravel(new DOMSource(contextNode)); -- XPathDynamicContext dc = xpath.createDynamicContext(null); -- dc.setContextItem(contextItem); -- dc.setVariable(thisVar, contextItem); -- -- List saxonNodes = xpath.evaluate(dc); -- for (ListIterator it = saxonNodes.listIterator(); it.hasNext(); ) -- { -- Object o = it.next(); -- if (o instanceof NodeInfo) -- { -- if (o instanceof NodeWrapper) -- { -- Node n = getUnderlyingNode((NodeWrapper)o); -- it.set(n); -- } -- else -- { -- it.set(((NodeInfo)o).getStringValue()); -- } -- } -- else if (o instanceof Item) -- it.set(Value.convertToJava((Item)o)); -- } -- return saxonNodes; -- } -- catch (TransformerException e) -- { -- throw new RuntimeException(e); -- } -- } -- -- public List selectPath(Object node) -- { -- return selectNodes(node); -- } -- -- /** -- * According to the Saxon javadoc: -- * getUnderlyingNode in NodeWrapper implements -- * the method specified in the interface VirtualNode, and -- * the specification of the latter says that it may return another -- * VirtualNode, and you may have to drill down through -- * several layers of wrapping. -- * To be safe, this method is provided to drill down through multiple -- * layers of wrapping. -- * @param v The VirtualNode -- * @return The underlying node -- */ -- private static Node getUnderlyingNode(VirtualNode v) -- { -- Object o = v; -- while (o instanceof VirtualNode) -- { -- o = ((VirtualNode)o).getUnderlyingNode(); -- } -- return (Node)o; -- } -- --} ---- a/src/xpath_xquery/org/apache/xmlbeans/impl/xquery/saxon/XBeansXQuery.java -+++ /dev/null -@@ -1,125 +0,0 @@ --/* Copyright 2004 The Apache Software Foundation -- * -- * Licensed under the Apache License, Version 2.0 (the "License"); -- * you may not use this file except in compliance with the License. -- * You may obtain a copy of the License at -- * -- * http://www.apache.org/licenses/LICENSE-2.0 -- * -- * Unless required by applicable law or agreed to in writing, software -- * distributed under the License is distributed on an "AS IS" BASIS, -- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- * See the License for the specific language governing permissions and -- * limitations under the License. -- */ -- --package org.apache.xmlbeans.impl.xquery.saxon; -- --import java.util.List; --import java.util.Map; --import java.util.Iterator; --import java.util.ListIterator; -- --import javax.xml.transform.dom.DOMSource; --import javax.xml.transform.TransformerException; -- --import org.w3c.dom.Node; -- --import net.sf.saxon.Configuration; --import net.sf.saxon.dom.NodeOverNodeInfo; --import net.sf.saxon.om.NodeInfo; --import net.sf.saxon.query.DynamicQueryContext; --import net.sf.saxon.query.StaticQueryContext; --import net.sf.saxon.query.XQueryExpression; -- --import org.apache.xmlbeans.XmlRuntimeException; --import org.apache.xmlbeans.XmlTokenSource; --import org.apache.xmlbeans.impl.store.QueryDelegate; -- --public class XBeansXQuery -- implements QueryDelegate.QueryInterface --{ -- private XQueryExpression xquery; -- private String contextVar; -- private Configuration config; -- -- /** -- * Construct given an XQuery expression string. -- * @param query The XQuery expression -- * @param contextVar The name of the context variable -- * @param boundary The offset of the end of the prolog -- */ -- public XBeansXQuery(String query, String contextVar, Integer boundary) -- { -- config = new Configuration(); -- config.setDOMLevel(2); -- config.setTreeModel(net.sf.saxon.event.Builder.STANDARD_TREE); -- StaticQueryContext sc = new StaticQueryContext(config); -- this.contextVar = contextVar; -- int bdry = boundary.intValue(); -- //Saxon requires external variables at the end of the prolog... -- query = (bdry == 0) ? -- "declare variable $" + -- contextVar + " external;" + query : -- query.substring(0, bdry) + -- "declare variable $" + -- contextVar + " external;" + -- query.substring(bdry); -- try -- { -- xquery = sc.compileQuery(query); -- } -- catch (TransformerException e) -- { -- throw new XmlRuntimeException(e); -- } -- } -- -- public List execQuery(Object node, Map variableBindings) -- { -- try -- { -- Node contextNode = (Node)node; -- NodeInfo contextItem = -- config.buildDocument(new DOMSource(contextNode)); -- //config.unravel(new DOMSource(contextNode)); -- DynamicQueryContext dc = new DynamicQueryContext(config); -- dc.setContextItem(contextItem); -- dc.setParameter(contextVar, contextItem); -- // Set the other variables -- if (variableBindings != null) -- { -- for (Iterator it = variableBindings.entrySet().iterator(); -- it.hasNext(); ) -- { -- Map.Entry entry = (Map.Entry)it.next(); -- String key = (String)entry.getKey(); -- Object value = entry.getValue(); -- if (value instanceof XmlTokenSource) -- { -- Node paramObject = ((XmlTokenSource)value).getDomNode(); -- dc.setParameter(key, paramObject); -- } -- else if (value instanceof String) -- dc.setParameter(key, value); -- } -- } -- -- List saxonNodes = xquery.evaluate(dc); -- for (ListIterator it = saxonNodes.listIterator(); it.hasNext(); ) -- { -- Object o = it.next(); -- if(o instanceof NodeInfo) -- { -- Node n = NodeOverNodeInfo.wrap((NodeInfo)o); -- it.set(n); -- } -- } -- return saxonNodes; -- } -- catch (TransformerException e) -- { -- throw new RuntimeException("Error binding " + contextVar, e); -- } -- } --} diff --git a/debian/patches/scripts.patch b/debian/patches/scripts.patch index 74b7a73..56898fe 100644 --- a/debian/patches/scripts.patch +++ b/debian/patches/scripts.patch @@ -3,8 +3,8 @@ Description: Fix XMLBEANS_LIB variables in all CLI scripts Author: Damien Raude-Morvan Last-Update: 2010-03-26 Forwarded: not-needed ---- a/bin/dumpxsb -+++ b/bin/dumpxsb +--- a/src/main/shell/dumpxsb ++++ b/src/main/shell/dumpxsb @@ -18,11 +18,9 @@ #XSB file dumper #Prints the contents of an xsb file in human-readmble form @@ -14,13 +14,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi - --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/inst2xsd -+++ b/bin/inst2xsd +--- a/src/main/shell/inst2xsd ++++ b/src/main/shell/inst2xsd @@ -18,9 +18,9 @@ #Instance to Schema tool #Builds xsd files from xml instance files. @@ -28,13 +28,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/scomp -+++ b/bin/scomp +--- a/src/main/shell/scomp ++++ b/src/main/shell/scomp @@ -18,9 +18,9 @@ #Schema compiler #Builds XBean types from xsd files. @@ -42,13 +42,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$JAVA_HOME/lib/tools.jar:$XMLBEANS_LIB/resolver.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$JAVA_HOME/lib/tools.jar:$XMLBEANS_LIB/resolver.jar +-cp=$XMLBEANS_LIB/*:$JAVA_HOME/lib/tools.jar ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$JAVA_HOME/lib/tools.jar:$XMLBEANS_LIB/resolver.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/sdownload -+++ b/bin/sdownload +--- a/src/main/shell/sdownload ++++ b/src/main/shell/sdownload @@ -18,9 +18,9 @@ #Schema downloader #Tool to download Schema files @@ -56,13 +56,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/sfactor -+++ b/bin/sfactor +--- a/src/main/shell/sfactor ++++ b/src/main/shell/sfactor @@ -20,9 +20,9 @@ ## Factors redundant definitions out of a set of schemas and ## uses imports instead. @@ -70,13 +70,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar +-cp=$XMLBEANS_LIB/*:$XMLBEANS_LIB/resolver.jar ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/svalidate -+++ b/bin/svalidate +--- a/src/main/shell/svalidate ++++ b/src/main/shell/svalidate @@ -19,9 +19,9 @@ # # Validates an instance against a schema. @@ -84,13 +84,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/jsr173_1.0_ri.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/jsr173_1.0_ri.jar +-cp=$XMLBEANS_LIB/*:$XMLBEANS_LIB/jsr173_1.0_ri.jar ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/jsr173_1.0_ri.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/validate -+++ b/bin/validate +--- a/src/main/shell/validate ++++ b/src/main/shell/validate @@ -19,9 +19,9 @@ # # Validates an instance against a schema. @@ -98,13 +98,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/xpretty -+++ b/bin/xpretty +--- a/src/main/shell/xpretty ++++ b/src/main/shell/xpretty @@ -17,9 +17,9 @@ #Invokes pretty printer @@ -112,13 +112,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/xsd2inst -+++ b/bin/xsd2inst +--- a/src/main/shell/xsd2inst ++++ b/src/main/shell/xsd2inst @@ -17,9 +17,9 @@ #Schema to instance tool @@ -126,13 +126,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/xsdtree -+++ b/bin/xsdtree +--- a/src/main/shell/xsdtree ++++ b/src/main/shell/xsdtree @@ -17,9 +17,9 @@ # Invokes type hierarchy printer @@ -140,13 +140,13 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +-cp=$XMLBEANS_LIB/* ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) ---- a/bin/xstc -+++ b/bin/xstc +--- a/src/main/shell/xstc ++++ b/src/main/shell/xstc @@ -17,9 +17,9 @@ # Invokes XSTC @@ -154,8 +154,8 @@ Forwarded: not-needed -if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi +XMLBEANS_LIB=/usr/share/java --cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar -+cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar +-cp=$XMLBEANS_LIB/*:$XMLBEANS_LIB/resolver.jar ++cp=$XMLBEANS_LIB/xmlbeans.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar:/usr/share/java/javaparser-core.jar case "`uname`" in CYGWIN*) diff --git a/debian/patches/series b/debian/patches/series index 8b37b09..641da24 100644 --- a/debian/patches/series +++ b/debian/patches/series @@ -1,2 +1,4 @@ scripts.patch -saxon_9.7.patch +saxon-compatibility.patch +xmlbeans-compatibility.patch +javasource-option.patch diff --git a/debian/patches/xmlbeans-compatibility.patch b/debian/patches/xmlbeans-compatibility.patch new file mode 100644 index 0000000..db09ffe --- /dev/null +++ b/debian/patches/xmlbeans-compatibility.patch @@ -0,0 +1,14 @@ +Description: Fixes a build failure with xmlbeans 3 +Author: Emmanuel Bourg +Forwarded: not-needed +--- a/build.xml ++++ b/build.xml +@@ -307,7 +307,7 @@ + + + +- ++ + + + diff --git a/debian/poms/xmlbeans.xml b/debian/poms/xmlbeans.xml index 8e356f7..59d3afd 100644 --- a/debian/poms/xmlbeans.xml +++ b/debian/poms/xmlbeans.xml @@ -1,8 +1,28 @@ + + + 4.0.0 org.apache.xmlbeans xmlbeans - 3.0.2 + 4.0.0 XmlBeans XmlBeans main jar @@ -10,7 +30,7 @@ jira - http://issues.apache.org/jira/secure/BrowseProject.jspa?id=10436 + https://issues.apache.org/jira/browse/XMLBEANS @@ -26,7 +46,7 @@ dev-unsubscribe@poi.apache.org http://mail-archives.apache.org/mod_mbox/poi-dev/ - + @@ -38,9 +58,7 @@ scm:svn:https://svn.apache.org/repos/asf/xmlbeans/ - - scm:svn:https://${maven.username}@svn.apache.org/repos/asf/xmlbeans/ - + scm:svn:https://${maven.username}@svn.apache.org/repos/asf/xmlbeans/ https://svn.apache.org/repos/asf/xmlbeans/ @@ -50,36 +68,6 @@ - - Cezar Andrei - cezar - cezar.andrei@no#spam#!gma|l.com - - - - Radu Preotiuc - radup - radupr@nos#pam.gm@il.com - - - - Radu Preotiuc - radup - radu.preotiuc-pietro@nos#pam.bea.com - - - - Wing Yew Poon - wpoon - wing-yew.poon@nos#pam.oracle.com - - - - Jacob Danner - jdanner - jacob.danner@nos#pam.oracle.com - - POI Team poi @@ -88,6 +76,34 @@ - + + + net.sf.saxon + Saxon-HE + 10.2 + provided + + + com.github.javaparser + javaparser-core + 3.16.1 + provided + + + + + java8 + + 1.8 + + + + xml-apis + xml-apis + 1.4.01 + + + + diff --git a/debian/rules b/debian/rules index 845f4f1..6c577a7 100755 --- a/debian/rules +++ b/debian/rules @@ -1,19 +1,13 @@ #!/usr/bin/make -f -export CLASSPATH=/usr/share/java/xmlbeans.jar - %: dh $@ --with maven-repo-helper override_dh_auto_build: - mkdir -p external/lib/ - ln -s /usr/share/java/xmlbeans.jar external/lib/oldxbean.jar - ln -s /usr/share/java/junit.jar external/lib/junit.jar - - mkdir -p build/lib/ - ln -s /usr/share/java/geronimo-stax-1.0-spec.jar build/lib/jsr173_1.0_api.jar + mkdir -p src/xpath_xquery + mkdir -p lib/main - ANT_OPTS=-Dfile.encoding=iso-8859-1 dh_auto_build -- xbean.jar + ANT_OPTS=-Dfile.encoding=iso-8859-1 dh_auto_build -- package -Djars.present=true override_dh_install: dh_install @@ -21,8 +15,7 @@ override_dh_install: # Rename to fix filename conflict: See #578032 mv debian/xmlbeans/usr/bin/validate debian/xmlbeans/usr/bin/xsdvalidate -POM_VERSION := 3.0.2 +POM_VERSION := 4.0.0 get-orig-pom: wget -O debian/poms/xmlbeans.xml https://repo1.maven.org/maven2/org/apache/xmlbeans/xmlbeans/$(POM_VERSION)/xmlbeans-$(POM_VERSION).pom - wget -O debian/poms/xpath.xml https://repo1.maven.org/maven2/org/apache/xmlbeans/xmlbeans-xpath/$(POM_VERSION)/xmlbeans-xpath-$(POM_VERSION).pom diff --git a/debian/watch b/debian/watch index bb62b49..cce8bba 100644 --- a/debian/watch +++ b/debian/watch @@ -1,3 +1,3 @@ version=3 -opts="dversionmangle=s/\+dfsg//,repack,compression=xz" \ -https://github.com/apache/xmlbeans/tags .*/([\d\.]+).tar.gz +opts="dversionmangle=s/\+dfsg//,uversionmangle=s/_/./g,repack,compression=xz" \ +https://github.com/apache/xmlbeans/tags .*/(?:REL_)?([\d\._]+).tar.gz diff --git a/debian/xmlbeans.install b/debian/xmlbeans.install index 96d11c4..e370eec 100644 --- a/debian/xmlbeans.install +++ b/debian/xmlbeans.install @@ -1,11 +1,11 @@ -bin/dumpxsb /usr/bin/ -bin/inst2xsd /usr/bin/ -bin/scomp /usr/bin/ -bin/sdownload /usr/bin/ -bin/sfactor /usr/bin/ -bin/svalidate /usr/bin/ -bin/validate /usr/bin/ -bin/xpretty /usr/bin/ -bin/xsd2inst /usr/bin/ -bin/xsdtree /usr/bin/ -bin/xstc /usr/bin/ +src/main/shell/dumpxsb /usr/bin/ +src/main/shell/inst2xsd /usr/bin/ +src/main/shell/scomp /usr/bin/ +src/main/shell/sdownload /usr/bin/ +src/main/shell/sfactor /usr/bin/ +src/main/shell/svalidate /usr/bin/ +src/main/shell/validate /usr/bin/ +src/main/shell/xpretty /usr/bin/ +src/main/shell/xsd2inst /usr/bin/ +src/main/shell/xsdtree /usr/bin/ +src/main/shell/xstc /usr/bin/ diff --git a/docs/guide/antXmlbean.html b/docs/guide/antXmlbean.html index bc0b228..8bdead1 100644 --- a/docs/guide/antXmlbean.html +++ b/docs/guide/antXmlbean.html @@ -215,6 +215,12 @@

Parameters

the executing VM in the classpath; defaults to no. No + + nowarn + Whether the -nowarn switch should be passed to + the JDK compiler; defaults to no. + No + fork Whether to execute javac using the JDK compiler diff --git a/docs/guide/conSelectingXMLwithXQueryPathXPath.html b/docs/guide/conSelectingXMLwithXQueryPathXPath.html index 648cde6..41b7849 100644 --- a/docs/guide/conSelectingXMLwithXQueryPathXPath.html +++ b/docs/guide/conSelectingXMLwithXQueryPathXPath.html @@ -225,9 +225,9 @@

Using XQuery with the execQuery Method

You use the execQuery method to execute XQuery expressions. With XQuery expressions, XML returned is a copy of XML in the document queried against. In other words, changes your code makes to the values returned by execQuery are not reflected in the document queried against.

-

Note: To execute XQuery expressions, you must have the SaxonB 8.6.1 versions of the saxon8.jar and saxon8-dom.jar files on your classpath. These are two of the jars from inside the zip file saxonb8-6-1.zip +

Note: To execute XQuery expressions, you must have the SaxonB 9.0.0.4 versions of the saxon9.jar and saxon9-dom.jar files on your classpath. These are two of the jars from inside the zip file saxonb9-0-0-4j.zip which can be downloaded from the Saxon web site. - If you build XMLBeans from source then the saxonb8-6-1.zip file and the two Saxon jar files are available in the external/lib directory.

+ If you build XMLBeans from source then the saxonb9-0-0-4j.zip file and the two Saxon jar files are available in the external/lib directory.

Calling XmlObject.execQuery

As with selectPath, calling execQuery diff --git a/docs/stylesheet.css b/docs/stylesheet.css deleted file mode 100644 index df91b48..0000000 --- a/docs/stylesheet.css +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* Javadoc style sheet */ - -/* Define colors, fonts and other style attributes here to override the defaults */ - -/* Page background color */ -body { - font-family: Verdana, Arial, Helvetica, sans-serif; - background-color: #FFFFFF -} - -body { -/* padding: 0px 0px 0px 15px; */ - background: #ffffff; - color: #00000; - font-size: 80%; -} - -/* Table colors */ -.TableHeadingColor { background: #CCCCFF } /* Dark mauve */ -.TableSubHeadingColor { background: #EEEEFF } /* Light mauve */ -.TableRowColor { background: #FFFFFF } /* White */ - -/* Font used in left-hand frame lists */ -.FrameTitleFont { font-size: 10pts; font-family: Helvetica, Arial, san-serif } -.FrameHeadingFont { font-size: 10pts; font-family: Helvetica, Arial, san-serif } -.FrameItemFont { font-size: 10pts; font-family: Helvetica, Arial, san-serif } - -/* Example of smaller, sans-serif font in frames */ -/* .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } */ - -/* Navigation bar fonts and colors */ -.NavBarCell1 { background-color:#EEEEFF;}/* Light mauve */ -.NavBarCell1Rev { background-color:#00008B;}/* Dark Blue */ -.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} -.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} - -.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} -.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} - diff --git a/external/lib/jam-0.1.0-src.jar b/external/lib/jam-0.1.0-src.jar deleted file mode 100644 index 158a023..0000000 Binary files a/external/lib/jam-0.1.0-src.jar and /dev/null differ diff --git a/external/lib/jam.LICENSE.txt b/external/lib/jam.LICENSE.txt deleted file mode 100644 index 57bc88a..0000000 --- a/external/lib/jam.LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/release-guide.txt b/release-guide.txt new file mode 100644 index 0000000..e2eee97 --- /dev/null +++ b/release-guide.txt @@ -0,0 +1,235 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + + ============================== + XMLBeans Release Guide + ============================== + + +(I) Prerequisites + + 1. You should read the Apache Release FAQ + 2a. You must have shell access to people.apache.org; and you should + have key-based authentication set up + 1. Generate ssh key with ssh-keygen -t rsa -b 4096 + (e.g. how to.) + 2. Add contents of id_rsa.pub to SSH Key (authorized_keys) line on https://id.apache.org/ + 3. ssh -v username@people.apache.org + Verify authenticity of host: https://www.apache.org/dev/machines + 4. Only sftp access is necessary + 2b. You must be a member of the committee group + 3. Release manager must have their public key appended to the KEYS file checked in to SVN and the key published on one of the public key servers. + More info can be found here: https://www.apache.org/dev/release-signing.html + 4. You must have Java JDK 8 installed and active. + 5. You must have the following utilities installed on your local machine and available in your path: + * ssh + * gnupg + * openssl + For Windows users, install Cygwin and make sure you have the above utilities + 6a. The POI build system requires two components to perform a build + * Ant 1.9.x or higher + * Forrest 0.90. + Make sure ANT_HOME and FORREST_HOME are set. + + 6b. Ensure you can log in to https://repository.apache.org/ with your Apache + credentials, and that you can see the "Staging Repositories" area on + the left hand side. + + 6c. It's a good idea to check at + https://builds.apache.org/view/P/view/POI/job/POI-XMLBeans-DSL-1.8/ + that Jenkins is in a good state (i.e. most recent build passed + and is up to date with SVN). You probably also want to e-mail + the dev list with a note to say you're building a release. + + 7. Before building, you should run the "rat-check" build task, which + uses Apache Rat + to check the source tree for files lacking license headers. Files + without headers should be either fixed, or added to the exclude list + + 8. Check file permissions are correct in SVN. + There can be files in the SVN tree marked executable (have the + svn:executable property set), but which should not be. Checking them + out will cause the executable bit to be set for them on filesystems + which support it. The flag can be removed in batch using + +{code:sh} +svn pd 'svn:executable' $(find -name .svn -prune -or -type f ! -name \*.sh \ + -print0 | xargs -0 svn pg 'svn:executable' | cut -d ' ' -f 1) +{code} + + 9. Before building, review any new or updated dependencies to ensure that + if they required LICENSE or NOTICE updates then these were done. + + 10. Ensure that CHANGES.txt is up to date + + 11. Ensure that the KEYS files in the dist areas are up-to-date with the + latest ones in POI svn: + https://dist.apache.org/repos/dist/dev/poi/KEYS + https://dist.apache.org/repos/dist/release/poi/KEYS + Dist is a regular svn repo that can be checked out and committed to. + To upload to dist: https://www.apache.org/dev/release-distribution + + +(II) Making release artifacts + + 1. Grab the output from a successful Jenkins build for the desired revision: + https://builds.apache.org/view/P/view/POI/job/POI-XMLBeans-DSL-1.8/lastBuild/artifact/build/ + - xmlbeans-VERSION.jar + - xmlbeans-VERSION-javadoc.jar + - xmlbeans-VERSION-sources.jar + - xmlbeans-bin-VERSION-DATE.zip + - xmlbeans-bin-VERSION-DATE.tgz + - xmlbeans-src-VERSION-DATE.zip + - xmlbeans-src-VERSION-DATE.tgz + + 2. Grab the current deployed POM, and edit the version # and anything else that has changed: + https://repository.apache.org/service/local/repo_groups/public/content/org/apache/xmlbeans/xmlbeans/VERSION/xmlbeans-VERSION.pom + + 3. Sign the jars, zip, tgz, and pom with your key (gpg doesn't sign via --multifile yet): + for f in *.jar *.zip *.tgz *.pom; do gpg --default-key 1556F3A4 -ab $f; done + + 4. Build the nexus bundle.jar to upload to + repository.apache.org: + jar -cvf bundle.jar *.pom *.pom.asc *.jar *.jar.asc + + 5. Upload the bundle to https://repository.apache.org/ + + 6. Generate checksums (sha256sum, sha512sum) for the *.zip and *.tgz files + + for f in *.zip *.tgz + do + for b in 256 512 + do + sha${b}sum $f > $f.sha$b + done + done + + 7. Commit the *.tgz and *.zip files, their signatures, and sha256 and sha512 + checksums to the release candidate repo at + https://dist.apache.org/repos/dist/dev/poi/xmlbeans/ + + + (III) Calling the vote: + + 1. The release manager should call the vote + 2. Include the URL of the release artifacts + 3. Include the time for the vote to run (3 day minimum, can be longer) + 4. Provide guidance on what needs to be checked + 5. Complete a tally, and send a result once the time has passed + + (IV) After the vote: + +Deploy the artifacts from the staging area (https://dist.apache.org/repos/dist/dev/poi/xmlbeans) +to the release area of the dist repo: + https://dist.apache.org/repos/dist/release/poi/xmlbeans/release/ + +Perform a sparse checkout of the dist repo to move artifacts in the staging area to the release area +In the following example, replace FIXME3.0.2 or FIXME3.1.0 with the version you are releasing + +{code:sh} +svn checkout https://dist.apache.org/repos/dist/ --depth immediates +svn update --set-depth immediates dist/dev/poi/ +svn update --set-depth infinity dist/dev/poi/xmlbeans/ +svn update --set-depth infinity dist/release/poi/xmlbeans/ +svn rm dist/release/poi/xmlbeans/release/src/* dist/release/poi/xmlbeans/release/bin/* +svn mv dist/dev/poi/xmlbeans/src/* dist/release/poi/xmlbeans/release/src/ +svn mv dist/dev/poi/xmlbeans/bin/* dist/release/poi/xmlbeans/release/bin/ +svn mv dist/release/poi/xmlbeans/release/dev/RELEASE-NOTES-FIXME3.0.2.txt dist/release/poi/xmlbeans/dev/ +# non-SVN copy to create a new artifact with its own history +cp dist/release/poi/xmlbeans/dev/RELEASE-NOTES-FIXME3.0.2.txt dist/release/poi/xmlbeans/release/dev/RELEASE-NOTES-FIXME3.1.0.txt +# edit the RELEASE-NOTES file to reflect the current version +svn add dist/release/poi/xmlbeans/release/dev/RELEASE-NOTES-FIXME3.1.0.txt +svn ci dist/ -m "deploy FIXME3.1.0 release artifacts from staging area" +{code} + + +You should get an email from the Apache Reporter Service (no-reply@reporter.apache.org) +at your Apache email address. +The email instructions will ask you to log on to https://reporter.apache.org/addrelease.html?poi +and add your release data (version and date) to the database. + +Log into https://repository.apache.org/ and go to the "Staging Repositories" area. +Find the "orgapachexmlbeans" entry, check it has the right content, then Close the repository +Select all artifacts and Release (and Automatically Drop) them. +Refresh to verify that the artifacts are no longer in the Staging Repositories area. + +2. Wait for the distributions to appear on your favourite mirror (anywhere from 3-24 hours) + https://www.apache.org/dyn/closer.lua/xmlbeans/dev/ + +3. Wait for the maven artifacts to appear on Maven Central, and ensure they work: + Maven Central: https://search.maven.org/#search|ga|1|g%3A%22org.apache.xmlbeans%22 + +4. Edit the website homepage and list the new release there. + https://xmlbeans.apache.org/index.html + https://xmlbeans.apache.org/changes.html + remove older releases. + +5. Edit the website, in particular the download page, listing the new release there. + This should reference the checksums, so take care when updating + + site/src/documentation/content/xdocs/index.xml + site/src/documentation/content/xdocs/news.xml + site/src/documentation/content/xdocs/site.xml + site/src/documentation/content/xdocs/status.xml + site/src/documentation/content/xdocs/download/index.xml + +6. Build site using a recent version of Java 1.8 + Generating with Forrest may result in line ending changes, making change diffs + hard to read. That may be fixed eventually, but for now dos2linux and linux2dos + are your friend to minimize these. + + Or, you can follow this process to only replace generated files where you know + the source changed: + + forrest run + * inspect the generated changed pages in a local browser + * save the generated HTML, replacing originals in the site/build/ directory + * compare new HTML with SVN source, and pass files through dos2unix or unix2dos as needed + ** some files generate with line endings different than stored in SVN, making diffs annoying + +6a.Commit the site changes to svn, and publish live + +7. Don't forget to upload the latest version of the site and javadocs + +8. Send announcements: +From: your @apache.org e-mail address +To: user@poi.apache.org, dev@poi.apache.org, general@poi.apache.org, and announce@apache.org +Subject: [ANNOUNCE] Apache XMLBeans FIXME3.1.0 released +Body: +""" +The Apache POI PMC is pleased to announce the release of Apache XMLBeans FIXME3.1.0. + +Apache XMLBeans is a technology for accessing XML by binding it to Java types. + +For detailed changes in this release, refer to the release notes [1] and the changelog [2]. + +Thank you to all our contributors for making this release possible. + +On behalf of the Apache POI PMC, +Your Name + +[1] Release notes: https://www.apache.org/dyn/closer.lua/poi/xmlbeans/release/dev/RELEASE-NOTES-FIXME3.1.0.txt +[2] Changelog: https://xmlbeans.apache.org/status.html#rel_FIXME310 +""" + +Note, announcements should be sent from your @apache.org e-mail address. + +9. Add the version to the DOAP file too + https://svn.apache.org/repos/asf/xmlbeans/trunk/xkit/doap_XMLBeans.rdf + +11. Delete directory that held RC, if any. diff --git a/samples/AbstractTypes/build.xml b/samples/AbstractTypes/build.xml index e7e8dd3..d90fb66 100644 --- a/samples/AbstractTypes/build.xml +++ b/samples/AbstractTypes/build.xml @@ -70,7 +70,7 @@ - + diff --git a/samples/Any/build.xml b/samples/Any/build.xml index 3b8a564..7555baf 100644 --- a/samples/Any/build.xml +++ b/samples/Any/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="Any.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/DateTime/build.xml b/samples/DateTime/build.xml index 0704a6d..d6fd9ef 100644 --- a/samples/DateTime/build.xml +++ b/samples/DateTime/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="DateTime.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/MixedContent/build.xml b/samples/MixedContent/build.xml index c450919..ab2f525 100644 --- a/samples/MixedContent/build.xml +++ b/samples/MixedContent/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="MixedContent.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/OrderMatters/build.xml b/samples/OrderMatters/build.xml index 44d94a2..4253690 100644 --- a/samples/OrderMatters/build.xml +++ b/samples/OrderMatters/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="OrderMatters.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/SampleTemplate/build.xml b/samples/SampleTemplate/build.xml index 7eb97e6..639a1c7 100644 --- a/samples/SampleTemplate/build.xml +++ b/samples/SampleTemplate/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="SampleTemplate.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/SchemaEnum/build.xml b/samples/SchemaEnum/build.xml index 6c78e93..77d16ce 100644 --- a/samples/SchemaEnum/build.xml +++ b/samples/SchemaEnum/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="SchemaEnum.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/SchemaEnum/src/org/apache/xmlbeans/samples/enumeration/SchemaEnum.java b/samples/SchemaEnum/src/org/apache/xmlbeans/samples/enumeration/SchemaEnum.java index f48104b..50d6f50 100644 --- a/samples/SchemaEnum/src/org/apache/xmlbeans/samples/enumeration/SchemaEnum.java +++ b/samples/SchemaEnum/src/org/apache/xmlbeans/samples/enumeration/SchemaEnum.java @@ -163,13 +163,13 @@ public String sortByThreshold(PriceSummaryDocument summaryDoc) PriceSummaryDocument.PriceSummary summary = summaryDoc.getPriceSummary(); PriceType[] priceElements = summary.getPriceArray(); - StringBuffer responseBuffer = new StringBuffer(); + StringBuilder responseBuffer = new StringBuilder(); // Create string buffers to hold the sorted results of the values // retrieved. - StringBuffer zeroBuffer = new StringBuffer("\nItems under 10 dollars: \n"); - StringBuffer tenBuffer = new StringBuffer("\nItems between 10 and 20 dollars: \n"); - StringBuffer twentyBuffer = new StringBuffer("\nItems more than 20 dollars: \n"); + StringBuilder zeroBuffer = new StringBuilder("\nItems under 10 dollars: \n"); + StringBuilder tenBuffer = new StringBuilder("\nItems between 10 and 20 dollars: \n"); + StringBuilder twentyBuffer = new StringBuilder("\nItems more than 20 dollars: \n"); // Loop through the price elements, extracting the array of child // elements in each. diff --git a/samples/SubstitutionGroup/build.xml b/samples/SubstitutionGroup/build.xml index 524b4c6..d56d0f9 100644 --- a/samples/SubstitutionGroup/build.xml +++ b/samples/SubstitutionGroup/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="SubstitutionGroup.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/Validation/build.xml b/samples/Validation/build.xml index 777ecce..19afee5 100644 --- a/samples/Validation/build.xml +++ b/samples/Validation/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="Validation.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/XQueryXPath/build.xml b/samples/XQueryXPath/build.xml index 96b11af..1f20a72 100644 --- a/samples/XQueryXPath/build.xml +++ b/samples/XQueryXPath/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="XQueryXPath.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/XmlSort/build.xml b/samples/XmlSort/build.xml index 4389038..5fd27b7 100644 --- a/samples/XmlSort/build.xml +++ b/samples/XmlSort/build.xml @@ -65,7 +65,7 @@ limitations under the License. destdir="build/classes" classpathref="XmlSort.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/XmlTree/build.xml b/samples/XmlTree/build.xml index 6d44c54..be193b6 100644 --- a/samples/XmlTree/build.xml +++ b/samples/XmlTree/build.xml @@ -89,7 +89,7 @@ limitations under the License. destdir="build/classes" classpathref="XmlTree.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/samples/XsdConfig/build.xml b/samples/XsdConfig/build.xml index af78db9..c43b427 100644 --- a/samples/XsdConfig/build.xml +++ b/samples/XsdConfig/build.xml @@ -120,13 +120,13 @@ limitations under the License. destdir="build/classes" classpathref="XsdConfig.path" debug="on" - source="1.6" + source="1.8" /> diff --git a/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java b/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java deleted file mode 100644 index 984e0d4..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java +++ /dev/null @@ -1,430 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import java.util.HashMap; -import java.util.Iterator; -import java.nio.charset.Charset; - -public class EncodingMap -{ - public static String getJava2IANAMapping ( String java ) - { - String iana = (String) _java_to_iana.get( java.toUpperCase() ); - if (iana != null) - return iana; - // Try to use the information in the JDK to see if it is an encoding it supports - if (Charset.isSupported( java )) - { - try - { - iana = Charset.forName( java ).name(); - return iana; - } - catch (IllegalArgumentException iae) - { - return null; - } - } - return null; - } - - public static String getIANA2JavaMapping ( String iana ) - { - String java = (String) _iana_to_java.get( iana.toUpperCase() ); - if (java != null) - return java; - else if (Charset.isSupported( iana )) - return iana; - else - return null; - } - - private EncodingMap ( ) { } - - private final static HashMap _iana_to_java = new HashMap(); - private final static HashMap _java_to_iana = new HashMap(); - - private final static void addMapping ( - String java, String iana, boolean isDefault ) - { - assert !_iana_to_java.containsKey( iana ); - assert java.toUpperCase().equals( java ); - assert iana.toUpperCase().equals( iana ); - - _iana_to_java.put( iana, java ); - - if (isDefault) - { - assert !_java_to_iana.containsKey( java ); - _java_to_iana.put( java, iana ); - } - } - - private final static boolean completeMappings ( ) - { - HashMap m = new HashMap(); - - for ( Iterator i = _iana_to_java.keySet().iterator() ; i.hasNext() ; ) - m.put( _iana_to_java.get( i.next() ), null ); - - for ( Iterator i = m.keySet().iterator() ; i.hasNext() ; ) - { - Object k = i.next(); - assert _java_to_iana.containsKey( k ): k; - } - - return true; - } - - static - { - addMapping( "ASCII", "ANSI_X3.4-1986", false ); - addMapping( "ASCII", "ASCII", true ); - addMapping( "ASCII", "CP367", false ); - addMapping( "ASCII", "CSASCII", false ); - addMapping( "ASCII", "IBM-367", false ); - addMapping( "ASCII", "IBM367", false ); - addMapping( "ASCII", "ISO-IR-6", false ); - addMapping( "ASCII", "ISO646-US", false ); - addMapping( "ASCII", "ISO_646.IRV:1991", false ); - addMapping( "ASCII", "US", false ); - addMapping( "ASCII", "US-ASCII", false ); - addMapping( "BIG5", "BIG5", true ); - addMapping( "BIG5", "CSBIG5", false ); - addMapping( "CP037", "CP037", false ); - addMapping( "CP037", "CSIBM037", false ); - addMapping( "CP037", "EBCDIC-CP-CA", false ); - addMapping( "CP037", "EBCDIC-CP-NL", false ); - addMapping( "CP037", "EBCDIC-CP-US", true ); - addMapping( "CP037", "EBCDIC-CP-WT", false ); - addMapping( "CP037", "IBM-37", false ); - addMapping( "CP037", "IBM037", false ); - addMapping( "CP1026", "CP1026", false ); - addMapping( "CP1026", "CSIBM1026", false ); - addMapping( "CP1026", "IBM-1026", false ); - addMapping( "CP1026", "IBM1026", true ); - addMapping( "CP1047", "CP1047", false ); - addMapping( "CP1047", "IBM-1047", false ); - addMapping( "CP1047", "IBM1047", true ); - addMapping( "CP1140", "CCSID01140", false ); - addMapping( "CP1140", "CP01140", false ); - addMapping( "CP1140", "IBM-1140", false ); - addMapping( "CP1140", "IBM01140", true ); - addMapping( "CP1141", "CCSID01141", false ); - addMapping( "CP1141", "CP01141", false ); - addMapping( "CP1141", "IBM-1141", false ); - addMapping( "CP1141", "IBM01141", true ); - addMapping( "CP1142", "CCSID01142", false ); - addMapping( "CP1142", "CP01142", false ); - addMapping( "CP1142", "IBM-1142", false ); - addMapping( "CP1142", "IBM01142", true ); - addMapping( "CP1143", "CCSID01143", false ); - addMapping( "CP1143", "CP01143", false ); - addMapping( "CP1143", "IBM-1143", false ); - addMapping( "CP1143", "IBM01143", true ); - addMapping( "CP1144", "CCSID01144", false ); - addMapping( "CP1144", "CP01144", false ); - addMapping( "CP1144", "IBM-1144", false ); - addMapping( "CP1144", "IBM01144", true ); - addMapping( "CP1145", "CCSID01145", false ); - addMapping( "CP1145", "CP01145", false ); - addMapping( "CP1145", "IBM-1145", false ); - addMapping( "CP1145", "IBM01145", true ); - addMapping( "CP1146", "CCSID01146", false ); - addMapping( "CP1146", "CP01146", false ); - addMapping( "CP1146", "IBM-1146", false ); - addMapping( "CP1146", "IBM01146", true ); - addMapping( "CP1147", "CCSID01147", false ); - addMapping( "CP1147", "CP01147", false ); - addMapping( "CP1147", "IBM-1147", false ); - addMapping( "CP1147", "IBM01147", true ); - addMapping( "CP1148", "CCSID01148", false ); - addMapping( "CP1148", "CP01148", false ); - addMapping( "CP1148", "IBM-1148", false ); - addMapping( "CP1148", "IBM01148", true ); - addMapping( "CP1149", "CCSID01149", false ); - addMapping( "CP1149", "CP01149", false ); - addMapping( "CP1149", "IBM-1149", false ); - addMapping( "CP1149", "IBM01149", true ); - addMapping( "CP1250", "WINDOWS-1250", true ); - addMapping( "CP1251", "WINDOWS-1251", true ); - addMapping( "CP1252", "WINDOWS-1252", true ); - addMapping( "CP1253", "WINDOWS-1253", true ); - addMapping( "CP1254", "WINDOWS-1254", true ); - addMapping( "CP1255", "WINDOWS-1255", true ); - addMapping( "CP1256", "WINDOWS-1256", true ); - addMapping( "CP1257", "WINDOWS-1257", true ); - addMapping( "CP1258", "WINDOWS-1258", true ); - addMapping( "CP273", "CP273", false ); - addMapping( "CP273", "CSIBM273", false ); - addMapping( "CP273", "IBM-273", false ); - addMapping( "CP273", "IBM273", true ); - addMapping( "CP277", "CP277", false ); - addMapping( "CP277", "CSIBM277", false ); - addMapping( "CP277", "EBCDIC-CP-DK", true ); - addMapping( "CP277", "EBCDIC-CP-NO", false ); - addMapping( "CP277", "IBM-277", false ); - addMapping( "CP277", "IBM277", false ); - addMapping( "CP278", "CP278", false ); - addMapping( "CP278", "CSIBM278", false ); - addMapping( "CP278", "EBCDIC-CP-FI", true ); - addMapping( "CP278", "EBCDIC-CP-SE", false ); - addMapping( "CP278", "IBM-278", false ); - addMapping( "CP278", "IBM278", false ); - addMapping( "CP280", "CP280", false ); - addMapping( "CP280", "CSIBM280", false ); - addMapping( "CP280", "EBCDIC-CP-IT", true ); - addMapping( "CP280", "IBM-280", false ); - addMapping( "CP280", "IBM280", false ); - addMapping( "CP284", "CP284", false ); - addMapping( "CP284", "CSIBM284", false ); - addMapping( "CP284", "EBCDIC-CP-ES", true ); - addMapping( "CP284", "IBM-284", false ); - addMapping( "CP284", "IBM284", false ); - addMapping( "CP285", "CP285", false ); - addMapping( "CP285", "CSIBM285", false ); - addMapping( "CP285", "EBCDIC-CP-GB", true ); - addMapping( "CP285", "IBM-285", false ); - addMapping( "CP285", "IBM285", false ); - addMapping( "CP290", "CP290", false ); - addMapping( "CP290", "CSIBM290", false ); - addMapping( "CP290", "EBCDIC-JP-KANA", true ); - addMapping( "CP290", "IBM-290", false ); - addMapping( "CP290", "IBM290", false ); - addMapping( "CP297", "CP297", false ); - addMapping( "CP297", "CSIBM297", false ); - addMapping( "CP297", "EBCDIC-CP-FR", true ); - addMapping( "CP297", "IBM-297", false ); - addMapping( "CP297", "IBM297", false ); - addMapping( "CP420", "CP420", false ); - addMapping( "CP420", "CSIBM420", false ); - addMapping( "CP420", "EBCDIC-CP-AR1", true ); - addMapping( "CP420", "IBM-420", false ); - addMapping( "CP420", "IBM420", false ); - addMapping( "CP424", "CP424", false ); - addMapping( "CP424", "CSIBM424", false ); - addMapping( "CP424", "EBCDIC-CP-HE", true ); - addMapping( "CP424", "IBM-424", false ); - addMapping( "CP424", "IBM424", false ); - addMapping( "CP437", "437", false ); - addMapping( "CP437", "CP437", false ); - addMapping( "CP437", "CSPC8CODEPAGE437", false ); - addMapping( "CP437", "IBM-437", false ); - addMapping( "CP437", "IBM437", true ); - addMapping( "CP500", "CP500", false ); - addMapping( "CP500", "CSIBM500", false ); - addMapping( "CP500", "EBCDIC-CP-BE", false ); - addMapping( "CP500", "EBCDIC-CP-CH", true ); - addMapping( "CP500", "IBM-500", false ); - addMapping( "CP500", "IBM500", false ); - addMapping( "CP775", "CP775", false ); - addMapping( "CP775", "CSPC775BALTIC", false ); - addMapping( "CP775", "IBM-775", false ); - addMapping( "CP775", "IBM775", true ); - addMapping( "CP850", "850", false ); - addMapping( "CP850", "CP850", false ); - addMapping( "CP850", "CSPC850MULTILINGUAL", false ); - addMapping( "CP850", "IBM-850", false ); - addMapping( "CP850", "IBM850", true ); - addMapping( "CP852", "852", false ); - addMapping( "CP852", "CP852", false ); - addMapping( "CP852", "CSPCP852", false ); - addMapping( "CP852", "IBM-852", false ); - addMapping( "CP852", "IBM852", true ); - addMapping( "CP855", "855", false ); - addMapping( "CP855", "CP855", false ); - addMapping( "CP855", "CSIBM855", false ); - addMapping( "CP855", "IBM-855", false ); - addMapping( "CP855", "IBM855", true ); - addMapping( "CP857", "857", false ); - addMapping( "CP857", "CP857", false ); - addMapping( "CP857", "CSIBM857", false ); - addMapping( "CP857", "IBM-857", false ); - addMapping( "CP857", "IBM857", true ); - addMapping( "CP858", "CCSID00858", false ); - addMapping( "CP858", "CP00858", false ); - addMapping( "CP858", "IBM-858", false ); - addMapping( "CP858", "IBM00858", true ); - addMapping( "CP860", "860", false ); - addMapping( "CP860", "CP860", false ); - addMapping( "CP860", "CSIBM860", false ); - addMapping( "CP860", "IBM-860", false ); - addMapping( "CP860", "IBM860", true ); - addMapping( "CP861", "861", false ); - addMapping( "CP861", "CP-IS", false ); - addMapping( "CP861", "CP861", false ); - addMapping( "CP861", "CSIBM861", false ); - addMapping( "CP861", "IBM-861", false ); - addMapping( "CP861", "IBM861", true ); - addMapping( "CP862", "862", false ); - addMapping( "CP862", "CP862", false ); - addMapping( "CP862", "CSPC862LATINHEBREW", false ); - addMapping( "CP862", "IBM-862", false ); - addMapping( "CP862", "IBM862", true ); - addMapping( "CP863", "863", false ); - addMapping( "CP863", "CP863", false ); - addMapping( "CP863", "CSIBM863", false ); - addMapping( "CP863", "IBM-863", false ); - addMapping( "CP863", "IBM863", true ); - addMapping( "CP864", "CP864", false ); - addMapping( "CP864", "CSIBM864", false ); - addMapping( "CP864", "IBM-864", false ); - addMapping( "CP864", "IBM864", true ); - addMapping( "CP865", "865", false ); - addMapping( "CP865", "CP865", false ); - addMapping( "CP865", "CSIBM865", false ); - addMapping( "CP865", "IBM-865", false ); - addMapping( "CP865", "IBM865", true ); - addMapping( "CP866", "866", false ); - addMapping( "CP866", "CP866", false ); - addMapping( "CP866", "CSIBM866", false ); - addMapping( "CP866", "IBM-866", false ); - addMapping( "CP866", "IBM866", true ); - addMapping( "CP868", "CP-AR", false ); - addMapping( "CP868", "CP868", false ); - addMapping( "CP868", "CSIBM868", false ); - addMapping( "CP868", "IBM-868", false ); - addMapping( "CP868", "IBM868", true ); - addMapping( "CP869", "CP-GR", false ); - addMapping( "CP869", "CP869", false ); - addMapping( "CP869", "CSIBM869", false ); - addMapping( "CP869", "IBM-869", false ); - addMapping( "CP869", "IBM869", true ); - addMapping( "CP870", "CP870", false ); - addMapping( "CP870", "CSIBM870", false ); - addMapping( "CP870", "EBCDIC-CP-ROECE", true ); - addMapping( "CP870", "EBCDIC-CP-YU", false ); - addMapping( "CP870", "IBM-870", false ); - addMapping( "CP870", "IBM870", false ); - addMapping( "CP871", "CP871", false ); - addMapping( "CP871", "CSIBM871", false ); - addMapping( "CP871", "EBCDIC-CP-IS", true ); - addMapping( "CP871", "IBM-871", false ); - addMapping( "CP871", "IBM871", false ); - addMapping( "CP918", "CP918", false ); - addMapping( "CP918", "CSIBM918", false ); - addMapping( "CP918", "EBCDIC-CP-AR2", true ); - addMapping( "CP918", "IBM-918", false ); - addMapping( "CP918", "IBM918", false ); - addMapping( "CP924", "CCSID00924", false ); - addMapping( "CP924", "CP00924", false ); - addMapping( "CP924", "EBCDIC-LATIN9--EURO", false ); - addMapping( "CP924", "IBM-924", false ); - addMapping( "CP924", "IBM00924", true ); - addMapping( "CP936", "GBK", true ); - addMapping( "CP936", "CP936", false ); - addMapping( "CP936", "MS936", false ); - addMapping( "CP936", "WINDOWS-936", false ); - addMapping( "EUCJIS", "CSEUCPKDFMTJAPANESE", false ); - addMapping( "EUCJIS", "EUC-JP", true ); - addMapping( "EUCJIS", "EXTENDED_UNIX_CODE_PACKED_FORMAT_FOR_JAPANESE", false ); - addMapping( "GB18030", "GB18030", true ); - addMapping( "GB2312", "CSGB2312", false ); - addMapping( "GB2312", "GB2312", true ); - addMapping( "ISO2022CN", "ISO-2022-CN", true ); - addMapping( "ISO2022KR", "CSISO2022KR", false ); - addMapping( "ISO2022KR", "ISO-2022-KR", true ); - addMapping( "ISO8859_1", "CP819", false ); - addMapping( "ISO8859_1", "CSISOLATIN1", false ); - addMapping( "ISO8859_1", "IBM-819", false ); - addMapping( "ISO8859_1", "IBM819", false ); - addMapping( "ISO8859_1", "ISO-8859-1", true ); - addMapping( "ISO8859_1", "ISO-IR-100", false ); - addMapping( "ISO8859_1", "ISO_8859-1", false ); - addMapping( "ISO8859_1", "L1", false ); - addMapping( "ISO8859_1", "LATIN1", false ); - addMapping( "ISO8859_2", "CSISOLATIN2", false ); - addMapping( "ISO8859_2", "ISO-8859-2", true ); - addMapping( "ISO8859_2", "ISO-IR-101", false ); - addMapping( "ISO8859_2", "ISO_8859-2", false ); - addMapping( "ISO8859_2", "L2", false ); - addMapping( "ISO8859_2", "LATIN2", false ); - addMapping( "ISO8859_3", "CSISOLATIN3", false ); - addMapping( "ISO8859_3", "ISO-8859-3", true ); - addMapping( "ISO8859_3", "ISO-IR-109", false ); - addMapping( "ISO8859_3", "ISO_8859-3", false ); - addMapping( "ISO8859_3", "L3", false ); - addMapping( "ISO8859_3", "LATIN3", false ); - addMapping( "ISO8859_4", "CSISOLATIN4", false ); - addMapping( "ISO8859_4", "ISO-8859-4", true ); - addMapping( "ISO8859_4", "ISO-IR-110", false ); - addMapping( "ISO8859_4", "ISO_8859-4", false ); - addMapping( "ISO8859_4", "L4", false ); - addMapping( "ISO8859_4", "LATIN4", false ); - addMapping( "ISO8859_5", "CSISOLATINCYRILLIC", false ); - addMapping( "ISO8859_5", "CYRILLIC", false ); - addMapping( "ISO8859_5", "ISO-8859-5", true ); - addMapping( "ISO8859_5", "ISO-IR-144", false ); - addMapping( "ISO8859_5", "ISO_8859-5", false ); - addMapping( "ISO8859_6", "ARABIC", false ); - addMapping( "ISO8859_6", "ASMO-708", false ); - addMapping( "ISO8859_6", "CSISOLATINARABIC", false ); - addMapping( "ISO8859_6", "ECMA-114", false ); - addMapping( "ISO8859_6", "ISO-8859-6", true ); - addMapping( "ISO8859_6", "ISO-IR-127", false ); - addMapping( "ISO8859_6", "ISO_8859-6", false ); - addMapping( "ISO8859_7", "CSISOLATINGREEK", false ); - addMapping( "ISO8859_7", "ECMA-118", false ); - addMapping( "ISO8859_7", "ELOT_928", false ); - addMapping( "ISO8859_7", "GREEK", false ); - addMapping( "ISO8859_7", "GREEK8", false ); - addMapping( "ISO8859_7", "ISO-8859-7", true ); - addMapping( "ISO8859_7", "ISO-IR-126", false ); - addMapping( "ISO8859_7", "ISO_8859-7", false ); - addMapping( "ISO8859_8", "CSISOLATINHEBREW", false ); - addMapping( "ISO8859_8", "HEBREW", false ); - addMapping( "ISO8859_8", "ISO-8859-8", true ); - addMapping( "ISO8859_8", "ISO-8859-8-I", false ); - addMapping( "ISO8859_8", "ISO-IR-138", false ); - addMapping( "ISO8859_8", "ISO_8859-8", false ); - addMapping( "ISO8859_9", "CSISOLATIN5", false ); - addMapping( "ISO8859_9", "ISO-8859-9", true ); - addMapping( "ISO8859_9", "ISO-IR-148", false ); - addMapping( "ISO8859_9", "ISO_8859-9", false ); - addMapping( "ISO8859_9", "L5", false ); - addMapping( "ISO8859_9", "LATIN5", false ); - addMapping( "JIS", "CSISO2022JP", false ); - addMapping( "JIS", "ISO-2022-JP", true ); - addMapping( "JIS0201", "CSISO13JISC6220JP", false ); - addMapping( "JIS0201", "X0201", true ); - addMapping( "JIS0208", "CSISO87JISX0208", false ); - addMapping( "JIS0208", "ISO-IR-87", false ); - addMapping( "JIS0208", "X0208", true ); - addMapping( "JIS0208", "X0208DBIJIS_X0208-1983", false ); - addMapping( "JIS0212", "CSISO159JISX02121990", false ); - addMapping( "JIS0212", "ISO-IR-159", true ); - addMapping( "JIS0212", "X0212", false ); - addMapping( "KOI8_R", "CSKOI8R", false ); - addMapping( "KOI8_R", "KOI8-R", true ); - addMapping( "KSC5601", "EUC-KR", true ); - addMapping( "MS932", "CSWINDOWS31J", false ); - addMapping( "MS932", "WINDOWS-31J", true ); - addMapping( "SJIS", "CSSHIFTJIS", false ); - addMapping( "SJIS", "MS_KANJI", false ); - addMapping( "SJIS", "SHIFT_JIS", true ); - addMapping( "TIS620", "TIS-620", true ); - addMapping( "UNICODE", "UTF-16", true ); - addMapping( "UTF-16BE", "UTF-16BE", true ); - addMapping( "UTF-16BE", "UTF_16BE", false ); - addMapping( "ISO-10646-UCS-2","ISO-10646-UCS-2", true ); - addMapping( "UTF-16LE", "UTF-16LE", true ); - addMapping( "UTF-16LE", "UTF_16LE", false ); - addMapping( "UTF8", "UTF-8", true ); - - assert completeMappings(); - }; -} diff --git a/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java b/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java deleted file mode 100644 index e70dfa0..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java +++ /dev/null @@ -1,243 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import org.apache.xmlbeans.xml.stream.ReferenceResolver; -import org.apache.xmlbeans.xml.stream.XMLEvent; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLName; -import org.apache.xmlbeans.xml.stream.XMLStreamException; - -/** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ -public class GenericXmlInputStream implements XMLInputStream -{ - public GenericXmlInputStream ( ) - { - _master = this; - _elementCount = 1; // Go all the way - } - - private GenericXmlInputStream ( GenericXmlInputStream master ) - { - (_master = master).ensureInit(); - _nextEvent = master._nextEvent; - } - - // - // The source for all events - // - - protected XMLEvent nextEvent ( ) throws XMLStreamException - { - throw new RuntimeException( "nextEvent not overridden" ); - } - - // - // - // - - private class EventItem - { - EventItem ( XMLEvent e ) - { - _event = e; - } - - int getType ( ) { return _event.getType(); } - boolean hasName ( ) { return _event.hasName(); } - XMLName getName ( ) { return _event.getName(); } - - final XMLEvent _event; - - EventItem _next; - } - - private void ensureInit ( ) - { - if (!_master._initialized) - { - try - { - _master._nextEvent = getNextEvent(); - } - catch ( XMLStreamException e ) - { - throw new RuntimeException( e ); - } - - _master._initialized = true; - } - } - - private EventItem getNextEvent ( ) throws XMLStreamException - { - XMLEvent e = nextEvent(); - - return e == null ? null : new EventItem( e ); - } - - public XMLEvent next ( ) throws XMLStreamException - { - ensureInit(); - - EventItem currentEvent = _nextEvent; - - if (_nextEvent != null) - { - if (_nextEvent._next == null) - _nextEvent._next = _master.getNextEvent(); - - _nextEvent = _nextEvent._next; - } - - if (currentEvent == null) - return null; - - if (currentEvent.getType() == XMLEvent.END_ELEMENT) - { - if (--_elementCount <= 0) - _nextEvent = null; - } - else if (currentEvent.getType() == XMLEvent.START_ELEMENT) - _elementCount++; - - return currentEvent._event; - } - - public boolean hasNext ( ) throws XMLStreamException - { - ensureInit(); - - return _nextEvent != null; - } - - public void skip ( ) throws XMLStreamException - { - next(); - } - - public void skipElement ( ) throws XMLStreamException - { - ensureInit(); - - for ( ; _nextEvent != null ; next() ) - { - if (_nextEvent.getType() == XMLEvent.START_ELEMENT) - break; - } - - int count = 0; - - for ( ; _nextEvent != null ; next() ) - { - int type = next().getType(); - - if (type == XMLEvent.START_ELEMENT) - count++; - else if (type == XMLEvent.END_ELEMENT && --count == 0) - break; - } - } - - public XMLEvent peek ( ) throws XMLStreamException - { - ensureInit(); - - return _nextEvent._event; - } - - public boolean skip ( int eventType ) throws XMLStreamException - { - ensureInit(); - - for ( ; _nextEvent != null ; next() ) - { - if (_nextEvent.getType() == eventType) - return true; - } - - return false; - } - - public boolean skip ( XMLName name ) throws XMLStreamException - { - ensureInit(); - - for ( ; _nextEvent != null ; next() ) - { - if (_nextEvent.hasName() && _nextEvent.getName().equals( name )) - return true; - } - - return false; - } - - public boolean skip ( XMLName name, int eventType ) throws XMLStreamException - { - ensureInit(); - - for ( ; _nextEvent != null ; next() ) - { - if (_nextEvent.getType() == eventType && - _nextEvent.hasName() && - _nextEvent.getName().equals( name )) - { - return true; - } - } - - return false; - } - - public XMLInputStream getSubStream ( ) throws XMLStreamException - { - ensureInit(); - - GenericXmlInputStream subStream = new GenericXmlInputStream( this ); - - subStream.skip( XMLEvent.START_ELEMENT ); - - return subStream; - } - - public void close ( ) throws XMLStreamException - { - // BUGBUG - can I do anything here, really? - // SHould I count the number of open sub streams? - // I have no destructor, how can I close properly? - } - - public ReferenceResolver getReferenceResolver ( ) - { - ensureInit(); - - throw new RuntimeException( "Not impl" ); - } - - public void setReferenceResolver ( ReferenceResolver resolver ) - { - ensureInit(); - - throw new RuntimeException( "Not impl" ); - } - - private boolean _initialized; - private EventItem _nextEvent; - private int _elementCount; - private GenericXmlInputStream _master; -} diff --git a/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java b/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java deleted file mode 100644 index f959be2..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java +++ /dev/null @@ -1,668 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import org.apache.xmlbeans.impl.common.ValidatorListener.Event; -import javax.xml.namespace.QName; -import javax.xml.stream.Location; - -import org.apache.xmlbeans.*; -import java.util.*; - -/** - * Identity constraint engine. Performs streaming validation of identity constraints. - * This includes key, keyref, & unique, as well as ID & IDRef. - */ -public class IdentityConstraint { - - private ConstraintState _constraintStack; - private ElementState _elementStack; - private Collection _errorListener; - private boolean _invalid; - private boolean _trackIdrefs; // We only track idrefs if validating from the root element - - public IdentityConstraint(Collection errorListener, boolean trackIdrefs) { - _errorListener = errorListener; - _trackIdrefs = trackIdrefs; - } - - public void element(Event e, SchemaType st, SchemaIdentityConstraint[] ics) { - - // Construct a new state for the element - newState(); - - // First dispatch this element event - for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next) - cs.element(e, st); - - // Create a new SelectorState for each new Identity Constraint - - for (int i = 0 ; ics != null && i < ics.length ; i++) - newConstraintState(ics[i], e, st); - } - - public void endElement(Event e) { - // Pop the element state stack and any constraints at this depth - if (_elementStack._hasConstraints) - { - for (ConstraintState cs = _constraintStack ; cs != null && cs != _elementStack._savePoint ; cs = cs._next) - cs.remove( e ); - - _constraintStack = _elementStack._savePoint; - } - - _elementStack = _elementStack._next; - - // Dispatch the event - for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next) - cs.endElement(e); - - } - - public void attr(Event e, QName name, SchemaType st, String value) { - for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next) - cs.attr(e, name, st, value); - } - - public void text(Event e, SchemaType st, String value, boolean emptyContent) { - for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next) - cs.text(e, st, value, emptyContent); - } - - public boolean isValid() { - return !_invalid; - } - - private void newConstraintState(SchemaIdentityConstraint ic, Event e, SchemaType st) - { - if (ic.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) - new KeyrefState(ic, e, st); - else - new SelectorState(ic, e, st); - } - - private void buildIdStates() - { - // Construct states to hold the values for IDs and IDRefs - IdState ids = new IdState(); - if (_trackIdrefs) - new IdRefState(ids); - } - - private void newState() { - boolean firstTime = _elementStack == null; - - ElementState st = new ElementState(); - st._next = _elementStack; - _elementStack = st; - - if (firstTime) - buildIdStates(); - } - - private void emitError ( Event event, String code, Object[] args ) - { - _invalid = true; - - if (_errorListener != null) - { - assert event != null; - - _errorListener.add(errorForEvent(code, args, XmlError.SEVERITY_ERROR, event)); - } - } - - public static XmlError errorForEvent(String code, Object[] args, int severity, Event event) - { - XmlCursor loc = event.getLocationAsCursor(); - XmlError error; - if (loc!=null) - error = XmlError.forCursor(code, args, severity, loc); - else - { - Location location = event.getLocation(); - if (location!=null) - { - error = XmlError.forLocation(code, args, severity, - location.getSystemId(), location.getLineNumber(), - location.getColumnNumber(), location.getCharacterOffset()); - } - else - { - error = XmlError.forMessage(code, args, severity); - } - } - return error; - } - - private void emitError ( Event event, String msg ) - { - _invalid = true; - - if (_errorListener != null) - { - assert event != null; - - _errorListener.add(errorForEvent(msg, XmlError.SEVERITY_ERROR, event)); - } - } - - public static XmlError errorForEvent(String msg, int severity, Event event) - { - XmlCursor loc = event.getLocationAsCursor(); - XmlError error; - if (loc!=null) - error = XmlError.forCursor(msg, severity, loc); - else - { - Location location = event.getLocation(); - if (location!=null) - { - error = XmlError.forLocation(msg, severity, - location.getSystemId(), location.getLineNumber(), - location.getColumnNumber(), location.getCharacterOffset()); - } - else - { - error = XmlError.forMessage(msg, severity); - } - } - return error; - } - - private void setSavePoint( ConstraintState cs ) - { - if (! _elementStack._hasConstraints) - _elementStack._savePoint = cs; - - _elementStack._hasConstraints = true; - } - - private static XmlObject newValue(SchemaType st, String value) - { - try { - return st.newValue(value); - } - catch (IllegalArgumentException e) { - // This is a bit hacky. newValue throws XmlValueOutOfRangeException which is - // unchecked and declared in typeimpl. I can only catch its parent class, - // typeimpl is built after common. - - // Ignore these exceptions. Assume that validation will catch them. - return null; - } - } - - /** - * Return the simple type for schema type. If the schema type is already - * simple, just return it. If it is a complex type with simple content, - * return the simple type it extends. - */ - static SchemaType getSimpleType(SchemaType st) - { - assert st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT : - st + " does not have simple content."; - - while (! st.isSimpleType() ) - st = st.getBaseType(); - - return st; - } - - static boolean hasSimpleContent(SchemaType st) - { - return st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT; - } - - public abstract class ConstraintState { - ConstraintState _next; - - ConstraintState() - { - setSavePoint(_constraintStack); - _next = _constraintStack; - _constraintStack = this; - } - - abstract void element(Event e, SchemaType st); - abstract void endElement(Event e); - abstract void attr(Event e, QName name, SchemaType st, String value); - abstract void text(Event e, SchemaType st, String value, boolean emptyContent); - abstract void remove(Event e); - - } - - public class SelectorState extends ConstraintState { - SchemaIdentityConstraint _constraint; - Set _values = new LinkedHashSet(); - XPath.ExecutionContext _context; - - SelectorState(SchemaIdentityConstraint constraint, Event e, SchemaType st) { - _constraint = constraint; - _context = new XPath.ExecutionContext(); - _context.init((XPath)_constraint.getSelectorPath()); - - if ( ( _context.start() & XPath.ExecutionContext.HIT ) != 0 ) - createFieldState(e, st); - } - - void addFields(XmlObjectList fields, Event e) - { - if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) - _values.add(fields); - else if (_values.contains(fields)) - { - if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_UNIQUE) - emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_UNIQUE, - new Object[] { fields, QNameHelper.pretty(_constraint.getName()) }); - else - emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_KEY, - new Object[] { fields, QNameHelper.pretty(_constraint.getName()) }); - } - else - _values.add(fields); - } - - void element(Event e, SchemaType st) - { - if ( ( _context.element(e.getName()) & XPath.ExecutionContext.HIT) != 0 ) - createFieldState(e, st); - } - - void endElement(Event e) - { - _context.end(); - } - - void createFieldState(Event e, SchemaType st) { - new FieldState(this, e, st); - } - - void remove(Event e) { - // Bubble up key, unique values to keyrefs - for (ConstraintState cs = _next ; cs != null ; cs = cs._next ) - { - if (cs instanceof KeyrefState) - { - KeyrefState kr = (KeyrefState)cs; - if (kr._constraint.getReferencedKey() == this._constraint) - kr.addKeyValues(_values, true); - } - } - } - - void attr(Event e, QName name, SchemaType st, String value) {} - void text(Event e, SchemaType st, String value, boolean emptyContent) {} - } - - public class KeyrefState extends SelectorState { - Map _keyValues = new HashMap(); - private Object CHILD_ADDED = new Object(); - private Object CHILD_REMOVED = new Object(); - private Object SELF_ADDED = new Object(); - - KeyrefState(SchemaIdentityConstraint constraint, Event e, SchemaType st) { - super(constraint, e, st); - } - - void addKeyValues(final Set values, boolean child) - { - /** If the key values are added by children, then if two or - more children add the same value, the value dissapears from the map - but if is added by the element in question directly then it will - be present in the map regardless of what children contained */ - for (Iterator it = values.iterator(); it.hasNext();) - { - Object key = it.next(); - Object value = _keyValues.get(key); - if (value == null) - _keyValues.put(key, child ? CHILD_ADDED : SELF_ADDED); - else if (value == CHILD_ADDED) - { - if (child) - _keyValues.put(key, CHILD_REMOVED); - else - _keyValues.put(key, SELF_ADDED); - } - else if (value == CHILD_REMOVED) - { - if (!child) - _keyValues.put(key, SELF_ADDED); - } - } - } - - private boolean hasKeyValue(Object key) - { - Object value = _keyValues.get(key); - return value != null && value != CHILD_REMOVED; - } - - void remove(Event e) { - // First check if there are any keys at the same stack level as this - // that may contribute key values to me - for (ConstraintState cs = _next ; cs != null && cs != _elementStack._savePoint ; cs = cs._next) - { - if (cs instanceof SelectorState) - { - SelectorState sel = (SelectorState)cs; - if (sel._constraint == _constraint.getReferencedKey()) - addKeyValues(sel._values, false); - } - } - - - // validate all values have been seen - for (Iterator it = _values.iterator() ; it.hasNext() ; ) - { - - XmlObjectList fields = (XmlObjectList)it.next(); - if (fields.unfilled() < 0 && ! hasKeyValue(fields)) - { - // KHK: cvc-identity-constraint.4.3 ? - emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$KEYREF_KEY_NOT_FOUND, - new Object[] {fields, QNameHelper.pretty(_constraint.getName())}); - return; - } - } - } - } - - public class FieldState extends ConstraintState { - SelectorState _selector; - XPath.ExecutionContext[] _contexts; - boolean[] _needsValue; - XmlObjectList _value; - - FieldState(SelectorState selector, Event e, SchemaType st) { - - // System.out.println("Creating new Field State for: " + e.getName()); - - _selector = selector; - SchemaIdentityConstraint ic = selector._constraint; - - int fieldCount = ic.getFields().length; - _contexts = new XPath.ExecutionContext[fieldCount]; - _needsValue = new boolean[fieldCount]; - _value = new XmlObjectList(fieldCount); - - for (int i = 0 ; i < fieldCount ; i++) - { - _contexts[i] = new XPath.ExecutionContext(); - _contexts[i].init((XPath)ic.getFieldPath(i)); - if ( ( _contexts[i].start() & XPath.ExecutionContext.HIT ) != 0 ) - { - // System.out.println("hit for element: " + e.getName()); - - if (!hasSimpleContent(st)) - // KHK: cvc-identity-constraint.3 - emitError(e, "Identity constraint field must have simple content"); - else - _needsValue[i] = true; - } - } - - } - - void element(Event e, SchemaType st) - { - for (int i = 0 ; i < _contexts.length ; i++) { - if (_needsValue[i]) - { - // KHK: cvc-identity-constraint.3 - emitError(e, "Identity constraint field must have simple content"); - _needsValue[i] = false; - } - } - - for (int i = 0 ; i < _contexts.length ; i++) { - if ( ( _contexts[i].element(e.getName()) & XPath.ExecutionContext.HIT) != 0 ) - { - if (! hasSimpleContent(st)) - // KHK: cvc-identity-constraint.3 - emitError(e, "Identity constraint field must have simple content"); - else - _needsValue[i] = true; - } - } - } - - void attr(Event e, QName name, SchemaType st, String value) { - - // Null value indicates previously reported validation problem - if (value == null) return; - - for (int i = 0 ; i < _contexts.length ; i++) { - if ( _contexts[i].attr(name) ) { - XmlObject o = newValue(st, value); - - // Ignore invalid values. Assume that validation catches these - if (o == null) return; - - boolean set = _value.set(o, i); - - // KHK: ? - if (! set) - emitError(e, "Multiple instances of field with xpath: '" - + _selector._constraint.getFields()[i] + "' for a selector"); - } - - } - } - - - void text(Event e, SchemaType st, String value, boolean emptyContent) { - - // Null value indicates previously reported validation problem - if (value == null && !emptyContent) return; - - for (int i = 0 ; i < _contexts.length ; i++) { - if ( _needsValue[i] ) { - - if (emptyContent || !hasSimpleContent(st)) - { - // KHK: cvc-identity-constraint.3 - emitError(e, "Identity constraint field must have simple content"); - return; - } - - SchemaType simpleType = getSimpleType(st); - XmlObject o = newValue(simpleType, value); - - // Ignore invalid values. Assume that validation catches these - if (o == null) return; - - boolean set = _value.set(o, i); - - // KHK: ? - if (! set) - emitError(e, "Multiple instances of field with xpath: '" - + _selector._constraint.getFields()[i] + "' for a selector"); - } - } - } - - void endElement(Event e) { - // reset any _needsValue flags - // assume that if we didn't see the text, it was because of another validation - // error, so don't emit another one. - for (int i = 0 ; i < _needsValue.length ; i++) - { - _contexts[i].end(); - _needsValue[i] = false; - } - - } - - void remove(Event e) - { - - if (_selector._constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEY && - _value.unfilled() >= 0 ) - { - // KHK: cvc-identity-constraint.4.2.1 ? - // keys must have all values supplied - emitError(e, "Key " + QNameHelper.pretty(_selector._constraint.getName()) + " is missing field with xpath: '" + _selector._constraint.getFields()[_value.unfilled()] + "'"); - } - else - { - // Finished. Add these fields to the selector state - _selector.addFields(_value, e); - } - } - - } - - public class IdState extends ConstraintState - { - Set _values = new LinkedHashSet(); - - IdState() { } - - void attr(Event e, QName name, SchemaType st, String value) - { - handleValue(e, st, value); - } - - void text(Event e, SchemaType st, String value, boolean emptyContent) - { - if (emptyContent) - return; - - handleValue(e, st, value); - } - - private void handleValue(Event e, SchemaType st, String value) - { - - // Null value indicates previously reported validation problem - if (value == null) return; - - if (st == null || st.isNoType()) - { - // ignore invalid values. Assume that validation catches these - return; - } - - if (XmlID.type.isAssignableFrom(st)) - { - XmlObjectList xmlValue = new XmlObjectList(1); - XmlObject o = newValue(XmlID.type, value); - - // Ignore invalid values. Assume that validation catches these - if (o == null) return; - - xmlValue.set(o, 0); - - if (_values.contains(xmlValue)) - emitError(e, XmlErrorCodes.ID_VALID$DUPLICATE, new Object[] { value }); - else - _values.add(xmlValue); - } - } - - void element(Event e, SchemaType st) {} - void endElement(Event e){} - void remove(Event e){} - - } - - public class IdRefState extends ConstraintState - { - IdState _ids; - List _values; - - IdRefState(IdState ids) - { - _ids = ids; - _values = new ArrayList(); - } - - private void handleValue(Event e, SchemaType st, String value) - { - // Null value indicates previously reported validation problem - if (value == null) return; - - if (st == null || st.isNoType()) - { - // ignore invalid values. Assume that validation catches these - return; - } - if (XmlIDREFS.type.isAssignableFrom(st)) - { - XmlIDREFS lv = (XmlIDREFS)newValue(XmlIDREFS.type, value); - - // Ignore invalid values. Assume that validation catches these - if (lv == null) return; - - List l = lv.xgetListValue(); - - // Add one value for each idref in the list - for (int i = 0 ; i < l.size() ; i++) - { - XmlObjectList xmlValue = new XmlObjectList(1); - XmlIDREF idref = (XmlIDREF)l.get(i); - xmlValue.set(idref, 0); - _values.add(xmlValue); - } - } - else if (XmlIDREF.type.isAssignableFrom(st)) - { - XmlObjectList xmlValue = new XmlObjectList(1); - XmlIDREF idref = (XmlIDREF)st.newValue(value); - - // Ignore invalid values. Assume that validation catches these - if (idref == null) return; - - xmlValue.set(idref, 0); - _values.add(xmlValue); - } - } - - void attr(Event e, QName name, SchemaType st, String value) - { - handleValue(e, st, value); - } - void text(Event e, SchemaType st, String value, boolean emptyContent) - { - if (emptyContent) - return; - - handleValue(e, st, value); - } - void remove(Event e) - { - // Validate each ref has a corresponding ID - for (Iterator it = _values.iterator() ; it.hasNext() ; ) - { - Object o = it.next(); - if (! _ids._values.contains(o)) - { - // KHK: cvc-id.1 - emitError(e, "ID not found for IDRef value '" + o + "'"); - } - } - } - void element(Event e, SchemaType st) { } - void endElement(Event e) { } - } - - private static class ElementState { - ElementState _next; - boolean _hasConstraints; - ConstraintState _savePoint; - } -} diff --git a/src/common/org/apache/xmlbeans/impl/common/NameUtil.java b/src/common/org/apache/xmlbeans/impl/common/NameUtil.java deleted file mode 100644 index 7278f86..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/NameUtil.java +++ /dev/null @@ -1,815 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import javax.xml.namespace.QName; - -import java.util.*; - -public class NameUtil -{ - // punctuation characters - public final static char HYPHEN = '\u002D'; - public final static char PERIOD = '\u002E'; - public final static char COLON = '\u003A'; - public final static char USCORE = '\u005F'; - public final static char DOT = '\u00B7'; - public final static char TELEIA = '\u0387'; - public final static char AYAH = '\u06DD'; - public final static char ELHIZB = '\u06DE'; - - private final static boolean DEBUG = false; - - private final static Set javaWords = new HashSet(Arrays.asList( - new String[] - { - "assert", - "abstract", - "boolean", - "break", - "byte", - "case", - "catch", - "char", - "class", - "const", - "continue", - "default", - "do", - "double", - "else", - "enum", // since JDK1.5 - "extends", - "false", // not a keyword - "final", - "finally", - "float", - "for", - "goto", - "if", - "implements", - "import", - "instanceof", - "int", - "interface", - "long", - "native", - "new", - "null", // not a keyword - "package", - "private", - "protected", - "public", - "return", - "short", - "static", - "strictfp", - "super", - "switch", - "synchronized", - "this", - "threadsafe", - "throw", - "throws", - "transient", - "true", // not a keyword - "try", - "void", - "volatile", - "while", - } - )); - - private final static Set extraWords = new HashSet(Arrays.asList( - new String[] - { - "i", // used for indexes - "target", // used for parameter - "org", // used for package names - "com", // used for package names - } - )); - - /* - private final static Set javaNames = new HashSet(Arrays.asList( - new String[] - { - "CharSequence", - "Cloneable", - "Comparable", - "Runnable", - - "Boolean", - "Byte", - "Character", - "Class", - "ClassLoader", - "Compiler", - "Double", - "Float", - "InheritableThreadLocal", - "Integer", - "Long", - "Math", - "Number", - "Object", - "Package", - "Process", - "Runtime", - "RuntimePermission", - "SecurityManager", - "Short", - "StackTraceElement", - "StrictMath", - "String", - "StringBuffer", - "System", - "Thread", - "ThreadGroup", - "ThreadLocal", - "Throwable", - "Void", - - "ArithmeticException", - "ArrayIndexOutOfBoundsException", - "ArrayStoreException", - "ClassCastException", - "ClassNotFoundException", - "CloneNotSupportedException", - "Exception", - "IllegalAccessException", - "IllegalArgumentException", - "IllegalMonitorStateException", - "IllegalStateException", - "IllegalThreadStateException", - "IndexOutOfBoundsException", - "InstantiationException", - "InterruptedException", - "NegativeArraySizeException", - "NoSuchFieldException", - "NoSuchMethodException", - "NullPointerException", - "NumberFormatException", - "RuntimeException", - "SecurityException", - "StringIndexOutOfBoundsException", - "UnsupportedOperationException", - - "AbstractMethodError", - "AssertionError", - "ClassCircularityError", - "ClassFormatError", - "Error", - "ExceptionInInitializerError", - "IllegalAccessError", - "IncompatibleClassChangeError", - "InstantiationError", - "InternalError", - "LinkageError", - "NoClassDefFoundError", - "NoSuchFieldError", - "NoSuchMethodError", - "OutOfMemoryError", - "StackOverflowError", - "ThreadDeath", - "UnknownError", - "UnsatisfiedLinkError", - "UnsupportedClassVersionError", - "VerifyError", - "VirtualMachineError", - } - )); - */ - - private final static Set javaNames = new HashSet(Arrays.asList( - new String[] - { - // 1. all the Java.lang classes [1.4.1 JDK]. - "CharSequence", - "Cloneable", - "Comparable", - "Runnable", - - "Boolean", - "Byte", - "Character", - "Class", - "ClassLoader", - "Compiler", - "Double", - "Float", - "InheritableThreadLocal", - "Integer", - "Long", - "Math", - "Number", - "Object", - "Package", - "Process", - "Runtime", - "RuntimePermission", - "SecurityManager", - "Short", - "StackTraceElement", - "StrictMath", - "String", - "StringBuffer", - "System", - "Thread", - "ThreadGroup", - "ThreadLocal", - "Throwable", - "Void", - - "ArithmeticException", - "ArrayIndexOutOfBoundsException", - "ArrayStoreException", - "ClassCastException", - "ClassNotFoundException", - "CloneNotSupportedException", - "Exception", - "IllegalAccessException", - "IllegalArgumentException", - "IllegalMonitorStateException", - "IllegalStateException", - "IllegalThreadStateException", - "IndexOutOfBoundsException", - "InstantiationException", - "InterruptedException", - "NegativeArraySizeException", - "NoSuchFieldException", - "NoSuchMethodException", - "NullPointerException", - "NumberFormatException", - "RuntimeException", - "SecurityException", - "StringIndexOutOfBoundsException", - "UnsupportedOperationException", - - "AbstractMethodError", - "AssertionError", - "ClassCircularityError", - "ClassFormatError", - "Error", - "ExceptionInInitializerError", - "IllegalAccessError", - "IncompatibleClassChangeError", - "InstantiationError", - "InternalError", - "LinkageError", - "NoClassDefFoundError", - "NoSuchFieldError", - "NoSuchMethodError", - "OutOfMemoryError", - "StackOverflowError", - "ThreadDeath", - "UnknownError", - "UnsatisfiedLinkError", - "UnsupportedClassVersionError", - "VerifyError", - "VirtualMachineError", - - // 2. other classes used as primitive types by xml beans - "BigInteger", - "BigDecimal", - "Enum", - "Date", - "GDate", - "GDuration", - "QName", - "List", - - // 3. the top few org.apache.xmlbeans names - "XmlObject", - "XmlCursor", - "XmlBeans", - "SchemaType", - } - )); - - public static boolean isValidJavaIdentifier(String id) - { - if (id == null) - throw new IllegalArgumentException("id cannot be null"); - - int len = id.length(); - if (len == 0) - return false; - - if (javaWords.contains(id)) - return false; - - if (!Character.isJavaIdentifierStart(id.charAt(0))) - return false; - - for (int i = 1; i < len; i++) - { - if (!Character.isJavaIdentifierPart(id.charAt(i))) - return false; - } - - return true; - } - - public static String getClassNameFromQName(QName qname) - { - return getClassNameFromQName(qname, false); - } - - public static String getClassNameFromQName(QName qname, boolean useJaxRpcRules) - { - String java_type = upperCamelCase(qname.getLocalPart(), useJaxRpcRules); - - String uri = qname.getNamespaceURI(); - String java_pkg = null; - - java_pkg = getPackageFromNamespace(uri, useJaxRpcRules); - - if (java_pkg != null) - return java_pkg + "." + java_type; - else - return java_type; - } - - private static final String JAVA_NS_PREFIX="java:"; - private static final String LANG_PREFIX = "java."; - - public static String getNamespaceFromPackage(final Class clazz) - { - Class curr_clazz = clazz; - - while (curr_clazz.isArray()) - curr_clazz = curr_clazz.getComponentType(); - - String fullname = clazz.getName(); - int lastdot = fullname.lastIndexOf('.'); - String pkg_name = lastdot < 0 ? "" : fullname.substring(0, lastdot); - - //special case for builtin types - /* - if (curr_clazz.isPrimitive()) - { - pkg_name = c.getJavaLanguageNamespaceUri(); - } - else if (pkg_name.startsWith(LANG_PREFIX)) - { - final String rem_str = pkg_name.substring(LANG_PREFIX.length()); - pkg_name = c.getJavaLanguageNamespaceUri() + "." + rem_str; - } - */ - return JAVA_NS_PREFIX + pkg_name; - } - - private static boolean isUriSchemeChar(char ch) - { - return (ch >= 'a' && ch <='z' || - ch >= 'A' && ch <='Z' || - ch >= '0' && ch <='9' || - ch == '-' || ch == '.' || ch == '+'); - } - - private static boolean isUriAlphaChar(char ch) - { - return (ch >= 'a' && ch <='z' || ch >= 'A' && ch <= 'Z'); - } - - private static int findSchemeColon(String uri) - { - int len = uri.length(); - if (len == 0) - return -1; - if (!isUriAlphaChar(uri.charAt(0))) - return -1; - int i; - for (i = 1; i < len; i++) - if (!isUriSchemeChar(uri.charAt(i))) - break; - if (i == len) - return -1; - if (uri.charAt(i) != ':') - return -1; - // consume consecutive colons - for (; i < len; i++) - if (uri.charAt(i) != ':') - break; - // for the "scheme:::" case, return len-1 - return i-1; - } - - private static String jls77String(String name) - { - StringBuffer buf = new StringBuffer(name); - for (int i = 0; i < name.length(); i++) - { - // We need to also make sure that our package names don't contain the - // "$" character in them, which, although a valid Java identifier part, - // would create confusion when trying to generate fully-qualified names - if (!Character.isJavaIdentifierPart(buf.charAt(i)) || '$' == buf.charAt(i)) - buf.setCharAt(i, '_'); - } - if (buf.length() == 0 || !Character.isJavaIdentifierStart(buf.charAt(0))) - buf.insert(0, '_'); - if (isJavaReservedWord(name)) - buf.append('_'); - return buf.toString(); - } - - private static List splitDNS(String dns) - { - // JAXB says: only split+reverse DNS if TLD matches known TLDs or ISO 3166 - // We are ignoring this now (TH) - - List result = new ArrayList(); - - int end = dns.length(); - int begin = dns.lastIndexOf('.'); - for ( ; begin != -1 ; begin--) - { - if (dns.charAt(begin) == '.') { - result.add(jls77String(dns.substring(begin + 1, end))); - end = begin; - } - } - result.add(jls77String(dns.substring(0, end))); - - // JAXB draft example implies removal of www - if (result.size() >= 3 && - ((String)result.get(result.size() - 1)).toLowerCase().equals("www")) - result.remove(result.size() - 1); - - return result; - } - - private static String processFilename(String filename) - { - // JAXB says: strip 2 or 3 letter extension or ".html" - - int i = filename.lastIndexOf('.'); - if (i > 0 && ( - i + 1 + 2 == filename.length() || - i + 1 + 3 == filename.length() || - filename.substring(i + 1).toLowerCase() == "html")) - { - return filename.substring(0, i); - } - - return filename; - } - - public static String getPackageFromNamespace(String uri) - { - return getPackageFromNamespace(uri, false); - } - - public static String getPackageFromNamespace(String uri, boolean useJaxRpcRules) - { - // special case: no namespace -> package "noNamespace" - if (uri == null || uri.length() == 0) - return "noNamespace"; - - // apply draft JAXB rules - int len = uri.length(); - int i = findSchemeColon(uri); - List result = null; - - if (i == len-1) - { - // XMLBEANS-57: colon is at end so just use scheme as the package name - result = new ArrayList(); - result.add(uri.substring(0, i)); - } - else if (i >= 0 && uri.substring(0, i).equals("java")) - { - result = Arrays.asList(uri.substring(i + 1).split("\\.")); - } - else { - result = new ArrayList(); - outer: for (i = i + 1; i < len; ) - { - while (uri.charAt(i) == '/') - if (++i >= len) break outer; - int start = i; - while (uri.charAt(i) != '/') - if (++i >= len) break; - int end = i; - result.add(uri.substring(start, end)); - } - if (result.size() > 1) - result.set(result.size() - 1, processFilename((String)result.get(result.size() - 1))); - - if (result.size() > 0) - { - List splitdns = splitDNS((String)result.get(0)); - result.remove(0); - result.addAll(0, splitdns); - } - } - - StringBuffer buf = new StringBuffer(); - for (Iterator it = result.iterator(); it.hasNext(); ) - { - String part = nonJavaKeyword(lowerCamelCase((String)it.next(), useJaxRpcRules, true)); - if (part.length() > 0) - { - buf.append(part); - buf.append('.'); - } - } - if (buf.length() == 0) - return "noNamespace"; - if (useJaxRpcRules) - return buf.substring(0, buf.length() - 1).toLowerCase(); - return buf.substring(0, buf.length() - 1); // chop off extra dot - } - - public static void main(String[] args) - { - for (int i = 0; i < args.length; i++) - System.out.println(upperCaseUnderbar(args[i])); - } - - /** - * Returns a upper-case-and-underbar string using the JAXB rules. - * Always starts with a capital letter that is a valid - * java identifier start. (If JAXB rules don't produce - * one, then "X_" is prepended.) - */ - public static String upperCaseUnderbar(String xml_name) - { - StringBuffer buf = new StringBuffer(); - List words = splitWords(xml_name, false); - - final int sz = words.size() - 1; - if (sz >= 0 && !Character.isJavaIdentifierStart(((String)words.get(0)).charAt(0))) - buf.append("X_"); - - for(int i = 0 ; i < sz ; i++) - { - buf.append((String)words.get(i)); - buf.append(USCORE); - } - - if (sz >= 0) - { - buf.append((String)words.get(sz)); - } - - //upcase entire buffer - final int len = buf.length(); - for(int j = 0 ; j < len ; j++) - { - char c = buf.charAt(j); - buf.setCharAt(j, Character.toUpperCase(c)); - } - - return buf.toString(); - } - - /** - * Returns a camel-cased string using the JAXB rules. - * Always starts with a capital letter that is a valid - * java identifier start. (If JAXB rules don't produce - * one, then "X" is prepended.) - */ - public static String upperCamelCase(String xml_name) - { - return upperCamelCase(xml_name, false); - } - - /** - * Returns a camel-cased string, but either JAXB or JAX-RPC rules - * are used - */ - public static String upperCamelCase(String xml_name, boolean useJaxRpcRules) - { - StringBuffer buf = new StringBuffer(); - List words = splitWords(xml_name, useJaxRpcRules); - - if (words.size() > 0) - { - if (!Character.isJavaIdentifierStart(((String)words.get(0)).charAt(0))) - buf.append("X"); - - Iterator itr = words.iterator(); - while(itr.hasNext()) - buf.append((String)itr.next()); - } - return buf.toString(); - } - - /** - * Returns a camel-cased string using the JAXB rules, - * where the first component is lowercased. Note that - * if the first component is an acronym, the whole - * thigns gets lowercased. - * Always starts with a lowercase letter that is a valid - * java identifier start. (If JAXB rules don't produce - * one, then "x" is prepended.) - */ - public static String lowerCamelCase(String xml_name) - { - return lowerCamelCase(xml_name, false, true); - } - - /** - * Returns a camel-cased string using the JAXB or JAX-RPC rules - */ - public static String lowerCamelCase(String xml_name, boolean useJaxRpcRules, - boolean fixGeneratedName) - { - StringBuffer buf = new StringBuffer(); - List words = splitWords(xml_name, useJaxRpcRules); - - if (words.size() > 0) - { - String first = ((String)words.get(0)).toLowerCase(); - char f = first.charAt(0); - if (!Character.isJavaIdentifierStart(f) && fixGeneratedName) - buf.append("x"); - buf.append(first); - - Iterator itr = words.iterator(); - itr.next(); // skip already-lowercased word - while(itr.hasNext()) - buf.append((String)itr.next()); - } - return buf.toString(); - } - - public static String upperCaseFirstLetter(String s) - { - if (s.length() == 0 || Character.isUpperCase(s.charAt(0))) - return s; - - StringBuffer buf = new StringBuffer(s); - buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); - return buf.toString(); - } - - - /** - split an xml name into words via JAXB approach, upcasing first - letter of each word as needed, if upcase is true - - ncname is xml ncname (i.e. no colons). - */ - private static void addCapped(List list, String str) - { - if (str.length() > 0) - list.add(upperCaseFirstLetter(str)); - } - - public static List splitWords(String name, boolean useJaxRpcRules) - { - List list = new ArrayList(); - int len = name.length(); - int start = 0; - int prefix = START; - for (int i = 0; i < len; i++) - { - int current = getCharClass(name.charAt(i), useJaxRpcRules); - if (prefix != PUNCT && current == PUNCT) - { - addCapped(list, name.substring(start, i)); - while ((current = getCharClass(name.charAt(i), useJaxRpcRules)) == PUNCT) - if (++i >= len) return list; - start = i; - } - else if ((prefix == DIGIT) != (current == DIGIT) || - (prefix == LOWER && current != LOWER) || - (isLetter(prefix) != isLetter(current))) - { - addCapped(list, name.substring(start, i)); - start = i; - } - else if (prefix == UPPER && current == LOWER && i > start + 1) - { - addCapped(list, name.substring(start, i - 1)); - start = i - 1; - } - prefix = current; - } - addCapped(list, name.substring(start)); - return list; - } - - //char classes - private final static int START = 0; - private final static int PUNCT = 1; - private final static int DIGIT = 2; - private final static int MARK = 3; - private final static int UPPER = 4; - private final static int LOWER= 5; - private final static int NOCASE= 6; - - public static int getCharClass(char c, boolean useJaxRpcRules) - { - //ordering is important here. - if (isPunctuation(c, useJaxRpcRules)) - return PUNCT; - else if (Character.isDigit(c)) - return DIGIT; - else if (Character.isUpperCase(c)) - return UPPER; - else if (Character.isLowerCase(c)) - return LOWER; - else if (Character.isLetter(c)) - return NOCASE; - else if (Character.isJavaIdentifierPart(c)) - return MARK; - else - return PUNCT; // not covered by JAXB: treat it as punctuation - } - - private static boolean isLetter(int state) - { - return (state==UPPER - || state==LOWER - || state==NOCASE); - } - - public static boolean isPunctuation(char c, boolean useJaxRpcRules) - { - return (c == HYPHEN - || c == PERIOD - || c == COLON - || c == DOT - || (c == USCORE && !useJaxRpcRules) - || c == TELEIA - || c == AYAH - || c == ELHIZB); - } - - /** - * Intended to be applied to a lowercase-starting identifier that - * may collide with a Java keyword. If it does collide, this - * prepends the letter "x". - */ - public static String nonJavaKeyword(String word) - { - if (isJavaReservedWord(word)) - return 'x' + word; - return word; - } - - /** - * Intended to be applied to a lowercase-starting identifier that - * may collide with a Java keyword. If it does collide, this - * prepends the letter "x". - */ - public static String nonExtraKeyword(String word) - { - if (isExtraReservedWord(word, true)) - return word + "Value"; - return word; - } - - /** - * Intended to be applied to an uppercase-starting identifier that - * may collide with a java.lang.* classname. If it does collide, this - * prepends the letter "X". - */ - public static String nonJavaCommonClassName(String name) - { - if (isJavaCommonClassName(name)) - return "X" + name; - return name; - } - - private static boolean isJavaReservedWord(String word) - { - return isJavaReservedWord(word, true); - } - - private static boolean isJavaReservedWord(String word, boolean ignore_case) - { - if (ignore_case) - word = word.toLowerCase(); - return javaWords.contains(word); - } - - private static boolean isExtraReservedWord(String word, boolean ignore_case) - { - if (ignore_case) - word = word.toLowerCase(); - return extraWords.contains(word); - } - - public static boolean isJavaCommonClassName(String word) - { - return javaNames.contains(word); - } -} diff --git a/src/common/org/apache/xmlbeans/impl/common/ResolverUtil.java b/src/common/org/apache/xmlbeans/impl/common/ResolverUtil.java deleted file mode 100644 index 626e48b..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/ResolverUtil.java +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import org.apache.xmlbeans.SystemProperties; - -import org.xml.sax.EntityResolver; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -/** - * Author: Cezar Andrei (cezar.andrei at bea.com) - * Date: Dec 3, 2003 - */ -public class ResolverUtil -{ - private static EntityResolver _entityResolver = null; - - static - { - try - { - String erClassName = SystemProperties.getProperty("xmlbean.entityResolver"); - if (erClassName != null) { - Object o = Class.forName(erClassName).newInstance(); - _entityResolver = (EntityResolver)o; - } - } - catch (Exception e) - { - _entityResolver = null; - } - } - - public static EntityResolver getGlobalEntityResolver() - { - return _entityResolver; - } - - public static EntityResolver resolverForCatalog(String catalogFile) - { - if (catalogFile==null) - return null; - - try - { - Class cmClass = Class.forName("org.apache.xml.resolver.CatalogManager"); - Constructor cstrCm = cmClass.getConstructor(new Class[] {}); - Object cmObj = cstrCm.newInstance(new Object[] {}); - Method cmMethod = cmClass.getMethod("setCatalogFiles", new Class[] {String.class}); - cmMethod.invoke(cmObj, new String[] {catalogFile}); - - Class crClass = Class.forName("org.apache.xml.resolver.tools.CatalogResolver"); - Constructor cstrCr = crClass.getConstructor(new Class[] {cmClass}); - Object crObj = cstrCr.newInstance(new Object[] {cmObj}); - - return (EntityResolver)crObj; - } - catch( Exception e ) - { - return null; - } - } -} diff --git a/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java b/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java deleted file mode 100644 index 611af92..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java +++ /dev/null @@ -1,296 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import java.io.InputStream; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.ByteArrayInputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.Charset; - -public class SniffedXmlInputStream extends BufferedInputStream -{ - // We don't sniff more than 192 bytes. - public static int MAX_SNIFFED_BYTES = 192; - - public SniffedXmlInputStream(InputStream stream) throws IOException - { - super(stream); - - // read byte order marks and detect EBCDIC etc - _encoding = sniffFourBytes(); - - if (_encoding != null && _encoding.equals("IBM037")) - { - // First four bytes suggest EBCDIC with - // assuming we can read it as UTF-8. - _encoding = sniffForXmlDecl("UTF-8"); - } - - if (_encoding == null) - { - // The XML spec says these two things: - - // (1) "In the absence of external character encoding information - // (such as MIME headers), parsed entities which are stored in an - // encoding other than UTF-8 or UTF-16 must begin with a text - // declaration (see 4.3.1 The Text Declaration) containing an - // encoding declaration:" - - // (2) "In the absence of information provided by an external - // transport protocol (e.g. HTTP or MIME), it is an error - // for an entity including an encoding declaration to be - // presented to the XML processor in an encoding other than - // that named in the declaration, or for an entity which begins - // with neither a Byte Order Mark nor an encoding declaration - // to use an encoding other than UTF-8." - - // Since we're using a sniffed stream, we do not have external - // character encoding information. - - // Since we're here, we also don't have a recognized byte order - // mark or an explicit encoding declaration that can be read in - // either ASCII or EBDIC style. - - // Therefore, we must use UTF-8. - - _encoding = "UTF-8"; - } - } - - private int readAsMuchAsPossible(byte[] buf, int startAt, int len) throws IOException - { - int total = 0; - while (total < len) - { - int count = read(buf, startAt + total, len - total); - if (count < 0) - break; - total += count; - } - return total; - } - - private String sniffFourBytes() throws IOException - { - mark(4); - int skip = 0; - try - { - byte[] buf = new byte[4]; - if (readAsMuchAsPossible(buf, 0, 4) < 4) - return null; - long result = 0xFF000000 & (buf[0] << 24) | 0x00FF0000 & (buf[1] << 16) | 0x0000FF00 & (buf[2] << 8) | 0x000000FF & buf[3]; - - if (result == 0x0000FEFF) - return "UCS-4"; - else if (result == 0xFFFE0000) - return "UCS-4"; - else if (result == 0x0000003C) - return "UCS-4BE"; - else if (result == 0x3C000000) - return "UCS-4LE"; - else if (result == 0x003C003F) - return "UTF-16BE"; - else if (result == 0x3C003F00) - return "UTF-16LE"; - else if (result == 0x3C3F786D) - return null; // looks like US-ASCII with = 0) - { - int i = xmlpi + 5; - ScannedAttribute attr = new ScannedAttribute(); - while (i < limit) - { - i = scanAttribute(buf, i, limit, attr); - if (i < 0) - return null; - if (attr.name.equals("encoding")) - return attr.value; - } - } - return null; - } - - private static int firstIndexOf(String s, char[] buf, int startAt, int limit) - { - assert(s.length() > 0); - char[] lookFor = s.toCharArray(); - - char firstchar = lookFor[0]; - searching: for (limit -= lookFor.length; startAt < limit; startAt++) - { - if (buf[startAt] == firstchar) - { - for (int i = 1; i < lookFor.length; i++) - { - if (buf[startAt + i] != lookFor[i]) - { - continue searching; - } - } - return startAt; - } - } - - return -1; - } - - private static int nextNonmatchingByte(char[] lookFor, char[] buf, int startAt, int limit) - { - searching: for (; startAt < limit; startAt++) - { - int thischar = buf[startAt]; - for (int i = 0; i < lookFor.length; i++) - if (thischar == lookFor[i]) - continue searching; - return startAt; - } - return -1; - } - - private static int nextMatchingByte(char[] lookFor, char[] buf, int startAt, int limit) - { - searching: for (; startAt < limit; startAt++) - { - int thischar = buf[startAt]; - for (int i = 0; i < lookFor.length; i++) - if (thischar == lookFor[i]) - return startAt; - } - return -1; - } - - private static int nextMatchingByte(char lookFor, char[] buf, int startAt, int limit) - { - searching: for (; startAt < limit; startAt++) - { - if (buf[startAt] == lookFor) - return startAt; - } - return -1; - } - private static char[] WHITESPACE = new char[] { ' ', '\r', '\t', '\n' }; - private static char[] NOTNAME = new char[] { '=', ' ', '\r', '\t', '\n', '?', '>', '<', '\'', '\"' }; - - private static class ScannedAttribute - { - public String name; - public String value; - } - - private static int scanAttribute(char[] buf, int startAt, int limit, ScannedAttribute attr) - { - int nameStart = nextNonmatchingByte(WHITESPACE, buf, startAt, limit); - if (nameStart < 0) - return -1; - int nameEnd = nextMatchingByte(NOTNAME, buf, nameStart, limit); - if (nameEnd < 0) - return -1; - int equals = nextNonmatchingByte(WHITESPACE, buf, nameEnd, limit); - if (equals < 0) - return -1; - if (buf[equals] != '=') - return -1; - int valQuote = nextNonmatchingByte(WHITESPACE, buf, equals + 1, limit); - if (buf[valQuote] != '\'' && buf[valQuote] != '\"') - return -1; - int valEndquote = nextMatchingByte(buf[valQuote], buf, valQuote + 1, limit); - if (valEndquote < 0) - return -1; - attr.name = new String(buf, nameStart, nameEnd - nameStart); - attr.value = new String(buf, valQuote + 1, valEndquote - valQuote - 1); - return valEndquote + 1; - } -} diff --git a/src/common/org/apache/xmlbeans/impl/common/SystemCache.java b/src/common/org/apache/xmlbeans/impl/common/SystemCache.java deleted file mode 100644 index 580a1f7..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/SystemCache.java +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.common; - -import java.lang.ref.SoftReference; -import java.util.ArrayList; - -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SystemProperties; - -/** - * This class encapsulates the caching strategy for XmlBeans. - * By subclassing this, a client of XmlBeans can implement caches that are - * more suitable for different applications using information that XmlBeans - * cannot know. - *

- * This class works as a singleton and as a default implementation for the cache. - * You can set a particular implementation using the "xmlbean.systemcacheimpl" - * system property or using the static {@link set} method. - * Subclasses of this need to be thread-safe. An implementation can be replaced - * at any time, so use of static variables is discouraged to ensure proper cleanup. - */ -public class SystemCache -{ - private static SystemCache INSTANCE = new SystemCache(); - - static - { - String cacheClass = SystemProperties.getProperty("xmlbean.systemcacheimpl"); - Object impl = null; - if (cacheClass != null) - { - try - { - impl = Class.forName(cacheClass).newInstance(); - if (!(impl instanceof SystemCache)) - throw new ClassCastException("Value for system property " + - "\"xmlbean.systemcacheimpl\" points to a class (" + cacheClass + - ") which does not derive from SystemCache"); - } - catch (ClassNotFoundException cnfe) - { - throw new RuntimeException("Cache class " + cacheClass + - " specified by \"xmlbean.systemcacheimpl\" was not found.", - cnfe); - } - catch (InstantiationException ie) - { - throw new RuntimeException("Could not instantiate class " + - cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." + - " An empty constructor may be missing.", ie); - } - catch (IllegalAccessException iae) - { - throw new RuntimeException("Could not instantiate class " + - cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." + - " A public empty constructor may be missing.", iae); - } - } - if (impl != null) - INSTANCE = (SystemCache) impl; - } - - public static synchronized final void set(SystemCache instance) - { - INSTANCE = instance; - } - - public static final SystemCache get() - { - return INSTANCE; - } - - public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) - { - return null; - } - - public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) - { - return; - } - - private ThreadLocal tl_saxLoaders = new ThreadLocal(); - - public Object getSaxLoader() - { - SoftReference s = (SoftReference) tl_saxLoaders.get(); - if (s == null) - return null; - else - return s.get(); - } - - public void setSaxLoader(Object saxLoader) - { - tl_saxLoaders.set(new SoftReference(saxLoader)); - } -} diff --git a/src/common/org/apache/xmlbeans/impl/common/XBeanDebug.java b/src/common/org/apache/xmlbeans/impl/common/XBeanDebug.java deleted file mode 100644 index 19f2c4a..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/XBeanDebug.java +++ /dev/null @@ -1,119 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import org.apache.xmlbeans.SystemProperties; - -import java.io.File; -import java.io.PrintStream; -import java.io.FileOutputStream; -import java.io.IOException; - -public class XBeanDebug -{ - public static final int TRACE_SCHEMA_LOADING = 0x0001; - public static final String traceProp = "org.apache.xmlbeans.impl.debug"; - public static final String defaultProp = ""; // "TRACE_SCHEMA_LOADING"; - - private static int _enabled = initializeBitsFromProperty(); - private static int _indent = 0; - private static String _indentspace = " "; - - private static int initializeBitsFromProperty() - { - int bits = 0; - String prop = SystemProperties.getProperty(traceProp, defaultProp); - if (prop.indexOf("TRACE_SCHEMA_LOADING") >= 0) - bits |= TRACE_SCHEMA_LOADING; - return bits; - } - public static void enable(int bits) - { - _enabled = _enabled | bits; - } - - public static void disable(int bits) - { - _enabled = _enabled & ~bits; - } - - public static void trace(int bits, String message, int indent) - { - if (test(bits)) - { - synchronized (XBeanDebug.class) - { - if (indent < 0) - _indent += indent; - - String spaces = _indent < 0 ? "" : _indent > _indentspace.length() ? _indentspace : _indentspace.substring(0, _indent); - String logmessage = Thread.currentThread().getName() + ": " + spaces + message + "\n"; - System.err.print(logmessage); - - if (indent > 0) - _indent += indent; - } - } - } - - public static boolean test(int bits) - { - return (_enabled & bits) != 0; - } - - static PrintStream _err; - - public static String log(String message) - { - log(message, null); - return message; - } - - public static String logStackTrace(String message) - { - log(message, new Throwable()); - return message; - } - - private synchronized static String log(String message, Throwable stackTrace) - { - if (_err == null) - { - try - { - File diagnosticFile = File.createTempFile("xmlbeandebug", ".log"); - _err = new PrintStream(new FileOutputStream(diagnosticFile)); - System.err.println("Diagnostic XML Bean debug log file created: " + diagnosticFile); - } - catch (IOException e) - { - _err = System.err; - } - } - _err.println(message); - if (stackTrace != null) - { - stackTrace.printStackTrace(_err); - } - return message; - } - - public static Throwable logException(Throwable t) - { - log(t.getMessage(), t); - return t; - } -} diff --git a/src/common/org/apache/xmlbeans/impl/common/XPath.java b/src/common/org/apache/xmlbeans/impl/common/XPath.java deleted file mode 100644 index e3edd92..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/XPath.java +++ /dev/null @@ -1,1119 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import javax.xml.namespace.QName; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.impl.common.XMLChar; - - -public class XPath -{ - public static class XPathCompileException extends XmlException - { - XPathCompileException ( XmlError err ) - { - super( err.toString(), null, err ); - } - } - - // - // - // - - public static class ExecutionContext - { - public ExecutionContext ( ) - { - _stack = new ArrayList(); - } - - public static final int HIT = 0x1; - public static final int DESCEND = 0x2; - public static final int ATTRS = 0x4; - - public final void init ( XPath xpath ) - { - if (_xpath != xpath) - { - _xpath = xpath; - - _paths = new PathContext [ xpath._selector._paths.length ]; - - for ( int i = 0 ; i < _paths.length ; i++ ) - _paths[ i ] = new PathContext(); - } - - _stack.clear(); - - for ( int i = 0 ; i < _paths.length ; i++ ) - _paths[ i ].init( xpath._selector._paths[ i ] ); - } - - public final int start ( ) - { - int result = 0; - - for ( int i = 0 ; i < _paths.length ; i++ ) - result |= _paths[ i ].start(); - - return result; - } - - public final int element ( QName name ) - { - assert name != null; - - _stack.add( name ); - - int result = 0; - - for ( int i = 0 ; i < _paths.length ; i++ ) - result |= _paths[ i ].element( name ); - - return result; - } - - public final boolean attr ( QName name ) - { - boolean hit = false; - - for ( int i = 0 ; i < _paths.length ; i++ ) - hit = hit | _paths[ i ].attr( name ); - - return hit; - } - - public final void end ( ) - { - _stack.remove( _stack.size() - 1 ); - - for ( int i = 0 ; i < _paths.length ; i++ ) - _paths[ i ].end(); - } - - private final class PathContext - { - PathContext ( ) - { - _prev = new ArrayList(); - } - - void init ( Step steps ) - { - _curr = steps; - _prev.clear(); - } - - private QName top ( int i ) - { - return (QName) ExecutionContext.this._stack.get( _stack.size() - 1 - i ); - } - - // goes back to the begining of the sequence since last // wildcard - private void backtrack ( ) - { - assert _curr != null; - - if (_curr._hasBacktrack) - { // _backtrack seems to be a pointer to the step that follows a // wildcard - // ex: for .//b/c/d steps c and d should backtrack to b in case there isn't a match - _curr = _curr._backtrack; - return; - } - - assert !_curr._deep; - - _curr = _curr._prev; - - search: for ( ; !_curr._deep ; _curr = _curr._prev ) - { - int t = 0; - - for ( Step s = _curr ; !s._deep ; s = s._prev ) - { - if (!s.match( top( t++ ))) - continue search; - } - - break; - } - } - - int start ( ) - { - assert _curr != null; - assert _curr._prev == null; - - if (_curr._name != null) - return _curr._flags; - - // If the steps consist on only a terminator, then the path can - // only be '.'. In this case, we get a hit, but there is - // nothing else to match. No need to backtrack. - - _curr = null; - - return HIT; - } - - int element ( QName name ) - { - //System.out.println(" Path.element: " + name); - _prev.add( _curr ); - - if (_curr == null) - return 0; - - assert _curr._name != null; - - if (!_curr._attr && _curr.match( name )) - { - if ((_curr = _curr._next)._name != null) - return _curr._flags; - - backtrack(); - - //System.out.println(" element - HIT " + _curr._flags); - return _curr == null ? HIT : HIT | _curr._flags; - } - - for ( ; ; ) - { - backtrack(); - - if (_curr == null) - return 0; - - if (_curr.match( name )) - { - _curr = _curr._next; - break; - } - - if (_curr._deep) - break; - } - - return _curr._flags; - } - - boolean attr ( QName name ) - { - return _curr != null && _curr._attr && _curr.match( name ); - } - - void end ( ) - { - //System.out.println(" Path.end "); - _curr = (Step) _prev.remove( _prev.size() - 1 ); - } - - private Step _curr; - private List _prev; - } - - private XPath _xpath; - private ArrayList _stack; - private PathContext[] _paths; - } - - // - // - // - - public static XPath compileXPath ( String xpath ) - throws XPathCompileException - { - return compileXPath( xpath, "$this", null ); - } - - public static XPath compileXPath ( String xpath, String currentNodeVar ) - throws XPathCompileException - { - return compileXPath( xpath, currentNodeVar, null ); - } - - public static XPath compileXPath ( String xpath, Map namespaces ) - throws XPathCompileException - { - return compileXPath( xpath, "$this", namespaces ); - } - - public static XPath compileXPath ( - String xpath, String currentNodeVar, Map namespaces ) - throws XPathCompileException - { - return - new CompilationContext( namespaces, currentNodeVar ). - compile( xpath ); - } - - private static class CompilationContext - { - CompilationContext ( Map namespaces, String currentNodeVar ) - { - assert - _currentNodeVar == null || - _currentNodeVar.startsWith( "$" ); - - if (currentNodeVar == null) - _currentNodeVar = "$this"; - else - _currentNodeVar = currentNodeVar; - - _namespaces = new HashMap(); - - _externalNamespaces = - namespaces == null ? new HashMap() : namespaces; - } - - XPath compile ( String expr ) throws XPathCompileException - { - _offset = 0; - _line = 1; - _column = 1; - _expr = expr; - - return tokenizeXPath(); - } - - int currChar ( ) - { - return currChar( 0 ); - } - - int currChar ( int offset ) - { - return - _offset + offset >= _expr.length() - ? -1 - : _expr.charAt( _offset + offset ); - } - - void advance ( ) - { - if (_offset < _expr.length()) - { - char ch = _expr.charAt( _offset ); - - _offset++; - _column++; - - if (ch == '\r' || ch == '\n') - { - _line++; - _column = 1; - - if (_offset + 1 < _expr.length()) - { - char nextCh = _expr.charAt( _offset + 1 ); - - if ((nextCh == '\r' || nextCh == '\n') && ch != nextCh) - _offset++; - } - } - } - } - - void advance ( int count ) - { - assert count >= 0; - - while ( count-- > 0 ) - advance(); - } - - boolean isWhitespace ( ) - { - return isWhitespace( 0 ); - } - - boolean isWhitespace ( int offset ) - { - int ch = currChar( offset ); - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'; - } - - boolean isNCNameStart ( ) - { - return - currChar() == -1 - ? false : - XMLChar.isNCNameStart( currChar() ); - } - - boolean isNCName ( ) - { - return - currChar() == -1 - ? false : - XMLChar.isNCName( currChar() ); - } - - boolean startsWith ( String s ) - { - return startsWith( s, 0 ); - } - - boolean startsWith ( String s, int offset ) - { - if (_offset + offset >= _expr.length()) - return false; - - return _expr.startsWith( s, _offset + offset ); - } - - private XPathCompileException newError ( String msg ) - { - XmlError err = - XmlError.forLocation( - msg, XmlError.SEVERITY_ERROR, null, - _line, _column, _offset ); - - return new XPathCompileException( err ); - } - - String lookupPrefix ( String prefix ) throws XPathCompileException - { - if (_namespaces.containsKey( prefix )) - return (String) _namespaces.get( prefix ); - - if (_externalNamespaces.containsKey( prefix )) - return (String) _externalNamespaces.get( prefix ); - - if (prefix.equals( "xml" )) - return "http://www.w3.org/XML/1998/namespace"; - - if (prefix.equals( "xs" )) - return "http://www.w3.org/2001/XMLSchema"; - - if (prefix.equals( "xsi" )) - return "http://www.w3.org/2001/XMLSchema-instance"; - - if (prefix.equals( "fn" )) - return "http://www.w3.org/2002/11/xquery-functions"; - - if (prefix.equals( "xdt" )) - return "http://www.w3.org/2003/11/xpath-datatypes"; - - if (prefix.equals( "local" )) - return "http://www.w3.org/2003/11/xquery-local-functions"; - - throw newError( "Undefined prefix: " + prefix ); - } - - private boolean parseWhitespace ( ) throws XPathCompileException - { - boolean sawSpace = false; - - while ( isWhitespace() ) - { - advance(); - sawSpace = true; - } - - return sawSpace; - } - - // - // Tokenizing will consume whitespace followed by the tokens, separated - // by whitespace. The whitespace following the last token is not - // consumed. - // - - private boolean tokenize ( String s ) - { - assert s.length() > 0; - - int offset = 0; - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s, offset )) - return false; - - offset += s.length(); - - advance( offset ); - - return true; - } - - private boolean tokenize ( String s1, String s2 ) - { - assert s1.length() > 0; - assert s2.length() > 0; - - int offset = 0; - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s1, offset )) - return false; - - offset += s1.length(); - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s2, offset )) - return false; - - offset += s2.length(); - - advance( offset ); - - return true; - } - - private boolean tokenize ( String s1, String s2, String s3) - { - assert s1.length() > 0; - assert s2.length() > 0; - assert s3.length() > 0; - - int offset = 0; - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s1, offset )) - return false; - - offset += s1.length(); - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s2, offset )) - return false; - - offset += s2.length(); - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s3, offset )) - return false; - - offset += s3.length(); - - while ( isWhitespace( offset ) ) - offset++; - - advance( offset ); - - return true; - } - private boolean tokenize ( String s1, String s2, String s3,String s4) { - assert s1.length() > 0; - assert s2.length() > 0; - assert s3.length() > 0; - assert s4.length() > 0; - - int offset = 0; - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s1, offset )) - return false; - - offset += s1.length(); - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s2, offset )) - return false; - - offset += s2.length(); - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s3, offset )) - return false; - - offset += s3.length(); - - while ( isWhitespace( offset ) ) - offset++; - - if (!startsWith( s4, offset )) - return false; - - offset += s4.length(); - - advance( offset ); - - return true; - } - - - private String tokenizeNCName ( ) throws XPathCompileException - { - parseWhitespace(); - - if (!isNCNameStart()) - throw newError( "Expected non-colonized name" ); - - StringBuffer sb = new StringBuffer(); - - sb.append( (char) currChar() ); - - for ( advance() ; isNCName() ; advance() ) - sb.append( (char) currChar() ); - - return sb.toString(); - } - - private QName getAnyQName ( ) - { - return new QName( "", "" ); - } - - private QName tokenizeQName ( ) throws XPathCompileException - { - if (tokenize( "*" )) - return getAnyQName(); - - String ncName = tokenizeNCName(); - - if (!tokenize( ":" )) - return new QName( lookupPrefix( "" ), ncName ); - - return - new QName( - lookupPrefix( ncName ), - tokenize( "*" ) ? "" : tokenizeNCName() ); - } - - private String tokenizeQuotedUri ( ) throws XPathCompileException - { - char quote; - - if (tokenize( "\"" )) - quote = '"'; - else if (tokenize( "'" )) - quote = '\''; - else - throw newError( "Expected quote (\" or ')" ); - - StringBuffer sb = new StringBuffer(); - - for ( ; ; ) - { - if (currChar() == -1) - throw newError( "Path terminated in URI literal" ); - - if (currChar() == quote) - { - advance(); - - if (currChar() != quote) - break; - } - - sb.append( (char) currChar() ); - - advance(); - } - - return sb.toString(); - } - - private Step addStep ( boolean deep, boolean attr, QName name, Step steps ) - { - Step step = new Step( deep, attr, name ); - - if (steps == null) - return step; - - Step s = steps; - - while ( steps._next != null ) - steps = steps._next; - - steps._next = step; - step._prev = steps; - - return s; - } - - private Step tokenizeSteps ( ) throws XPathCompileException - { - if (tokenize( "/" )) - throw newError( "Absolute paths unsupported" ); - - boolean deep; - - if (tokenize( "$", _currentNodeVar, "//" ) || tokenize( ".", "//" )) - deep = true; - else if (tokenize( "$", _currentNodeVar, "/" ) || tokenize( ".", "/" )) - deep = false; - else if (tokenize( "$", _currentNodeVar ) || tokenize( "." )) - return addStep( false, false, null, null ); - else - deep = false; - - Step steps = null; - - // Compile the steps removing /. and mergind //. with the next step - - boolean deepDot = false; - - for ( ; ; ) - { - if (tokenize( "attribute", "::" ) || tokenize( "@" )) - { - steps = addStep( deep, true, tokenizeQName(), steps ); - break; - } - - QName name; - - if (tokenize( "." )) - deepDot = deepDot || deep; - else - { - tokenize( "child", "::" ); - if ((name = tokenizeQName()) != null) - { - steps = addStep( deep, false, name, steps ); - deep = false; // only this step needs to be deep - // other folowing steps will be deep only if they are preceded by // wildcard - } - } - - if (tokenize( "//" )) - { - deep = true; - deepDot = false; - } - else if (tokenize( "/" )) - { - if (deepDot) - deep = true; - } - else - break; - } - - // If there was a //. at the end of th path, then we need to make - // two paths, one with * at the end and another with @* at the end. - - if ((_lastDeepDot = deepDot)) - { - _lastDeepDot = true; - steps = addStep( true, false, getAnyQName(), steps ); - } - - // Add sentinal step (_name == null) - - return addStep( false, false, null, steps ); - } - - private void computeBacktrack ( Step steps ) - throws XPathCompileException - { - // - // Compute static backtrack information - // - // Note that I use the fact that _hasBacktrack is initialized to - // false and _backtrack to null in the following code. - // - - Step s, t; - - for ( s = steps ; s != null ; s = t ) - { - // Compute the segment from [ s, t ) - - for ( t = s._next ; t != null && !t._deep ; ) - t = t._next; - - // If the segment is NOT rooted at //, then the backtrack is - // null for the entire segment, including possible attr and/or - // sentinal - - if (!s._deep) - { - for ( Step u = s ; u != t ; u = u._next ) - u._hasBacktrack = true; - - continue; - } - - // Compute the sequence [ s, u ) of length n which contain no - // wild steps. - - int n = 0; - Step u = s; - - while ( u != t && u._name != null && !u.isWild() && !u._attr ) - { - n++; - u = u._next; - } - - // Now, apply KMP to [ s, u ) for fast backtracking - - QName [] pattern = new QName [ n + 1 ]; - int [] kmp = new int [ n + 1 ]; - - Step v = s; - - for ( int i = 0 ; i < n ; i++ ) - { - pattern[ i ] = v._name; - v = v._next; - } - - pattern[ n ] = getAnyQName(); - - int i = 0; - int j = kmp[ 0 ] = -1; - - while ( i < n ) - { - while ( j > -1 && !pattern[ i ].equals( pattern[ j ] ) ) - j = kmp[ j ]; - - if (pattern[ ++i ].equals( pattern[ ++j ] )) - kmp[ i ] = kmp[ j ]; - else - kmp[ i ] = j; - } - - i = 0; - - for ( v = s ; v != u ; v = v._next ) - { - v._hasBacktrack = true; - v._backtrack = s; - - for ( j = kmp[ i ] ; j > 0 ; j-- ) - v._backtrack = v._backtrack._next; - - i++; - } - - // Compute the success backtrack and stuff it into an attr and - // sentinal if they exist for this segment - - v = s; - - if (n > 1) - { - for ( j = kmp[ n - 1 ] ; j > 0 ; j-- ) - v = v._next; - } - - if (u != t && u._attr) - { - u._hasBacktrack = true; - u._backtrack = v; - u = u._next; - } - - if (u != t && u._name == null) - { - u._hasBacktrack = true; - u._backtrack = v; - } - - // The first part of a deep segment always backtracks to itself - - assert s._deep; - - s._hasBacktrack = true; - s._backtrack = s; - } - } - - private void tokenizePath ( ArrayList paths ) - throws XPathCompileException - { - _lastDeepDot = false; - - Step steps = tokenizeSteps(); - - computeBacktrack( steps ); - - paths.add( steps ); - - // If the last path ended in //., that path will match all - // elements, here I make a path which matches all attributes. - - if (_lastDeepDot) - { - _sawDeepDot = true; - - Step s = null; - - for ( Step t = steps ; t != null ; t = t._next ) - { - if (t._next != null && t._next._next == null) - s = addStep( t._deep, true, t._name, s ); - else - s = addStep( t._deep, t._attr, t._name, s ); - } - - computeBacktrack( s ); - - paths.add( s ); - } - } - - private Selector tokenizeSelector ( ) throws XPathCompileException - { - ArrayList paths = new ArrayList(); - - tokenizePath( paths ); - - while ( tokenize( "|" ) ) - tokenizePath( paths ); - - return new Selector( (Step[]) paths.toArray( new Step [ 0 ] ) ); - } - - private XPath tokenizeXPath ( ) throws XPathCompileException - { - for ( ; ; ) - { - if (tokenize( "declare", "namespace" )) - { - if (!parseWhitespace()) - throw newError( "Expected prefix after 'declare namespace'" ); - - String prefix = tokenizeNCName(); - - if (!tokenize( "=" )) - throw newError( "Expected '='" ); - - String uri = tokenizeQuotedUri(); - - if (_namespaces.containsKey( prefix )) - { - throw newError( - "Redefinition of namespace prefix: " + prefix ); - } - - _namespaces.put( prefix, uri ); - - //return these to saxon:? Is it an error to pass external NS - //that conflicts? or should we just override it? - if (_externalNamespaces.containsKey( prefix )) - { - throw newError( - "Redefinition of namespace prefix: " + prefix ); - } - _externalNamespaces.put( prefix, uri ); - - if (! tokenize( ";" )) - { -// throw newError( -// "Namespace declaration must end with ;" ); - } - - _externalNamespaces.put(_NS_BOUNDARY,new Integer(_offset)); - - continue; - } - - if (tokenize( "declare","default", "element", "namespace" )) - { - String uri = tokenizeQuotedUri(); - - if (_namespaces.containsKey( "" )) - { - throw newError( - "Redefinition of default element namespace" ); - } - - _namespaces.put( "", uri ); - - //return these to saxon:? Is it an error to pass external NS - //that conflicts? or should we just override it? - if (_externalNamespaces.containsKey( XPath._DEFAULT_ELT_NS )) - { - throw newError("Redefinition of default element namespace : "); - } - _externalNamespaces.put( XPath._DEFAULT_ELT_NS, uri ); - - if (! tokenize( ";" )) - throw newError("Default Namespace declaration must end with ;" ); - //the boundary is the last ; in the prolog... - _externalNamespaces.put(_NS_BOUNDARY,new Integer(_offset)); - - continue; - } - - break; - } - - // Add the default prefix mapping if it has not been redefined - - if (!_namespaces.containsKey( "" )) - _namespaces.put( "", "" ); - - Selector selector = tokenizeSelector(); - - parseWhitespace(); - - if (currChar() != -1) - { - throw newError( - "Unexpected char '" + (char) currChar() + "'" ); - } - - return new XPath( selector, _sawDeepDot ); - } - - //split of prolog decls that are not standard XPath syntax - //but work in v1 - private void processNonXpathDecls(){ - - } - - private String _expr; - - private boolean _sawDeepDot; // Saw one overall - private boolean _lastDeepDot; - - private String _currentNodeVar; - - // private Map _namespaces; - protected Map _namespaces; - private Map _externalNamespaces; - - private int _offset; - private int _line; - private int _column; - } - - private static final class Step - { - Step ( boolean deep, boolean attr, QName name ) - { - _name = name; - - _deep = deep; - _attr = attr; - - int flags = 0; - - if (_deep || !_attr) - flags |= ExecutionContext.DESCEND; - - if (_attr) - flags |= ExecutionContext.ATTRS; - - _flags = flags; - } - - boolean isWild ( ) - { - return _name.getLocalPart().length() == 0; - } - - boolean match ( QName name ) - { - String local = _name.getLocalPart(); - String nameLocal = name.getLocalPart(); - String uri; - String nameUri; - - int localLength = local.length(); - int uriLength; - - // match any name to _name when _name is empty ""@"" - if (localLength==0) - { - uri = _name.getNamespaceURI(); - uriLength = uri.length(); - - if (uriLength==0) - return true; - - return uri.equals(name.getNamespaceURI()); - } - - if (localLength!=nameLocal.length()) - return false; - - uri = _name.getNamespaceURI(); - nameUri = name.getNamespaceURI(); - - if (uri.length()!=nameUri.length()) - return false; - - return local.equals(nameLocal) && uri.equals(nameUri); - } - - final boolean _attr; - final boolean _deep; - - int _flags; - - final QName _name; - - Step _next, _prev; - - boolean _hasBacktrack; - Step _backtrack; - } - - private static final class Selector - { - Selector ( Step[] paths ) - { - _paths = paths; - } - - final Step[] _paths; - } - - // - // - // - - private XPath ( Selector selector, boolean sawDeepDot ) - { - _selector = selector; - _sawDeepDot = sawDeepDot; - } - - public boolean sawDeepDot ( ) - { - return _sawDeepDot; - } - - public static final String _NS_BOUNDARY = "$xmlbeans!ns_boundary"; - public static final String _DEFAULT_ELT_NS = "$xmlbeans!default_uri"; - private final Selector _selector; - private final boolean _sawDeepDot; -} \ No newline at end of file diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java b/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java deleted file mode 100644 index eae88ac..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import org.apache.xmlbeans.XmlError; - -import java.util.AbstractCollection; -import java.util.Iterator; -import java.util.Collections; -import java.net.URI; - -public class XmlErrorPrinter extends AbstractCollection -{ - private boolean _noisy; - private URI _baseURI; - - public XmlErrorPrinter(boolean noisy, URI baseURI) - { - _noisy = noisy; - _baseURI = baseURI; - } - - public boolean add(Object o) - { - if (o instanceof XmlError) - { - XmlError err = (XmlError)o; - if (err.getSeverity() == XmlError.SEVERITY_ERROR || - err.getSeverity() == XmlError.SEVERITY_WARNING) - System.err.println(err.toString(_baseURI)); - else if (_noisy) - System.out.println(err.toString(_baseURI)); - } - return false; - } - - public Iterator iterator() - { - return Collections.EMPTY_LIST.iterator(); - } - - public int size() - { - return 0; - } -} - diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java b/src/common/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java deleted file mode 100644 index d802590..0000000 --- a/src/common/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java +++ /dev/null @@ -1,69 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.common; - -import org.apache.xmlbeans.XmlError; - -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Iterator; -import java.util.Collections; - -public class XmlErrorWatcher extends AbstractCollection -{ - private Collection _underlying; - private XmlError _firstError; - - public XmlErrorWatcher(Collection underlying) - { - _underlying = underlying; - } - - public boolean add(Object o) - { - if (_firstError == null && o instanceof XmlError && ((XmlError)o).getSeverity() == XmlError.SEVERITY_ERROR) - _firstError = (XmlError)o; - if (_underlying == null) - return false; - return _underlying.add(o); - } - - public Iterator iterator() - { - if (_underlying == null) - return Collections.EMPTY_LIST.iterator(); - - return _underlying.iterator(); - } - - public int size() - { - if (_underlying == null) - return 0; - - return _underlying.size(); - } - - public boolean hasError() - { - return _firstError != null; - } - - public XmlError firstError() - { - return _firstError; - } -} diff --git a/src/jamsupport/org/apache/xmlbeans/impl/jam/internal/javadoc/JavadocTigerDelegateImpl_150.java b/src/jamsupport/org/apache/xmlbeans/impl/jam/internal/javadoc/JavadocTigerDelegateImpl_150.java deleted file mode 100644 index a5583f4..0000000 --- a/src/jamsupport/org/apache/xmlbeans/impl/jam/internal/javadoc/JavadocTigerDelegateImpl_150.java +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.jam.internal.javadoc; - -import com.sun.javadoc.ClassDoc; -import com.sun.javadoc.ExecutableMemberDoc; -import com.sun.javadoc.Parameter; -import com.sun.javadoc.ProgramElementDoc; -import org.apache.xmlbeans.impl.jam.internal.elements.ElementContext; -import org.apache.xmlbeans.impl.jam.provider.JamLogger; -import org.apache.xmlbeans.impl.jam.mutable.MAnnotatedElement; -import org.apache.xmlbeans.impl.jam.mutable.MClass; - - -/** - * This class is required by JAM so it runs under JDK1.5 - * Since XmlBeans doesn't require 1.5 in order to run - * this stub replaces the real impl. - */ -public final class JavadocTigerDelegateImpl_150 extends JavadocTigerDelegate -{ - public void init(ElementContext ctx) - {} - - public void init(JamLogger logger) - {} - - public void populateAnnotationTypeIfNecessary(ClassDoc cd, - MClass clazz, - JavadocClassBuilder builder) - { - } - - - // ======================================================================== - // OLD STUFF remove someday - - - public void extractAnnotations(MAnnotatedElement dest, ProgramElementDoc src) - { - } - - public void extractAnnotations(MAnnotatedElement dest, - ExecutableMemberDoc method, - Parameter src) - { - } - - public boolean isEnum(ClassDoc cd) - { - return false; // under 1.4, nothing is enum - } -} diff --git a/src/jamsupport/org/apache/xmlbeans/impl/jam/internal/reflect/ReflectTigerDelegateImpl_150.java b/src/jamsupport/org/apache/xmlbeans/impl/jam/internal/reflect/ReflectTigerDelegateImpl_150.java deleted file mode 100644 index 0fe8a42..0000000 --- a/src/jamsupport/org/apache/xmlbeans/impl/jam/internal/reflect/ReflectTigerDelegateImpl_150.java +++ /dev/null @@ -1,87 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.jam.internal.reflect; - -import org.apache.xmlbeans.impl.jam.JClass; -import org.apache.xmlbeans.impl.jam.mutable.MAnnotatedElement; -import org.apache.xmlbeans.impl.jam.mutable.MAnnotation; -import org.apache.xmlbeans.impl.jam.mutable.MClass; -import org.apache.xmlbeans.impl.jam.mutable.MConstructor; -import org.apache.xmlbeans.impl.jam.mutable.MField; -import org.apache.xmlbeans.impl.jam.mutable.MMember; -import org.apache.xmlbeans.impl.jam.mutable.MParameter; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - - -/** - * This class is required by JAM so it runs under JDK1.5 - * Since XmlBeans doesn't require 1.5 in order to run - * this stub replaces the real impl. - */ -public final class ReflectTigerDelegateImpl_150 extends ReflectTigerDelegate -{ - // ======================================================================== - // Reflect15Delegate implementation - - public void populateAnnotationTypeIfNecessary(Class cd, - MClass clazz, - ReflectClassBuilder builder) - { - } - - public void extractAnnotations(MMember dest, Method src) - { - } - - public void extractAnnotations(MConstructor dest, Constructor src) - { - } - - public void extractAnnotations(MField dest, Field src) - { - } - - public void extractAnnotations(MClass dest, Class src) - { - } - - public void extractAnnotations(MParameter dest, Method src, - int paramNum) - { - } - - public void extractAnnotations(MParameter dest, Constructor src, - int paramNum) - { - } - - public boolean isEnum(Class clazz) - { return false; } - - public Constructor getEnclosingConstructor(Class clazz) - { - return null; // JDK1.4 doesn't support this - } - - public Method getEnclosingMethod(Class clazz) - { - return null; // JDK1.4 doesn't support this - } -} diff --git a/src/main/java/org/apache/xmlbeans/BindingConfig.java b/src/main/java/org/apache/xmlbeans/BindingConfig.java new file mode 100755 index 0000000..93bd145 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/BindingConfig.java @@ -0,0 +1,118 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.namespace.QName; + +/** + * The BindingConfig class is used during compilation to control the generation of java source files. + * The default BindingConfig does nothing, but sub-classes should provide more interesting behavior. + * + * @see XmlBeans#compileXmlBeans(String, SchemaTypeSystem, XmlObject[], BindingConfig, SchemaTypeLoader, Filer, XmlOptions) XmlBeans.compileXmlBeans() + */ +public class BindingConfig { + private static final InterfaceExtension[] EMPTY_INTERFACE_EXT_ARRAY = new InterfaceExtension[0]; + private static final PrePostExtension[] EMPTY_PREPOST_EXT_ARRAY = new PrePostExtension[0]; + private static final UserType[] EMPTY_USER_TYPE_ARRY = new UserType[0]; + + public static final int QNAME_TYPE = 1; + public static final int QNAME_DOCUMENT_TYPE = 2; + public static final int QNAME_ACCESSOR_ELEMENT = 3; + public static final int QNAME_ACCESSOR_ATTRIBUTE = 4; + + /** + * @param uri the namespace uri + * @return the package name for a namespace or null. + */ + public String lookupPackageForNamespace(String uri) { + return null; + } + + /** + * @param uri the namespace uri + * @return the prefix applied to each java name for a namespace or null. + */ + public String lookupPrefixForNamespace(String uri) { + return null; + } + + /** + * @param uri the namespace uri + * @return Get the suffix applied to each java name for a namespace or null. + */ + public String lookupSuffixForNamespace(String uri) { + return null; + } + + + /** + * @param qname the qname of the java name + * @param kind the type of the qname, which one of {@link #QNAME_TYPE}, {@link #QNAME_DOCUMENT_TYPE}, + * {@link #QNAME_ACCESSOR_ELEMENT}, {@link #QNAME_ACCESSOR_ATTRIBUTE} + * @return Get the java name for a QName of a specific component kind, or null. + */ + public String lookupJavanameForQName(QName qname, int kind) { + return null; + } + + /** + * @return all configured InterfaceExtensions or an empty array. + */ + public InterfaceExtension[] getInterfaceExtensions() { + return EMPTY_INTERFACE_EXT_ARRAY; + } + + /** + * @param fullJavaName the fully qualified java type name + * @return all InterfaceExtensions defined for the fully qualified java + * type generated from schema compilation or an empty array. + */ + public InterfaceExtension[] getInterfaceExtensions(String fullJavaName) { + return EMPTY_INTERFACE_EXT_ARRAY; + } + + /** + * @return all configued PrePostExtensions or an empty array. + */ + public PrePostExtension[] getPrePostExtensions() { + return EMPTY_PREPOST_EXT_ARRAY; + } + + /** + * @param fullJavaName the fully qualified java type name + * @return the PrePostExtension defined for the fully qualified java + * type generated from schema compilation or null. + */ + public PrePostExtension getPrePostExtension(String fullJavaName) { + return null; + } + + /** + * @return all defined user types. + */ + public UserType[] getUserTypes() { + return EMPTY_USER_TYPE_ARRY; + } + + /** + * @param qname the qname of the user type + * @return a user defined Java type for a given QName. + */ + public UserType lookupUserTypeForQName(QName qname) { + return null; + } + +} diff --git a/src/xmlpublic/org/apache/xmlbeans/CDataBookmark.java b/src/main/java/org/apache/xmlbeans/CDataBookmark.java similarity index 87% rename from src/xmlpublic/org/apache/xmlbeans/CDataBookmark.java rename to src/main/java/org/apache/xmlbeans/CDataBookmark.java index 7f3cd2a..57f9766 100644 --- a/src/xmlpublic/org/apache/xmlbeans/CDataBookmark.java +++ b/src/main/java/org/apache/xmlbeans/CDataBookmark.java @@ -16,19 +16,19 @@ /** * Represents a CDATA bookmark.

- * + *

* When XmlOption UseCDataBookmarks is setted on parse methods, * the loader will set these CDataBookmarks in the store on the respective * TEXT fields that were represented as CDATA.

- * + *

* Users can modify the 'look' of TEXT fields, by annotating them with * this bookmark, or remove the bookmark.

- * + *

* Additionaly if setted on save methods, the output will look for these * bookmarks and will output the text as CDATA. * Note: The SaveCDataEntityCountThreshold and SaveCDataLengthThreshold * options and their default values still apply.

- * + *

* Note: Due to the store representation, a CDATA will not be recognized * if it is imediately after non CDATA text and all text following it will * be considered CDATA.
@@ -42,17 +42,14 @@ * @see XmlOptions#setUseCDataBookmarks() * @see org.apache.xmlbeans.XmlObject.Factory#parse(String, XmlOptions) * @see org.apache.xmlbeans.XmlObject#save(java.io.OutputStream, XmlOptions) - * @see XmlOptions#setSaveCDataEntityCountThreshold(int) + * @see XmlOptions#setSaveCDataEntityCountThreshold(int) * @see XmlOptions#setSaveCDataLengthThreshold(int) - * @author Cezar Andrei (cezar dot andrei at gmail dot com) */ -public class CDataBookmark - extends XmlCursor.XmlBookmark -{ +public class CDataBookmark extends XmlCursor.XmlBookmark { /** * The actual bookmark object representing CData.
* Users must use this bookmark in addition to UseCDataBookmarks * option to make use of CDATA representation in XML text. */ - public static CDataBookmark CDATA_BOOKMARK = new CDataBookmark(); + public static final CDataBookmark CDATA_BOOKMARK = new CDataBookmark(); } \ No newline at end of file diff --git a/src/xmlpublic/org/apache/xmlbeans/DelegateXmlObject.java b/src/main/java/org/apache/xmlbeans/DelegateXmlObject.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/DelegateXmlObject.java rename to src/main/java/org/apache/xmlbeans/DelegateXmlObject.java diff --git a/src/xmlpublic/org/apache/xmlbeans/Filer.java b/src/main/java/org/apache/xmlbeans/Filer.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/Filer.java rename to src/main/java/org/apache/xmlbeans/Filer.java diff --git a/src/main/java/org/apache/xmlbeans/FilterXmlObject.java b/src/main/java/org/apache/xmlbeans/FilterXmlObject.java new file mode 100644 index 0000000..b0c2cf8 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/FilterXmlObject.java @@ -0,0 +1,389 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +/** + * A FilterXmlObject delegates to some other XmlObject, which it can use as + * its basic source of data, possibly transforming the data along the way or + * providing additional functionality. The class FilterXmlObject itself + * simply overrides all methods of XmlObject with versions that pass all + * requests to the underlying XmlObject. Subclasses of FilterXmlObject may + * further override some of these methods and may also provide additional + * methods and fields. + *

+ * Note: it is important that FilterXmlObject has no storage (i.e., no + * non-transient fields), because subclasses may be serializable and + * adding storage would break the serialization format. + */ +public abstract class FilterXmlObject implements XmlObject, SimpleValue, DelegateXmlObject { + public SchemaType schemaType() { + return underlyingXmlObject().schemaType(); + } + + public boolean validate() { + return underlyingXmlObject().validate(); + } + + public boolean validate(XmlOptions options) { + return underlyingXmlObject().validate(options); + } + + public XmlObject[] selectPath(String path) { + return underlyingXmlObject().selectPath(path); + } + + public XmlObject[] selectPath(String path, XmlOptions options) { + return underlyingXmlObject().selectPath(path, options); + } + + public XmlObject[] execQuery(String query) { + return underlyingXmlObject().execQuery(query); + } + + public XmlObject[] execQuery(String query, XmlOptions options) { + return underlyingXmlObject().execQuery(query, options); + } + + public XmlObject changeType(SchemaType newType) { + return underlyingXmlObject().changeType(newType); + } + + public boolean isNil() { + return underlyingXmlObject().isNil(); + } + + public void setNil() { + underlyingXmlObject().setNil(); + } + + public boolean isImmutable() { + return underlyingXmlObject().isImmutable(); + } + + public XmlObject set(XmlObject srcObj) { + return underlyingXmlObject().set(srcObj); + } + + public XmlObject copy() { + return underlyingXmlObject().copy(); + } + + public XmlObject copy(XmlOptions options) { + return underlyingXmlObject().copy(options); + } + + public boolean valueEquals(XmlObject obj) { + return underlyingXmlObject().valueEquals(obj); + } + + public int valueHashCode() { + return underlyingXmlObject().valueHashCode(); + } + + public int compareTo(Object obj) { + return underlyingXmlObject().compareTo(obj); + } + + public int compareValue(XmlObject obj) { + return underlyingXmlObject().compareValue(obj); + } + + public Object monitor() { + return underlyingXmlObject().monitor(); + } + + public XmlDocumentProperties documentProperties() { + return underlyingXmlObject().documentProperties(); + } + + public XmlCursor newCursor() { + return underlyingXmlObject().newCursor(); + } + + public XMLStreamReader newXMLStreamReader() { + return underlyingXmlObject().newXMLStreamReader(); + } + + public String xmlText() { + return underlyingXmlObject().xmlText(); + } + + public InputStream newInputStream() { + return underlyingXmlObject().newInputStream(); + } + + public Reader newReader() { + return underlyingXmlObject().newReader(); + } + + public Node newDomNode() { + return underlyingXmlObject().newDomNode(); + } + + public Node getDomNode() { + return underlyingXmlObject().getDomNode(); + } + + public void save(ContentHandler ch, LexicalHandler lh) throws SAXException { + underlyingXmlObject().save(ch, lh); + } + + public void save(File file) throws IOException { + underlyingXmlObject().save(file); + } + + public void save(OutputStream os) throws IOException { + underlyingXmlObject().save(os); + } + + public void save(Writer w) throws IOException { + underlyingXmlObject().save(w); + } + + public XMLStreamReader newXMLStreamReader(XmlOptions options) { + return underlyingXmlObject().newXMLStreamReader(options); + } + + public String xmlText(XmlOptions options) { + return underlyingXmlObject().xmlText(options); + } + + public InputStream newInputStream(XmlOptions options) { + return underlyingXmlObject().newInputStream(options); + } + + public Reader newReader(XmlOptions options) { + return underlyingXmlObject().newReader(options); + } + + public Node newDomNode(XmlOptions options) { + return underlyingXmlObject().newDomNode(options); + } + + public void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException { + underlyingXmlObject().save(ch, lh, options); + } + + public void save(File file, XmlOptions options) throws IOException { + underlyingXmlObject().save(file, options); + } + + public void save(OutputStream os, XmlOptions options) throws IOException { + underlyingXmlObject().save(os, options); + } + + public void save(Writer w, XmlOptions options) throws IOException { + underlyingXmlObject().save(w, options); + } + + public SchemaType instanceType() { + return ((SimpleValue) underlyingXmlObject()).instanceType(); + } + + public String getStringValue() { + return ((SimpleValue) underlyingXmlObject()).getStringValue(); + } + + public boolean getBooleanValue() { + return ((SimpleValue) underlyingXmlObject()).getBooleanValue(); + } + + public byte getByteValue() { + return ((SimpleValue) underlyingXmlObject()).getByteValue(); + } + + public short getShortValue() { + return ((SimpleValue) underlyingXmlObject()).getShortValue(); + } + + public int getIntValue() { + return ((SimpleValue) underlyingXmlObject()).getIntValue(); + } + + public long getLongValue() { + return ((SimpleValue) underlyingXmlObject()).getLongValue(); + } + + public BigInteger getBigIntegerValue() { + return ((SimpleValue) underlyingXmlObject()).getBigIntegerValue(); + } + + public BigDecimal getBigDecimalValue() { + return ((SimpleValue) underlyingXmlObject()).getBigDecimalValue(); + } + + public float getFloatValue() { + return ((SimpleValue) underlyingXmlObject()).getFloatValue(); + } + + public double getDoubleValue() { + return ((SimpleValue) underlyingXmlObject()).getDoubleValue(); + } + + public byte[] getByteArrayValue() { + return ((SimpleValue) underlyingXmlObject()).getByteArrayValue(); + } + + public StringEnumAbstractBase getEnumValue() { + return ((SimpleValue) underlyingXmlObject()).getEnumValue(); + } + + public Calendar getCalendarValue() { + return ((SimpleValue) underlyingXmlObject()).getCalendarValue(); + } + + public Date getDateValue() { + return ((SimpleValue) underlyingXmlObject()).getDateValue(); + } + + public GDate getGDateValue() { + return ((SimpleValue) underlyingXmlObject()).getGDateValue(); + } + + public GDuration getGDurationValue() { + return ((SimpleValue) underlyingXmlObject()).getGDurationValue(); + } + + public QName getQNameValue() { + return ((SimpleValue) underlyingXmlObject()).getQNameValue(); + } + + public List getListValue() { + return ((SimpleValue) underlyingXmlObject()).getListValue(); + } + + public List xgetListValue() { + return ((SimpleValue) underlyingXmlObject()).xgetListValue(); + } + + public Object getObjectValue() { + return ((SimpleValue) underlyingXmlObject()).getObjectValue(); + } + + public void setStringValue(String obj) { + ((SimpleValue) underlyingXmlObject()).setStringValue(obj); + } + + public void setBooleanValue(boolean v) { + ((SimpleValue) underlyingXmlObject()).setBooleanValue(v); + } + + public void setByteValue(byte v) { + ((SimpleValue) underlyingXmlObject()).setByteValue(v); + } + + public void setShortValue(short v) { + ((SimpleValue) underlyingXmlObject()).setShortValue(v); + } + + public void setIntValue(int v) { + ((SimpleValue) underlyingXmlObject()).setIntValue(v); + } + + public void setLongValue(long v) { + ((SimpleValue) underlyingXmlObject()).setLongValue(v); + } + + public void setBigIntegerValue(BigInteger obj) { + ((SimpleValue) underlyingXmlObject()).setBigIntegerValue(obj); + } + + public void setBigDecimalValue(BigDecimal obj) { + ((SimpleValue) underlyingXmlObject()).setBigDecimalValue(obj); + } + + public void setFloatValue(float v) { + ((SimpleValue) underlyingXmlObject()).setFloatValue(v); + } + + public void setDoubleValue(double v) { + ((SimpleValue) underlyingXmlObject()).setDoubleValue(v); + } + + public void setByteArrayValue(byte[] obj) { + ((SimpleValue) underlyingXmlObject()).setByteArrayValue(obj); + } + + public void setEnumValue(StringEnumAbstractBase obj) { + ((SimpleValue) underlyingXmlObject()).setEnumValue(obj); + } + + public void setCalendarValue(Calendar obj) { + ((SimpleValue) underlyingXmlObject()).setCalendarValue(obj); + } + + public void setDateValue(Date obj) { + ((SimpleValue) underlyingXmlObject()).setDateValue(obj); + } + + public void setGDateValue(GDate obj) { + ((SimpleValue) underlyingXmlObject()).setGDateValue(obj); + } + + public void setGDurationValue(GDuration obj) { + ((SimpleValue) underlyingXmlObject()).setGDurationValue(obj); + } + + public void setQNameValue(QName obj) { + ((SimpleValue) underlyingXmlObject()).setQNameValue(obj); + } + + public void setListValue(List obj) { + ((SimpleValue) underlyingXmlObject()).setListValue(obj); + } + + public void setObjectValue(Object obj) { + ((SimpleValue) underlyingXmlObject()).setObjectValue(obj); + } + + public XmlObject[] selectChildren(QName elementName) { + return underlyingXmlObject().selectChildren(elementName); + } + + public XmlObject[] selectChildren(String elementUri, String elementLocalName) { + return underlyingXmlObject().selectChildren(elementUri, elementLocalName); + } + + public XmlObject[] selectChildren(QNameSet elementNameSet) { + return underlyingXmlObject().selectChildren(elementNameSet); + } + + public XmlObject selectAttribute(QName attributeName) { + return underlyingXmlObject().selectAttribute(attributeName); + } + + public XmlObject selectAttribute(String attributeUri, String attributeLocalName) { + return underlyingXmlObject().selectAttribute(attributeUri, attributeLocalName); + } + + public XmlObject[] selectAttributes(QNameSet attributeNameSet) { + return underlyingXmlObject().selectAttributes(attributeNameSet); + } +} diff --git a/src/main/java/org/apache/xmlbeans/GDate.java b/src/main/java/org/apache/xmlbeans/GDate.java new file mode 100644 index 0000000..81fb6ef --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/GDate.java @@ -0,0 +1,1089 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +/** + * Represents an XML Schema-compatible Gregorian date. + *

+ * There are many date types in XML Schema, and this type + * represents the natural union of all those types. A GDate + * can hold any subset of date fields (Year, Month, Day, Time, + * Timezone, or some combination). Wherever the specification + * provides guidance, the guidelines in the + * XML Schema 1.0 specification + * (plus published errata) are followed. + *

+ * Instances may separately have values or no values for + * the year, month, day-of-month, and time-of-day. Not all + * operations are meaningful on all combinations. + */ +public final class GDate implements GDateSpecification, java.io.Serializable { + private static final long serialVersionUID = 1L; + + // XMLSchema spec requires support only for years 1 to 9999, but XMLBeans covers more up to the following limitations + // to avoid losing precision when transforming to a java.util.Date + static final int MAX_YEAR = 292277265; // is Long.MAX_VALUE ms in years - 1 (for the 11month, 31days, 23h, 59m, 59sec case). + static final int MIN_YEAR = -292275295; // is Long.MIN_VALUE ms in years + 1970 + 1 + + // for fast equality comparison, hashing, and serialization + private transient String _canonicalString; + private transient String _string; + + private int _bits; + private int _CY; + private int _M; + private int _D; + private int _h; + private int _m; + private int _s; + private BigDecimal _fs; + private int _tzsign; + private int _tzh; + private int _tzm; + + + /* package */ static final BigDecimal _zero = BigDecimal.ZERO; + /* package */ static final BigDecimal _one = BigDecimal.ONE; + + /** + * Constructs a GDate based on a lexical representation. + */ + public GDate(CharSequence string) { + // first trim XML whitespace + int len = string.length(); + int start = 0; + while (len > 0 && isSpace(string.charAt(len - 1))) { + len -= 1; + } + while (start < len && isSpace(string.charAt(start))) { + start += 1; + } + + // pick optional timezone off the end + if (len - start >= 1 && string.charAt(len - 1) == 'Z') { + _bits |= HAS_TIMEZONE; + len -= 1; + } else if (len - start >= 6) { + timezone: + { + int tzsign; + int tzhour; + int tzminute; + + if (string.charAt(len - 3) != ':') { + break timezone; + } + + switch (string.charAt(len - 6)) { + case '-': + tzsign = -1; + break; + case '+': + tzsign = 1; + break; + default: + break timezone; + } + + tzhour = twoDigit(string, len - 5); + tzminute = twoDigit(string, len - 2); + if (tzhour > 14) { + throw new IllegalArgumentException("time zone hour must be two digits between -14 and +14"); + } + if (tzminute > 59) { + throw new IllegalArgumentException("time zone minute must be two digits between 00 and 59"); + } + _bits |= HAS_TIMEZONE; + _tzsign = tzsign; + _tzh = tzhour; + _tzm = tzminute; + len -= 6; + } + } + + // pick date fields off the beginning if it doesn't look like a time + if (start < len && (start + 2 >= len || string.charAt(start + 2) != ':')) { + scandate: + { + // parse year sign + boolean negyear = false; + if (string.charAt(start) == '-') { + negyear = true; + start += 1; + } + + // scan year digits + int value = 0; + int digits = -start; + char ch; + boolean startsWithZero = start < len && digitVal(string.charAt(start)) == 0; + + for (; ; ) { + ch = start < len ? string.charAt(start) : '\0'; + if (!isDigit(ch)) { + break; + } + + if (startsWithZero && start + digits >= 4) { + throw new IllegalArgumentException("year value starting with zero must be 4 or less digits: " + string); + } + + value = value * 10 + digitVal(ch); + start += 1; + } + digits += start; + if (digits > 9) { + throw new IllegalArgumentException("year too long (up to 9 digits)"); + } else if (digits >= 4) { + _bits |= HAS_YEAR; + _CY = negyear ? -value : value; + if (_CY == 0) { + throw new IllegalArgumentException("year must not be zero"); + } + } else if (digits > 0) { + throw new IllegalArgumentException("year must be four digits (may pad with zeroes, e.g., 0560)"); + } + + if (_CY > MAX_YEAR) { + throw new IllegalArgumentException("year value not supported: too big, must be less than " + MAX_YEAR); + } + + if (_CY < MIN_YEAR) { + throw new IllegalArgumentException("year values not supported: too small, must be bigger than " + MIN_YEAR); + } + + // hyphen introduces a month + if (ch != '-') { + if (negyear && !hasYear()) { + throw new IllegalArgumentException(); // a single minus + } else { + break scandate; + } + } + start += 1; + + // two-digit month + if (len - start >= 2) { + value = twoDigit(string, start); + if (value >= 1 && value <= 12) { + _bits |= HAS_MONTH; + _M = value; + start += 2; + } + } + + // hyphen introduces a day + ch = start < len ? string.charAt(start) : '\0'; + if (ch != '-') { + if (!hasMonth()) { + throw new IllegalArgumentException(); // minus after a year + } else { + break scandate; + } + } + start += 1; + + // two-digit day + if (len - start >= 2) { + value = twoDigit(string, start); + if (value >= 1 && value <= 31) { + _bits |= HAS_DAY; + _D = value; + start += 2; + } + } + + if (!hasDay()) { + // error in the original schema spec permits an extra '-' here + if (hasMonth() && !hasYear()) { + ch = start < len ? string.charAt(start) : '\0'; + if (ch == '-') { + start += 1; + break scandate; + } + } + throw new IllegalArgumentException(); // minus after a month + } + } + } + + // time + if (start < len) { + if (hasYear() || hasMonth() || hasDay()) { + if (string.charAt(start) != 'T') { + throw new IllegalArgumentException("date and time must be separated by 'T'"); + } + start += 1; + } + + if (len < start + 8 || string.charAt(start + 2) != ':' || string.charAt(start + 5) != ':') { + throw new IllegalArgumentException(); + } + + int h = twoDigit(string, start); + if (h > 24) { + throw new IllegalArgumentException("hour must be between 00 and 23"); + } + int m = twoDigit(string, start + 3); + if (m >= 60) { + throw new IllegalArgumentException("minute must be between 00 and 59"); + } + int s = twoDigit(string, start + 6); + if (s >= 60) { + throw new IllegalArgumentException("second must be between 00 and 59"); + } + + start += 8; + + BigDecimal fs = _zero; + if (start < len) { + if (string.charAt(start) != '.') { + throw new IllegalArgumentException(); + } + if (start + 1 < len) { + for (int i = start + 1; i < len; i++) { + if (!isDigit(string.charAt(i))) { + throw new IllegalArgumentException(); + } + } + try { + fs = new BigDecimal(string.subSequence(start, len).toString()); + } catch (Throwable e) { + throw new IllegalArgumentException(); + } + } + } + + _bits |= HAS_TIME; + _h = h; + _m = m; + _s = s; + _fs = fs; + } + + if (hasTime() && _h == 24) { + if (_m != 0 || _s != 0 || _fs.compareTo(_zero) != 0) { + throw new IllegalArgumentException("if hour is 24, minutes, seconds and fraction must be 0"); + } else { // normalize to next day if it has date or at least has day + if (hasDate()) { + GDateBuilder gdb = new GDateBuilder(_CY, _M, _D, _h, _m, _s, _fs, _tzsign, _tzh, _tzm); + gdb.normalize24h(); + + _D = gdb.getDay(); + _M = gdb.getMonth(); + _CY = gdb.getYear(); + _h = 0; + } else if (hasDay()) // if no date only days increment + { + _D++; + _h = 0; + } + } + } + + if (!isValid()) { + throw new IllegalArgumentException("invalid date"); + } + } + + /** + * Constructs a GDate with the specified year, month, day, + * hours, minutes, seconds, and optional fractional seconds, in + * an unspecified timezone. + *

+ * Note that by not specifying the timezone the GDate + * becomes partially unordered with respect to times that + * do have a specified timezone. + */ + public GDate( + int year, + int month, + int day, + int hour, + int minute, + int second, + BigDecimal fraction) { + _bits = HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; + + _CY = year; + _M = month; + _D = day; + _h = hour; + _m = minute; + _s = second; + _fs = fraction == null ? _zero : fraction; + + if (!isValid()) { + throw new IllegalArgumentException(); + } + } + + /** + * Constructs an absolute GDate with the specified year, + * month, day, hours, minutes, seconds, and optional fractional + * seconds, and in the timezone specified. + *

+ * If you wish to have a time or date that isn't in a specified timezone, + * then use the constructor that does not include the timezone arguments. + */ + public GDate( + int year, + int month, + int day, + int hour, + int minute, + int second, + BigDecimal fraction, + int tzSign, + int tzHour, + int tzMinute) { + _bits = HAS_TIMEZONE | HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; + + _CY = year; + _M = month; + _D = day; + _h = hour; + _m = minute; + _s = second; + _fs = fraction == null ? _zero : fraction; + _tzsign = tzSign; + _tzh = tzHour; + _tzm = tzMinute; + + if (!isValid()) { + throw new IllegalArgumentException(); + } + } + + /** + * Constructs a GDate based on a java.util.Date. + *

+ * The current offset of the default timezone is used as the timezone. + *

+ * For example, if eastern daylight time is in effect at the given + * date, the timezone on the east coast of the united states + * translates to GMT-05:00 (EST) + 1:00 (DT offset) == GMT-04:00. + */ + public GDate(Date date) { + // requires some date math, so ctor lives on GDateBuilder + this(new GDateBuilder(date)); + } + + /** + * Constructs a GDate based on a java.util.Calendar. + *

+ * If the calendar does not have some fields set, the same absence + * of information is reflected in the GDate. Note that + * java.util.GregorianCalendar fills in all fields as soon as any + * are fetched, so constructing a GDate with the same calendar object + * twice may result in a different GDate because of a changed calendar. + * Note that org.apache.xmlbeans.XmlCalendar is stable if you re-get a set field, + * so it does not have the same problem. + */ + public GDate(Calendar calendar) { + // we must scrape the "isSet" information out before accessing anything + boolean isSetYear = calendar.isSet(Calendar.YEAR); + boolean isSetEra = calendar.isSet(Calendar.ERA); + boolean isSetMonth = calendar.isSet(Calendar.MONTH); + boolean isSetDay = calendar.isSet(Calendar.DAY_OF_MONTH); + boolean isSetHourOfDay = calendar.isSet(Calendar.HOUR_OF_DAY); + boolean isSetHour = calendar.isSet(Calendar.HOUR); + boolean isSetAmPm = calendar.isSet(Calendar.AM_PM); + boolean isSetMinute = calendar.isSet(Calendar.MINUTE); + boolean isSetSecond = calendar.isSet(Calendar.SECOND); + boolean isSetMillis = calendar.isSet(Calendar.MILLISECOND); + boolean isSetZone = calendar.isSet(Calendar.ZONE_OFFSET); + boolean isSetDst = calendar.isSet(Calendar.DST_OFFSET); + + if (isSetYear) { + int y = calendar.get(Calendar.YEAR); + if (isSetEra && calendar instanceof GregorianCalendar) { + if (calendar.get(Calendar.ERA) == GregorianCalendar.BC) { + y = -y; //1 - y; + } + } + _bits |= HAS_YEAR; + _CY = y; + } + if (isSetMonth) { + _bits |= HAS_MONTH; + _M = calendar.get(Calendar.MONTH) + 1; // !!note + } + if (isSetDay) { + _bits |= HAS_DAY; + _D = calendar.get(Calendar.DAY_OF_MONTH); + } + boolean gotTime = false; + + int h = 0; + int m = 0; + int s = 0; + BigDecimal fs = _zero; + + if (isSetHourOfDay) { + h = calendar.get(Calendar.HOUR_OF_DAY); + gotTime = true; + } else if (isSetHour && isSetAmPm) { + h = calendar.get(Calendar.HOUR) + calendar.get(Calendar.AM_PM) * 12; + gotTime = true; + } + + if (isSetMinute) { + m = calendar.get(Calendar.MINUTE); + gotTime = true; + } + + if (isSetSecond) { + s = calendar.get(Calendar.SECOND); + gotTime = true; + } + + if (isSetMillis) { + fs = BigDecimal.valueOf(calendar.get(Calendar.MILLISECOND), 3); + gotTime = true; + } + + if (gotTime) { + _bits |= HAS_TIME; + _h = h; + _m = m; + _s = s; + _fs = fs; + } + + if (isSetZone) { + int zoneOffsetInMilliseconds = calendar.get(Calendar.ZONE_OFFSET); + if (isSetDst) { + zoneOffsetInMilliseconds += calendar.get(Calendar.DST_OFFSET); + } + + _bits |= HAS_TIMEZONE; + if (zoneOffsetInMilliseconds == 0) { + _tzsign = 0; + _tzh = 0; + _tzm = 0; + TimeZone zone = calendar.getTimeZone(); + String id = zone.getID(); + if (id != null && id.length() > 3) { + switch (id.charAt(3)) { + case '+': + _tzsign = 1; + break; // GMT+00:00 + case '-': + _tzsign = -1; + break; // GMT-00:00 + } + } + } else { + _tzsign = (zoneOffsetInMilliseconds < 0 ? -1 : +1); + zoneOffsetInMilliseconds = zoneOffsetInMilliseconds * _tzsign; + _tzh = zoneOffsetInMilliseconds / 3600000; + _tzm = (zoneOffsetInMilliseconds - _tzh * 3600000) / 60000; + } + } + } + + /** + * Constructs a GDate based on another GDateSpecification. + */ + public GDate(GDateSpecification gdate) { + if (gdate.hasTimeZone()) { + _bits |= HAS_TIMEZONE; + _tzsign = gdate.getTimeZoneSign(); + _tzh = gdate.getTimeZoneHour(); + _tzm = gdate.getTimeZoneMinute(); + } + + if (gdate.hasTime()) { + _bits |= HAS_TIME; + _h = gdate.getHour(); + _m = gdate.getMinute(); + _s = gdate.getSecond(); + _fs = gdate.getFraction(); + } + + if (gdate.hasDay()) { + _bits |= HAS_DAY; + _D = gdate.getDay(); + } + + if (gdate.hasMonth()) { + _bits |= HAS_MONTH; + _M = gdate.getMonth(); + } + + if (gdate.hasYear()) { + _bits |= HAS_YEAR; + _CY = gdate.getYear(); + } + } + + /* package */ + static boolean isDigit(char ch) { + return ((char) (ch - '0') <= '9' - '0'); // char is unsigned + } + + /* package */ + static boolean isSpace(char ch) { + switch (ch) { + case ' ': + case '\t': + case '\r': + case '\n': + return true; + default: + return false; + } + } + + /* package */ + static int digitVal(char ch) { + return (ch - '0'); + } + + private static int twoDigit(CharSequence str, int index) { + char ch1 = str.charAt(index); + char ch2 = str.charAt(index + 1); + if (!isDigit(ch1) || !isDigit(ch2)) { + return 100; // not two digits + } + return digitVal(ch1) * 10 + digitVal(ch2); + } + + /** + * Returns true: all GDate instances are immutable. + */ + public final boolean isImmutable() { + return true; + } + + /** + * Returns a combination of flags indicating the information + * contained by this GDate. The five flags are + * HAS_TIMEZONE, HAS_YEAR, HAS_MONTH, HAS_DAY, and HAS_TIME. + */ + public int getFlags() { + return _bits; + } + + /** + * True if this date/time specification specifies a timezone. + */ + public final boolean hasTimeZone() { + return ((_bits & HAS_TIMEZONE) != 0); + } + + /** + * True if this date/time specification specifies a year. + */ + public final boolean hasYear() { + return ((_bits & HAS_YEAR) != 0); + } + + /** + * True if this date/time specification specifies a month-of-year. + */ + public final boolean hasMonth() { + return ((_bits & HAS_MONTH) != 0); + } + + /** + * True if this date/time specification specifies a day-of-month. + */ + public final boolean hasDay() { + return ((_bits & HAS_DAY) != 0); + } + + /** + * True if this date/time specification specifies a time-of-day. + */ + public final boolean hasTime() { + return ((_bits & HAS_TIME) != 0); + } + + /** + * True if this date/time specification specifies a full date (year, month, day) + */ + public final boolean hasDate() { + return ((_bits & (HAS_DAY | HAS_MONTH | HAS_YEAR)) == (HAS_DAY | HAS_MONTH | HAS_YEAR)); + } + + /** + * Gets the year. Should be a four-digit year specification. + */ + public final int getYear() { + return _CY; + } + + /** + * Gets the month-of-year. January is 1. + */ + public final int getMonth() { + return _M; + } + + /** + * Gets the day-of-month. The first day of each month is 1. + */ + public final int getDay() { + return _D; + } + + /** + * Gets the hour-of-day. Midnight is 0, and 11PM is 23. + */ + public final int getHour() { + return _h; + } + + /** + * Gets the minute-of-hour. Range from 0 to 59. + */ + public final int getMinute() { + return _m; + } + + /** + * Gets the second-of-minute. Range from 0 to 59. + */ + public final int getSecond() { + return _s; + } + + /** + * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). + */ + public final BigDecimal getFraction() { + return _fs; + } + + /** + * Gets the time zone sign. For time zones east of GMT, + * this is positive; for time zones west, this is negative. + */ + public final int getTimeZoneSign() { + return _tzsign; + } + + /** + * Gets the time zone hour. + *

+ * This is always positive: for the sign, look at + * getTimeZoneSign(). + */ + public final int getTimeZoneHour() { + return _tzh; + } + + /** + * Gets the time zone minutes. + *

+ * This is always positive: for the sign, look at + * getTimeZoneSign(). + */ + public final int getTimeZoneMinute() { + return _tzm; + } + + /** + * Gets the rounded millisecond value. Range from 0 to 999 + */ + public int getMillisecond() { + if (_fs == null) { + return 0; + } + return _fs.setScale(3, RoundingMode.DOWN).unscaledValue().intValue(); + } + + /** + * The canonical string representation. Specific moments or + * times-of-day in a specified timezone are normalized to + * UTC time to produce a canonical string form for them. + * Other recurring time specifications keep their timezone + * information. + */ + public String canonicalString() { + ensureCanonicalString(); + return _canonicalString; + } + + /** + * True if this GDate corresponds to a valid gregorian date value + * in XML schema. + */ + public boolean isValid() { + return GDateBuilder.isValidGDate(this); + } + + /** + * Returns the Julian date corresponding to this Gregorian date. + * The Julian date (JD) is a continuous count of days from + * 1 January 4713 BC. + */ + public int getJulianDate() { + return GDateBuilder.julianDateForGDate(this); + } + + /** + * Retrieves the value of the current time as an {@link XmlCalendar}. + *

+ * {@link XmlCalendar} is a subclass of {@link java.util.GregorianCalendar} + * which is slightly customized to match XML schema date rules. + *

+ * The returned {@link XmlCalendar} has only those time and date fields + * set that are reflected in the GDate object. Because of the way the + * {@link java.util.Calendar} contract works, any information in the isSet() vanishes + * as soon as you view any unset field using get() methods. + * This means that if it is important to understand which date fields + * are set, you must call isSet() first before get(). + */ + public XmlCalendar getCalendar() { + return new XmlCalendar(this); + } + + + /** + * Retrieves the value of the current time as a java.util.Date + * instance. + */ + public Date getDate() { + return GDateBuilder.dateForGDate(this); + } + + /** + * Comparison to another GDate. + *

    + *
  • Returns -1 if this < date. (less-than) + *
  • Returns 0 if this == date. (equal) + *
  • Returns 1 if this > date. (greater-than) + *
  • Returns 2 if this <> date. (incomparable) + *
+ * Two instances are incomparable if they have different amounts + * of information. + */ + public int compareToGDate(GDateSpecification datespec) { + return GDateBuilder.compareGDate(this, datespec); + } + + /** + * Returns the builtin type code for the shape of the information + * contained in this instance, or 0 if the + * instance doesn't contain information corresponding to a + * Schema type. + *

+ * Value will be equal to + * {@link SchemaType#BTC_NOT_BUILTIN}, + * {@link SchemaType#BTC_G_YEAR}, + * {@link SchemaType#BTC_G_YEAR_MONTH}, + * {@link SchemaType#BTC_G_MONTH}, + * {@link SchemaType#BTC_G_MONTH_DAY}, + * {@link SchemaType#BTC_G_DAY}, + * {@link SchemaType#BTC_DATE}, + * {@link SchemaType#BTC_DATE_TIME}, or + * {@link SchemaType#BTC_TIME}. + */ + public int getBuiltinTypeCode() { + return GDateBuilder.btcForFlags(_bits); + } + + /** + * Adds a duration to this GDate, and returns a new GDate. + */ + public GDate add(GDurationSpecification duration) { + GDateBuilder builder = new GDateBuilder(this); + builder.addGDuration(duration); + return builder.toGDate(); + } + + /** + * Adds a duration to this GDate, and returns a new GDate. + */ + public GDate subtract(GDurationSpecification duration) { + GDateBuilder builder = new GDateBuilder(this); + builder.subtractGDuration(duration); + return builder.toGDate(); + } + + /** + * GDate is an immutable class, and equality is computed based + * on its canonical value. + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof GDate)) { + return false; + } + + ensureCanonicalString(); + return _canonicalString.equals(((GDate) obj).canonicalString()); + } + + /** + * Returns a hash code for this GDate. + */ + public int hashCode() { + ensureCanonicalString(); + return _canonicalString.hashCode(); + } + + /** + * The canonical string representation. Specific moments or + * times-of-day in a specified timezone are normalized to + * UTC time to produce a canonical string form for them. + * Other recurring time specifications keep their timezone + * information. + */ + private void ensureCanonicalString() { + if (_canonicalString != null) { + return; + } + + boolean needNormalize = + (hasTimeZone() && getTimeZoneSign() != 0 && hasTime() && + ((hasDay() == hasMonth() && hasDay() == hasYear()))); + + if (!needNormalize && getFraction() != null && getFraction().scale() > 0) { + BigInteger bi = getFraction().unscaledValue(); + needNormalize = (bi.mod(GDateBuilder.TEN).signum() == 0); + } + + if (!needNormalize) { + _canonicalString = toString(); + } else { + GDateBuilder gdb = new GDateBuilder(this); + gdb.normalize(); + _canonicalString = gdb.toString(); + } + } + + /** + * The natural string representation. This represents the information + * that is available, including timezone. For types that correspond + * to defined schema types (schemaBuiltinTypeCode() > 0), + * this provides the natural lexical representation. + *

+ * When both time and timezone are specified, this string is not + * the canonical representation unless the timezone is UTC (Z) + * (since the same moment in time can be expressed in different + * timezones). To get a canonical string, use the canonicalString() + * method. + */ + public String toString() { + if (_string == null) { + _string = formatGDate(this); + } + return _string; + } + + private final static char[] _tensDigit = + { + '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', + '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', + '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', + '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', + '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', + '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', + '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', + '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', + '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', + '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', + }; + private final static char[] _onesDigit = + { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + }; + + private static int _padTwoAppend(char[] b, int i, int n) { + assert (n >= 0 && n < 100); + b[i] = _tensDigit[n]; + b[i + 1] = _onesDigit[n]; + return i + 2; + } + + private static int _padFourAppend(char[] b, int n) { + int i = 0; + if (n < 0) { + b[i++] = '-'; + n = -n; + } + if (n >= 10000) { + String s = Integer.toString(n); + s.getChars(0, s.length(), b, i); + return i + s.length(); + } + int q = n / 100; + int r = n - q * 100; + b[i] = _tensDigit[q]; + b[i + 1] = _onesDigit[q]; + b[i + 2] = _tensDigit[r]; + b[i + 3] = _onesDigit[r]; + return i + 4; + } + + private static final TimeZone GMTZONE = TimeZone.getTimeZone("GMT"); + private static final TimeZone[] MINUSZONE = + { + TimeZone.getTimeZone("GMT-00:00"), + TimeZone.getTimeZone("GMT-01:00"), + TimeZone.getTimeZone("GMT-02:00"), + TimeZone.getTimeZone("GMT-03:00"), + TimeZone.getTimeZone("GMT-04:00"), + TimeZone.getTimeZone("GMT-05:00"), + TimeZone.getTimeZone("GMT-06:00"), + TimeZone.getTimeZone("GMT-07:00"), + TimeZone.getTimeZone("GMT-08:00"), + TimeZone.getTimeZone("GMT-09:00"), + TimeZone.getTimeZone("GMT-10:00"), + TimeZone.getTimeZone("GMT-11:00"), + TimeZone.getTimeZone("GMT-12:00"), + TimeZone.getTimeZone("GMT-13:00"), + TimeZone.getTimeZone("GMT-14:00"), + }; + private static final TimeZone[] PLUSZONE = + { + TimeZone.getTimeZone("GMT+00:00"), + TimeZone.getTimeZone("GMT+01:00"), + TimeZone.getTimeZone("GMT+02:00"), + TimeZone.getTimeZone("GMT+03:00"), + TimeZone.getTimeZone("GMT+04:00"), + TimeZone.getTimeZone("GMT+05:00"), + TimeZone.getTimeZone("GMT+06:00"), + TimeZone.getTimeZone("GMT+07:00"), + TimeZone.getTimeZone("GMT+08:00"), + TimeZone.getTimeZone("GMT+09:00"), + TimeZone.getTimeZone("GMT+10:00"), + TimeZone.getTimeZone("GMT+11:00"), + TimeZone.getTimeZone("GMT+12:00"), + TimeZone.getTimeZone("GMT+13:00"), + TimeZone.getTimeZone("GMT+14:00"), + }; + + /* package */ + static TimeZone timeZoneForGDate(GDateSpecification date) { + // use a cached timezone if integral; otherwise make a new one. + if (!date.hasTimeZone()) { + return TimeZone.getDefault(); + } + if (date.getTimeZoneSign() == 0) { + return GMTZONE; + } + if (date.getTimeZoneMinute() == 0 && date.getTimeZoneHour() <= 14 && date.getTimeZoneHour() >= 0) { + return date.getTimeZoneSign() < 0 ? MINUSZONE[date.getTimeZoneHour()] : PLUSZONE[date.getTimeZoneHour()]; + } + + char[] zb = new char[9]; + zb[0] = 'G'; + zb[1] = 'M'; + zb[2] = 'T'; + zb[3] = (date.getTimeZoneSign() < 0) ? '-' : '+'; + GDate._padTwoAppend(zb, 4, date.getTimeZoneHour()); + zb[6] = ':'; + GDate._padTwoAppend(zb, 7, date.getTimeZoneMinute()); + return TimeZone.getTimeZone(new String(zb)); + } + + /* package */ + static String formatGDate(GDateSpecification spec) { + // We've used a char[] rather than a StringBuffer for a 4x speedup + // -YY(10)YY-MM-DDTHH:MM:SS.FFFFFF+ZH:ZM + // 1 + 10 + 3+ 3+ 3+ 3+ 3+1 + s + 3+ 3 = 33 + s + BigDecimal fs = spec.getFraction(); + char[] message = new char[33 + (fs == null ? 0 : fs.scale())]; + int i = 0; + + if (spec.hasYear() || spec.hasMonth() || spec.hasDay()) { + dmy: + { + if (spec.hasYear()) { + i = _padFourAppend(message, spec.getYear()); + } else { + message[i++] = '-'; + } + + if (!(spec.hasMonth() || spec.hasDay())) { + break dmy; + } + + message[i++] = '-'; + if (spec.hasMonth()) { + i = _padTwoAppend(message, i, spec.getMonth()); + } + + if (!spec.hasDay()) { + break dmy; + } + + message[i++] = '-'; + i = _padTwoAppend(message, i, spec.getDay()); + } + if (spec.hasTime()) { + message[i++] = 'T'; + } + } + + if (spec.hasTime()) { + i = _padTwoAppend(message, i, spec.getHour()); + message[i++] = ':'; + i = _padTwoAppend(message, i, spec.getMinute()); + message[i++] = ':'; + i = _padTwoAppend(message, i, spec.getSecond()); + if (fs != null && !_zero.equals(fs)) // (optimization ~3%) + { + String frac = fs.toString(); + int point = frac.indexOf('.'); + if (point >= 0) { + frac.getChars(point, frac.length(), message, i); + i += frac.length() - point; + } + } + } + + if (spec.hasTimeZone()) { + if (spec.getTimeZoneSign() == 0) { + message[i++] = 'Z'; + } else { + message[i++] = spec.getTimeZoneSign() > 0 ? '+' : '-'; + i = _padTwoAppend(message, i, spec.getTimeZoneHour()); + message[i++] = ':'; + i = _padTwoAppend(message, i, spec.getTimeZoneMinute()); + } + } + + // it would be nice to use (0, i, message) ctor instead + return new String(message, 0, i); + } + +} + diff --git a/src/main/java/org/apache/xmlbeans/GDateBuilder.java b/src/main/java/org/apache/xmlbeans/GDateBuilder.java new file mode 100644 index 0000000..4388b75 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/GDateBuilder.java @@ -0,0 +1,1527 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +/** + * Used to build {@link GDate GDates}. + *

+ * Like GDate, a GDateBuilder represents an Gregorian Date, Time, + * and Timezone, or subset of information (Year, Month, Day, + * Time, Timezone, or some combination). Wherever it provides + * guidance, the XML Schema 1.0 specification (plus published + * errata) is followed. + *

+ * Instances may separately set or clear the year, month, + * day-of-month, and time-of-day. Not all operations are + * meaningful on all combinations. In particular, timezone + * normalization is only possible if there is a time, or + * a time together with a full date. + */ +public final class GDateBuilder implements GDateSpecification, java.io.Serializable { + private static final long serialVersionUID = 1L; + + private int _bits; + private int _CY; + private int _M; + private int _D; + private int _h; + private int _m; + private int _s; + private BigDecimal _fs; + private int _tzsign; + private int _tzh; + private int _tzm; + + /** + * Constructs a GDateBuilder specifying no date or time + */ + public GDateBuilder() { + } + + /** + * Builds another GDateBuilder with the same value + * as this one. + */ + public Object clone() { + return new GDateBuilder(this); + } + + /** + * Builds a GDate from this GDateBuilder. + */ + public GDate toGDate() { + return new GDate(this); + } + + /** + * Construts a GDateBuilder by copying another GDateSpecificaiton. + */ + public GDateBuilder(GDateSpecification gdate) { + if (gdate.hasTimeZone()) { + setTimeZone(gdate.getTimeZoneSign(), gdate.getTimeZoneHour(), gdate.getTimeZoneMinute()); + } + + if (gdate.hasTime()) { + setTime(gdate.getHour(), gdate.getMinute(), gdate.getSecond(), gdate.getFraction()); + } + + if (gdate.hasDay()) { + setDay(gdate.getDay()); + } + + if (gdate.hasMonth()) { + setMonth(gdate.getMonth()); + } + + if (gdate.hasYear()) { + setYear(gdate.getYear()); + } + } + + // Forms: + + // Date part: + // Year: (-?\d{4,}) + // YearMonth: (-?\d{4,})-(\d{2}) + // Date: (-?\d{4,})-(\d{2})-(\d{2}) + // Month: --(\d{2})(--)? //errata R-48 + // MonthDay: --(\d{2})-(\d{2}) + // Day: ---(\d{2}) + + // Time part: + // Time: (\d{2}):(\d{2}):(\d{2})(.\d*)? + + // Timezone part: + // TZ: (Z)|([+-]\d{2}):(\d{2}) + + /** + * Constructs a GDateBuilder from a lexical + * representation. The lexical space contains the + * union of the lexical spaces of all the schema + * date/time types (except for duration). + */ + public GDateBuilder(CharSequence string) { + this(new GDate(string)); + } + + + public GDateBuilder(Calendar calendar) { + this(new GDate(calendar)); + } + + /** + * Constructs a GDateBuilder with the specified year, month, day, + * hours, minutes, seconds, and optional fractional seconds, in + * an unspecified timezone. + *

+ * Note that by not specifying the timezone the GDateBuilder + * becomes partially unordered with respect to timesthat do have a + * specified timezone. + * + * @param year The year + * @param month The month, from 1-12 + * @param day The day of month, from 1-31 + * @param hour The hour of day, from 0-23 + * @param minute The minute of hour, from 0-59 + * @param second The second of minute, from 0-59 + * @param fraction The fraction of second, 0.0 to 0.999... (may be null) + */ + public GDateBuilder( + int year, + int month, + int day, + int hour, + int minute, + int second, + BigDecimal fraction) { + _bits = HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; + + if (year == 0) { + throw new IllegalArgumentException(); + } + + _CY = (year > 0 ? year : year + 1); + _M = month; + _D = day; + _h = hour; + _m = minute; + _s = second; + _fs = fraction == null ? GDate._zero : fraction; + + if (!isValid()) { + throw new IllegalArgumentException(); + } + } + + /** + * Constructs an absolute GDateBuilder with the specified year, + * month, day, hours, minutes, seconds, and optional fractional + * seconds, and in the timezone specified. + *

+ * Note that you can reexpress the GDateBuilder in any timezone using + * normalizeToTimeZone(). The normalize() method normalizes to UTC. + *

+ * If you wish to have a time or date that isn't in a specified timezone, + * then use the constructor that does not include the timezone arguments. + * + * @param year the year + * @param month the month, from 1-12 + * @param day the day of month, from 1-31 + * @param hour the hour of day, from 0-23 + * @param minute the minute of hour, from 0-59 + * @param second the second of minute, from 0-59 + * @param fraction the fraction of second, 0.0 to 0.999... (may be null) + * @param tzSign the timezone offset sign, either +1, 0, or -1 + * @param tzHour the timezone offset hour + * @param tzMinute the timezone offset minute + */ + public GDateBuilder( + int year, + int month, + int day, + int hour, + int minute, + int second, + BigDecimal fraction, + int tzSign, + int tzHour, + int tzMinute) { + _bits = HAS_TIMEZONE | HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; + + if (year == 0) { + throw new IllegalArgumentException(); + } + + _CY = (year > 0 ? year : year + 1); + _M = month; + _D = day; + _h = hour; + _m = minute; + _s = second; + _fs = fraction == null ? GDate._zero : fraction; + _tzsign = tzSign; + _tzh = tzHour; + _tzm = tzMinute; + + if (!isValid()) { + throw new IllegalArgumentException(); + } + } + + /** + * Constructs a GDateBuilder based on a java.util.Date. + *

+ * The current offset of the default timezone is used as the timezone. + *

+ * For example, if eastern daylight time is in effect at the given + * date, the timezone on the east coast of the united states + * translates to GMT-05:00 (EST) + 1:00 (DT offset) == GMT-04:00. + * + * @param date the date object to copy + */ + public GDateBuilder(Date date) { + setDate(date); + } + + /** + * True if the instance is immutable. + */ + public boolean isImmutable() { + return false; + } + + /** + * Returns a combination of flags indicating the information + * contained by this GDate. The five flags are + * HAS_TIMEZONE, HAS_YEAR, HAS_MONTH, HAS_DAY, and HAS_TIME. + */ + public int getFlags() { + return _bits; + } + + /** + * True if this date/time specification specifies a timezone. + */ + public final boolean hasTimeZone() { + return ((_bits & HAS_TIMEZONE) != 0); + } + + /** + * True if this date/time specification specifies a year. + */ + public final boolean hasYear() { + return ((_bits & HAS_YEAR) != 0); + } + + /** + * True if this date/time specification specifies a month-of-year. + */ + public final boolean hasMonth() { + return ((_bits & HAS_MONTH) != 0); + } + + /** + * True if this date/time specification specifies a day-of-month. + */ + public final boolean hasDay() { + return ((_bits & HAS_DAY) != 0); + } + + /** + * True if this date/time specification specifies a time-of-day. + */ + public final boolean hasTime() { + return ((_bits & HAS_TIME) != 0); + } + + /** + * True if this date/time specification specifies a full date (year, month, day) + */ + public final boolean hasDate() { + return ((_bits & (HAS_DAY | HAS_MONTH | HAS_YEAR)) == (HAS_DAY | HAS_MONTH | HAS_YEAR)); + } + + /** + * Gets the year. Should be a four-digit year specification. + */ + public final int getYear() { + return (_CY > 0 ? _CY : _CY - 1); + } + + /** + * Gets the month-of-year. January is 1. + */ + public final int getMonth() { + return _M; + } + + /** + * Gets the day-of-month. The first day of each month is 1. + */ + public final int getDay() { + return _D; + } + + /** + * Gets the hour-of-day. Midnight is 0, and 11PM is 23. + */ + public final int getHour() { + return _h; + } + + /** + * Gets the minute-of-hour. Range from 0 to 59. + */ + public final int getMinute() { + return _m; + } + + /** + * Gets the second-of-minute. Range from 0 to 59. + */ + public final int getSecond() { + return _s; + } + + + /** + * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). + */ + public final BigDecimal getFraction() { + return _fs; + } + + + /** + * Gets the rounded millisecond value. Range from 0 to 999 + */ + public final int getMillisecond() { + if (_fs == null || GDate._zero.equals(_fs)) { + return 0; + } + return _fs.setScale(3, RoundingMode.HALF_UP).unscaledValue().intValue(); + } + + /** + * Gets the time zone sign. For time zones east of GMT, + * this is positive; for time zones west, this is negative. + */ + public final int getTimeZoneSign() { + return _tzsign; + } + + /** + * Gets the time zone hour. + * This is always positive: for the sign, look at + * getTimeZoneSign(). + */ + public final int getTimeZoneHour() { + return _tzh; + } + + /** + * Gets the time zone minutes. + * This is always positive: for the sign, look at + * getTimeZoneSign(). + */ + public final int getTimeZoneMinute() { + return _tzm; + } + + + /** + * Sets the year. Should be a four-digit year specification. + * + * @param year the year + */ + public void setYear(int year) { + if (year < GDate.MIN_YEAR || year > GDate.MAX_YEAR) { + throw new IllegalArgumentException("year out of range"); + } + if (year == 0) { + throw new IllegalArgumentException("year cannot be 0"); + } + _bits |= HAS_YEAR; + _CY = (year > 0 ? year : year + 1); + } + + /** + * Sets the month-of-year. January is 1. + * + * @param month the month, from 1-12 + */ + public void setMonth(int month) { + if (month < 1 || month > 12) { + throw new IllegalArgumentException("month out of range"); + } + _bits |= HAS_MONTH; + _M = month; + } + + /** + * Sets the day-of-month. The first day of each month is 1. + * + * @param day the day of month, from 1-31 + */ + public void setDay(int day) { + if (day < 1 || day > 31) { + throw new IllegalArgumentException("day out of range"); + } + _bits |= HAS_DAY; + _D = day; + } + + /** + * Sets the time. Hours in the day range from 0 to 23; + * minutes and seconds range from 0 to 59; and fractional + * seconds range from 0 (inclusive) to 1 (exclusive). + * The fraction can be null and is assumed to be zero. + * + * @param hour the hour of day, from 0-23 or 24 only if min, sec and fraction are 0 + * @param minute the minute of hour, from 0-59 + * @param second the second of minute, from 0-59 + * @param fraction the fraction of second, 0.0 to 0.999... (may be null) + */ + public void setTime(int hour, int minute, int second, BigDecimal fraction) { + if (hour < 0 || hour > 24) { + throw new IllegalArgumentException("hour out of range"); + } + if (minute < 0 || minute > 59) { + throw new IllegalArgumentException("minute out of range"); + } + if (second < 0 || second > 59) { + throw new IllegalArgumentException("second out of range"); + } + if (fraction != null && (fraction.signum() < 0 || GDate._one.compareTo(fraction) <= 0)) { + throw new IllegalArgumentException("fraction out of range"); + } + if (hour == 24 && (minute != 0 || second != 0 || (fraction != null && (GDate._zero.compareTo(fraction) != 0)))) { + throw new IllegalArgumentException("when hour is 24, min sec and fracton must be 0"); + } + + _bits |= HAS_TIME; + _h = hour; + _m = minute; + _s = second; + _fs = fraction == null ? GDate._zero : fraction; + } + + /** + * Sets the time zone without changing the other time + * fields. If you with to adjust other time fields to express + * the same actual moment in time in a different time zone, + * use normalizeToTimeZone. + *

+ * Timezones must be between -14:00 and +14:00. Sign + * must be -1 or 1 (or 0 for UTC only), and the offset hours + * and minute arguments must be nonnegative. + * + * @param tzSign the timezone offset sign, either +1, 0, or -1 + * @param tzHour the timezone offset hour + * @param tzMinute the timezone offset minute + */ + public void setTimeZone(int tzSign, int tzHour, int tzMinute) { + if (!((tzSign == 0 && tzHour == 0 && tzMinute == 0) || + ((tzSign == -1 || tzSign == 1) && + (tzHour >= 0 && tzMinute >= 0) && + (tzHour == 14 && tzMinute == 0 || tzHour < 14 && tzMinute < 60)))) { + throw new IllegalArgumentException("time zone out of range (-14:00 to +14:00). (" + + (tzSign < 0 ? "-" : "+") + tzHour + ":" + tzMinute + ")"); + } + + _bits |= HAS_TIMEZONE; + _tzsign = tzSign; + _tzh = tzHour; + _tzm = tzMinute; + } + + /** + * Sets the time zone based on a number of offset minutes rather + * than sign/hour/minute; for example, setTimeZone(-60) is the + * same as setTimeZone(-1, 1, 0). + */ + public void setTimeZone(int tzTotalMinutes) { + if (tzTotalMinutes < -14 * 60 || tzTotalMinutes > 14 * 60) { + throw new IllegalArgumentException("time zone out of range (-840 to 840 minutes). (" + tzTotalMinutes + ")"); + } + + int tzSign = Integer.compare(tzTotalMinutes, 0); + tzTotalMinutes *= tzSign; + int tzH = tzTotalMinutes / 60; + int tzM = tzTotalMinutes - tzH * 60; + + setTimeZone(tzSign, tzH, tzM); + } + + /** + * Clears the year. After clearing, hasYear returns false and the + * value of getYear is undefined. + */ + public void clearYear() { + _bits &= ~HAS_YEAR; + _CY = 0; + } + + /** + * Clears the month-of-year. After clearing. hasMonth returns false and + * the value of getMonth is undefined. + */ + public void clearMonth() { + _bits &= ~HAS_MONTH; + _M = 0; + } + + /** + * Clears the day-of-month. After clearing. hasDay returns false and + * the value of getDay is undefined. + */ + public void clearDay() { + _bits &= ~HAS_DAY; + _D = 0; + } + + /** + * Clears the time-of-day. + * After clearing. hasTime returns false and + * the value of getTime is undefined. + */ + public void clearTime() { + _bits &= ~HAS_TIME; + _h = 0; + _m = 0; + _s = 0; + _fs = null; + } + + /** + * Clears the timezone. After clearing. hasTimeZone returns false and + * the value of getTimeZoneHour and getTimeZoneMinute are undefined. + * Does not change the other time fields. + */ + public void clearTimeZone() { + _bits &= ~HAS_TIMEZONE; + _tzsign = 0; + _tzh = 0; + _tzm = 0; + } + + /** + * True if all date fields lie within their legal ranges. A GDateBuilder + * can be invalid, for example, if you change the month to February + * and the day-of-month is 31. + */ + public boolean isValid() { + return isValidGDate(this); + } + + /* package */ + static boolean isValidGDate(GDateSpecification date) { + if (date.hasYear() && date.getYear() == 0) { + return false; + } + + if (date.hasMonth() && (date.getMonth() < 1 || date.getMonth() > 12)) { + return false; + } + + if (date.hasDay() && + (date.getDay() < 1 || date.getDay() > 31 || + date.getDay() > 28 && + date.hasMonth() && + (date.hasYear() ? + date.getDay() > _maxDayInMonthFor((date.getYear() > 0 ? + date.getYear() : + date.getYear() + 1), + date.getMonth()) : + date.getDay() > _maxDayInMonth(date.getMonth())))) { + return false; + } + + if (date.hasTime() && ((date.getHour() < 0 || date.getHour() > 23 || + date.getMinute() < 0 || date.getMinute() > 59 || + date.getSecond() < 0 || date.getSecond() > 59 || + date.getFraction().signum() < 0 || date.getFraction().compareTo(GDate._one) >= 0)) && + // check for 24:00:00 valid format + !(date.getHour() == 24 && date.getMinute() == 0 && date.getSecond() == 0 && + date.getFraction().compareTo(GDate._zero) == 0)) { + return false; + } + + if (date.hasTimeZone() && + (!((date.getTimeZoneSign() == 0 && date.getTimeZoneHour() == 0 && date.getTimeZoneMinute() == 0) || + ((date.getTimeZoneSign() == -1 || date.getTimeZoneSign() == +1) && + // NB: allow +00:00 and -00:00 + // (date.getTimeZoneHour() == 0 && date.getTimeZoneMinute() > 0 || date.getTimeZoneHour() > 0 && date.getTimeZoneMinute() >= 0) && + (date.getTimeZoneHour() >= 0 && date.getTimeZoneMinute() >= 0) && + (date.getTimeZoneHour() == 14 && date.getTimeZoneMinute() == 0 || date.getTimeZoneHour() < 14 && date.getTimeZoneMinute() < 60))))) { + return false; + } + + // everyting looks kosher + return true; + } + + + /** + * Normalizes the instance, ensuring date and time fields are within + * their normal ranges. + *

+ * If no timezone or no time is specified, or if a partial date is specified, this + * method does nothing, and leaves the timezone information as-is. + *

+ * If a time or time and date is specified, this method normalizes the timezone + * to UTC. + */ + public void normalize() { + // DateTime or Time, with TimeZone: normalize to UTC. + // In the process all the fields will be normalized. + if (hasDay() == hasMonth() && hasDay() == hasYear() && + hasTimeZone() && hasTime()) { + normalizeToTimeZone(0, 0, 0); + } else { + // No timezone, or incomplete date. + _normalizeTimeAndDate(); + } + + // remove trailing zeros from fractional seconds + if (hasTime() && _fs != null && _fs.scale() > 0) { + if (_fs.signum() == 0) { + _fs = GDate._zero; + } else { + BigInteger bi = _fs.unscaledValue(); + String str = bi.toString(); + int lastzero; + for (lastzero = str.length(); lastzero > 0; lastzero -= 1) { + if (str.charAt(lastzero - 1) != '0') { + break; + } + } + if (lastzero < str.length()) { + _fs = _fs.setScale(_fs.scale() - str.length() + lastzero, RoundingMode.UNNECESSARY); + } + } + } + } + + /** + * Normalizes the instance when hour is 24. If day is present, hour 24 is equivalent to hour 00 next day. + */ + void normalize24h() { + if (!hasTime() || getHour() != 24) { + return; + } + + _normalizeTimeAndDate(); + } + + + private void _normalizeTimeAndDate() { + long carry = 0; + + if (hasTime()) { + carry = _normalizeTime(); + } + + if (hasDay()) { + _D += carry; + } + + if (hasDate()) { + _normalizeDate(); + } else if (hasMonth()) { + // with incomplete dates, just months can be normalized: + // days stay denormalized. + if (_M < 1 || _M > 12) { + int temp = _M; + _M = _modulo(temp, 1, 13); + if (hasYear()) { + _CY = _CY + (int) _fQuotient(temp, 1, 13); + } + } + } + } + + /** + * If the time and timezone are known, this method changes the timezone to the + * specified UTC offset, altering minutes, hours, day, month, and year as + * necessary to ensure that the actual described moment in time is the same. + *

+ * It is an error to operate on instances without a time or timezone, or + * with a partially specified date. + * + * @param tzSign the timezone offset sign, either +1, 0, or -1 + * @param tzHour the timezone offset hour + * @param tzMinute the timezone offset minute + */ + public void normalizeToTimeZone(int tzSign, int tzHour, int tzMinute) { + if (!((tzSign == 0 && tzHour == 0 && tzMinute == 0) || + ((tzSign == -1 || tzSign == 1) && + (tzHour >= 0 && tzMinute >= 0) && + (tzHour == 14 && tzMinute == 0 || tzHour < 14 && tzMinute < 60)))) { + throw new IllegalArgumentException("time zone must be between -14:00 and +14:00"); + } + + if (!hasTimeZone() || !hasTime()) { + throw new IllegalStateException("cannot normalize time zone without both time and timezone"); + } + + if (!(hasDay() == hasMonth() && hasDay() == hasYear())) { + throw new IllegalStateException("cannot do date math without a complete date"); + } + + int hshift = tzSign * tzHour - _tzsign * _tzh; + int mshift = tzSign * tzMinute - _tzsign * _tzm; + + _tzsign = tzSign; + _tzh = tzHour; + _tzm = tzMinute; + addDuration(1, 0, 0, 0, hshift, mshift, 0, null); + } + + /** + * Normalizes to a time zone specified by a number of offset minutes rather + * than sign/hour/minute; for example, normalizeToTimeZone(-60) is the + * same as normalizeToTimeZone(-1, 1, 0). + */ + public void normalizeToTimeZone(int tzTotalMinutes) { + if (tzTotalMinutes < -14 * 60 || tzTotalMinutes > 14 * 60) { + throw new IllegalArgumentException("time zone out of range (-840 to 840 minutes). (" + tzTotalMinutes + ")"); + } + + int tzSign = Integer.compare(tzTotalMinutes, 0); + tzTotalMinutes *= tzSign; + int tzH = tzTotalMinutes / 60; + int tzM = tzTotalMinutes - tzH * 60; + + normalizeToTimeZone(tzSign, tzH, tzM); + } + + + /** + * Adds a given duration to the date/time. + * + * @param duration the duration to add + */ + public void addGDuration(GDurationSpecification duration) { + addDuration(duration.getSign(), duration.getYear(), duration.getMonth(), duration.getDay(), + duration.getHour(), duration.getMinute(), duration.getSecond(), duration.getFraction()); + } + + /** + * Subtracts a given duration from the date/time. + * + * @param duration the duration to subtract + */ + public void subtractGDuration(GDurationSpecification duration) { + addDuration(-duration.getSign(), duration.getYear(), duration.getMonth(), duration.getDay(), + duration.getHour(), duration.getMinute(), duration.getSecond(), duration.getFraction()); + } + + + /** + * Normalizes the date by carrying over to the year any months outside 1..12 + * and carrying over to the month any days outside 1..(days-in-month). + */ + private void _normalizeDate() { + if (_M < 1 || _M > 12 || _D < 1 || _D > _maxDayInMonthFor(_CY, _M)) { + // fix months first + int temp = _M; + _M = _modulo(temp, 1, 13); + _CY = _CY + (int) _fQuotient(temp, 1, 13); + + // then pull days out + int extradays = _D - 1; + _D = 1; + + // then use the julian date function to fix + setJulianDate(getJulianDate() + extradays); + } + } + + /** + * Normalizes time so that fractions are 0..1(exc), seconds/minutes 0..59, + * and hours 0..24. Returns the number of days to carry over from normalizing + * away more than 24 hours. + */ + private long _normalizeTime() { + long carry = 0; + long temp; + + // fractions + if (_fs != null && (_fs.signum() < 0 || _fs.compareTo(GDate._one) >= 0)) { + BigDecimal bdcarry = _fs.setScale(0, RoundingMode.FLOOR); + _fs = _fs.subtract(bdcarry); + carry = bdcarry.longValue(); + } + + if (carry != 0 || _s < 0 || _s > 59 || _m < 0 || _m > 50 || _h < 0 || _h > 23) { + // seconds + temp = _s + carry; + carry = _fQuotient(temp, 60); + _s = _mod(temp, 60, carry); + + // minutes + temp = _m + carry; + carry = _fQuotient(temp, 60); + _m = _mod(temp, 60, carry); + + // hours + temp = _h + carry; + carry = _fQuotient(temp, 24); + _h = _mod(temp, 24, carry); + } + + return carry; + } + + /** + * Adds a given duration to the date/time. + * + * @param sign +1 to add, -1 to subtract + * @param year the number of years to add + * @param month the number of months to add + * @param day the number of days to add + * @param hour the number of hours to add + * @param minute the number of minutes to add + * @param second the number of seconds to add + * @param fraction the number of fractional seconds to add (may be null) + */ + public void addDuration(int sign, int year, int month, int day, + int hour, int minute, int second, BigDecimal fraction) { + boolean timemath = hour != 0 || minute != 0 || second != 0 || fraction != null && fraction.signum() != 0; + if (timemath && !hasTime()) { + throw new IllegalStateException("cannot do time math without a complete time"); + } + boolean datemath = hasDay() && (day != 0 || timemath); + if (datemath && !hasDate()) { + throw new IllegalStateException("cannot do date math without a complete date"); + } + + int temp; + + // months + years are easy + if (month != 0 || year != 0) { + // Prepare the _D to be pegged before changing month + if (hasDay()) { + _normalizeDate(); + } + + // Add months and years + temp = _M + sign * month; + _M = _modulo(temp, 1, 13); + _CY = _CY + sign * year + (int) _fQuotient(temp, 1, 13); + + // In new month, day may need to be pegged before proceeding + if (hasDay()) { + assert (_D >= 1); + temp = _maxDayInMonthFor(_CY, _M); + if (_D > temp) { + _D = temp; + } + } + } + + long carry = 0; + + if (timemath) { + // fractions + if (fraction != null && fraction.signum() != 0) { + if (_fs.signum() == 0 && sign == 1) { + _fs = fraction; + } else { + _fs = (sign == 1) ? _fs.add(fraction) : _fs.subtract(fraction); + } + } + + // seconds, minutes, hours + _s += sign * second; + _m += sign * minute; + _h += sign * hour; + + // normalize time + carry = _normalizeTime(); + } + + if (datemath) { + // days: may require renormalization + _D += sign * day + carry; + _normalizeDate(); + } + } + + /** + * Given {year,month} computes maximum + * number of days for given month + */ + private static int _maxDayInMonthFor(int year, int month) { + if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } + + if (month == 2) { + return (_isLeapYear(year) ? 29 : 28); + } + + return 31; + } + + /** + * Given {year,month} computes maximum + * number of days for given month + */ + private static int _maxDayInMonth(int month) { + if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } + + if (month == 2) { + return 29; + } + + return 31; + } + + /** + * Returns the Julian date corresponding to this Gregorian date. + * The Julian date (JD) is a continuous count of days from + * 1 January 4713 BC. + */ + public final int getJulianDate() { + return julianDateForGDate(this); + } + + + /** + * Sets the Gregorian date based on the given Julian date. + * The Julian date (JD) is a continuous count of days from + * 1 January 4713 BC. + * + * @param julianday the julian day number + */ + public void setJulianDate(int julianday) { + if (julianday < 0) { + throw new IllegalArgumentException("date before year -4713"); + } + + int temp; + int qepoc; + + // from http://aa.usno.navy.mil/faq/docs/JD_Formula.html + temp = julianday + 68569; + qepoc = 4 * temp / 146097; + temp = temp - (146097 * qepoc + 3) / 4; + _CY = 4000 * (temp + 1) / 1461001; + temp = temp - 1461 * _CY / 4 + 31; + _M = 80 * temp / 2447; + _D = temp - 2447 * _M / 80; + temp = _M / 11; + _M = _M + 2 - 12 * temp; + _CY = 100 * (qepoc - 49) + _CY + temp; + + _bits |= HAS_DAY | HAS_MONTH | HAS_YEAR; + } + + + /** + * Sets the current time and date based on a java.util.Date instance. + *

+ * The timezone offset used is based on the default TimeZone. (The + * default TimeZone is consulted to incorporate daylight savings offsets + * if applicable for the current date as well as the base timezone offset.) + *

+ * If you wish to normalize the timezone, e.g., to UTC, follow this with + * a call to normalizeToTimeZone. + * + * @param date the Date object to copy + */ + public void setDate(Date date) { + // Default timezone + TimeZone dtz = TimeZone.getDefault(); + int offset = dtz.getOffset(date.getTime()); + int offsetsign = 1; + if (offset < 0) { + offsetsign = -1; + offset = -offset; + } + int offsetmin = offset / (1000 * 60); + int offsethr = offsetmin / 60; + offsetmin = offsetmin - offsethr * 60; + + setTimeZone(offsetsign, offsethr, offsetmin); + + // paranoia: tz.getOffset can return fractions of minutes, but we must round + int roundedoffset = offsetsign * (offsethr * 60 + offsetmin) * 60 * 1000; + + // midnight + setTime(0, 0, 0, GDate._zero); + + // Set to January 1, 1970. + // setJulianDate(2440588); + _bits |= HAS_DAY | HAS_MONTH | HAS_YEAR; + _CY = 1970; + _M = 1; + _D = 1; + + // Add a duration representing the number of milliseconds + addGDuration(new GDuration(1, 0, 0, 0, 0, 0, 0, + BigDecimal.valueOf(date.getTime() + roundedoffset, 3))); + + // special case: ss.000 -> ss + if (_fs.signum() == 0) { + _fs = GDate._zero; + } + } + + /** + * Copies a GDateSpecification, completely replacing the current + * information in this GDateBuilder. + * + * @param gdate the GDateSpecification to copy + */ + public void setGDate(GDateSpecification gdate) { + _bits = gdate.getFlags() & (HAS_TIMEZONE | HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME); + int year = gdate.getYear(); + _CY = (year > 0 ? year : year + 1); + _M = gdate.getMonth(); + _D = gdate.getDay(); + _h = gdate.getHour(); + _m = gdate.getMinute(); + _s = gdate.getSecond(); + _fs = gdate.getFraction(); + _tzsign = gdate.getTimeZoneSign(); + _tzh = gdate.getTimeZoneHour(); + _tzm = gdate.getTimeZoneMinute(); + } + + + /** + * Retrieves the value of the current time as an {@link XmlCalendar}. + *

+ * {@link XmlCalendar} is a subclass of {@link java.util.GregorianCalendar} + * which is slightly customized to match XML schema date rules. + *

+ * The returned {@link XmlCalendar} has only those time and date fields + * set that are reflected in the GDate object. Because of the way the + * {@link java.util.Calendar} contract works, any information in the isSet() vanishes + * as soon as you view any unset field using get() methods. + * This means that if it is important to understand which date fields + * are set, you must call isSet() first before get(). + */ + public XmlCalendar getCalendar() { + return new XmlCalendar(this); + } + + /** + * Retrieves the value of the current time as a java.util.Date + * instance. + */ + public Date getDate() { + return dateForGDate(this); + } + + /* package */ + static int julianDateForGDate(GDateSpecification date) { + if (!date.hasDate()) { + throw new IllegalStateException("cannot do date math without a complete date"); + } + + // from http://aa.usno.navy.mil/faq/docs/JD_Formula.html + int day = date.getDay(); + int month = date.getMonth(); + int year = date.getYear(); + year = (year > 0 ? year : year + 1); + int result = day - 32075 + 1461 * (year + 4800 + (month - 14) / 12) / 4 + + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4; + + if (result < 0) { + throw new IllegalStateException("date too far in the past (year allowed to -4713)"); + } + + return result; + } + + /* package */ + static Date dateForGDate(GDateSpecification date) { + long jDate = julianDateForGDate(date); + long to1970Date = jDate - 2440588; + long to1970Ms = 1000 * 60 * 60 * 24 * to1970Date; + + to1970Ms += date.getMillisecond(); + to1970Ms += date.getSecond() * 1000; + to1970Ms += date.getMinute() * 60 * 1000; + to1970Ms += date.getHour() * 60 * 60 * 1000; + if (date.hasTimeZone()) { + to1970Ms -= (date.getTimeZoneMinute() * date.getTimeZoneSign()) * 60 * 1000; + to1970Ms -= (date.getTimeZoneHour() * date.getTimeZoneSign()) * 60 * 60 * 1000; + } else { + TimeZone def = TimeZone.getDefault(); + int offset = def.getOffset(to1970Ms); + to1970Ms -= offset; + } + + return new Date(to1970Ms); + } + + /** + * True for leap years. + */ + private static boolean _isLeapYear(int year) { + // BUGBUG: Julian calendar? + return ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))); + } + + /** + * fQuotient(a, b) = the greatest integer less than or equal to a/b + */ + private static long _fQuotient(long a, int b) { + if ((a < 0) == (b < 0)) { + return a / b; + } + + return -((b - a - 1) / b); + } + + /** + * modulo(a, b) = a - fQuotient(a,b)*b + */ + private static int _mod(long a, int b, long quotient) { + return (int) (a - quotient * b); + } + + /** + * modulo(a - low, high - low) + low + */ + private static int _modulo(long temp, int low, int high) { + long a = temp - low; + int b = high - low; + return (_mod(a, b, _fQuotient(a, b)) + low); + } + + /** + * Quotient(a - low, high - low) + */ + private static long _fQuotient(long temp, int low, int high) { + return _fQuotient(temp - low, high - low); + } + + /** + * Sets to the first possible moment that matches the given + * specification. + */ + private void _setToFirstMoment() { + // 1584 was the first leap year during which the Gregorian + // calendar was in use: seems like the most reasonable "first" + // year to use in absence of a year. + + if (!hasYear()) { + setYear(1584); + } + + if (!hasMonth()) { + setMonth(1); + } + + if (!hasDay()) { + setDay(1); + } + + if (!hasTime()) { + setTime(0, 0, 0, GDate._zero); + } + } + + /** + * Comparison to another GDate. + *

    + *
  • Returns -1 if this < date. (less-than) + *
  • Returns 0 if this == date. (equal) + *
  • Returns 1 if this > date. (greater-than) + *
  • Returns 2 if this <> date. (incomparable) + *
+ * Two instances are incomparable if they have different amounts + * of information. + * + * @param datespec the date to compare against + */ + public final int compareToGDate(GDateSpecification datespec) { + return compareGDate(this, datespec); + } + + + /* package */ + static int compareGDate(GDateSpecification tdate, GDateSpecification datespec) { + // same amount of information: looks good + int bitdiff = tdate.getFlags() ^ datespec.getFlags(); + + if ((bitdiff & (HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME | HAS_TIMEZONE)) == 0) { + // If the other date needs to be normalized to + // our timezone, make a clone and do so if possible + if (tdate.hasTimeZone() && + (datespec.getTimeZoneHour() != tdate.getTimeZoneHour() || + datespec.getTimeZoneMinute() != tdate.getTimeZoneMinute() || + datespec.getTimeZoneSign() != tdate.getTimeZoneSign())) { + datespec = new GDateBuilder(datespec); + + int flags = tdate.getFlags() & (HAS_YEAR | HAS_MONTH | HAS_DAY); + if (flags != 0 && flags != (HAS_YEAR | HAS_MONTH | HAS_DAY) || !tdate.hasTime()) { + // in these cases we'll need to fill in fields + ((GDateBuilder) datespec)._setToFirstMoment(); + tdate = new GDateBuilder(tdate); + ((GDateBuilder) tdate)._setToFirstMoment(); + } + + ((GDateBuilder) datespec).normalizeToTimeZone(tdate.getTimeZoneSign(), tdate.getTimeZoneHour(), tdate.getTimeZoneMinute()); + } + + // compare by field + return fieldwiseCompare(tdate, datespec); + } + + // different amounts of information (except timezone): not comparable + if ((bitdiff & (HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME)) != 0) { + return 2; + } + + // The schema spec says we should try to compare with-timezone and + // without-timezone specifications... Well, OK, sure, if they say so. + + // We don't have a timezone but the other does: reverse the call + if (!tdate.hasTimeZone()) { + int result = compareGDate(datespec, tdate); + return result == 2 ? 2 : -result; + } + + // Now tdate is guaranteed to have a timezone and datespec not. + + // To muck with the times, make clones + GDateBuilder pdate = new GDateBuilder(tdate); + + // To cover the one uncovered case: if one date is 02/28 and the + // other date is 03/01, shift days closer by one to simulate being + // the last day of the month within a leap year + if ((tdate.getFlags() & (HAS_YEAR | HAS_MONTH | HAS_DAY)) == (HAS_MONTH | HAS_DAY)) { + if (tdate.getDay() == 28 && tdate.getMonth() == 2) { + if (datespec.getDay() == 1 && datespec.getMonth() == 3) { + pdate.setDay(29); + } + } else if (datespec.getDay() == 28 && datespec.getMonth() == 2) { + if (tdate.getDay() == 1 && tdate.getMonth() == 3) { + pdate.setMonth(2); + pdate.setDay(29); + } + } + } + + // For timespans, compare by first instant of time + // possible. Therefore, fill in Midnight, January 1, 1584 (a leap year) + // in absence of other information. + pdate._setToFirstMoment(); + + // P < Q if P < (Q with time zone +14:00) + GDateBuilder qplusdate = new GDateBuilder(datespec); + qplusdate._setToFirstMoment(); + qplusdate.setTimeZone(1, 14, 0); + qplusdate.normalizeToTimeZone(tdate.getTimeZoneSign(), tdate.getTimeZoneHour(), tdate.getTimeZoneMinute()); + if (fieldwiseCompare(pdate, qplusdate) == -1) { + return -1; + } + + // P > Q if P > (Q with time zone -14:00) + GDateBuilder qminusdate = qplusdate; + qminusdate.setGDate(datespec); + qminusdate._setToFirstMoment(); + qminusdate.setTimeZone(-1, 14, 0); + qminusdate.normalizeToTimeZone(tdate.getTimeZoneSign(), tdate.getTimeZoneHour(), tdate.getTimeZoneMinute()); + if (fieldwiseCompare(pdate, qminusdate) == 1) { + return 1; + } + + // P <> Q otherwise + return 2; + } + + /** + * Does a simple most-significant-digit-first comparison, + * ignoring any timezone or has/doesn't have issues. + * The data must have been digested first. + */ + private static int fieldwiseCompare(GDateSpecification tdate, GDateSpecification date) { + if (tdate.hasYear()) { + int CY = date.getYear(); + int TCY = tdate.getYear(); + if (TCY < CY) { + return -1; + } + if (TCY > CY) { + return 1; + } + } + if (tdate.hasMonth()) { + int M = date.getMonth(); + int TM = tdate.getMonth(); + if (TM < M) { + return -1; + } + if (TM > M) { + return 1; + } + } + if (tdate.hasDay()) { + int D = date.getDay(); + int TD = tdate.getDay(); + if (TD < D) { + return -1; + } + if (TD > D) { + return 1; + } + } + if (tdate.hasTime()) { + int h = date.getHour(); + int th = tdate.getHour(); + if (th < h) { + return -1; + } + if (th > h) { + return 1; + } + int m = date.getMinute(); + int tm = tdate.getMinute(); + if (tm < m) { + return -1; + } + if (tm > m) { + return 1; + } + int s = date.getSecond(); + int ts = tdate.getSecond(); + if (ts < s) { + return -1; + } + if (ts > s) { + return 1; + } + BigDecimal fs = date.getFraction(); + BigDecimal tfs = tdate.getFraction(); + if (tfs == null && fs == null) { + return 0; + } + return (tfs == null ? GDate._zero : tfs).compareTo(fs == null ? GDate._zero : fs); + } + + return 0; + } + + /** + * Returns the builtin type code for the shape of the information + * contained in this instance, or 0 if the + * instance doesn't contain information corresponding to a + * Schema type. + *

+ * Value will be equal to + * {@link SchemaType#BTC_NOT_BUILTIN}, + * {@link SchemaType#BTC_G_YEAR}, + * {@link SchemaType#BTC_G_YEAR_MONTH}, + * {@link SchemaType#BTC_G_MONTH}, + * {@link SchemaType#BTC_G_MONTH_DAY}, + * {@link SchemaType#BTC_G_DAY}, + * {@link SchemaType#BTC_DATE}, + * {@link SchemaType#BTC_DATE_TIME}, or + * {@link SchemaType#BTC_TIME}. + */ + public final int getBuiltinTypeCode() { + return btcForFlags(_bits); + } + + /* package */ + static int btcForFlags(int flags) { + switch (flags & (HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME)) { + case HAS_YEAR: + return SchemaType.BTC_G_YEAR; + case HAS_YEAR | HAS_MONTH: + return SchemaType.BTC_G_YEAR_MONTH; + case HAS_MONTH: + return SchemaType.BTC_G_MONTH; + case HAS_MONTH | HAS_DAY: + return SchemaType.BTC_G_MONTH_DAY; + case HAS_DAY: + return SchemaType.BTC_G_DAY; + case HAS_YEAR | HAS_MONTH | HAS_DAY: + return SchemaType.BTC_DATE; + case HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME: + return SchemaType.BTC_DATE_TIME; + case HAS_TIME: + return SchemaType.BTC_TIME; + default: + return SchemaType.BTC_NOT_BUILTIN; + } + } + + /** + * Clears the fields in this GDateBuilder that are not applicable + * for the given SchemaType date code. The code should be + * {@link SchemaType#BTC_G_YEAR}, + * {@link SchemaType#BTC_G_YEAR_MONTH}, + * {@link SchemaType#BTC_G_MONTH}, + * {@link SchemaType#BTC_G_MONTH_DAY}, + * {@link SchemaType#BTC_G_DAY}, + * {@link SchemaType#BTC_DATE}, + * {@link SchemaType#BTC_DATE_TIME}, or + * {@link SchemaType#BTC_TIME}. + * + * @param typeCode the type code to apply + */ + public void setBuiltinTypeCode(int typeCode) { + switch (typeCode) { + case SchemaType.BTC_G_YEAR: + //HAS_YEAR + clearMonth(); + clearDay(); + clearTime(); + return; + case SchemaType.BTC_G_YEAR_MONTH: + //HAS_YEAR | HAS_MONTH + clearDay(); + clearTime(); + return; + case SchemaType.BTC_G_MONTH: + //HAS_MONTH + clearYear(); + clearDay(); + clearTime(); + return; + case SchemaType.BTC_G_MONTH_DAY: + //HAS_MONTH | HAS_DAY + clearYear(); + clearTime(); + return; + case SchemaType.BTC_G_DAY: + //HAS_DAY + clearYear(); + clearMonth(); + clearTime(); + return; + case SchemaType.BTC_DATE: + //HAS_YEAR | HAS_MONTH | HAS_DAY + clearTime(); + return; + case SchemaType.BTC_DATE_TIME: + //HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME + return; + case SchemaType.BTC_TIME: + //HAS_TIME + clearYear(); + clearMonth(); + clearDay(); + return; + default: + throw new IllegalArgumentException("codeType must be one of SchemaType BTC_ DATE TIME related types."); + } + } + + + /* package */ static final BigInteger TEN = BigInteger.valueOf(10); + + /** + * The canonical string representation. Specific moments or + * times-of-day in a specified timezone are normalized to + * UTC time to produce a canonical string form for them. + * Other recurring time specifications keep their timezone + * information. + */ + public String canonicalString() { + boolean needNormalize = + (hasTimeZone() && getTimeZoneSign() != 0 && hasTime() && + ((hasDay() == hasMonth() && hasDay() == hasYear()))); + + if (!needNormalize && getFraction() != null && getFraction().scale() > 0) { + BigInteger bi = getFraction().unscaledValue(); + needNormalize = (bi.mod(TEN).signum() == 0); + } + + if (!needNormalize) { + return toString(); + } + + GDateBuilder cdate = new GDateBuilder(this); + cdate.normalize(); + return cdate.toString(); + } + + /** + * The natural string representation. This represents the information + * that is available, including timezone. For types that correspond + * to defined schema types (schemaBuiltinTypeCode() > 0), + * this provides the natural lexical representation. + *

+ * When both time and timezone are specified, this string is not + * the canonical representation unless the timezone is UTC (Z) + * (since the same moment in time can be expressed in different + * timezones). To get a canonical string, use the canonicalString() + * method. + */ + public final String toString() { + return GDate.formatGDate(this); + } + +} diff --git a/src/xmlpublic/org/apache/xmlbeans/GDateSpecification.java b/src/main/java/org/apache/xmlbeans/GDateSpecification.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/GDateSpecification.java rename to src/main/java/org/apache/xmlbeans/GDateSpecification.java diff --git a/src/xmlpublic/org/apache/xmlbeans/GDuration.java b/src/main/java/org/apache/xmlbeans/GDuration.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/GDuration.java rename to src/main/java/org/apache/xmlbeans/GDuration.java diff --git a/src/main/java/org/apache/xmlbeans/GDurationBuilder.java b/src/main/java/org/apache/xmlbeans/GDurationBuilder.java new file mode 100644 index 0000000..83c304f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/GDurationBuilder.java @@ -0,0 +1,662 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; + +/** + * Used to build {@link GDuration GDurations}. + */ +public class GDurationBuilder implements GDurationSpecification, java.io.Serializable { + private static final long serialVersionUID = 1L; + + private int _sign; + private int _CY; + private int _M; + private int _D; + private int _h; + private int _m; + private int _s; + private BigDecimal _fs; + + /** + * Constructs an empty GDurationBuilder representing zero seconds. + */ + public GDurationBuilder() { + _sign = +1; + _fs = GDate._zero; + } + + /** + * Constructs a GDuration from a lexical + * representation. + */ + public GDurationBuilder(String s) { + this(new GDuration(s)); + } + + /** + * Constructs a GDurationBuilder with the specified sign, + * year, month, day, hours, minutes, seconds, and optional + * fractional seconds. + * + * @param sign +1 for a positive duration, -1 for a negative duration + * @throws java.lang.IllegalArgumentException if the sign is not 1 or -1 + */ + public GDurationBuilder( + int sign, + int year, + int month, + int day, + int hour, + int minute, + int second, + BigDecimal fraction) { + if (sign != 1 && sign != -1) { + throw new IllegalArgumentException(); + } + _sign = sign; + _CY = year; + _M = month; + _D = day; + _h = hour; + _m = minute; + _s = second; + _fs = fraction == null ? GDate._zero : fraction; + } + + /** + * Constructs a GDurationBuilder from another GDurationBuilderSpecification. + */ + public GDurationBuilder(GDurationSpecification gDuration) { + _sign = gDuration.getSign(); + _CY = gDuration.getYear(); + _M = gDuration.getMonth(); + _D = gDuration.getDay(); + _h = gDuration.getHour(); + _m = gDuration.getMinute(); + _s = gDuration.getSecond(); + _fs = gDuration.getFraction(); + } + + /** + * Builds another GDurationBuilder with the same value + * as this one. + */ + public Object clone() { + return new GDurationBuilder(this); + } + + /** + * Builds a GDuration from this GDurationBuilder. + */ + public GDuration toGDuration() { + return new GDuration(this); + } + + /** + * Adds to this duration. Does a fieldwise add, with no + * normalization. + */ + public void addGDuration(GDurationSpecification duration) { + int sign = _sign * duration.getSign(); + _add(duration, sign); + } + + /** + * Subtracts from this duration. Does a fieldwise subtraction, + * with no normalization. + */ + public void subtractGDuration(GDurationSpecification duration) { + int sign = -_sign * duration.getSign(); + _add(duration, sign); + } + + private void _add(GDurationSpecification duration, int sign) { + _CY += sign * duration.getYear(); + _M += sign * duration.getMonth(); + _D += sign * duration.getDay(); + _h += sign * duration.getHour(); + _m += sign * duration.getMinute(); + _s += sign * duration.getSecond(); + + if (duration.getFraction().signum() == 0) { + return; + } + + if (_fs.signum() == 0 && sign == 1) { + _fs = duration.getFraction(); + } else { + _fs = sign > 0 ? + _fs.add(duration.getFraction()) : + _fs.subtract(duration.getFraction()); + } + } + + /** + * Sets the sign. + */ + public final void setSign(int sign) { + if (sign != 1 && sign != -1) { + throw new IllegalArgumentException(); + } + _sign = sign; + } + + /** + * Sets the year component. + */ + public void setYear(int year) { + _CY = year; + } + + /** + * Sets the month component. + */ + public void setMonth(int month) { + _M = month; + } + + /** + * Sets the day component. + */ + public void setDay(int day) { + _D = day; + } + + /** + * Sets the hour component. + */ + public void setHour(int hour) { + _h = hour; + } + + /** + * Sets the minute component. + */ + public void setMinute(int minute) { + _m = minute; + } + + /** + * Sets the second component. + */ + public void setSecond(int second) { + _s = second; + } + + /** + * Sets the fraction-of-second component. + */ + public void setFraction(BigDecimal fraction) { + _fs = fraction == null ? GDate._zero : fraction; + } + + /** + * All GDuration instances return true. + */ + public final boolean isImmutable() { + return true; + } + + /** + * Returns the sign of the duration: +1 is forwards + * and -1 is backwards in time. + * This value does not necessarily reflect the + * true direction of the duration if the duration + * is not normalized or not normalizable. + */ + public final int getSign() { + return _sign; + } + + /** + * Gets the year component. + */ + public final int getYear() { + return _CY; + } + + /** + * Gets the month-of-year component. + */ + public final int getMonth() { + return _M; + } + + /** + * Gets the day-of-month component. + */ + public final int getDay() { + return _D; + } + + /** + * Gets the hour-of-day component. + */ + public final int getHour() { + return _h; + } + + /** + * Gets the minute-of-hour component. + */ + public final int getMinute() { + return _m; + } + + /** + * Gets the second-of-minute component. + */ + public final int getSecond() { + return _s; + } + + + /** + * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). + */ + public BigDecimal getFraction() { + return _fs; + } + + /** + * Returns true if all of the individual components + * of the duration are nonnegative. + */ + public boolean isValid() { + return GDurationBuilder.isValidDuration(this); + } + + + /** + * Normalize a duration value. This ensures that months, + * hours, minutes, seconds, and fractions are positive and + * within the ranges 0..11, 0..23, 0..59, etc. Negative + * durations are indicated by a negative sign rather + * than negative components. + *

+ * Most duration specifications can be normalized to + * valid durations with all positive components, but + * not all of them can. + *

+ * The only situations which cannot be normalized are + * where the year/month and the day/hour/minute/second + * offsets are of opposite sign. Days cannot be carried + * into months since the length of a Gregorian month is + * variable depending on when the duration is applied. + * In these cases, this method normalizes the components + * so that "day" is the only negative component. + */ + public void normalize() { + _normalizeImpl(true); + } + + /** + * fQuotient(a, b) = the greatest integer less than or equal to a/b + */ + private static long _fQuotient(long a, int b) { + if ((a < 0) == (b < 0)) { + return a / b; + } + + return -((b - a - 1) / b); + } + + /** + * modulo(a, b) = a - fQuotient(a,b)*b + */ + private static int _mod(long a, int b, long quotient) { + return (int) (a - quotient * b); + } + + + /** + * Private implemenation of normalize. The flag is + * to facilitate this method calling itself without + * danger of infinite recursion. + */ + private void _normalizeImpl(boolean adjustSign) { + long temp; + + // months to years + if (_M < 0 || _M > 11) { + temp = _M; + long ycarry = _fQuotient(temp, 12); + _M = _mod(temp, 12, ycarry); + _CY += ycarry; + } + + long carry = 0; + + // fractions to seconds + if (_fs != null && (_fs.signum() < 0 || _fs.compareTo(GDate._one) >= 0)) { + BigDecimal bdcarry = _fs.setScale(0, RoundingMode.FLOOR); + _fs = _fs.subtract(bdcarry); + carry = bdcarry.intValue(); + } + + if (carry != 0 || _s < 0 || _s > 59 || _m < 0 || _m > 50 || _h < 0 || _h > 23) { + // seconds + temp = _s + carry; + carry = _fQuotient(temp, 60); + _s = _mod(temp, 60, carry); + + // minutes + temp = _m + carry; + carry = _fQuotient(temp, 60); + _m = _mod(temp, 60, carry); + + // hours + temp = _h + carry; + carry = _fQuotient(temp, 24); + _h = _mod(temp, 24, carry); + _D += carry; + } + + if (_CY == 0 && _M == 0 && _D == 0 && _h == 0 && _m == 0 && _s == 0 && (_fs == null || _fs.signum() == 0)) { + _sign = 1; + } + + if (adjustSign && (_D < 0 || _CY < 0)) { + int sign = (_D <= 0 && (_CY < 0 || _CY == 0 && _M == 0)) ? -_sign : _getTotalSignSlowly(); + if (sign == 2) { + sign = (_CY < 0) ? -_sign : _sign; + } + if (sign == 0) { + sign = 1; + } + if (sign != _sign) { + _sign = sign; + _CY = -_CY; + _M = -_M; + _D = -_D; + _h = -_h; + _m = -_m; + _s = -_s; + if (_fs != null) { + _fs = _fs.negate(); + } + } + _normalizeImpl(false); + } + } + + + /* package */ + static boolean isValidDuration(GDurationSpecification spec) { + if (!(spec.getSign() == 1 || spec.getSign() == -1)) { + return false; + } + + return (spec.getYear() >= 0 && spec.getMonth() >= 0 && spec.getDay() >= 0 && + spec.getHour() >= 0 && spec.getMinute() >= 0 && spec.getSecond() >= 0 && + spec.getFraction().signum() >= 0); + } + + /** + * Comparison to another GDuration. + *

    + *
  • Returns -1 if this < duration. (less-than) + *
  • Returns 0 if this == duration. (equal) + *
  • Returns 1 if this > duration. (greater-than) + *
  • Returns 2 if this <> duration. (incomparable) + *
+ * Two instances are incomparable if they have different amounts + * of information. + */ + public final int compareToGDuration(GDurationSpecification duration) { + return GDurationBuilder.compareDurations(this, duration); + } + + /** + * The natural string representation of the duration. + *

+ * Any components that are zero are omitted. Note that if the duration + * is invalid, i.e., it has negative components, those negative + * components are serialized out here. To check for validity, use + * the isValid() method; and to normalize most durations to a valid + * form use the normalize() method. + */ + public String toString() { + return GDurationBuilder.formatDuration(this); + } + + /* package */ + static int compareDurations(GDurationSpecification d1, GDurationSpecification d2) { + // first do an all-fields check + if (d1.getFraction().signum() == 0 && d2.getFraction().signum() == 0) { + int s1 = d1.getSign(); + int s2 = d2.getSign(); + long month1 = s1 * ((long) d1.getYear() * 12 + d1.getMonth()); + long month2 = s2 * ((long) d2.getYear() * 12 + d2.getMonth()); + long sec1 = s1 * ((((long) d1.getDay() * 24 + d1.getHour()) * 60 + d1.getMinute()) * 60 + d1.getSecond()); + long sec2 = s2 * ((((long) d2.getDay() * 24 + d2.getHour()) * 60 + d2.getMinute()) * 60 + d2.getSecond()); + if (month1 == month2) { + if (sec1 == sec2) { + return 0; + } + return sec1 < sec2 ? -1 : 1; + } + if (month1 < month2 && sec1 - sec2 < 28 * 24 * 60 * 60) { + return -1; + } + if (month1 > month2 && sec2 - sec1 < 28 * 24 * 60 * 60) { + return 1; + } + } + + // the answer isn't obvious, so then do a total-sign check + GDurationBuilder diff = new GDurationBuilder(d1); + diff.subtractGDuration(d2); + return diff._getTotalSignSlowly(); + } + + /** + * Per schema spec, comparison of durations is simply done + * by calculating adding the duration to these four dates and + * comparing the results. If the results are ambiguous, the + * answer is "incomparable". + */ + private static final GDate[] _compDate = new GDate[] + { + new GDate(1696, 9, 1, 0, 0, 0, null, 0, 0, 0), + new GDate(1697, 2, 1, 0, 0, 0, null, 0, 0, 0), + new GDate(1903, 3, 1, 0, 0, 0, null, 0, 0, 0), + new GDate(1903, 7, 1, 0, 0, 0, null, 0, 0, 0) + }; + + + /** + * This returns the total sign of the duration, +1 + * if the duration moves forward in time, -1 if the + * duration moves backwards in time, 0 if the duration + * is zero-length, and 2 if the duration may be positive + * or negative depending on the date. + *

+ * (For example, one month minus 30 days is indeterminate). + */ + private int _getTotalSignSlowly() { + int pos = 0; + int neg = 0; + int zer = 0; + + GDateBuilder enddate = new GDateBuilder(); + for (GDate gDate : _compDate) { + enddate.setGDate(gDate); + enddate.addGDuration(this); + switch (enddate.compareToGDate(gDate)) { + case -1: + neg++; + break; + case 0: + zer++; + break; + case 1: + pos++; + break; + } + } + + if (pos == _compDate.length) { + return +1; + } + if (neg == _compDate.length) { + return -1; + } + if (zer == _compDate.length) { + return 0; + } + return 2; + } + + /* package */ + static String formatDuration(GDurationSpecification duration) { + // Sign+P: (-)?P + // Year: (?:(\d+)Y)? + // Month: (?:(\d+)M)? + // Day: (?:(\d+)D)? + // Time: (?:(T) + // Hours: (?:(\d+)H)? + // Minutes: (?:(\d+)M)? + // Seconds: (?:(\d+(?:\.\d*)?|(?:.\d+)S)? + + StringBuilder message = new StringBuilder(30); + + if (duration.getSign() < 0) { + message.append('-'); + } + + message.append('P'); + + if (duration.getYear() != 0) { + message.append(duration.getYear()); + message.append('Y'); + } + + if (duration.getMonth() != 0) { + message.append(duration.getMonth()); + message.append('M'); + } + + if (duration.getDay() != 0) { + message.append(duration.getDay()); + message.append('D'); + } + + if (duration.getHour() != 0 || duration.getMinute() != 0 || duration.getSecond() != 0 || + (duration.getFraction().signum() != 0)) { + message.append('T'); + } + + if (duration.getHour() != 0) { + message.append(duration.getHour()); + message.append('H'); + } + + if (duration.getMinute() != 0) { + message.append(duration.getMinute()); + message.append('M'); + } + + if (duration.getFraction().signum() != 0) { + BigDecimal s = duration.getFraction(); + if (duration.getSecond() != 0) { + s = s.add(BigDecimal.valueOf(duration.getSecond())); + } + // todo when upgrade to 1.5 message.append(s.stripTrailingZeros().toPlainString()); + message.append(stripTrailingZeros(toPlainString(s))); + message.append('S'); + } else if (duration.getSecond() != 0) { + message.append(duration.getSecond()); + message.append('S'); + } else if (message.length() <= 2) + // Specify zero seconds if everything was 0 + { + message.append("T0S"); + } + + return message.toString(); + } + + public static String toPlainString(BigDecimal bd) { + BigInteger intVal = bd.unscaledValue(); + int scale = bd.scale(); + String intValStr = intVal.toString(); + if (scale == 0) { + return intValStr; + } + + boolean isNegative = (intValStr.charAt(0) == '-'); + + int point = intValStr.length() - scale - (isNegative ? 1 : 0); + + StringBuilder sb = new StringBuilder(intValStr.length() + 2 + (point <= 0 ? (-point + 1) : 0)); + if (point <= 0) { + // prepend zeros and a decimal point. + if (isNegative) { + sb.append('-'); + } + sb.append('0').append('.'); + while (point < 0) { + sb.append('0'); + point++; + } + sb.append(intValStr.substring(isNegative ? 1 : 0)); + } else if (point < intValStr.length()) { + // No zeros needed + sb.append(intValStr); + sb.insert(point + (isNegative ? 1 : 0), '.'); + } else { + // append zeros if not 0 + sb.append(intValStr); + if (!intVal.equals(BigInteger.ZERO)) { + for (int i = intValStr.length(); i < point; i++) { + sb.append('0'); + } + } + } + return sb.toString(); + } + + public static String stripTrailingZeros(String s) { + boolean seenDot = false; + int i = s.length() - 1; + int zeroIndex = i; + + while (i >= 0) { + if (s.charAt(i) != '0') { + break; + } + i--; + zeroIndex--; + } + while (i >= 0) { + if (s.charAt(i) == 'E') { + return s; + } + if (s.charAt(i) == '.') { + seenDot = true; + break; + } + i--; + } + + return seenDot ? s.substring(0, zeroIndex + 1) : s; + } +} diff --git a/src/xmlpublic/org/apache/xmlbeans/GDurationSpecification.java b/src/main/java/org/apache/xmlbeans/GDurationSpecification.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/GDurationSpecification.java rename to src/main/java/org/apache/xmlbeans/GDurationSpecification.java diff --git a/src/xmlpublic/org/apache/xmlbeans/InterfaceExtension.java b/src/main/java/org/apache/xmlbeans/InterfaceExtension.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/InterfaceExtension.java rename to src/main/java/org/apache/xmlbeans/InterfaceExtension.java diff --git a/src/xmlpublic/org/apache/xmlbeans/ObjectFactory.java b/src/main/java/org/apache/xmlbeans/ObjectFactory.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/ObjectFactory.java rename to src/main/java/org/apache/xmlbeans/ObjectFactory.java diff --git a/src/xmlpublic/org/apache/xmlbeans/PrePostExtension.java b/src/main/java/org/apache/xmlbeans/PrePostExtension.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/PrePostExtension.java rename to src/main/java/org/apache/xmlbeans/PrePostExtension.java diff --git a/src/xmlpublic/org/apache/xmlbeans/QNameCache.java b/src/main/java/org/apache/xmlbeans/QNameCache.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/QNameCache.java rename to src/main/java/org/apache/xmlbeans/QNameCache.java diff --git a/src/main/java/org/apache/xmlbeans/QNameSet.java b/src/main/java/org/apache/xmlbeans/QNameSet.java new file mode 100644 index 0000000..f58c3f4 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/QNameSet.java @@ -0,0 +1,436 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.namespace.QName; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * This interface represents a lattice of finite and infinite sets of QNames. + * The lattice the minimal one that is closed under union, intersection, and + * inverse, and contains individual QNames as well as entire namespaces. + * Here is a summary of the two kinds of QNameSets: + *

    + *
  • A QNameSet can cover a finite set of namespaces, additionally including a finite + * set of QNames outside those namespaces, and with the exception of + * a finite set of QNames excluded from those namespaes: + *
      + *
    • excludedQNamesInIncludedURIs == the set of excluded QNames from coveredURIs namespaces + *
    • excludedURIs == null + *
    • includedURIs == the set of covered namespace URIs + *
    • includedQNamesInExcludedURIs == set of additional QNames outside coveredURIs namespaces + *
    + *
  • + *
  • A QNameSet can cover all namespaces except for a finite number of excluded ones, + * additionally including a finite set of QNames within the excluded namespaces, + * and with the exception of a finite set of QNames outside the excluded namespaces: + *
      + *
    • excludedQNamesInIncludedURIs == the set of excluded QNames outside uncoveredURIs namespaces + *
    • excludedURIs == the set of uncovered namespace URIs + *
    • includedURIs == null + *
    • includedQNamesInExcludedURIs == set of additional QNames from uncoveredURIs namespaces + *
    + *
  • + *
+ *

+ * Notice that a finite set of QNames is a degenerate case of the first + * category outlined above: + *

    + *
  • A QnameSet can contain a finite number of QNames: + *
      + *
    • excludedQNamesInIncludedURIs == empty set + *
    • excludedURIs == null + *
    • includedURIs == empty set + *
    • includedQNamesInExcludedURIs == set of included QNames + *
    + *
  • + *
+ * + * @see QNameSetBuilder + */ +public final class QNameSet implements QNameSetSpecification, java.io.Serializable { + private static final long serialVersionUID = 1L; + + private final boolean _inverted; + private final Set _includedURIs; + private final Set _excludedQNames; + private final Set _includedQNames; + + /** + * The empty QNameSet. + */ + public static final QNameSet EMPTY = new QNameSet(null, Collections.emptySet(), Collections.emptySet(), Collections.emptySet()); + + /** + * The QNameSet containing all QNames. + */ + public static final QNameSet ALL = new QNameSet(Collections.emptySet(), null, Collections.emptySet(), Collections.emptySet()); + + /** + * The QNameSet containing all QNames in the local (no-)namespace. + */ + public static final QNameSet LOCAL = new QNameSet(null, Collections.singleton(""), Collections.emptySet(), Collections.emptySet()); + + /** + * The QNameSet containing all QNames except for those in the local (no-)namespace. + */ + public static final QNameSet NONLOCAL = new QNameSet(Collections.singleton(""), null, Collections.emptySet(), Collections.emptySet()); + + /** + * Private function to minimize object creation when copying sets. + */ + private static Set minSetCopy(Set original) { + if (original == null) { + return null; + } + if (original.isEmpty()) { + return Collections.emptySet(); + } + if (original.size() == 1) { + return Collections.singleton(original.iterator().next()); + } + return new HashSet<>(original); + } + + /** + * Returns a QNameSet based on the given sets of excluded URIs, + * included URIs, excluded QNames in included namespaces, and included + * QNames in excluded namespaces. + * + * @param excludedURIs the finite set of namespace URI strings to exclude from the set, or null if this set is infinite + * @param includedURIs the finite set of namespace URI strings to include in the set, or null if this set is infinite + * @param excludedQNamesInIncludedURIs the finite set of exceptional QNames to exclude from the included namespaces + * @param includedQNamesInExcludedURIs the finite set of exceptional QNames to include that are in the excluded namespaces + * @return the constructed QNameSet + */ + public static QNameSet forSets(Set excludedURIs, Set includedURIs, Set excludedQNamesInIncludedURIs, Set includedQNamesInExcludedURIs) { + if ((excludedURIs != null) == (includedURIs != null)) { + throw new IllegalArgumentException("Exactly one of excludedURIs and includedURIs must be null"); + } + + if (excludedURIs == null && includedURIs.isEmpty() && includedQNamesInExcludedURIs.isEmpty()) { + return EMPTY; + } + if (includedURIs == null && excludedURIs.isEmpty() && excludedQNamesInIncludedURIs.isEmpty()) { + return ALL; + } + if (excludedURIs == null && includedURIs.size() == 1 && includedURIs.contains("") && + includedQNamesInExcludedURIs.isEmpty() && excludedQNamesInIncludedURIs.isEmpty()) { + return LOCAL; + } + if (includedURIs == null && excludedURIs.size() == 1 && excludedURIs.contains("") && + excludedQNamesInIncludedURIs.isEmpty() && includedQNamesInExcludedURIs.isEmpty()) { + return NONLOCAL; + } + + return new QNameSet( + minSetCopy(excludedURIs), + minSetCopy(includedURIs), + minSetCopy(excludedQNamesInIncludedURIs), + minSetCopy(includedQNamesInExcludedURIs)); + } + + /** + * Returns a QNameSet based on the given array of included QNames + * + * @param includedQNames the array of included QNames + */ + public static QNameSet forArray(QName[] includedQNames) { + if (includedQNames == null) { + throw new IllegalArgumentException("includedQNames cannot be null"); + } + + return new QNameSet(null, Collections.emptySet(), Collections.emptySet(), new HashSet<>(Arrays.asList(includedQNames))); + } + + /** + * Returns a QNameSet with the same contents as the given + * QNameSetSpecification. + * + * @return the copied QNameSet + */ + public static QNameSet forSpecification(QNameSetSpecification spec) { + if (spec instanceof QNameSet) { + return (QNameSet) spec; + } + return QNameSet.forSets(spec.excludedURIs(), spec.includedURIs(), spec.excludedQNamesInIncludedURIs(), spec.includedQNamesInExcludedURIs()); + } + + /** + * Returns a QNameSet corresponding to the given wildcard namespace string. + * This is a space-separated list of URIs, plus special tokens as specified + * in the XML Schema specification (##any, ##other, ##targetNamespace, ##local). + * + * @return the constructed QNameSet + */ + public static QNameSet forWildcardNamespaceString(String wildcard, String targetURI) { + return QNameSet.forSpecification(new QNameSetBuilder(wildcard, targetURI)); + } + + /** + * Returns a QNameSet containing only the given QName. + * + * @return the constructed QNameSet + */ + public static QNameSet singleton(QName name) { + return new QNameSet(null, Collections.emptySet(), Collections.emptySet(), Collections.singleton(name)); + } + + /** + * Constructs a QNameSetBuilder whose contents are given by + * the four sets. + *

+ * This constuctor is PRIVATE because it uses the given + * sets directly, and it trusts its callers to set only immutable values. + * This constructor is is only called by the static builder methods on + * QNameSet: those methods are all careful assign only unchanging sets. + */ + private QNameSet(Set excludedURIs, Set includedURIs, Set excludedQNamesInIncludedURIs, Set includedQNamesInExcludedURIs) { + if (includedURIs != null && excludedURIs == null) { + _inverted = false; + _includedURIs = includedURIs; + _excludedQNames = excludedQNamesInIncludedURIs; + _includedQNames = includedQNamesInExcludedURIs; + } else if (excludedURIs != null && includedURIs == null) { + _inverted = true; + _includedURIs = excludedURIs; + _excludedQNames = includedQNamesInExcludedURIs; + _includedQNames = excludedQNamesInIncludedURIs; + } else { + throw new IllegalArgumentException("Exactly one of excludedURIs and includedURIs must be null"); + } + } + + /** + * Local xml names are hased using "" as the namespace. + */ + private static String nsFromName(QName xmlName) { + String ns = xmlName.getNamespaceURI(); + return ns == null ? "" : ns; + } + + /** + * True if this ModelTransitionSet contains the given qname. + */ + public boolean contains(QName name) { + boolean in = _includedURIs.contains(nsFromName(name)) ? + !_excludedQNames.contains(name) : + _includedQNames.contains(name); + return _inverted ^ in; + } + + /** + * True if this ModelTransitionSet contains all QNames. + */ + public boolean isAll() { + return _inverted && _includedURIs.isEmpty() && _includedQNames.isEmpty(); + } + + /** + * True if this ModelTransitionSet contains no QNames. + */ + public boolean isEmpty() { + return !_inverted && _includedURIs.isEmpty() && _includedQNames.isEmpty(); + } + + /** + * Returns a new QNameSet that is the intersection of this one and another. + * + * @param set the set to insersect with + * @return the intersection + */ + public QNameSet intersect(QNameSetSpecification set) { + QNameSetBuilder result = new QNameSetBuilder(this); + result.restrict(set); + return result.toQNameSet(); + } + + /** + * Returns a new QNameSet that is the union of this one and another. + * + * @param set the set to union with + * @return the union + */ + public QNameSet union(QNameSetSpecification set) { + QNameSetBuilder result = new QNameSetBuilder(this); + result.addAll(set); + return result.toQNameSet(); + } + + /** + * Returns a new QNameSet that is the inverse of this one. + */ + public QNameSet inverse() { + if (this == EMPTY) { + return ALL; + } + if (this == ALL) { + return EMPTY; + } + if (this == LOCAL) { + return NONLOCAL; + } + if (this == NONLOCAL) { + return LOCAL; + } + return new QNameSet(includedURIs(), excludedURIs(), includedQNamesInExcludedURIs(), excludedQNamesInIncludedURIs()); + } + + /** + * True if the given set is a subset of this one. + * + * @param set the set to test + * @return true if this contains all QNames contained by the given set + */ + public boolean containsAll(QNameSetSpecification set) { + // a.contains(b) == a.inverse.isDisjoint(b) + if (!_inverted && set.excludedURIs() != null) { + return false; + } + + return inverse().isDisjoint(set); + } + + /** + * True if the given set is disjoint from this one. + * + * @param set the set to test + * @return true if the set is disjoint from this set + */ + public boolean isDisjoint(QNameSetSpecification set) { + if (_inverted && set.excludedURIs() != null) { + return false; + } + + if (_inverted) { + return isDisjointImpl(set, this); + } else { + return isDisjointImpl(this, set); + } + } + + private boolean isDisjointImpl(QNameSetSpecification set1, QNameSetSpecification set2) { + Set includeURIs = set1.includedURIs(); + Set otherIncludeURIs = set2.includedURIs(); + + if (otherIncludeURIs != null) { + if (!Collections.disjoint(includeURIs, otherIncludeURIs)) { + return false; + } + } else { + if (!set2.excludedURIs().containsAll(includeURIs)) { + return false; + } + } + + if (set1.includedQNamesInExcludedURIs().stream().anyMatch(set2::contains)) { + return false; + } + + if (set2.includedQNamesInExcludedURIs().stream().anyMatch(set1::contains)) { + return false; + } + + return true; + } + + + /** + * Namespaces that are fully excluded from the set except for a finite + * number of individual QName exceptions. Returns null if this set is infinite. + * + * @return the set of excluded namespace URI strings + */ + public Set excludedURIs() { + if (_inverted) { + return Collections.unmodifiableSet(_includedURIs); + } + return null; + } + + /** + * Namespaces that are fully included in set except for a finite + * number of individual QName exceptions. Returns null if this set is infinite. + * + * @return the set of included namespace URI strings + */ + public Set includedURIs() { + if (!_inverted) { + return _includedURIs; + } + return null; + } + + /** + * The set of QNames excluded from the set even though they are within + * a namespace that is otherwise fully included in the set. + * + * @return the set of excluded QNames from within includedURI namespaces + */ + public Set excludedQNamesInIncludedURIs() { + return Collections.unmodifiableSet(_inverted ? _includedQNames : _excludedQNames); + } + + /** + * The set of QNames included in the set even though they are within + * a namespace that is otherwise fully included in the set. + * + * @return the set of included QNames from within excludedURI namespaces + */ + public Set includedQNamesInExcludedURIs() { + return Collections.unmodifiableSet(_inverted ? _excludedQNames : _includedQNames); + } + + private String prettyQName(QName name) { + if (name.getNamespaceURI() == null) { + return name.getLocalPart(); + } + return name.getLocalPart() + "@" + name.getNamespaceURI(); + } + + /** + * Returns a string representation useful for debugging, subject to change. + */ + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("QNameSet"); + sb.append(_inverted ? "-(" : "+("); + for (String includedURIs : _includedURIs) { + sb.append("+*@"); + sb.append(includedURIs); + sb.append(", "); + } + for (QName excludedQName : _excludedQNames) { + sb.append("-"); + sb.append(prettyQName(excludedQName)); + sb.append(", "); + } + for (QName includedQName : _includedQNames) { + sb.append("+"); + sb.append(prettyQName(includedQName)); + sb.append(", "); + } + int index = sb.lastIndexOf(", "); + if (index > 0) { + sb.setLength(index); + } + sb.append(')'); + return sb.toString(); + } +} diff --git a/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java b/src/main/java/org/apache/xmlbeans/QNameSetBuilder.java similarity index 99% rename from src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java rename to src/main/java/org/apache/xmlbeans/QNameSetBuilder.java index 2594561..13d8e7e 100644 --- a/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java +++ b/src/main/java/org/apache/xmlbeans/QNameSetBuilder.java @@ -682,7 +682,7 @@ private String prettyQName(QName name) */ public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("QNameSetBuilder"); sb.append(_inverted ? "-(" : "+("); for (Iterator i = _includedURIs.iterator(); i.hasNext(); ) diff --git a/src/xmlpublic/org/apache/xmlbeans/QNameSetSpecification.java b/src/main/java/org/apache/xmlbeans/QNameSetSpecification.java similarity index 94% rename from src/xmlpublic/org/apache/xmlbeans/QNameSetSpecification.java rename to src/main/java/org/apache/xmlbeans/QNameSetSpecification.java index 49d2f10..68d0d0f 100644 --- a/src/xmlpublic/org/apache/xmlbeans/QNameSetSpecification.java +++ b/src/main/java/org/apache/xmlbeans/QNameSetSpecification.java @@ -16,19 +16,17 @@ package org.apache.xmlbeans; import javax.xml.namespace.QName; - import java.util.Set; /** * Represents a lattice of finite and infinite sets of QNames. - * + * * @see QNameSet */ -public interface QNameSetSpecification -{ +public interface QNameSetSpecification { /** * True if the set contains the given QName. - * + *

* Roughly equivalent to: * (includedURIs() == null ? * excludedURIs().contains(namespace) : @@ -51,9 +49,9 @@ public interface QNameSetSpecification /** * True if the parameter is a subset of this set. - */ + */ boolean containsAll(QNameSetSpecification set); - + /** * True if is disjoint from the specified set. */ @@ -88,7 +86,7 @@ public interface QNameSetSpecification *

* The same set as inverse().includedURIs(). */ - Set excludedURIs(); + Set excludedURIs(); /** * The finite set of namespace URIs that are almost completely included in @@ -101,7 +99,7 @@ public interface QNameSetSpecification *

* The same as inverse.excludedURIs(). */ - Set includedURIs(); + Set includedURIs(); /** * The finite set of QNames that are excluded from the set within namespaces @@ -113,7 +111,7 @@ public interface QNameSetSpecification *

* The same set as inverse().includedQNames(). */ - Set excludedQNamesInIncludedURIs(); + Set excludedQNamesInIncludedURIs(); /** * The finite set of QNames that are included in the set within namespaces @@ -125,5 +123,5 @@ public interface QNameSetSpecification *

* The same as inverse().excludedQNames(). */ - Set includedQNamesInExcludedURIs(); + Set includedQNamesInExcludedURIs(); } diff --git a/src/xmlpublic/org/apache/xmlbeans/ResourceLoader.java b/src/main/java/org/apache/xmlbeans/ResourceLoader.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/ResourceLoader.java rename to src/main/java/org/apache/xmlbeans/ResourceLoader.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaAnnotated.java b/src/main/java/org/apache/xmlbeans/SchemaAnnotated.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaAnnotated.java rename to src/main/java/org/apache/xmlbeans/SchemaAnnotated.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaAnnotation.java b/src/main/java/org/apache/xmlbeans/SchemaAnnotation.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaAnnotation.java rename to src/main/java/org/apache/xmlbeans/SchemaAnnotation.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaAttributeGroup.java b/src/main/java/org/apache/xmlbeans/SchemaAttributeGroup.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaAttributeGroup.java rename to src/main/java/org/apache/xmlbeans/SchemaAttributeGroup.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaAttributeModel.java b/src/main/java/org/apache/xmlbeans/SchemaAttributeModel.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaAttributeModel.java rename to src/main/java/org/apache/xmlbeans/SchemaAttributeModel.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaBookmark.java b/src/main/java/org/apache/xmlbeans/SchemaBookmark.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaBookmark.java rename to src/main/java/org/apache/xmlbeans/SchemaBookmark.java diff --git a/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java b/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java new file mode 100755 index 0000000..67821e7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java @@ -0,0 +1,31 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.io.IOException; +import java.io.Writer; + +/** + * This class is used to provide alternate implementations of the + * schema Java code generation. + */ + +public interface SchemaCodePrinter { + void printTypeImpl(Writer writer, SchemaType sType) throws IOException; + + void printType(Writer writer, SchemaType sType) throws IOException; +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java b/src/main/java/org/apache/xmlbeans/SchemaComponent.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java rename to src/main/java/org/apache/xmlbeans/SchemaComponent.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaField.java b/src/main/java/org/apache/xmlbeans/SchemaField.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaField.java rename to src/main/java/org/apache/xmlbeans/SchemaField.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaGlobalAttribute.java b/src/main/java/org/apache/xmlbeans/SchemaGlobalAttribute.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaGlobalAttribute.java rename to src/main/java/org/apache/xmlbeans/SchemaGlobalAttribute.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaGlobalElement.java b/src/main/java/org/apache/xmlbeans/SchemaGlobalElement.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaGlobalElement.java rename to src/main/java/org/apache/xmlbeans/SchemaGlobalElement.java diff --git a/src/main/java/org/apache/xmlbeans/SchemaIdentityConstraint.java b/src/main/java/org/apache/xmlbeans/SchemaIdentityConstraint.java new file mode 100644 index 0000000..bf3512e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/SchemaIdentityConstraint.java @@ -0,0 +1,103 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Map; + +/** + * Represents an identity constraint definition. + */ +public interface SchemaIdentityConstraint extends SchemaComponent, SchemaAnnotated { + /** + * Return the selector xpath as a string. + */ + String getSelector(); + + /** + * Return a compiled xpath object for the selector. + */ + Object getSelectorPath(); + + /** + * Return (a copy of) the xpaths for all the fields. + */ + String[] getFields(); + + /** + * Return a compiled xpath object for the field. + */ + Object getFieldPath(int index); + + /** + * Return a read-only copy of the namespace map. This is the + * set of prefix to URI mappings that were in scope in the + * schema at the point at which this constraint was declared + */ + Map getNSMap(); + + /** + * A xs:key constraint. See {@link #getConstraintCategory}. + */ + int CC_KEY = 1; + /** + * A xs:keyRef constraint. See {@link #getConstraintCategory}. + */ + int CC_KEYREF = 2; + /** + * A xs:unique constraint. See {@link #getConstraintCategory}. + */ + int CC_UNIQUE = 3; + + /** + * Return the constraint category. Either {@link #CC_KEY}, {@link #CC_KEYREF}, + * or {@link #CC_UNIQUE}. + */ + int getConstraintCategory(); + + /** + * Returns the key that a key ref refers to. Only valid for + * keyrefs. + */ + SchemaIdentityConstraint getReferencedKey(); + + /** + * Used to allow on-demand loading of identity constraints. + */ + final class Ref extends SchemaComponent.Ref { + public Ref(SchemaIdentityConstraint idc) { + super(idc); + } + + public Ref(SchemaTypeSystem system, String handle) { + super(system, handle); + } + + public final int getComponentType() { + return SchemaComponent.IDENTITY_CONSTRAINT; + } + + public final SchemaIdentityConstraint get() { + return (SchemaIdentityConstraint) getComponent(); + } + } + + /** + * Returns user-specific information. + * + * @see SchemaBookmark + */ + Object getUserData(); +} diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaLocalAttribute.java b/src/main/java/org/apache/xmlbeans/SchemaLocalAttribute.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaLocalAttribute.java rename to src/main/java/org/apache/xmlbeans/SchemaLocalAttribute.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaLocalElement.java b/src/main/java/org/apache/xmlbeans/SchemaLocalElement.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaLocalElement.java rename to src/main/java/org/apache/xmlbeans/SchemaLocalElement.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaModelGroup.java b/src/main/java/org/apache/xmlbeans/SchemaModelGroup.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaModelGroup.java rename to src/main/java/org/apache/xmlbeans/SchemaModelGroup.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaParticle.java b/src/main/java/org/apache/xmlbeans/SchemaParticle.java similarity index 85% rename from src/xmlpublic/org/apache/xmlbeans/SchemaParticle.java rename to src/main/java/org/apache/xmlbeans/SchemaParticle.java index 22dbd21..741dea6 100644 --- a/src/xmlpublic/org/apache/xmlbeans/SchemaParticle.java +++ b/src/main/java/org/apache/xmlbeans/SchemaParticle.java @@ -15,9 +15,8 @@ package org.apache.xmlbeans; -import java.math.BigInteger; - import javax.xml.namespace.QName; +import java.math.BigInteger; /** * Represents a Schema particle definition. @@ -33,44 +32,43 @@ * sequences, nonrepeating sequences with only one item, and so on. * (Pointless particles * are defined precisely in the XML Schema specification.) - * + * * @see SchemaType#getContentModel */ -public interface SchemaParticle -{ +public interface SchemaParticle { /** * Returns the particle type ({@link #ALL}, {@link #CHOICE}, - * {@link #SEQUENCE}, {@link #ELEMENT}, or {@link #WILDCARD}). - */ + * {@link #SEQUENCE}, {@link #ELEMENT}, or {@link #WILDCARD}). + */ int getParticleType(); - + /** * An xs:all group. * See {@link #getParticleType}. - */ - static final int ALL = 1; + */ + int ALL = 1; /** * A xs:choice group. * See {@link #getParticleType}. - */ - static final int CHOICE = 2; + */ + int CHOICE = 2; /** * A xs:sequence group. * See {@link #getParticleType}. - */ - static final int SEQUENCE = 3; + */ + int SEQUENCE = 3; /** * An xs:element particle. * This code means the particle can be coerced to {@link SchemaLocalElement}. * See {@link #getParticleType}. - */ - static final int ELEMENT = 4; + */ + int ELEMENT = 4; /** * An xs:any particle, * also known as an element wildcard. * See {@link #getParticleType}. - */ - static final int WILDCARD = 5; + */ + int WILDCARD = 5; /** * Returns the minOccurs value for this particle. @@ -90,14 +88,14 @@ public interface SchemaParticle * convenience of a validating state machine that doesn't count * higher than MAX_INT anyway. */ - public int getIntMinOccurs(); + int getIntMinOccurs(); /** * Returns the maxOccurs value, pegged to a 32-bit int for * convenience of a validating state machine that doesn't count * higher than MAX_INT anyway. Unbounded is given as MAX_INT. */ - public int getIntMaxOccurs(); + int getIntMaxOccurs(); /** @@ -151,19 +149,25 @@ public interface SchemaParticle */ int getWildcardProcess(); - /** Strict wildcard processing. See {@link #getWildcardProcess} */ - static final int STRICT = 1; - /** Lax wildcard processing. See {@link #getWildcardProcess} */ - static final int LAX = 2; - /** Skip wildcard processing. See {@link #getWildcardProcess} */ - static final int SKIP = 3; + /** + * Strict wildcard processing. See {@link #getWildcardProcess} + */ + int STRICT = 1; + /** + * Lax wildcard processing. See {@link #getWildcardProcess} + */ + int LAX = 2; + /** + * Skip wildcard processing. See {@link #getWildcardProcess} + */ + int SKIP = 3; /** * For elements only: the QName for the element use. * May be unqualified version of referenced element's name. */ QName getName(); - + /** * For elements only: returns the type of the element. */ @@ -178,7 +182,7 @@ public interface SchemaParticle * For elements only: returns the default (or fixed) text value */ String getDefaultText(); - + /** * For elements only: returns the default (or fixed) strongly-typed value */ @@ -193,5 +197,5 @@ public interface SchemaParticle * For elements only: true if is fixed value. */ boolean isFixed(); - + } diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaProperty.java b/src/main/java/org/apache/xmlbeans/SchemaProperty.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaProperty.java rename to src/main/java/org/apache/xmlbeans/SchemaProperty.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaStringEnumEntry.java b/src/main/java/org/apache/xmlbeans/SchemaStringEnumEntry.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaStringEnumEntry.java rename to src/main/java/org/apache/xmlbeans/SchemaStringEnumEntry.java diff --git a/src/main/java/org/apache/xmlbeans/SchemaType.java b/src/main/java/org/apache/xmlbeans/SchemaType.java new file mode 100644 index 0000000..8c55dc7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/SchemaType.java @@ -0,0 +1,1111 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.namespace.QName; + +/** + * Represents a schema type. + *

+ * SchemaType is the metadata "type" class for {@link XmlObject}, and it plays the + * analogous role for {@link XmlObject} that {@link java.lang.Class} plays for + * {@link java.lang.Object}. + *

+ * Every XML Bean class corresponds to a singleton SchemaType object + * obtainable by ClassName.type (e.g., {@link XmlNonPositiveInteger#type}), and + * every XML Bean instance has an actual SchemaType, obtainable by + * {@link XmlObject#schemaType}. The ClassName.type and schemaType() mechanisms are + * analogous to the ordinary Java ClassName.class and obj.getClass() mechanisms. + *

+ * All schema types are represented by a SchemaType, this includes all types + * regardless of whether they are built-in or user-defined, compiled or + * uncompiled, simple or complex. + *

+ * In addition, a compiled XML Bean type system includes special "document" schema types + * each representing a document containing nothing but a single element for each + * global element, and special "attribute" schema types each representing + * a fragment containing nothing but a single global attribute for global + * attribute. + *

+ * Do not confuse Schema Types with other types of Schema Components such as + * {@link SchemaGlobalElement Global Elements}, {@link SchemaGlobalAttribute Global Attributes}, + * {@link SchemaModelGroup Named Model Groups}, or {@link SchemaAttributeGroup Attribute Groups}. + * SchemaType represents a Type component, not any of the other kinds of components. + * There are different kinds of metadata objects for the different Schema components. + *

+ * The space of SchemaTypes is divided as follows: + * + *

    + *
  • First, there is the universal base type and the universal + * subtype. These are {@link XmlObject#type} + * (corresponding to xs:anyType) and {@link XmlBeans#NO_TYPE}, + * respectively. The first type is a base type of all other + * types. The other type indicates the absence of type information + * and, at least in set-theoretic terms, is a subtype of all other types. + *
  • There is another universal base type that is the base type + * for all simple types. This is the {@link XmlAnySimpleType#type}, + * corresponding to xs:anySimpleType. Only XmlObject.type and + * XmlAnySimpleType.type return true for {@link #isURType}, and + * only XmlBeans.NO_TYPE returns true for {@link #isNoType}. + *
  • The two "special" kinds of types that are generated that + * do not formally exist in the actual Schema specification are + * document types and global attribute types (corresponding to + * documents that contain a global element, or fragments that + * contain a global attribute). They can be detected using + * {@link #isDocumentType} and {@link #isAttributeType}. Other + * than their anonymity (lack of a type name) and their appearance + * only at the root of an instance, they are otherwise just like + * ordinary complex types. + *
  • Simple types can be detected using {@link #isSimpleType}. + * Complex types are consdered to be all the types that are + * not simple. + *
  • Simple types are divided into three varieties: atomic types, + * list types, and union types. Which variety of simple type + * you have can be discoverd using {@link #getSimpleVariety}. + * It will return either {@link #ATOMIC}, {@link #LIST}, or + * {@link #UNION}. + *
  • An {@link #ATOMIC} simple type is always based on one of the + * 20 built-in primitive schema types. You can determine + * the underlying primitive type for an atomic simple type + * by calling {@link #getPrimitiveType}. An atomic type + * may add facet restrictions on top of the primitive type, + * and these facets can be explored using {@link #getFacet}, + * {@link #getWhiteSpaceRule}, {@link #matchPatternFacet}, + * {@link #getEnumerationValues}, and related methods. + *
  • A {@link #LIST} simple type is always based on another non-list + * simple type. The underlying list item type can be obtained + * by using {@link #getListItemType}. + *
  • A {@link #UNION} simple type is always composed out of a number of + * other simple types. The direct members of the union can + * be obtained by {@link #getUnionMemberTypes}. When unions + * consist of other unions, it is useful to know useful to know + * the "leaves of the union tree", so the + * set of non-union types making up the union can be obtained + * by {@link #getUnionConstituentTypes}. The closure of the + * entire "union tree" is {@link #getUnionSubTypes} (this includes + * the type itself). For + * simple unions that do not consist of other unions, all three + * of these sets are the same. + *
  • Complex types have nested structure. They are divided into + * four content types: empty content, simple content, element-only + * content, and mixed content. All kinds of complex types may + * have attributes. The content type for a complex type can + * be dermined using {@link #getContentType}. This will return + * {@link #EMPTY_CONTENT}, {@link #SIMPLE_CONTENT}, + * {@link #ELEMENT_CONTENT}, or {@link #MIXED_CONTENT}. + *
  • If a complex type has {@link #EMPTY_CONTENT}, the content model will be null. + *
  • If a complex type has {@link #SIMPLE_CONTENT}, then it will extend the + * simple type that describes the content. In addition, the type + * may impose additional simple type facet restrictions; these can + * be determined in the same way they are for a simple type. + *
  • If a complex type has {@link #ELEMENT_CONTENT} or {@link #MIXED_CONTENT}, then + * the detailed content model can be determined by examining + * the particle tree (which may be null for MIXED_CONTENT). + * The particle tree can be obtained via {@link #getContentModel}. + *
  • When working with a complex type, most users will find it + * sufficient to discover the summarized shape of the content model + * and attribute model using {@link #getElementProperties}, + * {@link #getAttributeProperties}, and related methods rather than + * examining the particle tree and attribute model directly. + *
+ * + * @see SchemaTypeLoader + * @see XmlObject#schemaType + * @see SimpleValue#instanceType + */ +public interface SchemaType extends SchemaComponent, SchemaAnnotated { + /** + * The name used to describe the type in the schema. + * Null if the type is anonymous (nested), or if it is a document type. + */ + QName getName(); + + /** + * The parent schema element. + * Null for top-level (named) types and document types. + */ + SchemaField getContainerField(); + + /** + * True if this is a document type. + *

+ * Document types are generated for every global element. A document + * type is an unnamed complex type that contains exactly one element: + * we define these types, because they are the types of the "documents" + * which contain the defined global elements, and they all turn into + * Java types. (Named ElementnameDocument.) + */ + boolean isDocumentType(); + + /** + * True if this is a attribute type. + *

+ * Attribute types are generated for every global attribute. An attribute + * type is an unnamed complex type that contains exactly one attribute: + * we define these types, because they are the types of the "attribute documents" + * which contain the defined global attribute, and they all turn into + * Java types. (Named AttributenameAttribute.) + */ + boolean isAttributeType(); + + + /** + * Returns the document element name if this is a document type, + * or null otherwise. + */ + QName getDocumentElementName(); + + /** + * Returns the attribute qname if this is a attribute type, + * or null otherwise. + */ + QName getAttributeTypeAttributeName(); + + /** + * The outer schema type. + * Null for top-level (named) types. + */ + SchemaType getOuterType(); + + /** + * True if this anonymous type has no corresponding Java type. True for + * anonymous types nested within simple type restrictions. + */ + boolean isSkippedAnonymousType(); + + /** + * True if this schema type was compiled to have a corresponding + * Java class. + */ + boolean isCompiled(); + + /** + * The fully-qualified Java type name of the class. + */ + String getFullJavaName(); + + /** + * The short unqualfiied Java name for the class. + */ + String getShortJavaName(); + + /** + * The fully-qualified Java type name of the implementation class. + */ + String getFullJavaImplName(); + + /** + * The short unqualfiied Java name for the implementation class. + */ + String getShortJavaImplName(); + + /** + * The Java class corresponding to this schema type. + */ + Class getJavaClass(); + + /** + * The Java class corresponding to the enumeration type for this schema type, + * if applicable (or null if not an enumeration). + */ + Class getEnumJavaClass(); + + /** + * Returns user-specific information. + * + * @see SchemaBookmark + */ + Object getUserData(); + + /** + * True if the Xsd type is anonymous (i.e., not top-level). + */ + boolean isAnonymousType(); + + /** + * True for any of the 40+ built-in types. + */ + boolean isBuiltinType(); + + /** + * True for the anySimpleType and any restrictions/unions/lists. + */ + boolean isSimpleType(); + + /** + * Returns base restriction or extension type. Unions and lists + * return the anySimpleType. + */ + SchemaType getBaseType(); + + /** + * Returns common base type with the given type. The returned + * type is the most specific declared base type of both types. + */ + SchemaType getCommonBaseType(SchemaType type); + + /** + * True if the specified type derives from this type (or if + * it is the same type). + *

+ * Note that XmlObject.type (the anyType) is assignable + * from all type, and the XmlBeans.noType (the absence of + * a type) is assignable to all types. + */ + boolean isAssignableFrom(SchemaType type); + + /** + * Returns an integer for the derivation type, either + * {@link #DT_EXTENSION}, {@link #DT_RESTRICTION}, {@link #DT_NOT_DERIVED}. + */ + int getDerivationType(); + + /** + * Not derived. True for XmlObject.type only. See {@link #getDerivationType}. + */ + int DT_NOT_DERIVED = 0; + /** + * Derived by restriction. See {@link #getDerivationType}. + */ + int DT_RESTRICTION = 1; + /** + * Derived by extension. See {@link #getDerivationType}. + */ + int DT_EXTENSION = 2; + + /** + * Returns an integer for builtin types that can be used + * for quick comparison. + */ + int getBuiltinTypeCode(); + + /** + * Not a builtin type + */ + int BTC_NOT_BUILTIN = 0; + /** + * xs:anyType, aka {@link XmlObject#type} + */ + int BTC_ANY_TYPE = 1; + + /** + * The primitive types have codes between BTC_FIRST_PRIMITIVE and BTC_LAST_PRIMITIVE inclusive + */ + int BTC_FIRST_PRIMITIVE = 2; + + /** + * xs:anySimpleType, aka {@link XmlAnySimpleType#type} + */ + int BTC_ANY_SIMPLE = 2; + + /** + * xs:boolean, aka {@link XmlBoolean#type} + */ + int BTC_BOOLEAN = 3; + /** + * xs:base64Binary, aka {@link XmlBase64Binary#type} + */ + int BTC_BASE_64_BINARY = 4; + /** + * xs:hexBinary, aka {@link XmlBase64Binary#type} + */ + int BTC_HEX_BINARY = 5; + /** + * xs:anyURI, aka {@link XmlAnyURI#type} + */ + int BTC_ANY_URI = 6; + /** + * xs:QName, aka {@link XmlQName#type} + */ + int BTC_QNAME = 7; + /** + * xs:NOTATION, aka {@link XmlNOTATION#type} + */ + int BTC_NOTATION = 8; + /** + * xs:float, aka {@link XmlFloat#type} + */ + int BTC_FLOAT = 9; + /** + * xs:double, aka {@link XmlDouble#type} + */ + int BTC_DOUBLE = 10; + /** + * xs:decimal, aka {@link XmlDecimal#type} + */ + int BTC_DECIMAL = 11; + /** + * xs:string, aka {@link XmlString#type} + */ + int BTC_STRING = 12; + + /** + * xs:duration, aka {@link XmlDuration#type} + */ + int BTC_DURATION = 13; + /** + * xs:dateTime, aka {@link XmlDateTime#type} + */ + int BTC_DATE_TIME = 14; + /** + * xs:time, aka {@link XmlTime#type} + */ + int BTC_TIME = 15; + /** + * xs:date, aka {@link XmlDate#type} + */ + int BTC_DATE = 16; + /** + * xs:gYearMonth, aka {@link XmlGYearMonth#type} + */ + int BTC_G_YEAR_MONTH = 17; + /** + * xs:gYear, aka {@link XmlGYear#type} + */ + int BTC_G_YEAR = 18; + /** + * xs:gMonthDay, aka {@link XmlGMonthDay#type} + */ + int BTC_G_MONTH_DAY = 19; + /** + * xs:gDay, aka {@link XmlGDay#type} + */ + int BTC_G_DAY = 20; + /** + * xs:gMonth, aka {@link XmlGMonth#type} + */ + int BTC_G_MONTH = 21; + + /** + * The primitive types have codes between BTC_FIRST_PRIMITIVE and BTC_LAST_PRIMITIVE inclusive + */ + int BTC_LAST_PRIMITIVE = 21; + + // derived numerics + /** + * xs:integer, aka {@link XmlInteger#type} + */ + int BTC_INTEGER = 22; + /** + * xs:long, aka {@link XmlLong#type} + */ + int BTC_LONG = 23; + /** + * xs:int, aka {@link XmlInt#type} + */ + int BTC_INT = 24; + /** + * xs:short, aka {@link XmlShort#type} + */ + int BTC_SHORT = 25; + /** + * xs:byte, aka {@link XmlByte#type} + */ + int BTC_BYTE = 26; + /** + * xs:nonPositiveInteger, aka {@link XmlNonPositiveInteger#type} + */ + int BTC_NON_POSITIVE_INTEGER = 27; + /** + * xs:NegativeInteger, aka {@link XmlNegativeInteger#type} + */ + int BTC_NEGATIVE_INTEGER = 28; + /** + * xs:nonNegativeInteger, aka {@link XmlNonNegativeInteger#type} + */ + int BTC_NON_NEGATIVE_INTEGER = 29; + /** + * xs:positiveInteger, aka {@link XmlPositiveInteger#type} + */ + int BTC_POSITIVE_INTEGER = 30; + /** + * xs:unsignedLong, aka {@link XmlUnsignedLong#type} + */ + int BTC_UNSIGNED_LONG = 31; + /** + * xs:unsignedInt, aka {@link XmlUnsignedInt#type} + */ + int BTC_UNSIGNED_INT = 32; + /** + * xs:unsignedShort, aka {@link XmlUnsignedShort#type} + */ + int BTC_UNSIGNED_SHORT = 33; + /** + * xs:unsignedByte, aka {@link XmlUnsignedByte#type} + */ + int BTC_UNSIGNED_BYTE = 34; + + // derived strings + /** + * xs:normalizedString, aka {@link XmlNormalizedString#type} + */ + int BTC_NORMALIZED_STRING = 35; + /** + * xs:token, aka {@link XmlToken#type} + */ + int BTC_TOKEN = 36; + /** + * xs:Name, aka {@link XmlName#type} + */ + int BTC_NAME = 37; + /** + * xs:NCName, aka {@link XmlNCName#type} + */ + int BTC_NCNAME = 38; + /** + * xs:language, aka {@link XmlLanguage#type} + */ + int BTC_LANGUAGE = 39; + /** + * xs:ID, aka {@link XmlID#type} + */ + int BTC_ID = 40; + /** + * xs:IDREF, aka {@link XmlIDREF#type} + */ + int BTC_IDREF = 41; + /** + * xs:IDREFS, aka {@link XmlIDREFS#type} + */ + int BTC_IDREFS = 42; + /** + * xs:ENTITY, aka {@link XmlENTITY#type} + */ + int BTC_ENTITY = 43; + /** + * xs:ENTITIES, aka {@link XmlENTITIES#type} + */ + int BTC_ENTITIES = 44; + /** + * xs:NMTOKEN, aka {@link XmlNMTOKEN#type} + */ + int BTC_NMTOKEN = 45; + /** + * xs:NMTOKENS, aka {@link XmlNMTOKENS#type} + */ + int BTC_NMTOKENS = 46; + + int BTC_LAST_BUILTIN = 46; + + /** + * True for anyType and anySimpleType. + */ + boolean isURType(); + + /** + * True for the type object that represents a the absence of a determined type. + * XML Objects whose type isNoType() are never valid. + */ + boolean isNoType(); + + /** + * Returns the SchemaTypeLoader in which this type was defined. + * Complex types are defined and used in exactly one schema type + * system, but simple types are defined in one type system and can + * be used in any number of type systems. The most common case is + * the builtin types, which are defined in the builtin type system + * and used elsewhere. + */ + SchemaTypeSystem getTypeSystem(); + + /** + * True if this type cannot be used directly in instances + */ + boolean isAbstract(); + + /** + * True if other types cannot extend this type (only for complex types) + */ + boolean finalExtension(); + + /** + * True if other types cannot restrict this type + */ + boolean finalRestriction(); + + /** + * True if list derivation of this type is prohibited (only for simple types) + */ + boolean finalList(); + + /** + * True if union derivation of this type is prohibited (only for simple types) + */ + boolean finalUnion(); + + /** + * True if extensions of this type cannot be substituted for this type + */ + boolean blockExtension(); + + /** + * True if restrictions of this type cannot be substituted for this type + */ + boolean blockRestriction(); + + /** + * Returns {@link #EMPTY_CONTENT}, {@link #SIMPLE_CONTENT}, {@link #ELEMENT_CONTENT}, or + * {@link #MIXED_CONTENT} for complex types. For noncomplex types, returns + * {@link #NOT_COMPLEX_TYPE}. + */ + int getContentType(); + + /** + * Not a complex type. See {@link #getContentType()}. + */ + int NOT_COMPLEX_TYPE = 0; + /** + * Empty content. See {@link #getContentType()}. + */ + int EMPTY_CONTENT = 1; + /** + * Simple content. See {@link #getContentType()}. + */ + int SIMPLE_CONTENT = 2; + /** + * Element-only content. See {@link #getContentType()}. + */ + int ELEMENT_CONTENT = 3; + /** + * Mixed content. See {@link #getContentType()}. + */ + int MIXED_CONTENT = 4; + + + /** + * For complex types with simple content returns the base type for this + * type's content. In most cases, this is the same as the base type, but + * it can also be an anonymous type. + */ + SchemaType getContentBasedOnType(); + + /** + * Returns a {@link SchemaTypeElementSequencer} object, which can then + * be used to validate complex content inside this element. This is useful + * for example for trying out different names and see which one would be + * valid as a child of this element. + */ + SchemaTypeElementSequencer getElementSequencer(); + + /** + * The array of inner (anonymous) types defined + * within this type. + */ + SchemaType[] getAnonymousTypes(); + + /** + * Returns a SchemaProperty corresponding to an element within this + * complex type by looking up the element name. + */ + SchemaProperty getElementProperty(QName eltName); + + /** + * Returns all the SchemaProperties corresponding to elements. + */ + SchemaProperty[] getElementProperties(); + + /** + * Returns a SchemaProperty corresponding to an attribute within this + * complex type by looking up the attribute name. + */ + SchemaProperty getAttributeProperty(QName attrName); + + /** + * Returns all the SchemaProperties corresponding to attributes. + */ + SchemaProperty[] getAttributeProperties(); + + /** + * Returns all the SchemaProperties within this complex type, + * elements followed by attributes. + */ + SchemaProperty[] getProperties(); + + /** + * Returns the SchemaProperties defined by this complex type, + * exclusive of the base type (if any). + */ + SchemaProperty[] getDerivedProperties(); + + /** + * Returns the attribute model for this complex type (with simple or complex content). + */ + SchemaAttributeModel getAttributeModel(); + + /** + * True if this type permits wildcard attributes. See the attribute model for + * more information about which wildcards are allowed. + */ + boolean hasAttributeWildcards(); + + /** + * Returns the complex content model for this complex type (with complex content). + */ + SchemaParticle getContentModel(); + + /** + * True if this type permits element wildcards. See the content model for + * more information about which wildcards are allowed, and where. + */ + boolean hasElementWildcards(); + + /** + * For document types, true if the given name can be substituted for the + * document element name. + */ + boolean isValidSubstitution(QName name); + + /** + * True if the complex content model for this complex type is an "all" group. + */ + boolean hasAllContent(); + + /** + * True if particles have same defaults, nillability, etc, that are + * invariant when order changes. Computed only for Javaized types. + */ + boolean isOrderSensitive(); + + /** + * Returns the type of a child element based on the element name and + * an xsi:type attribute (and the type system within which names are + * resolved). + */ + SchemaType getElementType(QName eltName, QName xsiType, SchemaTypeLoader wildcardTypeLoader); + + /** + * Returns the type of an attribute based on the attribute name and + * the type system within which (wildcard) names are resolved. + */ + SchemaType getAttributeType(QName eltName, SchemaTypeLoader wildcardTypeLoader); + + /* *********************************************************** */ + /* SIMPLE TYPE MODEL BELOW */ + /* *********************************************************** */ + + /** + * xs:length facet + */ + int FACET_LENGTH = 0; + /** + * xs:minLength facet + */ + int FACET_MIN_LENGTH = 1; + /** + * xs:maxLength facet + */ + int FACET_MAX_LENGTH = 2; + /** + * xs:minExclusive facet + */ + int FACET_MIN_EXCLUSIVE = 3; + /** + * xs:minInclusive facet + */ + int FACET_MIN_INCLUSIVE = 4; + /** + * xs:maxInclusive facet + */ + int FACET_MAX_INCLUSIVE = 5; + /** + * xs:maxExclusive facet + */ + int FACET_MAX_EXCLUSIVE = 6; + /** + * xs:totalDigits facet + */ + int FACET_TOTAL_DIGITS = 7; + /** + * xs:fractionDigits facet + */ + int FACET_FRACTION_DIGITS = 8; + + int LAST_BASIC_FACET = 8; + + /** + * xs:whiteSpace facet - use {@link #getWhiteSpaceRule} instead + */ + int FACET_WHITE_SPACE = 9; + /** + * xs:pattern facet - use {@link #matchPatternFacet} instead + */ + int FACET_PATTERN = 10; + /** + * xs:enumeration facet - use {@link #getEnumerationValues} instead + */ + int FACET_ENUMERATION = 11; + + /** + * The last ordinary facet code + */ + int LAST_FACET = 11; + + /** + * @see #ordered + */ + int PROPERTY_ORDERED = 12; + /** + * @see #isBounded + */ + int PROPERTY_BOUNDED = 13; + /** + * @see #isFinite + */ + int PROPERTY_CARDINALITY = 14; + /** + * @see #isNumeric + */ + int PROPERTY_NUMERIC = 15; + + /** + * The last property code + */ + int LAST_PROPERTY = 15; + + + /** + * Returns the value of the given facet, or null if + * none is set. + */ + XmlAnySimpleType getFacet(int facetCode); + + /** + * True if the given facet is fixed. + */ + boolean isFacetFixed(int facetCode); + + /** + * True if ordered. Returns either {@link #UNORDERED}, + * {@link #PARTIAL_ORDER}, or {@link #TOTAL_ORDER}. + */ + int ordered(); + + /** + * Unordered. See {@link #ordered}. + */ + int UNORDERED = 0; + /** + * Partially ordered. See {@link #ordered}. + */ + int PARTIAL_ORDER = 1; + /** + * Totally ordered. See {@link #ordered}. + */ + int TOTAL_ORDER = 2; + + /** + * True if bounded. + */ + boolean isBounded(); + + /** + * True if finite. + */ + boolean isFinite(); + + /** + * True if numeric. + */ + boolean isNumeric(); + + /** + * True if there are regex pattern facents + */ + boolean hasPatternFacet(); + + /** + * True + */ + String[] getPatterns(); + + /** + * True if the given string matches the pattern facets. + * Always true if there are no pattern facets. + */ + boolean matchPatternFacet(String s); + + /** + * Returns the array of valid objects from the + * enumeration facet, null if no enumeration defined. + */ + XmlAnySimpleType[] getEnumerationValues(); + + /** + * True if this is a string enum where an integer + * is assigned to each enumerated value. + */ + boolean hasStringEnumValues(); + + /** + * If this is a string enumeration, returns the most basic base schema + * type that this enuemration is based on. Otherwise returns null. + */ + SchemaType getBaseEnumType(); + + /** + * Returns the array of SchemaStringEnumEntries for this type: this + * array includes information about the java constant names used for + * each string enum entry. + */ + SchemaStringEnumEntry[] getStringEnumEntries(); + + /** + * Returns the string enum entry corresponding to the given enumerated + * string, or null if there is no match or this type is not + * a string enumeration. + */ + SchemaStringEnumEntry enumEntryForString(String s); + + /** + * Returns the string enum value corresponding to the given enumerated + * string, or null if there is no match or this type is not + * a string enumeration. + */ + StringEnumAbstractBase enumForString(String s); + + /** + * Returns the string enum value corresponding to the given enumerated + * string, or null if there is no match or this type is not + * a string enumeration. + */ + StringEnumAbstractBase enumForInt(int i); + + /** + * True for any of the 20 primitive types (plus anySimpleType) + */ + boolean isPrimitiveType(); + + /** + * Returns whether the simple type is ATOMIC, UNION, or LIST. + * Returns {@link #NOT_SIMPLE}, {@link #ATOMIC}, {@link #UNION}, + * or {@link #LIST}. + */ + int getSimpleVariety(); + + /** + * Not a simple type or simple content. See {@link #getSimpleVariety}. + */ + int NOT_SIMPLE = 0; + /** + * Atomic type. See {@link #getSimpleVariety} + */ + int ATOMIC = 1; + /** + * Union type. See {@link #getSimpleVariety} + */ + int UNION = 2; + /** + * Simple list type. See {@link #getSimpleVariety} + */ + int LIST = 3; + + + /** + * For atomic types only: get the primitive type underlying this one. + *

+ * Returns null if this is not an atomic type. + */ + SchemaType getPrimitiveType(); + + /** + * For atomic numeric restrictions of decimal only: the + * numeric size category. Takes into account min and max + * restrictions as well as totalDigits and fractionDigits + * facets. + *

+ * Returns either {@link #NOT_DECIMAL}, + * {@link #SIZE_BYTE}, {@link #SIZE_SHORT}, {@link #SIZE_INT}, + * {@link #SIZE_LONG}, {@link #SIZE_BIG_INTEGER}, or + * {@link #SIZE_BIG_DECIMAL}. + */ + int getDecimalSize(); + + /** + * Not a decimal restriction. See {@link #getDecimalSize}. + */ + int NOT_DECIMAL = 0; + /** + * Fits in a byte. See {@link #getDecimalSize}. + */ + int SIZE_BYTE = 8; + /** + * Fits in a short. See {@link #getDecimalSize}. + */ + int SIZE_SHORT = 16; + /** + * Fits in an int. See {@link #getDecimalSize}. + */ + int SIZE_INT = 32; + /** + * Fits in a long. See {@link #getDecimalSize}. + */ + int SIZE_LONG = 64; + /** + * Fits in a {@link java.math.BigInteger}. See {@link #getDecimalSize}. + */ + int SIZE_BIG_INTEGER = 1000000; // "millions" + /** + * Fits in a {@link java.math.BigDecimal}. See {@link #getDecimalSize}. + */ + int SIZE_BIG_DECIMAL = 1000001; // "even more" + + /** + * For union types only: get the shallow member types. This + * returns the declared member types of the union, so, for + * example if the type contains another union, the nested + * members of that union are NOT returned here. + *

+ * Returns null if this type is not a union. + */ + SchemaType[] getUnionMemberTypes(); + + /** + * For union types only: gets the full tree of member types. + * This computes the closure of the set returned by + * getUnionMemberTypes(), so, for example, it returns + * all the types nested within unions of unions as well + * as the top-level members; the set also includes the + * type itself. If you are seeking only the basic + * non-union consituents, use getUnionConstituentTypes. + *

+ * Returns null if this type is not a union. + */ + SchemaType[] getUnionSubTypes(); + + /** + * For union types only: get the constituent member types. This + * returns only non-union types, so, for example, for unions of + * unions, this returns the flattened list of individual member + * types within the innermost unions. + *

+ * Returns null if this type is not a union. + */ + SchemaType[] getUnionConstituentTypes(); + + /** + * For union types only: get the most specific common base + * type of the constituent member types. May return a UR type. + *

+ * Returns null if this type is not a union. + */ + SchemaType getUnionCommonBaseType(); + + /** + * For anonymous types defined inside a union only: gets + * the integer indicating the declaration order of this + * type within the outer union type, or zero if this is + * not applicable. The first anonymous union member within + * a union type is numbered "1". Used to differentiate + * between different anonymous types. + */ + int getAnonymousUnionMemberOrdinal(); + + /** + * For list types only: get the item type. This is the atomic + * or union type that is the type of every entry in the list. + *

+ * Returns null if this type is not a list. + */ + SchemaType getListItemType(); + + /** + * For nonunion simple types: get the whitespace rule. This is + * either {@link #WS_PRESERVE}, {@link #WS_REPLACE}, or + * {@link #WS_COLLAPSE}. Returns {@link #WS_UNSPECIFIED} + * for unions and complex types. + */ + int getWhiteSpaceRule(); + + /** + * Whitespace rule unspecified. See {@link #getWhiteSpaceRule}. + */ + int WS_UNSPECIFIED = 0; + /** + * Whitespace preserved. See {@link #getWhiteSpaceRule}. + */ + int WS_PRESERVE = 1; + /** + * Whitespace replaced by ordinary space. See {@link #getWhiteSpaceRule}. + */ + int WS_REPLACE = 2; + /** + * Whitespace collapsed and trimmed. See {@link #getWhiteSpaceRule}. + */ + int WS_COLLAPSE = 3; + + /** + * Creates an immutable simple type value that does not reside in a tree. + */ + XmlAnySimpleType newValue(Object v); + + + /** + * Used to allow on-demand loading of types. + */ + final class Ref extends SchemaComponent.Ref { + public Ref(SchemaType type) { + super(type); + } + + public Ref(SchemaTypeSystem system, String handle) { + super(system, handle); + } + + public final int getComponentType() { + return SchemaComponent.TYPE; + } + + public final SchemaType get() { + return (SchemaType) getComponent(); + } + } + + /** + * Retruns a SchemaType.Ref pointing to this schema type itself. + */ + Ref getRef(); + + /** + * Returns a QNameSet of elements that may exist in wildcard + * buchets and are not explicitly defined in this schema type. + * Note: In this example: + * + * + * + * + * + * + * the returned QNameSet will not contain the qname of 'someElement'. + * + * @return the constructed QNameSet + */ + QNameSet qnameSetForWildcardElements(); + + /** + * Returns a QNameSet of attributes that may exist in wildcard + * buchets and are not explicitly defined in this schema type. + * Note: In this example: + * + * ... + * + * + * + * the returned QNameSet will not contain the qname of 'someAttribute'. + * + * @return the constructed QNameSet + */ + QNameSet qnameSetForWildcardAttributes(); +} diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaTypeElementSequencer.java b/src/main/java/org/apache/xmlbeans/SchemaTypeElementSequencer.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaTypeElementSequencer.java rename to src/main/java/org/apache/xmlbeans/SchemaTypeElementSequencer.java diff --git a/src/main/java/org/apache/xmlbeans/SchemaTypeLoader.java b/src/main/java/org/apache/xmlbeans/SchemaTypeLoader.java new file mode 100644 index 0000000..6928658 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/SchemaTypeLoader.java @@ -0,0 +1,223 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Node; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.net.URL; + +/** + * Represents a searchable set of XML Schema component definitions. + *

+ * SchemaTypeLoader is somewhat analogous to {@link java.lang.ClassLoader}, + * because it is responsible for finding {@link SchemaComponent} definitions + * by name, yet it is not responsible for being able to enumerate all the + * component definitons available. (If you wish to enumerate component + * definitions, see {@link SchemaTypeSystem}.) There are some ways in which + * SchemaTypeSystems are dissimilar from ClassLoaders, however. + * Since XML Schema has a number of instance-oriented typing mechanisms + * (such as wildcards) that do not exist in Java, a SchemaTypeLoader is + * not associated with a type; instead, a SchemaTypeLoader is associated + * with each XML instance. + *

+ * Every XML instance is loaded within the context of a SchemaTypeLoader; + * the SchemaTypeLoader for an instance is used to resolve all type definitions + * within the instance and for applying type-sensitive methods such as + * {@link XmlObject#validate}. + *

+ * Normally the SchemaTypeLoader being used for all instances is the + * context type loader (that is, the SchemaTypeLoader returned from + * {@link XmlBeans#getContextTypeLoader()}). The context type loader + * consults the thread's context ClassLoader (see {@link Thread#getContextClassLoader()}) + * to find schema type defintions that are available on the classpath. + * The net result is that you can use schema types simply by putting + * their compiled schema JARs on your classpath. + * If you wish to load instances using a different SchemaTypeLoader, then you must + * call {@link #parse} methods on the SchemaTypeLoader instance explicitly + * rather than using the normal convenient Factory methods. + *

+ * A SchemaTypeLoader can be obtained by dynamically loading XSD files + * using {@link XmlBeans#loadXsd}, or by assembling other SchemaTypeLoaders + * or SchemaTypeSystems on a path using {@link XmlBeans#typeLoaderUnion}. + * + * @see XmlBeans#loadXsd + * @see XmlBeans#getContextTypeLoader + * @see XmlBeans#typeLoaderUnion + * @see SchemaTypeSystem + */ +public interface SchemaTypeLoader { + /** + * Returns the type with the given name, or null if none. + */ + SchemaType findType(QName name); + + /** + * Returns the document type rooted at the given element name, or null if none. + */ + SchemaType findDocumentType(QName name); + + /** + * Returns the attribute type containing the given attribute name, or null if none. + */ + SchemaType findAttributeType(QName name); + + /** + * Returns the global element defintion with the given name, or null if none. + */ + SchemaGlobalElement findElement(QName name); + + /** + * Returns the global attribute defintion with the given name, or null if none. + */ + SchemaGlobalAttribute findAttribute(QName name); + + /** + * Returns the model group defintion with the given name, or null if none. + */ + SchemaModelGroup findModelGroup(QName name); + + /** + * Returns the attribute group defintion with the given name, or null if none. + */ + SchemaAttributeGroup findAttributeGroup(QName name); + + /** + * True if the typeloader contains any definitions in the given namespace. + */ + boolean isNamespaceDefined(String namespace); + + /** + * Used for on-demand loading. + */ + SchemaType.Ref findTypeRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaType.Ref findDocumentTypeRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaType.Ref findAttributeTypeRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaGlobalElement.Ref findElementRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaGlobalAttribute.Ref findAttributeRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaModelGroup.Ref findModelGroupRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaAttributeGroup.Ref findAttributeGroupRef(QName name); + + /** + * Used for on-demand loading. + */ + SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name); + + /** + * Finds a type for a given signature string + */ + SchemaType typeForSignature(String signature); + + /** + * Finds a type for a given fully-qualified XML Bean classname + */ + SchemaType typeForClassname(String classname); + + /** + * Loads original XSD source as a stream. See {@link SchemaType#getSourceName}. + */ + InputStream getSourceAsStream(String sourceName); + + /** + * Compiles an XPath + */ + String compilePath(String pathExpr, XmlOptions options) throws XmlException; + + /** + * Compiles an XQuery + */ + String compileQuery(String queryExpr, XmlOptions options) throws XmlException; + + /** + * Creates an instance of the given type. + */ + XmlObject newInstance(SchemaType type, XmlOptions options); + + /** + * Parses an instance of the given type. + */ + XmlObject parse(String xmlText, SchemaType type, XmlOptions options) throws XmlException; + + /** + * Parses an instance of the given type. + */ + XmlObject parse(File file, SchemaType type, XmlOptions options) throws XmlException, IOException; + + /** + * Parses an instance of the given type. + */ + XmlObject parse(URL file, SchemaType type, XmlOptions options) throws XmlException, IOException; + + /** + * Parses an instance of the given type. + */ + XmlObject parse(InputStream jiois, SchemaType type, XmlOptions options) throws XmlException, IOException; + + /** + * Parses an instance of the given type. + */ + XmlObject parse(XMLStreamReader xsr, SchemaType type, XmlOptions options) throws XmlException; + + /** + * Parses an instance of the given type. + */ + XmlObject parse(Reader jior, SchemaType type, XmlOptions options) throws XmlException, IOException; + + /** + * Parses an instance of the given type. + */ + XmlObject parse(Node node, SchemaType type, XmlOptions options) throws XmlException; + + /** + * Returns an XmlSaxHandler that can parse an instance of the given type. + */ + XmlSaxHandler newXmlSaxHandler(SchemaType type, XmlOptions options); + + /** + * Returns a DOMImplementation. + */ + DOMImplementation newDomImplementation(XmlOptions options); +} diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoaderException.java b/src/main/java/org/apache/xmlbeans/SchemaTypeLoaderException.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoaderException.java rename to src/main/java/org/apache/xmlbeans/SchemaTypeLoaderException.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaTypeSystem.java b/src/main/java/org/apache/xmlbeans/SchemaTypeSystem.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SchemaTypeSystem.java rename to src/main/java/org/apache/xmlbeans/SchemaTypeSystem.java diff --git a/src/main/java/org/apache/xmlbeans/SimpleValue.java b/src/main/java/org/apache/xmlbeans/SimpleValue.java new file mode 100644 index 0000000..9e6d5dd --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/SimpleValue.java @@ -0,0 +1,246 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.namespace.QName; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +/** + * All XmlObject implementations can be coerced to SimpleValue. + * For any given schema type, only a subset of the conversion + * methods will work. Others will throw an exception. + *

+ * SimpleValue is useful for declaring variables which can hold + * more than one similar schema type that may not happen to + * have a common XML base type, for example, two list types, + * or two unrelated integer restrictions that happen to fit + * into an int. + */ +public interface SimpleValue extends XmlObject { + /** + * The same as getSchemaType unless this is a union instance + * or nil value. + *

+ * For unions, this returns the non-union consituent type of + * this instance. This type may change if setters are called + * that cause the instance to change to another constituent + * type of the union. + *

+ * For nil values, this returns null. + */ + SchemaType instanceType(); + + /** + * Returns the value as a {@link String}. + */ + String getStringValue(); + + /** + * Returns the value as a boolean. + */ + boolean getBooleanValue(); + + /** + * Returns the value as a byte. + */ + byte getByteValue(); + + /** + * Returns the value as a short. + */ + short getShortValue(); + + /** + * Returns the value as an int. + */ + int getIntValue(); + + /** + * Returns the value as a long. + */ + long getLongValue(); + + /** + * Returns the value as a {@link BigInteger}. + */ + BigInteger getBigIntegerValue(); + + /** + * Returns the value as a {@link BigDecimal}. + */ + BigDecimal getBigDecimalValue(); + + /** + * Returns the value as a float. + */ + float getFloatValue(); + + /** + * Returns the value as a double. + */ + double getDoubleValue(); + + /** + * Returns the value as a byte array. + */ + byte[] getByteArrayValue(); + + /** + * Returns the value as a {@link StringEnumAbstractBase}. + */ + StringEnumAbstractBase getEnumValue(); + + /** + * Returns the value as a {@link Calendar}. + */ + Calendar getCalendarValue(); + + /** + * Returns the value as a {@link Date}. + */ + Date getDateValue(); + + /** + * Returns the value as a {@link GDate}. + */ + GDate getGDateValue(); + + /** + * Returns the value as a {@link GDuration}. + */ + GDuration getGDurationValue(); + + /** + * Returns the value as a {@link QName}. + */ + QName getQNameValue(); + + /** + * Returns the value as a {@link List} of friendly Java objects (String, Integer, Byte, Short, Long, BigInteger, Decimal, Float, Double, byte[], Calendar, GDuration). + */ + List getListValue(); + + /** + * Returns the value as a {@link List} of XmlAnySimpleType objects. + */ + List xgetListValue(); + + /** + * Returns a union value as a its natural friendly Java object (String, Integer, Byte, Short, Long, BigInteger, Decimal, Float, Double, byte[], Calendar, GDuration). + */ + Object getObjectValue(); + + // following are simple type value setters + + /** + * Sets the value as a {@link String}. + */ + void setStringValue(String obj); + + /** + * Sets the value as a boolean. + */ + void setBooleanValue(boolean v); + + /** + * Sets the value as a byte. + */ + void setByteValue(byte v); + + /** + * Sets the value as a short. + */ + void setShortValue(short v); + + /** + * Sets the value as an int. + */ + void setIntValue(int v); + + /** + * Sets the value as a long. + */ + void setLongValue(long v); + + /** + * Sets the value as a {@link BigInteger}. + */ + void setBigIntegerValue(BigInteger obj); + + /** + * Sets the value as a {@link BigDecimal}. + */ + void setBigDecimalValue(BigDecimal obj); + + /** + * Sets the value as a float. + */ + void setFloatValue(float v); + + /** + * Sets the value as a double. + */ + void setDoubleValue(double v); + + /** + * Sets the value as a byte array. + */ + void setByteArrayValue(byte[] obj); + + /** + * Sets the value as a {@link StringEnumAbstractBase}. + */ + void setEnumValue(StringEnumAbstractBase obj); + + /** + * Sets the value as a {@link Calendar}. + */ + void setCalendarValue(Calendar obj); + + /** + * Sets the value as a {@link Date}. + */ + void setDateValue(Date obj); + + /** + * Sets the value as a {@link GDate}. + */ + void setGDateValue(GDate obj); + + /** + * Sets the value as a {@link GDuration}. + */ + void setGDurationValue(GDuration obj); + + /** + * Sets the value as a {@link QName}. + */ + void setQNameValue(QName obj); + + /** + * Sets the value as a {@link List}. + */ + void setListValue(List obj); + + /** + * Sets the value as an arbitrary {@link Object}. + */ + void setObjectValue(Object obj); +} diff --git a/src/xmlpublic/org/apache/xmlbeans/StringEnumAbstractBase.java b/src/main/java/org/apache/xmlbeans/StringEnumAbstractBase.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/StringEnumAbstractBase.java rename to src/main/java/org/apache/xmlbeans/StringEnumAbstractBase.java diff --git a/src/xmlpublic/org/apache/xmlbeans/SystemProperties.java b/src/main/java/org/apache/xmlbeans/SystemProperties.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/SystemProperties.java rename to src/main/java/org/apache/xmlbeans/SystemProperties.java diff --git a/src/main/java/org/apache/xmlbeans/ThreadLocalUtil.java b/src/main/java/org/apache/xmlbeans/ThreadLocalUtil.java new file mode 100644 index 0000000..614cade --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/ThreadLocalUtil.java @@ -0,0 +1,46 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import org.apache.xmlbeans.impl.common.SystemCache; +import org.apache.xmlbeans.impl.schema.StscState; +import org.apache.xmlbeans.impl.store.CharUtil; +import org.apache.xmlbeans.impl.store.Locale; +import org.apache.xmlbeans.impl.values.NamespaceContext; + +public class ThreadLocalUtil { + + /** + * Clear {@link ThreadLocal}s of the current thread. + * + * This can be used to clean out a thread before "returning" + * it to a thread-pool or a Web-Container like Tomcat. + */ + public static void clearAllThreadLocals() { + // clear thread locals in all classes which may hold some + XmlBeans.clearThreadLocals(); + XmlFactoryHook.ThreadContext.clearThreadLocals(); + StscState.clearThreadLocals(); + CharUtil.clearThreadLocals(); + Locale.clearThreadLocals(); + NamespaceContext.clearThreadLocals(); + + // SystemCache is not a singleton, but also creates ThreadLocals, + // so we get the current instance and clean it out as well + SystemCache systemCache = SystemCache.get(); + systemCache.clearThreadLocals(); + } +} diff --git a/src/xmlpublic/org/apache/xmlbeans/UserType.java b/src/main/java/org/apache/xmlbeans/UserType.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/UserType.java rename to src/main/java/org/apache/xmlbeans/UserType.java diff --git a/src/main/java/org/apache/xmlbeans/XmlAnySimpleType.java b/src/main/java/org/apache/xmlbeans/XmlAnySimpleType.java new file mode 100644 index 0000000..b4d8a01 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlAnySimpleType.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:anySimpleType type. + *

+ * All simple types are convertible to {@link String}. + */ +public interface XmlAnySimpleType extends XmlObject { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_anySimpleType"); + + /** + * Returns the value as a {@link String} + **/ + String getStringValue(); + + /** + * Sets the value as a {@link String} + **/ + void setStringValue(String s); + + /** + * A class with methods for creating instances + * of {@link XmlAnySimpleType}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlAnySimpleType} + */ + public static XmlAnySimpleType newInstance() { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlAnySimpleType} + */ + public static XmlAnySimpleType newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlAnySimpleType} value + */ + public static XmlAnySimpleType newValue(Object obj) { + return type.newValue(obj); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a String. For example: "<xml-fragment>anything</xml-fragment>". + */ + public static XmlAnySimpleType parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a String. For example: "<xml-fragment>anything</xml-fragment>". + */ + public static XmlAnySimpleType parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a File. + */ + public static XmlAnySimpleType parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a File. + */ + public static XmlAnySimpleType parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a URL. + */ + public static XmlAnySimpleType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a URL. + */ + public static XmlAnySimpleType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from an InputStream. + */ + public static XmlAnySimpleType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from an InputStream. + */ + public static XmlAnySimpleType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a Reader. + */ + public static XmlAnySimpleType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a Reader. + */ + public static XmlAnySimpleType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a DOM Node. + */ + public static XmlAnySimpleType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from a DOM Node. + */ + public static XmlAnySimpleType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from an XMLStreamReader. + */ + public static XmlAnySimpleType parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlAnySimpleType} fragment from an XMLStreamReader. + */ + public static XmlAnySimpleType parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlAnyURI.java b/src/main/java/org/apache/xmlbeans/XmlAnyURI.java new file mode 100644 index 0000000..8fbe686 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlAnyURI.java @@ -0,0 +1,159 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:anyURI type. + *

+ * Convertible to {@link String}. + */ +public interface XmlAnyURI extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_anyURI"); + + /** + * A class with methods for creating instances + * of {@link XmlAnyURI}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlAnyURI} + */ + public static XmlAnyURI newInstance() { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlAnyURI} + */ + public static XmlAnyURI newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlAnyURI} value + */ + public static XmlAnyURI newValue(Object obj) { + return (XmlAnyURI) type.newValue(obj); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a String. For example: "<xml-fragment>http://www.w3.org/</xml-fragment>". + */ + public static XmlAnyURI parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a String. For example: "<xml-fragment>http://www.w3.org/</xml-fragment>". + */ + public static XmlAnyURI parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a File. + */ + public static XmlAnyURI parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a File. + */ + public static XmlAnyURI parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a URL. + */ + public static XmlAnyURI parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a URL. + */ + public static XmlAnyURI parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlAnyURI} fragment from an InputStream. + */ + public static XmlAnyURI parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from an InputStream. + */ + public static XmlAnyURI parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a Reader. + */ + public static XmlAnyURI parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a Reader. + */ + public static XmlAnyURI parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a DOM Node. + */ + public static XmlAnyURI parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from a DOM Node. + */ + public static XmlAnyURI parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlAnyURI} fragment from an XMLStreamReader. + */ + public static XmlAnyURI parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlAnyURI} fragment from an XMLStreamReader. + */ + public static XmlAnyURI parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlBase64Binary.java b/src/main/java/org/apache/xmlbeans/XmlBase64Binary.java new file mode 100644 index 0000000..52f4f29 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlBase64Binary.java @@ -0,0 +1,170 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:base64Binary type. + *

+ * Convertible to a byte array. + */ +public interface XmlBase64Binary extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_base64Binary"); + + /** + * Returns this value as a byte array. + **/ + byte[] getByteArrayValue(); + + /** + * Sets this value as a byte array. + */ + void setByteArrayValue(byte[] ba); + + + /** + * A class with methods for creating instances + * of {@link XmlBase64Binary}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlBase64Binary} + */ + public static XmlBase64Binary newInstance() { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlBase64Binary} + */ + public static XmlBase64Binary newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlBase64Binary} value + */ + public static XmlBase64Binary newValue(Object obj) { + return (XmlBase64Binary) type.newValue(obj); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a String. For example: "<xml-fragment>VGhpcyBzdHJp</xml-fragment>". + */ + public static XmlBase64Binary parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a String. For example: "<xml-fragment>VGhpcyBzdHJp</xml-fragment>". + */ + public static XmlBase64Binary parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a File. + */ + public static XmlBase64Binary parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a File. + */ + public static XmlBase64Binary parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a URL. + */ + public static XmlBase64Binary parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a URL. + */ + public static XmlBase64Binary parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from an InputStream. + */ + public static XmlBase64Binary parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from an InputStream. + */ + public static XmlBase64Binary parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a Reader. + */ + public static XmlBase64Binary parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a Reader. + */ + public static XmlBase64Binary parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a DOM Node. + */ + public static XmlBase64Binary parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from a DOM Node. + */ + public static XmlBase64Binary parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from an XMLStreamReader. + */ + public static XmlBase64Binary parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlBase64Binary} fragment from an XMLStreamReader. + */ + public static XmlBase64Binary parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlBeans.java b/src/main/java/org/apache/xmlbeans/XmlBeans.java new file mode 100644 index 0000000..5c131a2 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlBeans.java @@ -0,0 +1,521 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.schema.PathResourceLoader; +import org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl; +import org.apache.xmlbeans.impl.schema.SchemaTypeSystemCompiler; +import org.apache.xmlbeans.impl.store.Locale; +import org.w3c.dom.Node; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import java.io.File; +import java.lang.ref.SoftReference; +import java.lang.reflect.Field; + +/** + * Provides an assortment of utilities + * for managing XML Bean types, type systems, QNames, paths, + * and queries. + */ +public final class XmlBeans { + private static final String HOLDER_CLASS_NAME = "TypeSystemHolder"; + private static final String TYPE_SYSTEM_FIELD = "typeSystem"; + + private static String XMLBEANS_TITLE = "org.apache.xmlbeans"; + private static String XMLBEANS_VERSION = "4.0.0"; + private static String XMLBEANS_VENDOR = "Apache Software Foundation"; + + static { + Package pkg = XmlBeans.class.getPackage(); + if (pkg != null && pkg.getImplementationVersion() != null) { + XMLBEANS_TITLE = pkg.getImplementationTitle(); + XMLBEANS_VERSION = pkg.getImplementationVersion(); + XMLBEANS_VENDOR = pkg.getImplementationVendor(); + } + } + + /** + * Returns the XmlBeans Package title, "org.apache.xmlbeans", + * the value of + * {@link Package#getImplementationTitle() XmlBeans.class.getPackage().getImplementationTitle()}. + */ + public static final String getTitle() { + return XMLBEANS_TITLE; + } + + /** + * Returns the XmlBeans vendor, "Apache Software Foundation", + * the value of + * {@link Package#getImplementationVendor() XmlBeans.class.getPackage().getImplementationVendor()}. + */ + public static final String getVendor() { + return XMLBEANS_VENDOR; + } + + /** + * Returns the XmlBeans version, + * the value of + * {@link Package#getImplementationVersion() XmlBeans.class.getPackage().getImplementationVersion()}. + */ + public static final String getVersion() { + return XMLBEANS_VERSION; + } + + /** + * Thread local QName cache for general use + */ + private static final ThreadLocal _threadLocalLoaderQNameCache = + new ThreadLocal() { + protected Object initialValue() { + return new SoftReference(new QNameCache(32)); + } + }; + + public static void clearThreadLocals() { + // clear thread local here + _threadLocalLoaderQNameCache.remove(); + } + + /** + * Returns a thread local QNameCache + */ + public static QNameCache getQNameCache() { + SoftReference softRef = (SoftReference) _threadLocalLoaderQNameCache.get(); + QNameCache qnameCache = (QNameCache) (softRef).get(); + if (qnameCache == null) { + qnameCache = new QNameCache(32); + _threadLocalLoaderQNameCache.set(new SoftReference(qnameCache)); + } + return qnameCache; + } + + /** + * Obtains a name from the thread local QNameCache + */ + public static QName getQName(String localPart) { + return getQNameCache().getName("", localPart); + } + + /** + * Obtains a name from the thread local QNameCache + */ + + public static QName getQName(String namespaceUri, String localPart) { + return getQNameCache().getName(namespaceUri, localPart); + } + + private static RuntimeException causedException(RuntimeException e, Throwable cause) { + e.initCause(cause); + + return e; + } + + /** + * Compiles an XPath, returning a String equal to that which was passed, + * but whose identity is that of one which has been precompiled and cached. + */ + public static String compilePath(String pathExpr) throws XmlException { + return compilePath(pathExpr, null); + } + + /** + * Compiles an XPath, returning a String equal to that which was passed, + * but whose identity is that of one which has been precompiled and cached; + * takes an option for specifying text that indicates the name of context node. + * The default is "this", as in "$this". + * + * @param options Options for the path. For example, you can call + * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} + * method to specify a particular name for the expression + * variable that indicates the context node. + */ + public static String compilePath(String pathExpr, XmlOptions options) + throws XmlException { + return getContextTypeLoader().compilePath(pathExpr, options); + } + + /** + * Compiles an XQuery, returning a String equal to that which was passed, + * but whose identity is that of one which has been precompiled and cached. + */ + public static String compileQuery(String queryExpr) throws XmlException { + return compileQuery(queryExpr, null); + } + + /** + * Compiles an XQuery, returning a String equal to that which was passed, + * but whose identity is that of one which has been precompiled and cached; + * takes an option for specifying text that indicates the context node. + * + * @param options Options for the query. For example, you can call + * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} + * method to specify a particular name for the expression + * variable that indicates the context node and the + * {@link XmlOptions#setXqueryVariables(java.util.Map) XmlOptions.setXqueryVariables(Map)} + * method to map external variable names to values. + */ + public static String compileQuery(String queryExpr, XmlOptions options) + throws XmlException { + return getContextTypeLoader().compileQuery(queryExpr, options); + } + + /** + * Gets the SchemaTypeLoader based on the current thread's context + * ClassLoader. This is the SchemaTypeLoader that is used to assign + * schema types to XML documents by default. The SchemaTypeLoader is + * also consulted to resolve wildcards and xsi:type attributes. + *

+ * The "parse" methods of XmlBeans all delegate to the + * "parseInstance" methods of the context type loader. + */ + public static SchemaTypeLoader getContextTypeLoader() { + return SchemaTypeLoaderImpl.getContextTypeLoader(); + } + + /** + * Returns the builtin type system. This SchemaTypeSystem contains + * only the 46 builtin types defined by the XML Schema specification. + */ + public static SchemaTypeSystem getBuiltinTypeSystem() { + return BuiltinSchemaTypeSystem.get(); + } + + /** + * Creates an XmlCursor for a DOM node which is implemented by XmlBwans + */ + public static XmlCursor nodeToCursor(Node n) { + return Locale.nodeToCursor(n); + } + + /** + * Creates an XmlObject for a DOM node which is implemented by XmlBwans + */ + public static XmlObject nodeToXmlObject(Node n) { + return Locale.nodeToXmlObject(n); + } + + /** + * Creates an XmlObject for a DOM node which is implemented by XmlBwans + */ + public static XMLStreamReader nodeToXmlStreamReader(Node n) { + return Locale.nodeToXmlStream(n); + } + + /** + * Returns the XmlObject for a DOM node which is implemented by XmlBwans + */ + public static Node streamToNode(XMLStreamReader xs) { + return Locale.streamToNode(xs); + } + + /** + * Returns the SchemaTypeSystem that results from compiling the XML + * schema definitions passed. + *

+ * Just like compileXsd, but uses the context type loader for + * linking, and returns a unioned typeloader that is suitable for + * creating instances. + */ + public static SchemaTypeLoader loadXsd(XmlObject[] schemas) throws XmlException { + return loadXsd(schemas, null); + } + + /** + *

Returns the SchemaTypeSystem that results from compiling the XML + * schema definitions passed in schemas.

+ * + *

This is just like compileXsd, but uses the context type loader for + * linking, and returns a unioned typeloader that is suitable for + * creating instances.

+ * + *

Use the options parameter to specify one or both of the following:

+ * + *
    + *
  • A collection instance that should be used as an error listener during + * compilation, as described in {@link XmlOptions#setErrorListener}.
  • + *
  • Whether validation should not be done when building the SchemaTypeSystem, + * as described in {@link XmlOptions#setCompileNoValidation}.
  • + *
+ * + * @param schemas The schema definitions from which to build the schema type system. + * @param options Options specifying an error listener and/or validation behavior. + */ + public static SchemaTypeLoader loadXsd(XmlObject[] schemas, XmlOptions options) throws XmlException { + SchemaTypeSystem sts = SchemaTypeSystemCompiler.compile(null, null, schemas, null, getContextTypeLoader(), null, options); + return (sts == null) ? null : typeLoaderUnion(sts, getContextTypeLoader()); + } + + + /** + *

Returns the SchemaTypeSystem that results from compiling the XML + * schema definitions passed.

+ * + *

The XmlObjects passed in should be w3c <schema> elements whose type + * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in + * the XML namespace http://www.w3c.org/2001/XMLSchema.) Also + * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.

+ * + *

The optional second argument is a SchemaTypeLoader which will be + * consulted for already-compiled schema types which may be linked + * while processing the given schemas.

+ * + *

The SchemaTypeSystem that is returned should be combined + * (via {@link #typeLoaderUnion}) with the typepath typeloader in order + * to create a typeloader that can be used for creating and validating + * instances.

+ * + *

Use the options parameter to specify the following:

+ * + *
    + *
  • A collection instance that should be used as an error listener during + * compilation, as described in {@link XmlOptions#setErrorListener}.
  • + *
  • Whether validation should not be done when building the SchemaTypeSystem, + * as described in {@link XmlOptions#setCompileNoValidation}.
  • + *
+ * + * @param schemas The schema definitions from which to build the schema type system. + * @param typepath The path to already-compiled schema types for linking while processing. + * @param options Options specifying an error listener and/or validation behavior. + */ + public static SchemaTypeSystem compileXsd(XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException { + return compileXmlBeans(null, null, schemas, null, typepath, null, options); + } + + /** + *

Returns the SchemaTypeSystem that results from augumenting the + * SchemaTypeSystem passed in by incrementally adding the given XML + * schema definitions.

+ * + *

These could be new definitions (if the Schema document is not recorded into + * the existing SchemaTypeSystem), modifications to the already existing + * definitions (if the Schema document is already recorded in the existing + * SchemaTypeSystem), or deletions (if the Schema document is already recorded + * in the existing SchemaTypeSystem and the new definitions are empty). + * The identity of documents is established using + * {@link XmlDocumentProperties#getSourceName}, so if the caller choses to + * construct the Schema definitions using other methods than parsing an + * XML document, they should make sure that the names returned by that + * method are consistent with the caller's intent (add/modify).

+ * + *

The XmlObjects passed in should be w3c <schema> elements whose type + * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in + * the XML namespace http://www.w3c.org/2001/XMLSchema.) Also + * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.

+ * + *

The optional second argument is a SchemaTypeLoader which will be + * consulted for already-compiled schema types which may be linked + * while processing the given schemas.

+ * + *

The SchemaTypeSystem that is returned should be combined + * (via {@link #typeLoaderUnion}) with the typepath typeloader in order + * to create a typeloader that can be used for creating and validating + * instances.

+ * + *

Use the options parameter to specify the following:

+ * + *
    + *
  • A collection instance that should be used as an error listener during + * compilation, as described in {@link XmlOptions#setErrorListener}.
  • + *
  • Whether validation should not be done when building the SchemaTypeSystem, + * as described in {@link XmlOptions#setCompileNoValidation}.
  • + *
+ * + * @param schemas The schema definitions from which to build the schema type system. + * @param typepath The path to already-compiled schema types for linking while processing. + * @param options Options specifying an error listener and/or validation behavior. + */ + public static SchemaTypeSystem compileXsd(SchemaTypeSystem system, XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException { + return compileXmlBeans(null, system, schemas, null, typepath, null, options); + } + + /** + *

Returns the SchemaTypeSystem that results from augumenting the + * SchemaTypeSystem passed in by incrementally adding the given XML + * schema definitions.

+ * + *

These could be new definitions (if the Schema document is not recorded into + * the existing SchemaTypeSystem), modifications to the already existing + * definitions (if the Schema document is already recorded in the existing + * SchemaTypeSystem), or deletions (if the Schema document is already recorded + * in the existing SchemaTypeSystem and the new definitions are empty). + * The identity of documents is established using + * {@link XmlDocumentProperties#getSourceName}, so if the caller choses to + * construct the Schema definitions using other methods than parsing an + * XML document, they should make sure that the names returned by that + * method are consistent with the caller's intent (add/modify).

+ * + *

The XmlObjects passed in should be w3c <schema> elements whose type + * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in + * the XML namespace http://www.w3c.org/2001/XMLSchema.) Also + * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.

+ * + *

The optional name argument is used to name the compiled schema type system. + * A randomly generated name will be used if the name is null.

+ * + *

The optional {@link BindingConfig} argument is used to control the shape + * of the generated code. A BindingConfig isn't used if Filer + * is null.

+ * + *

The optional SchemaTypeLoader argument will be + * consulted for already-compiled schema types which may be linked + * while processing the given schemas. If not specified, the context + * typeloader (as returned by {@link #getContextTypeLoader}) will be used.

+ * + *

The optional {@link Filer} argument is used to create new binary or source + * files which are the product of the compilation. If the Filer is null, the + * schema binaries (.xsb) files and source files won't be generated.

+ * + *

The SchemaTypeSystem that is returned should be combined + * (via {@link #typeLoaderUnion}) with the typepath typeloader in order + * to create a typeloader that can be used for creating and validating + * instances.

+ * + *

Use the options parameter to specify the following:

+ * + *
    + *
  • A collection instance that should be used as an error listener during + * compilation, as described in {@link XmlOptions#setErrorListener}.
  • + *
  • Whether validation should not be done when building the SchemaTypeSystem, + * as described in {@link XmlOptions#setCompileNoValidation}.
  • + *
+ * + * @param name The type system name or null to use a randomly generated name. + * @param system A pre-existing SchemaTypeSystem used in incremental compilation. + * @param schemas The schema definitions from which to build the schema type system. + * @param config The configuration controls the code generation shape. + * @param typepath The path to already-compiled schema types for linking while processing. + * @param filer The Filer instance used to create binary binding files and source text files. + * @param options Options specifying an error listener and/or validation behavior. + */ + public static SchemaTypeSystem compileXmlBeans(String name, SchemaTypeSystem system, XmlObject[] schemas, BindingConfig config, SchemaTypeLoader typepath, Filer filer, XmlOptions options) throws XmlException { + return SchemaTypeSystemCompiler.compile(name, system, schemas, config, typepath != null ? typepath : getContextTypeLoader(), filer, options); + } + + + /** + * Returns the union of a list of typeLoaders. The returned + * SchemaTypeLoader searches the given list of SchemaTypeLoaders + * in order from first to last. + */ + public static SchemaTypeLoader typeLoaderUnion(SchemaTypeLoader... typeLoaders) { + return (typeLoaders.length == 1) ? typeLoaders[0] : SchemaTypeLoaderImpl.build(typeLoaders, null, null); + } + + /** + * Returns a SchemaTypeLoader that searches for compiled schema types + * in the given ClassLoader. + */ + public static SchemaTypeLoader typeLoaderForClassLoader(ClassLoader loader) { + return SchemaTypeLoaderImpl.build(null, null, loader); + } + + /** + * Returns a SchemaTypeLoader that searches for compiled schema types + * in the given ResourceLoader. + * + * @see XmlBeans#resourceLoaderForPath(File[]) + */ + public static SchemaTypeLoader typeLoaderForResource(ResourceLoader resourceLoader) { + return SchemaTypeLoaderImpl.build(null, resourceLoader, null); + } + + /** + * Returns the SchemaTypeSystem of the given name (as returned by + * {@link SchemaTypeSystem#getName}) for the given ClassLoader. + *

+ * Note: you will almost always need typeLoaderForClassLoader() + * instead (see {@link XmlBeans#typeLoaderForClassLoader}). + */ + public static SchemaTypeSystem typeSystemForClassLoader(ClassLoader loader, String stsName) { + try { + ClassLoader cl = loader == null ? Thread.currentThread().getContextClassLoader() : loader; + Class clazz = cl.loadClass(stsName + "." + HOLDER_CLASS_NAME); + SchemaTypeSystem sts = (SchemaTypeSystem) + (clazz.getDeclaredField(TYPE_SYSTEM_FIELD).get(null)); + if (sts == null) { + throw new RuntimeException("SchemaTypeSystem is null for field " + + TYPE_SYSTEM_FIELD + " on class with name " + stsName + + "." + HOLDER_CLASS_NAME + + ". Please verify the version of xmlbeans.jar is correct."); + } + return sts; + } catch (ClassNotFoundException e) { + throw causedException(new RuntimeException("Cannot load SchemaTypeSystem. " + + "Unable to load class with name " + stsName + "." + HOLDER_CLASS_NAME + + ". Make sure the generated binary files are on the classpath."), e); + } catch (NoSuchFieldException e) { + throw causedException(new RuntimeException("Cannot find field " + + TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME + + ". Please verify the version of xmlbeans.jar is correct."), e); + } catch (IllegalAccessException e) { + throw causedException(new RuntimeException("Field " + + TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME + + "is not accessible. Please verify the version of xmlbeans.jar is correct."), e); + } + } + + /** + * Returns a new ResourceLoader for a search path where each component of + * the path is either a directory or a compiled xmlbeans jar. + */ + public static ResourceLoader resourceLoaderForPath(File[] path) { + return new PathResourceLoader(path); + } + + /** + * Returns the SchemaType from a corresponding XmlObject subclass, + * or null if none. + */ + public static SchemaType typeForClass(Class c) { + if (c == null || !XmlObject.class.isAssignableFrom(c)) { + return null; + } + + try { + Field typeField = c.getField("type"); + + if (typeField == null) { + return null; + } + + return (SchemaType) typeField.get(null); + } catch (Exception e) { + return null; + } + } + + private static SchemaType getNoType() { + return org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem.getNoType(); + } + + /** + * The SchemaType object given to an XmlObject instance when + * no type can be determined. + *

+ * The NO_TYPE is the universal derived type. That is, it is + * derived from all other schema types, and no instances of the + * NO_TYPE are valid. (It is not to be confused with the anyType, + * which is the universal base type from which all other types + * can be derived, and of which all instances are valid.) + */ + public static final SchemaType NO_TYPE = getNoType(); + + private XmlBeans() { + } +} diff --git a/src/main/java/org/apache/xmlbeans/XmlBoolean.java b/src/main/java/org/apache/xmlbeans/XmlBoolean.java new file mode 100644 index 0000000..9d84b6f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlBoolean.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:boolean type. + *

+ * Naturally, convertible to Java boolean. + */ +public interface XmlBoolean extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_boolean"); + + /** + * Returns this value as a boolean + */ + boolean getBooleanValue(); + + /** + * Sets this value as a boolean + */ + void setBooleanValue(boolean v); + + /** + * A class with methods for creating instances + * of {@link XmlBoolean}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlBoolean} + */ + public static XmlBoolean newInstance() { + return (XmlBoolean) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlBoolean} + */ + public static XmlBoolean newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlBoolean) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlBoolean} value + */ + public static XmlBoolean newValue(Object obj) { + return (XmlBoolean) type.newValue(obj); + } + + /** + * Parses a {@link XmlBoolean} fragment from a String. For example: "<xml-fragment>true</xml-fragment>". + */ + public static XmlBoolean parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from a String. For example: "<xml-fragment>true</xml-fragment>". + */ + public static XmlBoolean parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlBoolean} fragment from a File. + */ + public static XmlBoolean parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from a File. + */ + public static XmlBoolean parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlBoolean} fragment from a URL. + */ + public static XmlBoolean parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from a URL. + */ + public static XmlBoolean parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlBoolean} fragment from an InputStream. + */ + public static XmlBoolean parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from an InputStream. + */ + public static XmlBoolean parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlBoolean} fragment from a Reader. + */ + public static XmlBoolean parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from a Reader. + */ + public static XmlBoolean parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlBoolean} fragment from a DOM Node. + */ + public static XmlBoolean parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from a DOM Node. + */ + public static XmlBoolean parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlBoolean} fragment from an XMLStreamReader. + */ + public static XmlBoolean parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlBoolean} fragment from an XMLStreamReader. + */ + public static XmlBoolean parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlBoolean) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlByte.java b/src/main/java/org/apache/xmlbeans/XmlByte.java new file mode 100644 index 0000000..05093e6 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlByte.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:byte type. + *

+ * Naturally, convertible to Java byte. + */ +public interface XmlByte extends XmlShort { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_byte"); + + /** + * Returns this value as a byte + */ + byte getByteValue(); + + /** + * Sets this value as a byte + */ + void setByteValue(byte s); + + /** + * A class with methods for creating instances + * of {@link XmlByte}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlByte} + */ + static XmlByte newInstance() { + return (XmlByte) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlByte} + */ + static XmlByte newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlByte) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlByte} value + */ + static XmlByte newValue(Object obj) { + return (XmlByte) type.newValue(obj); + } + + /** + * Parses a {@link XmlByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". + */ + static XmlByte parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". + */ + static XmlByte parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlByte} fragment from a File. + */ + static XmlByte parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from a File. + */ + static XmlByte parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlByte} fragment from a URL. + */ + static XmlByte parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from a URL. + */ + static XmlByte parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlByte} fragment from an InputStream. + */ + static XmlByte parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from an InputStream. + */ + static XmlByte parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlByte} fragment from a Reader. + */ + static XmlByte parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from a Reader. + */ + static XmlByte parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlByte} fragment from a DOM Node. + */ + static XmlByte parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from a DOM Node. + */ + static XmlByte parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlByte} fragment from an XMLStreamReader. + */ + static XmlByte parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlByte} fragment from an XMLStreamReader. + */ + static XmlByte parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlByte) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java b/src/main/java/org/apache/xmlbeans/XmlCalendar.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java rename to src/main/java/org/apache/xmlbeans/XmlCalendar.java diff --git a/src/main/java/org/apache/xmlbeans/XmlCursor.java b/src/main/java/org/apache/xmlbeans/XmlCursor.java new file mode 100644 index 0000000..cb49624 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlCursor.java @@ -0,0 +1,1918 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.namespace.QName; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.Collection; +import java.util.Map; + +/** + * Represents a position between two logical tokens in an XML document. + *

+ * The tokens themselves are not exposed as objects, but their type and properties + * are discoverable through methods on the cursor. In particular, the general + * category of token is represented by a {@link XmlCursor.TokenType TokenType}.

+ *

+ * You use an XmlCursor instance to navigate through and manipulate an XML + * instance document. + * Once you obtain an XML document, you can create a cursor to represent + * a specific place in the XML. Because you can use a cursor with or + * without a schema corresponding to the XML, cursors are an ideal + * way to handle XML without a schema. You can create a new cursor by + * calling the {@link XmlTokenSource#newCursor() newCursor} method + * exposed by an object representing + * the XML, whether it was parsed into a strong type compiled from + * schema or an {@link XmlObject XmlObject} (as in the no-schema case).

+ *

+ * With an XmlCursor, you can also:

+ * + *

    + *
  • Execute XQuery and XPath expressions against the XML with the + * execQuery and selectPath methods.
  • + * + *
  • Edit and reshape the document by inserting, moving, copying, and removing + * XML.
  • + * + *
  • Insert bookmarks that "stick" to the XML at the cursor's + * position even if the cursor or XML moves.
  • + * + *
  • Get and set values for containers (elements and whole documents), + * attributes, processing instructions, and comments.
  • + *
+ *

+ * A cursor moves through XML by moving past tokens. A + * token represents a category of XML markup, such as the start of an element, + * its end, an attribute, comment, and so on. XmlCursor methods such as + * toNextToken, toNextSibling, toParent, and so on move the cursor + * among tokens. Each token's category is of a particular type, represented + * by one of the nine types defined by the {@link XmlCursor.TokenType TokenType} class.

+ *

+ * When you get a new cursor for a whole instance document, the cursor is + * intially located before the STARTDOC token. This token, which has no analogy + * in the XML specification, is present in this logical model of XML + * so that you may distinguish between the document as a whole + * and the content of the document. Terminating the document is an ENDDOC + * token. This token is also not part of the XML specification. A cursor + * located immediately before this token is at the very end of the document. + * It is not possible to position the cursor after the ENDDOC token. + * Thus, the STARTDOC and ENDDOC tokens are effectively "bookends" for the content of + * the document.

+ *

+ * For example, for the following XML, if you were the navigate a cursor + * through the XML document using toNextToken(), the list of token types that + * follows represents the token sequence you would encounter.

+ * + *

+ * <sample x='y'>
+ *     <value>foo</value>
+ * </sample>
+ * 
+ *

+ * STARTDOC
+ * START (sample)
+ * ATTR (x='y')
+ * TEXT ("\n ")
+ * START (value)
+ * TEXT ("foo")
+ * END (value)
+ * TEXT ("\n")
+ * END (sample)
+ * ENDDOC

+ *

+ * When there are no more tokens available, hasNextToken() returns + * false and toNextToken() returns the special token type NONE and does not move + * the cursor. + *

+ *

+ * The {@link #currentTokenType() currentTokenType()} method + * will return the type of the token that is immediately after the cursor. + * You can also use a number of convenience methods that test for a particular + * token type. These include the methods isStart(), + * isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean + * value indicating whether the token that follows the cursor is the type + * in question. + *

+ *

+ * A few other methods determine whether the token is of a kind that may include + * multiple token types. The isAnyAttr() method, for example, returns true if + * the token immediately following the cursor is any kind of attribute, + * including those of the ATTR token type and xmlns attributes. + *

+ *

+ * Legitimate sequences of tokens for an XML document are described + * by the following Backus-Naur Form (BNF):
+ * + *

+ * <doc> ::= STARTDOC <attributes> <content> ENDDOC
+ * <element> ::= START <attributes> <content> END
+ * <attributes> ::= ( ATTR | NAMESPACE ) *
+ * <content> ::= ( COMMENT | PROCINST | TEXT | <element> ) *
+ * 
+ *

+ * Note that a legitimate sequence is STARTDOC ENDDOC, the result of + * creating a brand new instance of an empty document. Also note that + * attributes may only follow container tokens (STARTDOC or START) + */ +public interface XmlCursor extends XmlTokenSource { + /** + * An enumeration that identifies the type of an XML token. + */ + public static final class TokenType { + public String toString() { + return _name; + } + + /** + * Returns one of the INT_ values defined in this class. + */ + public int intValue() { + return _value; + } + + /** + * No token. See {@link #intValue}. + */ + public static final int INT_NONE = 0; + /** + * The start-document token. See {@link #intValue}. + */ + public static final int INT_STARTDOC = 1; + /** + * The end-document token. See {@link #intValue}. + */ + public static final int INT_ENDDOC = 2; + /** + * The start-element token. See {@link #intValue}. + */ + public static final int INT_START = 3; + /** + * The end-element token. See {@link #intValue}. + */ + public static final int INT_END = 4; + /** + * The text token. See {@link #intValue}. + */ + public static final int INT_TEXT = 5; + /** + * The attribute token. See {@link #intValue}. + */ + public static final int INT_ATTR = 6; + /** + * The namespace declaration token. See {@link #intValue}. + */ + public static final int INT_NAMESPACE = 7; + /** + * The comment token. See {@link #intValue}. + */ + public static final int INT_COMMENT = 8; + /** + * The processing instruction token. See {@link #intValue}. + */ + public static final int INT_PROCINST = 9; + + /** + * True if no token. + */ + public boolean isNone() { + return this == NONE; + } + + /** + * True if is start-document token. + */ + public boolean isStartdoc() { + return this == STARTDOC; + } + + /** + * True if is end-document token. + */ + public boolean isEnddoc() { + return this == ENDDOC; + } + + /** + * True if is start-element token. + */ + public boolean isStart() { + return this == START; + } + + /** + * True if is end-element token. + */ + public boolean isEnd() { + return this == END; + } + + /** + * True if is text token. + */ + public boolean isText() { + return this == TEXT; + } + + /** + * True if is attribute token. + */ + public boolean isAttr() { + return this == ATTR; + } + + /** + * True if is namespace declaration token. + */ + public boolean isNamespace() { + return this == NAMESPACE; + } + + /** + * True if is comment token. + */ + public boolean isComment() { + return this == COMMENT; + } + + /** + * True if is processing instruction token. + */ + public boolean isProcinst() { + return this == PROCINST; + } + + /** + * True if is start-document or start-element token + */ + public boolean isContainer() { + return this == STARTDOC || this == START; + } + + /** + * True if is end-document or end-element token + */ + public boolean isFinish() { + return this == ENDDOC || this == END; + } + + /** + * True if is attribute or namespace declaration token + */ + public boolean isAnyAttr() { + return this == NAMESPACE || this == ATTR; + } + + /** + * The singleton no-token type + */ + public static final TokenType NONE = new TokenType("NONE", INT_NONE); + /** + * The singleton start-document token type + */ + public static final TokenType STARTDOC = new TokenType("STARTDOC", INT_STARTDOC); + /** + * The singleton start-document token type + */ + public static final TokenType ENDDOC = new TokenType("ENDDOC", INT_ENDDOC); + /** + * The singleton start-element token type + */ + public static final TokenType START = new TokenType("START", INT_START); + /** + * The singleton end-element token type + */ + public static final TokenType END = new TokenType("END", INT_END); + /** + * The singleton text token type + */ + public static final TokenType TEXT = new TokenType("TEXT", INT_TEXT); + /** + * The singleton attribute token type + */ + public static final TokenType ATTR = new TokenType("ATTR", INT_ATTR); + /** + * The singleton namespace declaration token type + */ + public static final TokenType NAMESPACE = new TokenType("NAMESPACE", INT_NAMESPACE); + /** + * The singleton comment token type + */ + public static final TokenType COMMENT = new TokenType("COMMENT", INT_COMMENT); + /** + * The singleton processing instruction token type + */ + public static final TokenType PROCINST = new TokenType("PROCINST", INT_PROCINST); + + private TokenType(String name, int value) { + _name = name; + _value = value; + } + + private String _name; + private int _value; + } + + /** + * Deallocates resources needed to manage the cursor, rendering this cursor + * inoperable. Because cursors are managed by a mechanism which stores the + * XML, simply letting a cursor go out of scope and having the garbage collector + * attempt to reclaim it may not produce desirable performance.

+ *

+ * So, explicitly disposing a cursor allows the underlying implementation + * to release its responsibility of maintaining its position.

+ *

+ * After a cursor has been disposed, it may not be used again. It can + * throw IllegalStateException or NullPointerException if used after + * disposal.

+ */ + + void dispose(); + + /** + * Moves this cursor to the same position as the moveTo cursor. if the + * moveTo cursor is in a different document from this cursor, this cursor + * will not be moved, and false returned. + * + * @param moveTo The cursor at the location to which this cursor + * should be moved. + * @return true if the cursor moved; otherwise, false. + */ + + boolean toCursor(XmlCursor moveTo); + + /** + * Saves the current location of this cursor on an internal stack of saved + * positions (independent of selection). This location may be restored + * later by calling the pop() method. + */ + + void push(); + + /** + * Restores the cursor location most recently saved with the push() method. + * + * @return true if there was a location to restore; otherwise, false. + */ + + boolean pop(); + + /** + * Executes the specified XPath expression against the XML that this + * cursor is in. The cursor's position does not change. To navigate to the + * selections, use {@link #hasNextSelection} and {@link #toNextSelection} (similar to + * {@link java.util.Iterator}).

+ *

+ * The root referred to by the expression should be given as + * a dot. The following is an example path expression: + *

+     * cursor.selectPath("./purchase-order/line-item");
+     * 
+ *

+ * Note that this method does not support top-level XPath functions. + * + * @param path The path expression to execute. + * @throws XmlRuntimeException If the query expression is invalid. + */ + void selectPath(String path); + + /** + * Executes the specified XPath expression against the XML that this + * cursor is in. The cursor's position does not change. To navigate to the + * selections, use hasNextSelection and toNextSelection (similar to + * java.util.Iterator).

+ *

+ * The root referred to by the expression should be given as + * a dot. The following is an example path expression: + *

+     * cursor.selectPath("./purchase-order/line-item");
+     * 
+ *

+ * Note that this method does not support top-level XPath functions. + * + * @param path The path expression to execute. + * @param options Options for the query. For example, you can call + * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} + * method to specify a particular name for the query expression + * variable that indicates the context node. + * @throws XmlRuntimeException If the query expression is invalid. + */ + void selectPath(String path, XmlOptions options); + + /** + * Returns whether or not there is a next selection. + * + * @return true if there is a next selection; otherwise, false. + */ + + boolean hasNextSelection(); + + /** + * Moves this cursor to the next location in the selection, + * if any. See the {@link #selectPath} and {@link #addToSelection} methods. + * + * @return true if the cursor moved; otherwise, false. + */ + + boolean toNextSelection(); + + /** + * Moves this cursor to the specified location in the selection. + * If i is less than zero or greater than or equal to the selection + * count, this method returns false. + *

+ * See also the selectPath() and addToSelection() methods. + * + * @param i The index of the desired location. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toSelection(int i); + + /** + * Returns the count of the current selection. See also the selectPath() + * and addToSelection() methods. + *

+ * You may experience better performance if you use the iteration + * model using the toNextSelection method, rather than + * the indexing model using the getSelectionCount and + * toSelection methods. + * + * @return A number indicating the size of the current selection. + */ + + int getSelectionCount(); + + + /** + * Appends the current location of the cursor to the selection. + * See also the selectPath() method. You can use this as an + * alternative to calling the selectPath method when you want + * to define your own selection. + */ + + void addToSelection(); + + /** + * Clears this cursor's selection, but does not modify the document. + */ + void clearSelections(); + + /** + * Moves this cursor to the same position as the bookmark. If the + * bookmark is in a different document from this cursor or if the + * bookmark is orphaned, this cursor + * will not be moved, and false will be returned. + * + * @param bookmark The bookmark at the location to which this + * cursor should be moved. + * @return true if the cursor moved; otherwise, false. + */ + + boolean toBookmark(XmlBookmark bookmark); + + /** + * Moves this cursor to the location after its current position + * where a bookmark with the given key exists. Returns false if no + * such bookmark exists. + * + * @param key The key held by the next bookmark at the location to + * which this cursor should be moved. + * @return The next corresponding bookmark, if it exists; null if there + * is no next bookmark with the specified key. + */ + + XmlBookmark toNextBookmark(Object key); + + /** + * Moves this cursor to the location before its current position + * where a bookmark with the given key exists. Returns false if no + * such bookmark exists. + * + * @param key The key held by the previous bookmark at the location to + * which this cursor should be moved. + * @return The previous corresponding bookmark, if it exists; null if + * there is no previous bookmark with the specified key. + */ + + XmlBookmark toPrevBookmark(Object key); + + /** + * Returns the name of the current token. Names may be associated with + * START, ATTR, NAMESPACE or PROCINST. Returns null if there is no + * name associated with the current token. For START and ATTR, the + * name returned identifies the name of the element or attribute. + * For NAMESPACE, the local part of the name is the prefix, while + * the URI is the namespace defined. For PROCINST, the local part + * is the target and the uri is "". + *

+ * In the following example, xmlObject represents + * an XML instance whose root element is not preceded by any other XML. + * This code prints the root element name (here, the local name, or + * name without URI). + *

+     * XmlCursor cursor = xmlObject.newCursor();
+     * cursor.toFirstContentToken();
+     * String elementName = cursor.getName().getLocalPart();
+     * System.out.println(elementName);
+     * 
+ * + * @return The name of the XML at this cursor's location; null if there + * is no name. + */ + + QName getName(); + + /** + * Sets the name of the current token. This token can be START, NAMESPACE, + * ATTR or PROCINST. + * + * @param name The new name for the current token. + */ + + void setName(QName name); + + /** + * Returns the namespace URI indicated by the given prefix. The current + * context must be at a START or STARTDOC. Namespace prefix mappings + * are queried for the mappings defined at the current container first, + * then parents are queried. The prefix can be "" or null to indicate + * a search for the default namespace. To conform with the + * XML spec, the default namespace will return the no-namespace ("") + * if it is not mapped.

+ *

+ * Note that this queries the current state of the document. When the + * document is persisted, the saving mechanism may synthesize namespaces + * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are + * only present in the serialized form, and are not reflected back into + * the document being saved. + * + * @param prefix The namespace prefix for the requested namespace. + * @return The URI for corresponding to the specified prefix if it + * exists; otherwise, null. + */ + String namespaceForPrefix(String prefix); + + /** + * Returns a prefix that can be used to indicate a namespace URI. The + * current context must be at a START or STARTDOC. If there is an + * existing prefix that indicates the URI in the current context, that + * prefix may be returned. Otherwise, a new prefix for the URI will be + * defined by adding an xmlns attribute to the current container or a + * parent container. + *

+ * Note that this queries the current state of the document. When the + * document is persisted, the saving mechanism may synthesize namespaces + * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are + * only present in the serialized form, and are not reflected back into + * the document being saved. + * + * @param namespaceURI The namespace URI corresponding to the requested + * prefix. + * @return The prefix corresponding to the specified URI if it exists; + * otherwise, a newly generated prefix. + */ + String prefixForNamespace(String namespaceURI); + + /** + * Adds to the specified map, all the namespaces in scope at the container + * where this cursor is positioned. This method is useful for + * container tokens only. + * + * @param addToThis The Map to add the namespaces to. + */ + + void getAllNamespaces(Map addToThis); + + /** + * Returns the strongly-typed XmlObject at the current START, + * STARTDOC, or ATTR.

+ *

+ * The strongly-typed object can be cast to the strongly-typed + * XBean interface corresponding to the XML Schema Type given + * by result.getSchemaType().

+ *

+ * If a more specific type cannot be determined, an XmlObject + * whose schema type is anyType will be returned. + * + * @return The strongly-typed object at the cursor's current location; + * null if the current location is not a START, STARTDOC, or ATTR. + */ + + XmlObject getObject(); + + /** + * Returns the type of the current token. By definition, the current + * token is the token immediately to the right of the cursor. + * If you're in the middle of text, before a character, you get TEXT. + * You can't dive into the text of an ATTR, COMMENT or PROCINST.

+ *

+ * As an alternative, it may be more convenient for you to use one of the + * methods that test for a particular token type. These include the methods + * isStart(), isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean + * value indicating whether the token that follows the cursor is the type + * in question. + *

+ * + * @return The TokenType instance for the token at the cursor's current + * location. + */ + + TokenType currentTokenType(); + + /** + * True if the current token is a STARTDOC token type, meaning + * at the very root of the document. + * + * @return true if this token is a STARTDOC token type; + * otherwise, false. + */ + + boolean isStartdoc(); + + /** + * True if this token is an ENDDOC token type, meaning + * at the very end of the document. + * + * @return true if this token is an ENDDOC token type; + * otherwise, false. + */ + + boolean isEnddoc(); + + /** + * True if this token is a START token type, meaning + * just before an element's start. + * + * @return true if this token is a START token type; + * otherwise, false. + */ + + boolean isStart(); + + /** + * True if this token is an END token type, meaning + * just before an element's end. + * + * @return true if this token is an END token type; + * otherwise, false. + */ + + boolean isEnd(); + + /** + * True if the this token is a TEXT token type, meaning + * just before or inside text. + * + * @return true if this token is a TEXT token type; + * otherwise, false. + */ + + boolean isText(); + + /** + * True if this token is an ATTR token type, meaning + * just before an attribute. + * + * @return true if this token is an ATTR token type; + * otherwise, false. + */ + + boolean isAttr(); + + /** + * True if this token is a NAMESPACE token type, meaning + * just before a namespace declaration. + * + * @return true if this token is a NAMESPACE token type; + * otherwise, false. + */ + + boolean isNamespace(); + + /** + * True if this token is a COMMENT token type, meaning + * just before a comment. + * + * @return true if this token is a COMMENT token type; + * otherwise, false. + */ + + boolean isComment(); + + /** + * True if this token is a PROCINST token type, meaning + * just before a processing instruction. + * + * @return true if this token is a PROCINST token type; + * otherwise, false. + */ + + boolean isProcinst(); + + /** + * True if this token is a container token. The STARTDOC and START + * token types are containers. Containers, including documents and elements, + * have the same content model. In other words, a document and an element + * may have the same contents. For example, a document may contain attributes + * or text, without any child elements. + * + * @return true if this token is a container token; otherwise, false. + */ + + boolean isContainer(); + + /** + * True if this token is a finish token. A finish token can be an ENDDOC + * or END token type. + * + * @return true if this token is a finish token; otherwise, false. + */ + + boolean isFinish(); + + /** + * True if this token is any attribute. This includes an ATTR token type and + * the NAMESPACE token type attribute. + * + * @return true if the current cursor is at any attribute; otherwise, false. + */ + + boolean isAnyAttr(); + + /** + * Returns the type of the previous token. By definition, the previous + * token is the token immediately to the left of the cursor.

+ *

+ * If you're in the middle of text, after a character, you get TEXT. + * + * @return The TokenType instance for the token immediately before the + * token at the cursor's current location. + */ + + TokenType prevTokenType(); + + /** + * True if there is a next token. When this is false, as when the cursor is + * at the ENDDOC token, the toNextToken() method returns NONE and does not + * move the cursor. + * + * @return true if there is a next token; otherwise, false. + */ + + boolean hasNextToken(); + + + /** + * True if there is a previous token. When this is false, toPrevToken + * returns NONE and does not move the cursor. + * + * @return true if there is a previous token; otherwise, false. + */ + + boolean hasPrevToken(); + + /** + * Moves the cursor to the next token. When there are no more tokens + * available, hasNextToken returns false and toNextToken() returns + * NONE and does not move the cursor. Returns the token type + * of the token to the right of the cursor upon a successful move. + * + * @return The token type for the next token if the cursor was moved; + * otherwise, NONE. + */ + + TokenType toNextToken(); + + /** + * Moves the cursor to the previous token. When there is no + * previous token, returns NONE, otherwise returns the token + * to the left of the new position of the cursor. + * + * @return The token type for the previous token if the cursor was moved; + * otherwise, NONE. + */ + + TokenType toPrevToken(); + + /** + * Moves the cursor to the first token in the content of the current + * START or STARTDOC. That is, the first token after all ATTR and NAMESPACE + * tokens associated with this START.

+ *

+ * If the current token is not a START or STARTDOC, the cursor is not + * moved and NONE is returned. If the current START or STARTDOC + * has no content, the cursor is moved to the END or ENDDOC token.

+ * + * @return The new current token type. + */ + + TokenType toFirstContentToken(); + + + /** + * Moves the cursor to the END or ENDDOC token corresponding to the + * current START or STARTDOC, and returns END or ENDDOC.

+ *

+ * If the current token is not a START or STARTDOC, the cursor is not + * moved and NONE is returned. + * + * @return The new current token type. + */ + + TokenType toEndToken(); + + /** + * Moves the cursor forward by the specified number of characters, and + * stops at the next non-TEXT token. Returns the number of characters + * actually moved across, which is guaranteed to be less than or equal to + * maxCharacterCount. If there is no further text, or if + * there is no text at all, returns zero.

+ *

+ * Note this does not dive into attribute values, comment contents, + * processing instruction contents, etc., but only content text.

+ *

+ * You can pass maxCharacterCount < 0 to move over all the text to the + * right. This has the same effect as toNextToken, but returns the amount + * of text moved over. + * + * @param maxCharacterCount The maximum number of characters by which + * the cursor should be moved. + * @return The actual number of characters by which the cursor was moved; + * 0 if the cursor was not moved. + */ + + int toNextChar(int maxCharacterCount); + + /** + * Moves the cursor backwards by the number of characters given. Has + * similar characteristics to the {@link #toNextChar(int) toNextChar} method. + * + * @param maxCharacterCount The maximum number of characters by which + * the cursor should be moved. + * @return The actual number of characters by which the cursor was moved; + * 0 if the cursor was not moved. + */ + + int toPrevChar(int maxCharacterCount); + + /** + * Moves the cursor to the next sibling element, or returns + * false and does not move the cursor if there is no next sibling + * element. (By definition the position of an element is the same + * as the position of its START token.) + *

+ * If the current token is not s START, the cursor will be + * moved to the next START without moving out of the scope of the + * current element. + * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toNextSibling(); + + /** + * Moves the cursor to the previous sibling element, or returns + * false and does not move the cursor if there is no previous sibling + * element. (By definition the position of an element is the same + * as the position of its START token.) + * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toPrevSibling(); + + /** + * Moves the cursor to the parent element or STARTDOC, or returns + * false and does not move the cursor if there is no parent.

+ *

+ * Works if you're in attributes or content. Returns false only if at + * STARTDOC. Note that the parent of an END token is the corresponding + * START token. + * + * @return true if the cursor was moved; false if the cursor is at the STARTDOC + * token. + */ + + boolean toParent(); + + /** + * Moves the cursor to the first child element, or returns false and + * does not move the cursor if there are no element children.

+ *

+ * If the cursor is not currently in an element, it moves into the + * first child element of the next element. + * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toFirstChild(); + + /** + * Moves the cursor to the last element child, or returns false and + * does not move the cursor if there are no element children. + * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toLastChild(); + + /** + * Moves the cursor to the first child element of the specified name in + * no namespace. + * + * @param name The name of the element to move the cursor to. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toChild(String name); + + /** + * Moves the cursor to the first child element of the specified name in the + * specified namespace. + * + * @param namespace The namespace URI for the element to move the cursor + * to. + * @param name The name of the element to move to. + * @return true if the cursor was moved; otherwise, false. + * @throws IllegalArgumentException If the name is not a valid local name. + */ + + boolean toChild(String namespace, String name); + + /** + * Moves the cursor to the first child element of the specified qualified name. + * + * @param name The name of the element to move the cursor to. + */ + + boolean toChild(QName name); + + /** + * Moves the cursor to the child element specified by index. + * + * @param index The position of the element in the sequence of child + * elements. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toChild(int index); + + /** + * Moves the cursor to the specified index child element of the + * specified name, where that element is the . + * + * @param name The name of the child element to move the cursor to. + * @param index The position of the element in the sequence of child + * elements. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toChild(QName name, int index); + + /** + * Moves the cursor to the next sibling element of the specified name in no + * namespace. + * + * @param name The name of the element to move the cursor to. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toNextSibling(String name); + + /** + * Moves the cursor to the next sibling element of the specified name + * in the specified namespace. + * + * @param namespace The namespace URI for the element to move the cursor + * to. + * @param name The name of the element to move the cursor to. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toNextSibling(String namespace, String name); + + + /** + * Moves the cursor to the next sibling element of the specified + * qualified name. + * + * @param name The name of the element to move the cursor to. + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toNextSibling(QName name); + + /** + * Moves the cursor to the first attribute of this element, or + * returns false and does not move the cursor if there are no + * attributes. The order of attributes is arbitrary, but stable.

+ *

+ * If the cursor is on a STARTDOC of a document-fragment, this method will + * move it to the first top level attribute if one exists.

+ *

+ * xmlns attributes (namespace declarations) are not considered + * attributes by this function.

+ *

+ * The cursor must be on a START or STARTDOC (in the case of a + * document fragment with top level attributes) for this method to + * succeed. + *

+ * Example for looping through attributes: + *

+     *      XmlCursor cursor = ... //cursor on START or STARTDOC
+     *      if (cursor.toFirstAttribute())
+     *      {
+     *          do
+     *          {
+     *              // do something using attribute's name and value
+     *              cursor.getName();
+     *              cursor.getTextValue();
+     *          }
+     *          while (cursor.toNextAttribute());
+     *      }
+     * 
+ * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toFirstAttribute(); + + /** + * Moves the cursor to the last attribute of this element, or + * returns false and does not move the cursor if there are no + * attributes. The order of attributes is arbitrary, but stable.

+ *

+ * xmlns attributes (namespace declarations) are not considered + * attributes by this function.

+ *

+ * The cursor must be on a START or STARTDOC for this method + * to succeed. + * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toLastAttribute(); + + /** + * Moves the cursor to the next sibling attribute, or returns + * false and does not move the cursor if there is no next + * sibling attribute. The order of attributes is arbitrary, but stable.

+ *

+ * xmlns attributes (namespace declarations) are not considered + * attributes by this function.

+ *

+ * The cursor must be on an attribute for this method to succeed. + * + * @return true if the cursor was moved; otherwise, false. + * @see #toFirstAttribute() + */ + + boolean toNextAttribute(); + + /** + * Moves the cursor to the previous sibling attribute, or returns + * false and does not move the cursor if there is no previous + * sibling attribute. The order of attributes is arbitrary, but stable.

+ *

+ * xmlns attributes (namespace declarations) are not considered + * attributes by this function.

+ *

+ * The cursor must be on an attribute for this method to succeed. + * + * @return true if the cursor was moved; otherwise, false. + */ + + boolean toPrevAttribute(); + + /** + * When at a START or STARTDOC, returns the attribute text for the given + * attribute. When not at a START or STARTDOC or the attribute does not + * exist, returns null. + * + * @param attrName The name of the attribute whose value is requested. + * @return The attribute's value if it has one; otherwise, null. + */ + + String getAttributeText(QName attrName); + + /** + * When at a START or STARTDOC, sets the attribute text for the given + * attribute. When not at a START or STARTDOC returns false. + * If the attribute does not exist, one is created. + * + * @param attrName The name of the attribute whose value is being set. + * @param value The new value for the attribute. + * @return true if the new value was set; otherwise, false. + */ + + boolean setAttributeText(QName attrName, String value); + + /** + * When at a START or STARTDOC, removes the attribute with the given name. + * + * @param attrName The name of the attribute that should be removed. + * @return true if the attribute was removed; otherwise, false. + */ + + boolean removeAttribute(QName attrName); + + /** + * Gets the text value of the current document, element, attribute, + * comment, procinst or text token.

+ *

+ * When getting the text value of an element, non-text content such + * as comments and processing instructions are ignored and text is concatenated. + * For elements that have nested element children, this + * returns the concatenated text of all mixed content and the + * text of all the element children, recursing in first-to-last + * depthfirst order.

+ *

+ * For attributes, including namespaces, this returns the attribute value.

+ *

+ * For comments and processing instructions, this returns the text content + * of the comment or PI, not including the delimiting sequences <!-- -->, <? ?>. + * For a PI, the name of the PI is also not included. + *

+ * The value of an empty tag is the empty string.

+ *

+ * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.

+ * + * @return The text value of the current token if the token's type is + * START, STARTDOC, TEXT, ATTR, COMMENT, PROCINST, or NAMESPACE; null + * if the type is NONE. + */ + + String getTextValue(); + + /** + * Copies the text value of the current document, element, attribute, + * comment, processing instruction or text token, counting right from + * this cursor's location up to maxCharacterCount, + * and copies the returned text into returnedChars.

+ *

+ * When getting the text value of an element, non-text content such + * as comments and processing instructions are ignored and text is concatenated. + * For elements that have nested element children, this + * returns the concatenated text of all mixed content and the + * text of all the element children, recursing in first-to-last + * depthfirst order.

+ *

+ * For attributes, including namespaces, this returns the attribute value.

+ *

+ * For comments and processing instructions, this returns the text contents + * of the comment or PI, not including the delimiting sequences <!-- -->, <? ?>. For + * a PI, the text will not include the name of the PI.

+ *

+ * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.

+ *

+ * The value of an empty tag is the empty string.

+ * + * @param returnedChars A character array to hold the returned characters. + * @param offset The position within returnedChars to which the first of the + * returned characters should be copied. + * @param maxCharacterCount The maximum number of characters after this cursor's + * location to copy. A negative value specifies that all characters should be copied. + * @return The actual number of characters copied; 0 if no characters + * were copied. + */ + + int getTextValue(char[] returnedChars, int offset, int maxCharacterCount); + + /** + * Returns the characters of the current TEXT token. If the current token + * is not TEXT, returns "". If in the middle of a TEXT token, returns + * those chars to the right of the cursor of the TEXT token. + * + * @return The requested text; an empty string if the current token type is + * not TEXT. + */ + + /** + * Sets the text value of the XML at this cursor's location if that XML's + * token type is START, STARTDOC, ATTR, COMMENT or PROCINST.

+ *

+ * For elements that have nested children this first removes all + * the content of the element and replaces it with the given text. + * + * @param text The text to use as a new value. + * @throws java.lang.IllegalStateException If the token type at this + * cursor's location is not START, STARTDOC, ATTR, COMMENT or + * PROCINST. + */ + void setTextValue(String text); + + /** + * Sets the text value of the XML at this cursor's location (if that XML's + * token type is START, STARTDOC, ATTR, COMMENT or PROCINST) to the + * contents of the specified character array.

+ *

+ * For elements that have nested children this first removes all + * the content of the element and replaces it with the given text. + * + * @param sourceChars A character array containing the XML's new value. + * @param offset The position within sourceChars from which the first of + * the source characters should be copied. + * @param length The maximum number of characters to set as the XML's new + * value. + * @throws java.lang.IllegalArgumentException If the token type at this + * cursor's location is not START, STARTDOC, ATTR, COMMENT or + * PROCINST. + */ + void setTextValue(char[] sourceChars, int offset, int length); + + /** + * Returns characters to the right of the cursor up to the next token. + */ + String getChars(); + + /** + * Copies characters up to the specified maximum number, counting right from + * this cursor's location to the character at maxCharacterCount. The + * returned characters are added to returnedChars, with the first + * character copied to the offset position. The maxCharacterCount + * parameter should be less than or equal to the length of returnedChars + * minus offset. Copies a number of characters, which is + * either maxCharacterCount or the number of characters up to the next token, + * whichever is less. + * + * @param returnedChars A character array to hold the returned characters. + * @param offset The position within returnedChars at which the first of the + * returned characters should be added. + * @param maxCharacterCount The maximum number of characters after this cursor's + * location to return. + * @return The actual number of characters returned; 0 if no characters + * were returned or if the current token is not TEXT. + */ + + int getChars(char[] returnedChars, int offset, int maxCharacterCount); + + /** + * Moves the cursor to the STARTDOC token, which is the + * root of the document. + */ + + void toStartDoc(); + + /** + * Moves the cursor to the ENDDOC token, which is the end + * of the document. + */ + + void toEndDoc(); + + /** + * Determines if the specified cursor is in the same document as + * this cursor. + * + * @param cursor The cursor that may be in the same document + * as this cursor. + * @return true if the specified cursor is in the same document; + * otherwise, false. + */ + + boolean isInSameDocument(XmlCursor cursor); + + /** + * Returns an integer indicating whether this cursor is before, + * after, or at the same position as the specified cursor.

+ * + * a.comparePosition(b) < 0 means a is to the left of b.
+ * a.comparePosition(b) == 0 means a is at the same position as b.
+ * a.comparePosition(b) > 0 means a is to the right of b.

+ *

+ * The sort order of cursors in the document is the token order. + * For example, if cursor "a" is at a START token and the cursor "b" + * is at a token within the contents of the same element, then + * a.comparePosition(b) will return -1, meaning that the position + * of a is before b. + * + * @param cursor The cursor whose position should be compared + * with this cursor. + * @return 1 if this cursor is after the specified cursor; 0 if + * this cursor is at the same position as the specified cursor; + * -1 if this cursor is before the specified cursor. + * @throws java.lang.IllegalArgumentException If the specified + * cursor is not in the same document as this cursor. + */ + + int comparePosition(XmlCursor cursor); + + /** + * Determines if this cursor is to the left of (or before) + * the specified cursor. Note that this is the same as + * a.comparePosition(b) < 0 + * + * @param cursor The cursor whose position should be compared + * with this cursor. + * @return true if this cursor is to the left of the specified + * cursor; otherwise, false. + */ + + boolean isLeftOf(XmlCursor cursor); + + /** + * Determines if this cursor is at the same position as + * the specified cursor. Note that this is the same as + * a.comparePosition(b) == 0 + * + * @param cursor The cursor whose position should be compared + * with this cursor. + * @return true if this cursor is at the same position as + * the specified cursor; otherwise, false. + */ + + boolean isAtSamePositionAs(XmlCursor cursor); + + /** + * Determines if this cursor is to the right of (or after) + * the specified cursor. Note that this is the same as + * a.comparePosition(b) > 0 + * + * @param cursor The cursor whose position should be compared + * with this cursor. + * @return true if this cursor is to the right of the specified + * cursor; otherwise, false. + */ + + boolean isRightOf(XmlCursor cursor); + + /** + * Executes the specified XQuery expression against the XML this + * cursor is in.

+ *

+ * The query may be a String or a compiled query. You can precompile + * an XQuery expression using the XmlBeans.compileQuery method.

+ *

+ * The root referred to by the expression should be given as + * a dot. The following is an example path expression: + *

+     * XmlCursor results = cursor.execQuery("purchase-order/line-item[price <= 20.00]");
+     * 
+ * + * @param query The XQuery expression to execute. + * @return A cursor containing the results of the query. + * @throws XmlRuntimeException If the query expression is invalid. + */ + + XmlCursor execQuery(String query); + + /** + * Executes the specified XQuery expression against the XML this + * cursor is in, and using the specified options.

+ * + * @param query The XQuery expression to execute. + * @param options Options for the query. For example, you can call + * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} + * method to specify a particular name for the query expression + * variable that indicates the context node. + * @throws XmlRuntimeException If the query expression is invalid. + */ + + XmlCursor execQuery(String query, XmlOptions options); + + /** + * Represents the state of a dcoument at a particular point + * in time. It is used to determine if a document has been changed + * since that point in time. + */ + interface ChangeStamp { + /** + * Returns whether or not the document assoiated with this ChangeStamp + * has been altered since the ChangeStamp had been created. + */ + public boolean hasChanged(); + } + + /** + * Returns the current change stamp for the document the current cursor is in. + * This change stamp can be queried at a later point in time to find out + * if the document has changed. + * + * @return The change stamp for the document the current cursor is in. + */ + ChangeStamp getDocChangeStamp(); + + /** + * Subclasses of XmlBookmark can be used to annotate an XML document. + * This class is abstract to prevent parties from inadvertently + * interfering with each others' bookmarks without explicitly + * sharing a bookmark class. + */ + + abstract class XmlBookmark { + /** + * Constructs a strongly-referenced bookmark. + */ + public XmlBookmark() { + this(false); + } + + /** + * Constructs a bookmark. + * + * @param weak true if the document's reference to the bookmark should be a WeakReference + */ + public XmlBookmark(boolean weak) { + _ref = weak ? new WeakReference(this) : null; + } + + /** + * Call the createCursor method to create a new cursor which is + * positioned at the same splace as the bookmark. It is much more + * efficient to call toBookmark on an existing cursor than it + * is to create a new cursor. However, toBookmark may fail if the + * bookmark is in a different document than the cursor. It is + * under these circumstances where createCursor needs to be called + * on the bookmark. Subsequent navigations to bookmark + * positions should attempt to reuse the last cursor to + * improve performace. + * + * @return the new cursor + */ + public final XmlCursor createCursor() { + return _currentMark == null ? null : _currentMark.createCursor(); + } + + /** + * @param c the cursor to be moved + * @return the given cursor moved to this bookmark + */ + public final XmlCursor toBookmark(XmlCursor c) { + return c == null || !c.toBookmark(this) ? createCursor() : c; + } + + /** + * The default key for bookmarks is the class which implements + * them. This way, multiple parties using bookmarks in the + * same instance document will not interfere with eachother. + * One can, however, override getKey() to use a key other than + * the class. + * + * @return default key for bookmarks + */ + public Object getKey() { + return this.getClass(); + } + + /** + * The mark is set by the host document; it is capable of + * returning an XmlCursor implementation at the location of + * the bookmark. + */ + public XmlMark _currentMark; + + /** + * If non-null, the ref is used by the host document + * to maintain a reference to the bookmark. If it is a weak + * reference, the host document will not prevent the Bookmark + * from being garbage collected. + */ + public final Reference _ref; + } + + /** + * An abstract {@link XmlCursor} factory. + * Implementations of XmlCursor implement XmlMark to be able to + * reconstitute a cursor from a bookmark. When content moves between + * implementations, the XmlMark is set to the implmentation's which + * receives the new content. + */ + + interface XmlMark { + XmlCursor createCursor(); + } + + /** + * Sets a bookmark to the document at this cursor's location. + *

+ * The bookmark is attached to the token in the tree immediately + * after the cursor. If the tree is manipulated to move + * that object to a different place, the bookmark moves with it. + * If the tree is manipulated to delete that token from the + * tree, the bookmark is orphaned. Copy operations do not copy + * bookmarks. + * + * @param bookmark The bookmark to set. + */ + + void setBookmark(XmlBookmark bookmark); + + /** + * Retrieves the bookmark with the specified key + * at this cursor's location. If there is no bookmark whose key is + * given by the specified key at the current position, null is returned. + * If the {@link XmlCursor.XmlBookmark#getKey() getKey} method is not overridden on + * the bookmark, then the bookmark's class is used as the key. + * + * @param key The key for the bookmark to retrieve. + * @return The requested bookmark; null if there is no bookmark + * corresponding to the specified key. + */ + + XmlBookmark getBookmark(Object key); + + /** + * Clears the bookmark whose key is specified, if the bookmark + * exists at this cursor's location. + * + * @param key The for the bookmark to clear. + */ + + void clearBookmark(Object key); + + /** + * Retrieves all the bookmarks at this location, adding them to + * the specified collection. Bookmarks held by weak references are + * added to this collection as Weak referenced objects pointing to the + * bookmark. + * + * @param listToFill The collection that will contain bookmarks + * returned by this method. + */ + + void getAllBookmarkRefs(Collection listToFill); + + /** + * Removes the XML that is immediately after this cursor. + *

+ * For the TEXT, ATTR, NAMESPACE, COMMENT and PROCINST tokens, a single + * token is removed. For a START token, the corresponding element and all + * of its contents are removed. For all other tokens, this is a no-op. + * You cannot remove a STARTDOC. + *

+ * The cursors located in the XML that was removed all collapse to the + * same location. All bookmarks in this XML will be orphaned. + * + * @return true if anything was removed; false only if the cursor is + * just before END or ENDDOC token. + * @throws java.lang.IllegalArgumentException If the cursor is at a + * STARTDOC token. + */ + + boolean removeXml(); + + /** + * Moves the XML immediately after this cursor to the location + * specified by the toHere cursor, shifting XML at that location + * to the right to make room. For the TEXT, ATTR, NAMESPACE, + * COMMENT and PROCINST tokens, a single token is moved. For a start token, the + * element and all of its contents are moved. For all other tokens, this + * is a no-op. + *

+ * The bookmarks located in the XML that was moved also move to the + * new location; the cursors don't move with the content. + * + * @param toHere The cursor at the location to which the XML should + * be moved. + * @return true if anything was moved. This only happens when the XML to be + * moved contains the target of the move. + * @throws java.lang.IllegalArgumentException If the operation is not allowed + * at the cursor's location. This includes attempting to move an end token or the + * document as a whole. Also, moving to a location before the start document or moving + * an attribute to a location other than after another attribute or start token + * will throw. + */ + + boolean moveXml(XmlCursor toHere); + + /** + * Copies the XML immediately after this cursor to the location + * specified by the toHere cursor. For the TEXT, ATTR, NAMESPACE, + * COMMENT and PROCINST tokens, a single token is copied. For a start token, + * the element and all of its contents are copied. For all other tokens, this + * is a no-op. + *

+ * The cursors and bookmarks located in the XML that was copied are also copied + * to the new location. + * + * @param toHere The cursor at the location to which the XML should + * be copied. + * @return true if anything was copied; false if the token supports the operation, + * but nothing was copied. + * @throws java.lang.IllegalArgumentException If the operation is not allowed + * at the cursor's location. + */ + + boolean copyXml(XmlCursor toHere); + + /** + * Removes the contents of the container (STARTDOC OR START) immediately after + * this cursor. For all other situations, returns false. Does + * not remove attributes or namspaces. + * + * @return true if anything was copied; otherwise, false. + */ + + boolean removeXmlContents(); + + /** + * Moves the contents of the container (STARTDOC OR START) immediately after + * this cursor to the location specified by the toHere cursor. + * For all other situations, returns false. Does not move attributes or + * namespaces. + * + * @param toHere The cursor at the location to which the XML should be moved. + * @return true if anything was moved; otherwise, false. + */ + boolean moveXmlContents(XmlCursor toHere); + + /** + * Copies the contents of the container (STARTDOC OR START) immediately to + * the right of the cursor to the location specified by the toHere cursor. + * For all other situations, returns false. Does not copy attributes or + * namespaces. + * + * @param toHere The cursor at the location to which the XML should + * be copied. + * @return true if anything was copied; otherwise, false. + */ + boolean copyXmlContents(XmlCursor toHere); + + /** + * Removes characters up to the specified maximum number, counting right from + * this cursor's location to the character at maxCharacterCount. The + * space remaining from removing the characters collapses up to this cursor. + * + * @param maxCharacterCount The maximum number of characters after this cursor's + * location to remove. + * @return The actual number of characters removed. + * @throws java.lang.IllegalArgumentException If the operation is not allowed + * at the cursor's location. + */ + + int removeChars(int maxCharacterCount); + + /** + * Moves characters immediately after this cursor to the position immediately + * after the specified cursor. Characters are counted to the right up to the + * specified maximum number. XML after the destination cursor is + * shifted to the right to make room. The space remaining from moving the + * characters collapses up to this cursor. + * + * @param maxCharacterCount The maximum number of characters after this cursor's + * location to move. + * @param toHere The cursor to which the characters should be moved. + * @return The actual number of characters moved. + * @throws java.lang.IllegalArgumentException If the operation is not allowed + * at the cursor's location. + */ + + int moveChars(int maxCharacterCount, XmlCursor toHere); + + /** + * Copies characters to the position immediately after the specified cursor. + * Characters are counted to the right up to the specified maximum number. + * XML after the destination cursor is shifted to the right to make room. + * + * @param maxCharacterCount The maximum number of characters after this cursor's + * location to copy. + * @param toHere The cursor to which the characters should be copied. + * @return The actual number of characters copied. + * @throws java.lang.IllegalArgumentException If the operation is not allowed + * at the cursor's location. + */ + + int copyChars(int maxCharacterCount, XmlCursor toHere); + + /** + * Inserts the specified text immediately before this cursor's location. + * + * @param text The text to insert. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertChars(String text); + + /** + * Inserts an element immediately before this cursor's location, giving + * the element the specified qualified name. + * + * @param name The qualified name for the element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertElement(QName name); + + /** + * Inserts an element immediately before this cursor's location, giving + * the element the specified local name. + * + * @param localName The local name for the new element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertElement(String localName); + + /** + * Inserts a new element immediately before this cursor's location, giving the + * element the specified local name and associating it with specified namespace + * + * @param localName The local name for the new element. + * @param uri The URI for the new element's namespace. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertElement(String localName, String uri); + + /** + * Inserts a new element around this cursor, giving the element the specified + * qualified name. After the element is inserted, this cursor is between its start + * and end. This cursor can then be used to insert additional XML into + * the new element. + * + * @param name The qualified name for the new element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void beginElement(QName name); + + /** + * Inserts a new element around this cursor, giving the element the specified + * local name. After the element is inserted, this cursor is between its start + * and end. This cursor can then be used to insert additional XML into + * the new element. + * + * @param localName The local name for the new element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void beginElement(String localName); + + /** + * Inserts a new element around this cursor, giving the element the specified + * local name and associating it with the specified namespace. After the element + * is inserted, this cursor is between its start and end. This cursor + * can then be used to insert additional XML into the new element. + * + * @param localName The local name for the new element. + * @param uri The URI for the new element's namespace. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void beginElement(String localName, String uri); + + /** + * Inserts a new element immediately before this cursor's location, giving the + * element the specified qualified name and content. + * + * @param name The qualified name for the new element. + * @param text The content for the new element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertElementWithText(QName name, String text); + + /** + * Inserts a new element immediately before this cursor's location, giving the + * element the specified local name and content. + * + * @param localName The local name for the new element. + * @param text The content for the new element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertElementWithText(String localName, String text); + + /** + * Inserts a new element immediately before this cursor's location, giving the + * element the specified local name, associating it with the specified namespace, + * and giving it the specified content. + * + * @param localName The local name for the new element. + * @param uri The URI for the new element's namespace. + * @param text The content for the new element. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertElementWithText(String localName, String uri, String text); + + /** + * Inserts a new attribute immediately before this cursor's location, giving it + * the specified local name. + * + * @param localName The local name for the new attribute. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertAttribute(String localName); + + /** + * Inserts a new attribute immediately before this cursor's location, giving it + * the specified local name and associating it with the specified namespace. + * + * @param localName The local name for the new attribute. + * @param uri The URI for the new attribute's namespace. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertAttribute(String localName, String uri); + + /** + * Inserts a new attribute immediately before this cursor's location, giving it + * the specified name. + * + * @param name The local name for the new attribute. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertAttribute(QName name); + + /** + * Inserts a new attribute immediately before this cursor's location, giving it + * the specified value and name. + * + * @param Name The local name for the new attribute. + * @param value The value for the new attribute. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertAttributeWithValue(String Name, String value); + + /** + * Inserts an attribute immediately before the cursor's location, giving it + * the specified name and value, and associating it with the specified namespace. + * + * @param name The name for the new attribute. + * @param uri The URI for the new attribute's namespace. + * @param value The value for the new attribute. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertAttributeWithValue(String name, String uri, String value); + + /** + * Inserts an attribute immediately before the cursor's location, giving it + * the specified name and value. + * + * @param name The name for the new attribute. + * @param value The value for the new attribute. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertAttributeWithValue(QName name, String value); + + /** + * Inserts a namespace declaration immediately before the cursor's location, + * giving it the specified prefix and URI. + * + * @param prefix The prefix for the namespace. + * @param namespace The URI for the namespace. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertNamespace(String prefix, String namespace); + + /** + * Inserts an XML comment immediately before the cursor's location, + * giving it the specified content. + * + * @param text The new comment's content. + * @throws java.lang.IllegalArgumentException If the insertion is not allowed + * at the cursor's location. + */ + + void insertComment(String text); + + /** + * Inserts an XML processing instruction immediately before the cursor's location, + * giving it the specified target and text. + * + * @param target The target for the processing instruction. + * @param text The new processing instruction's text. + * @throws java.lang.IllegalStateException If the insertion is not allowed + * at the cursor's location. + */ + + void insertProcInst(String target, String text); +} diff --git a/src/main/java/org/apache/xmlbeans/XmlDate.java b/src/main/java/org/apache/xmlbeans/XmlDate.java new file mode 100644 index 0000000..4314338 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlDate.java @@ -0,0 +1,196 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; +import java.util.Date; + + +/** + * Corresponds to the XML Schema + * xs:date type. + *

+ * Convertible to {@link Calendar}, {@link Date}, and {@link GDate}. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlDate extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_date"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * Returns this value as a {@link Date} + */ + Date getDateValue(); + + /** + * Sets this value as a {@link Date} + */ + void setDateValue(Date d); + + /** + * A class with methods for creating instances + * of {@link XmlDate}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlDate} + */ + public static XmlDate newInstance() { + return (XmlDate) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlDate} + */ + public static XmlDate newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlDate) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlDate} value + */ + public static XmlDate newValue(Object obj) { + return (XmlDate) type.newValue(obj); + } + + /** + * Parses a {@link XmlDate} fragment from a String. For example: "<xml-fragment>2003-06-14</xml-fragment>". + */ + public static XmlDate parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from a String. For example: "<xml-fragment>2003-06-14</xml-fragment>". + */ + public static XmlDate parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlDate} fragment from a File. + */ + public static XmlDate parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from a File. + */ + public static XmlDate parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlDate} fragment from a URL. + */ + public static XmlDate parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from a URL. + */ + public static XmlDate parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlDate} fragment from an InputStream. + */ + public static XmlDate parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from an InputStream. + */ + public static XmlDate parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlDate} fragment from a Reader. + */ + public static XmlDate parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from a Reader. + */ + public static XmlDate parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlDate} fragment from a DOM Node. + */ + public static XmlDate parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from a DOM Node. + */ + public static XmlDate parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlDate} fragment from an XMLStreamReader. + */ + public static XmlDate parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlDate} fragment from an XMLStreamReader. + */ + public static XmlDate parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDate) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlDateTime.java b/src/main/java/org/apache/xmlbeans/XmlDateTime.java new file mode 100644 index 0000000..8b58428 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlDateTime.java @@ -0,0 +1,201 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; +import java.util.Date; + + +/** + * Corresponds to the XML Schema + * xs:dateTime type. + *

+ * Convertible to {@link Calendar}, {@link Date}, and {@link GDate}. + * + *

+ * The XmlDateTime class only encapsulates a schema DateTime value, if you need to perform operations + * on dates, see the GDate class + * + * @see XmlCalendar + * @see GDate + * @see GDuration + */ +public interface XmlDateTime extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_dateTime"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * Returns this value as a {@link Date} + */ + Date getDateValue(); + + /** + * Sets this value as a {@link Date} + */ + void setDateValue(Date d); + + /** + * A class with methods for creating instances + * of {@link XmlDateTime}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlDateTime} + */ + public static XmlDateTime newInstance() { + return (XmlDateTime) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlDateTime} + */ + public static XmlDateTime newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlDateTime) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlDateTime} value + */ + public static XmlDateTime newValue(Object obj) { + return (XmlDateTime) type.newValue(obj); + } + + /** + * Parses a {@link XmlDateTime} fragment from a String. For example: "<xml-fragment>2003-06-14T12:00:00</xml-fragment>". + */ + public static XmlDateTime parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from a String. For example: "<xml-fragment>2003-06-14T12:00:00</xml-fragment>". + */ + public static XmlDateTime parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlDateTime} fragment from a File. + */ + public static XmlDateTime parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from a File. + */ + public static XmlDateTime parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlDateTime} fragment from a URL. + */ + public static XmlDateTime parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from a URL. + */ + public static XmlDateTime parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlDateTime} fragment from an InputStream. + */ + public static XmlDateTime parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from an InputStream. + */ + public static XmlDateTime parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlDateTime} fragment from a Reader. + */ + public static XmlDateTime parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from a Reader. + */ + public static XmlDateTime parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlDateTime} fragment from a DOM Node. + */ + public static XmlDateTime parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from a DOM Node. + */ + public static XmlDateTime parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlDateTime} fragment from an XMLStreamReader. + */ + public static XmlDateTime parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlDateTime} fragment from an XMLStreamReader. + */ + public static XmlDateTime parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDateTime) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlDecimal.java b/src/main/java/org/apache/xmlbeans/XmlDecimal.java new file mode 100644 index 0000000..21d38d7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlDecimal.java @@ -0,0 +1,171 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.math.BigDecimal; + +/** + * Corresponds to the XML Schema + * xs:decimal type. + *

+ * Convertible to {@link BigDecimal}. + */ +public interface XmlDecimal extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_decimal"); + + /** + * Returns this value as a {@link BigDecimal} + */ + BigDecimal getBigDecimalValue(); + + /** + * Sets this value as a {@link BigDecimal} + */ + void setBigDecimalValue(BigDecimal bd); + + /** + * A class with methods for creating instances + * of {@link XmlDecimal}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlDecimal} + */ + public static XmlDecimal newInstance() { + return (XmlDecimal) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlDecimal} + */ + public static XmlDecimal newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlDecimal) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlDecimal} value + */ + public static XmlDecimal newValue(Object obj) { + return (XmlDecimal) type.newValue(obj); + } + + /** + * Parses a {@link XmlDecimal} fragment from a String. For example: "<xml-fragment>1234.56789</xml-fragment>". + */ + public static XmlDecimal parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from a String. For example: "<xml-fragment>1234.56789</xml-fragment>". + */ + public static XmlDecimal parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlDecimal} fragment from a File. + */ + public static XmlDecimal parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from a File. + */ + public static XmlDecimal parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlDecimal} fragment from a URL. + */ + public static XmlDecimal parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from a URL. + */ + public static XmlDecimal parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlDecimal} fragment from an InputStream. + */ + public static XmlDecimal parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from an InputStream. + */ + public static XmlDecimal parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlDecimal} fragment from a Reader. + */ + public static XmlDecimal parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from a Reader. + */ + public static XmlDecimal parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlDecimal} fragment from a DOM Node. + */ + public static XmlDecimal parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from a DOM Node. + */ + public static XmlDecimal parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlDecimal} fragment from an XMLStreamReader. + */ + public static XmlDecimal parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlDecimal} fragment from an XMLStreamReader. + */ + public static XmlDecimal parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDecimal) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlDocumentProperties.java b/src/main/java/org/apache/xmlbeans/XmlDocumentProperties.java similarity index 97% rename from src/xmlpublic/org/apache/xmlbeans/XmlDocumentProperties.java rename to src/main/java/org/apache/xmlbeans/XmlDocumentProperties.java index f61fad5..7de0aba 100644 --- a/src/xmlpublic/org/apache/xmlbeans/XmlDocumentProperties.java +++ b/src/main/java/org/apache/xmlbeans/XmlDocumentProperties.java @@ -79,7 +79,10 @@ public abstract class XmlDocumentProperties /** * Returns the standalone property */ - public boolean getStandalone ( ) { return get( STANDALONE ) != null; } + public boolean getStandalone ( ) { + Object flag = get( STANDALONE ); + return flag != null && flag.toString().equalsIgnoreCase("true"); + } /** * Sets the DOCTYPE name use in the <!DOCTYPE> declaration. diff --git a/src/main/java/org/apache/xmlbeans/XmlDouble.java b/src/main/java/org/apache/xmlbeans/XmlDouble.java new file mode 100644 index 0000000..4d17298 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlDouble.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:double type. + *

+ * Naturally, convertible to a Java double. + */ +public interface XmlDouble extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_double"); + + /** + * Returns this value as a double + */ + double getDoubleValue(); + + /** + * Sets this value as a double + */ + void setDoubleValue(double v); + + /** + * A class with methods for creating instances + * of {@link XmlDouble}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlDouble} + */ + public static XmlDouble newInstance() { + return (XmlDouble) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlDouble} + */ + public static XmlDouble newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlDouble) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlDouble} value + */ + public static XmlDouble newValue(Object obj) { + return (XmlDouble) type.newValue(obj); + } + + /** + * Parses a {@link XmlDouble} fragment from a String. For example: "<xml-fragment>123.34e+57</xml-fragment>". + */ + public static XmlDouble parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from a String. For example: "<xml-fragment>123.34e+57</xml-fragment>". + */ + public static XmlDouble parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlDouble} fragment from a File. + */ + public static XmlDouble parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from a File. + */ + public static XmlDouble parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlDouble} fragment from a URL. + */ + public static XmlDouble parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from a URL. + */ + public static XmlDouble parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlDouble} fragment from an InputStream. + */ + public static XmlDouble parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from an InputStream. + */ + public static XmlDouble parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlDouble} fragment from a Reader. + */ + public static XmlDouble parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from a Reader. + */ + public static XmlDouble parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlDouble} fragment from a DOM Node. + */ + public static XmlDouble parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from a DOM Node. + */ + public static XmlDouble parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlDouble} fragment from an XMLStreamReader. + */ + public static XmlDouble parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlDouble} fragment from an XMLStreamReader. + */ + public static XmlDouble parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDouble) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlDuration.java b/src/main/java/org/apache/xmlbeans/XmlDuration.java new file mode 100644 index 0000000..02241df --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlDuration.java @@ -0,0 +1,171 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:duration type. + *

+ * Convertible to a {@link GDuration}. + * + * @see GDuration + */ +public interface XmlDuration extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_duration"); + + /** + * Returns this value as a {@link GDuration} + */ + GDuration getGDurationValue(); + + /** + * Sets this value as a {@link GDuration} + */ + void setGDurationValue(GDuration gd); + + /** + * A class with methods for creating instances + * of {@link XmlDuration}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlDuration} + */ + public static XmlDuration newInstance() { + return (XmlDuration) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlDuration} + */ + public static XmlDuration newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlDuration) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlDuration} value + */ + public static XmlDuration newValue(Object obj) { + return (XmlDuration) type.newValue(obj); + } + + /** + * Parses a {@link XmlDuration} fragment from a String. For example: "<xml-fragment>P1Y2MT2H</xml-fragment>". + */ + public static XmlDuration parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from a String. For example: "<xml-fragment>P1Y2MT2H</xml-fragment>". + */ + public static XmlDuration parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlDuration} fragment from a File. + */ + public static XmlDuration parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from a File. + */ + public static XmlDuration parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlDuration} fragment from a URL. + */ + public static XmlDuration parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from a URL. + */ + public static XmlDuration parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlDuration} fragment from an InputStream. + */ + public static XmlDuration parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from an InputStream. + */ + public static XmlDuration parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlDuration} fragment from a Reader. + */ + public static XmlDuration parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from a Reader. + */ + public static XmlDuration parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlDuration} fragment from a DOM Node. + */ + public static XmlDuration parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from a DOM Node. + */ + public static XmlDuration parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlDuration} fragment from an XMLStreamReader. + */ + public static XmlDuration parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlDuration} fragment from an XMLStreamReader. + */ + public static XmlDuration parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlDuration) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlENTITIES.java b/src/main/java/org/apache/xmlbeans/XmlENTITIES.java new file mode 100644 index 0000000..4f037bc --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlENTITIES.java @@ -0,0 +1,178 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.List; + + +/** + * Corresponds to the XML Schema + * xs:ENTITIES type, + * a list type. + *

+ * A list type. + */ +public interface XmlENTITIES extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_ENTITIES"); + + /** + * Returns the value as a {@link List} of {@link String} values + */ + List getListValue(); + + /** + * Returns the value as a {@link List} of {@link XmlENTITY} values + **/ + List xgetListValue(); + + /** + * Sets the value as a {@link List} + */ + void setListValue(List l); + + /** + * A class with methods for creating instances + * of {@link XmlENTITIES}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlENTITIES} + */ + public static XmlENTITIES newInstance() { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlENTITIES} + */ + public static XmlENTITIES newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlENTITIES} value + */ + public static XmlENTITIES newValue(Object obj) { + return (XmlENTITIES) type.newValue(obj); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a String. + */ + public static XmlENTITIES parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a String. + */ + public static XmlENTITIES parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a File. + */ + public static XmlENTITIES parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a File. + */ + public static XmlENTITIES parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a URL. + */ + public static XmlENTITIES parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a URL. + */ + public static XmlENTITIES parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlENTITIES} fragment from an InputStream. + */ + public static XmlENTITIES parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from an InputStream. + */ + public static XmlENTITIES parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a Reader. + */ + public static XmlENTITIES parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a Reader. + */ + public static XmlENTITIES parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a DOM Node. + */ + public static XmlENTITIES parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from a DOM Node. + */ + public static XmlENTITIES parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlENTITIES} fragment from an XMLStreamReader. + */ + public static XmlENTITIES parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlENTITIES} fragment from an XMLStreamReader. + */ + public static XmlENTITIES parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlENTITY.java b/src/main/java/org/apache/xmlbeans/XmlENTITY.java new file mode 100644 index 0000000..955812e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlENTITY.java @@ -0,0 +1,159 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:ENTITY type. + *

+ * Convertible to {@link String}. + */ +public interface XmlENTITY extends XmlNCName { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_ENTITY"); + + /** + * A class with methods for creating instances + * of {@link XmlENTITY}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlENTITY} + */ + public static XmlENTITY newInstance() { + return (XmlENTITY) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlENTITY} + */ + public static XmlENTITY newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlENTITY) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlENTITY} value + */ + public static XmlENTITY newValue(Object obj) { + return (XmlENTITY) type.newValue(obj); + } + + /** + * Parses a {@link XmlENTITY} fragment from a String. + */ + public static XmlENTITY parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from a String. + */ + public static XmlENTITY parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlENTITY} fragment from a File. + */ + public static XmlENTITY parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from a File. + */ + public static XmlENTITY parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlENTITY} fragment from a URL. + */ + public static XmlENTITY parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from a URL. + */ + public static XmlENTITY parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlENTITY} fragment from an InputStream. + */ + public static XmlENTITY parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from an InputStream. + */ + public static XmlENTITY parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlENTITY} fragment from a Reader. + */ + public static XmlENTITY parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from a Reader. + */ + public static XmlENTITY parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlENTITY} fragment from a DOM Node. + */ + public static XmlENTITY parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from a DOM Node. + */ + public static XmlENTITY parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlENTITY} fragment from an XMLStreamReader. + */ + public static XmlENTITY parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlENTITY} fragment from an XMLStreamReader. + */ + public static XmlENTITY parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlENTITY) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlError.java b/src/main/java/org/apache/xmlbeans/XmlError.java new file mode 100644 index 0000000..5ae34a3 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlError.java @@ -0,0 +1,633 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.stream.Location; +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.text.MessageFormat; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.PropertyResourceBundle; +import java.util.ResourceBundle; + +/** + * Represents a message at a specific XML location. + *

+ * The message can be an error, warning, or simple information, and + * it may optionally be associated with a specific location in + * an XML document. The class includes methods for extracting + * the location as a line number, XmlCursor, or XmlObject, as + * well as for obtaining and message and severity of the + * error. + * + * @see XmlOptions#setErrorListener + * @see XmlException + */ +public class XmlError implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + private static final ResourceBundle _bundle = PropertyResourceBundle.getBundle("org.apache.xmlbeans.message", Locale.ROOT); + + private final String _message; + private final String _code; + private final String _source; + private final int _severity; + private final int _line; + private final int _column; + private int _offset = -1; + + private transient XmlCursor _cursor; + + /** + * Copy constructor. + * + * @param src The original XmlError to copy. + */ + public XmlError(XmlError src) { + _message = src.getMessage(); + _code = src.getErrorCode(); + _severity = src.getSeverity(); + _source = src.getSourceName(); + _line = src.getLine(); + _column = src.getColumn(); + _offset = src.getOffset(); + _cursor = src.getCursorLocation(); + } + + /** + * The static factory methods should be used instead of + * this constructor. + */ + private XmlError(String message, String code, int severity, + String source, int line, int column, int offset, XmlCursor cursor) { + _message = message; + _code = code; + _severity = severity; + _source = source; + _line = line; + _column = column; + _offset = offset; + _cursor = cursor; + } + + private XmlError(String code, Object[] args, int severity, + String source, int line, int column, int offset, XmlCursor cursor) { + this(XmlError.formattedMessage(code, args), code, severity, source, line, column, offset, cursor); + } + + /** + * The static factory methods should be used instead of + * this constructor. + */ + protected XmlError(String message, String code, int severity, XmlCursor cursor) { + String source = null; + int line = -1; + int column = -1; + int offset = -1; + + if (cursor != null) { + // Hunt down the line/column/offset + source = cursor.documentProperties().getSourceName(); + + XmlCursor c = cursor.newCursor(); + + XmlLineNumber ln = + (XmlLineNumber) c.getBookmark(XmlLineNumber.class); + + if (ln == null) { + ln = (XmlLineNumber) c.toPrevBookmark(XmlLineNumber.class); + } + + if (ln != null) { + line = ln.getLine(); + column = ln.getColumn(); + offset = ln.getOffset(); + } + + c.dispose(); + } + + _message = message; + _code = code; + _severity = severity; + _source = source; + _line = line; + _column = column; + _offset = offset; + _cursor = cursor; + } + + protected XmlError(String code, Object[] args, int severity, XmlCursor cursor) { + this(XmlError.formattedMessage(code, args), code, severity, cursor); + } + + /** + * The static factory methods should be used instead of + * this constructor. + */ + protected XmlError(String message, String code, int severity, Location loc) { + String source = null; + int line = -1; + int column = -1; + + if (loc != null) { + line = loc.getLineNumber(); + column = loc.getColumnNumber(); + source = loc.getPublicId(); + if (source == null) { + source = loc.getSystemId(); + } + } + + _message = message; + _code = code; + _severity = severity; + _source = source; + _line = line; + _column = column; + } + + protected XmlError(String code, Object[] args, int severity, Location loc) { + this(XmlError.formattedMessage(code, args), code, severity, loc); + } + + /** + * Returns an XmlError for the given message, with no location and {@link #SEVERITY_ERROR}. + * + * @param message the error message + */ + public static XmlError forMessage(String message) { + return forMessage(message, SEVERITY_ERROR); + } + + /** + * Returns an XmlError for the given message, with no location and the given severity. + * + * @param message the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + */ + public static XmlError forMessage(String message, int severity) { + return forSource(message, severity, null); + } + + /** + * Returns an XmlError for the given message, with no location and the given severity. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + */ + public static XmlError forMessage(String code, Object[] args) { + return forSource(code, args, SEVERITY_ERROR, null); + } + + /** + * Returns an XmlError for the given message, with no location and the given severity. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + */ + public static XmlError forMessage(String code, Object[] args, int severity) { + return forSource(code, args, severity, null); + } + + /** + * Returns an XmlError for the given message, located in the given file and {@link #SEVERITY_ERROR}. + * + * @param message the error message + * @param sourceName the URL or other name for the file + */ + public static XmlError forSource(String message, String sourceName) { + return forLocation(message, SEVERITY_ERROR, sourceName, -1, -1, -1); + } + + /** + * Returns an XmlError for the given message, with the given severity, located in the given file. + * + * @param message the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param sourceName the URL or other name for the file + */ + public static XmlError forSource(String message, int severity, String sourceName) { + return forLocation(message, severity, sourceName, -1, -1, -1); + } + + /** + * Returns an XmlError for the given message, with the given severity, located in the given file. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param sourceName the URL or other name for the file + */ + public static XmlError forSource(String code, Object[] args, int severity, String sourceName) { + return forLocation(code, args, severity, sourceName, -1, -1, -1); + } + + /** + * Returns an XmlError for the given message, located at a specific point in the given file and {@link #SEVERITY_ERROR}. + * + * @param message the error message + * @param sourceName the URL or other name for the file + * @param location the location from an xml stream + */ + public static XmlError forLocation(String message, String sourceName, Location location) { + return new XmlError(message, (String) null, SEVERITY_ERROR, sourceName, + location.getLineNumber(), location.getColumnNumber(), -1, null); + } + + /** + * Returns an XmlError for the given message, located at a specific point in the given file and {@link #SEVERITY_ERROR}. + * + * @param message the error message + * @param sourceName the URL or other name for the file + * @param line the 1-based line number, or -1 if not known + * @param column the 1-based column number, or -1 if not known + * @param offset the 0-base file character offset, or -1 if not known + */ + public static XmlError forLocation(String message, String sourceName, int line, int column, int offset) { + return new XmlError(message, (String) null, SEVERITY_ERROR, sourceName, line, column, offset, null); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at a specific point in the given file. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param sourceName the URL or other name for the file + * @param line the 1-based line number, or -1 if not known + * @param column the 1-based column number, or -1 if not known + * @param offset the 0-base file character offset, or -1 if not known + */ + public static XmlError forLocation(String code, Object[] args, int severity, String sourceName, int line, int column, int offset) { + return new XmlError(code, args, severity, sourceName, line, column, offset, null); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at a specific point in the given file. + * + * @param message the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param sourceName the URL or other name for the file + * @param line the 1-based line number, or -1 if not known + * @param column the 1-based column number, or -1 if not known + * @param offset the 0-base file character offset, or -1 if not known + */ + public static XmlError forLocation(String message, int severity, String sourceName, int line, int column, int offset) { + return new XmlError(message, (String) null, severity, sourceName, line, column, offset, null); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at the given physcial location and XmlCursor. + * + * @param message the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param sourceName the URL or other name for the file + * @param line the 1-based line number, or -1 if not known + * @param column the 1-based column number, or -1 if not known + * @param offset the 0-base file character offset, or -1 if not known + * @param cursor the XmlCursor representing the location of the error + */ + public static XmlError forLocationAndCursor(String message, int severity, String sourceName, int line, int column, int offset, XmlCursor cursor) { + return new XmlError(message, (String) null, severity, sourceName, line, column, offset, cursor); + } + + /** + * Returns an XmlError for the given message, located at the XmlObject, with {@link #SEVERITY_ERROR}. + * + * @param message the error message + * @param xobj the XmlObject representing the location of the error + */ + public static XmlError forObject(String message, XmlObject xobj) { + return forObject(message, SEVERITY_ERROR, xobj); + } + + /** + * Returns an XmlError for the given message, located at the XmlObject, with {@link #SEVERITY_ERROR}. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param xobj the XmlObject representing the location of the error + */ + public static XmlError forObject(String code, Object[] args, XmlObject xobj) { + return forObject(code, args, SEVERITY_ERROR, xobj); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at the XmlObject. + * + * @param message the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param xobj the XmlObject representing the location of the error + */ + public static XmlError forObject(String message, int severity, XmlObject xobj) { + if (xobj == null) { + return forMessage(message, severity); + } + + XmlCursor cur = xobj.newCursor(); + return forCursor(message, severity, cur); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at the XmlObject. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param xobj the XmlObject representing the location of the error + */ + public static XmlError forObject(String code, Object[] args, int severity, XmlObject xobj) { + if (xobj == null) { + return forMessage(code, args, severity); + } + + XmlCursor cur = xobj.newCursor(); + return forCursor(code, args, severity, cur); + } + + /** + * Returns an XmlError for the given message, located at the XmlCursor, with {@link #SEVERITY_ERROR}. + * + * @param message the error message + * @param cursor the XmlCursor representing the location of the error + */ + public static XmlError forCursor(String message, XmlCursor cursor) { + return forCursor(message, SEVERITY_ERROR, cursor); + } + + /** + * Returns an XmlError for the given message, located at the XmlCursor, with {@link #SEVERITY_ERROR}. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param cursor the XmlCursor representing the location of the error + */ + public static XmlError forCursor(String code, Object[] args, XmlCursor cursor) { + return forCursor(code, args, SEVERITY_ERROR, cursor); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at the XmlCursor. + * + * @param message the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param cursor the XmlCursor representing the location of the error + */ + public static XmlError forCursor(String message, int severity, XmlCursor cursor) { + return new XmlError(message, (String) null, severity, cursor); + } + + /** + * Returns an XmlError for the given message, with the given severity, located at the XmlCursor. + * + * @param code the error code + * @param args the arguments to use in formatting the error message + * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) + * @param cursor the XmlCursor representing the location of the error + */ + public static XmlError forCursor(String code, Object[] args, int severity, XmlCursor cursor) { + return new XmlError(code, args, severity, cursor); + } + + /** + * Tries to produce a nicely formatted filename from the given string. + */ + protected static String formattedFileName(String rawString, URI base) { + if (rawString == null) { + return null; + } + + URI uri; + + try { + // if it looks like an absolute URI, treat it as such + uri = new URI(rawString); + + // otherwise, treat it like a filename + if (!uri.isAbsolute()) { + uri = null; + } + } catch (URISyntaxException e) { + uri = null; + } + + // looks like a filename; convert it to uri for relativization + if (uri == null) { + uri = new File(rawString).toURI(); + } + + if (base != null) { + uri = base.relativize(uri); + } + + // filenames get their file: stripped off and their /'s turned into \'s (MSDOS) + if (uri.isAbsolute() ? uri.getScheme().compareToIgnoreCase("file") == 0 : + base != null && base.isAbsolute() && base.getScheme().compareToIgnoreCase("file") == 0) { + try { + return (new File(uri)).toString(); + } catch (Exception ignored) { + } + } + + return uri.toString(); + } + + /** + * Tries to format a message using the error code. + */ + public static String formattedMessage(String code, Object[] args) { + if (code == null) { + return null; + } + + try { + return new MessageFormat(_bundle.getString(code), Locale.ROOT).format(args); + } catch (MissingResourceException | IllegalArgumentException e) { + String bnd = (e instanceof MissingResourceException) ? "message.missing.resource" : "message.pattern.invalid"; + return new MessageFormat(_bundle.getString(bnd), Locale.ROOT).format(e.getMessage()); + } + } + + /** + * An error. See {@link #getSeverity}. + */ + public static final int SEVERITY_ERROR = 0; + /** + * A warning. See {@link #getSeverity}. + */ + public static final int SEVERITY_WARNING = 1; + /** + * An informational message. See {@link #getSeverity}. + */ + public static final int SEVERITY_INFO = 2; + + /** + * Returns the severity. Either {@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}. + */ + public int getSeverity() { + return _severity; + } + + /** + * Returns the error message without location information. + */ + public String getMessage() { + return _message; + } + + /** + * Returns the error code or null. See {@link XmlErrorCodes}. + */ + public String getErrorCode() { + return _code; + } + + /** + * Returns the URL (or other name) of the file with the error, if available. + */ + public String getSourceName() { + return _source; + } + + /** + * Returns the line number of the error, if available, -1 if not. + */ + public int getLine() { + return _line; + } + + /** + * Returns the column number of the error, if available, -1 if not. + */ + public int getColumn() { + return _column; + } + + /** + * Returns the file character offset of the error, if available, -1 if not. + */ + public int getOffset() { + return _offset; + } + + /** + * Returns a location object of the given type. XmlCursor.class and + * XmlObject.class can be passed, for example. Null if not available. + */ + public Object getLocation(Object type) { + if (type == XmlCursor.class) { + return _cursor; + } + if (type == XmlObject.class && _cursor != null) { + return _cursor.getObject(); + } + return null; + } + + /** + * Returns a location of the error as an {@link XmlCursor}, null if + * not available. + */ + public XmlCursor getCursorLocation() { + return (XmlCursor) getLocation(XmlCursor.class); + } + + /** + * Returns a location of the error as an {@link XmlObject}, null if + * not available. + */ + public XmlObject getObjectLocation() { + return (XmlObject) getLocation(XmlObject.class); + } + + /** + * Produces a standard string for the error message, complete with + * filename and location offsets if available. + */ + public String toString() { + return toString(null); + } + + /** + * Produces a standard string with the error message. If a non-null + * URI is supplied, source names are relativized against the given + * URI. + */ + public String toString(URI base) { + // modified to carefully match the IDE's + // workshop.workspace.ant.AntLogger regex + // which also matches javac (davidbau) + + StringBuilder sb = new StringBuilder(); + + String source = formattedFileName(getSourceName(), base); + + if (source != null) { + sb.append(source); + int line = getLine(); + if (line < 0) { + line = 0; + } + + sb.append(':'); + sb.append(line); + sb.append(':'); + if (getColumn() > 0) { + sb.append(getColumn()); + sb.append(':'); + } + sb.append(" "); + } + + switch (getSeverity()) { + case SEVERITY_ERROR: + sb.append("error: "); + break; + case SEVERITY_WARNING: + sb.append("warning: "); + break; + case SEVERITY_INFO: + break; + } + + if (getErrorCode() != null) { + sb.append(getErrorCode()).append(": "); + } + + String msg = getMessage(); + + sb.append(msg == null ? "" : msg); + + return sb.toString(); + } + + public static String severityAsString(int severity) { + switch (severity) { + case SEVERITY_ERROR: + return ("error"); + case SEVERITY_WARNING: + return ("warning"); + case SEVERITY_INFO: + return "info"; + default: + throw new IllegalArgumentException("unknown severity"); + } + } +} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlErrorCodes.java b/src/main/java/org/apache/xmlbeans/XmlErrorCodes.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/XmlErrorCodes.java rename to src/main/java/org/apache/xmlbeans/XmlErrorCodes.java diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlException.java b/src/main/java/org/apache/xmlbeans/XmlException.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/XmlException.java rename to src/main/java/org/apache/xmlbeans/XmlException.java diff --git a/src/main/java/org/apache/xmlbeans/XmlFactoryHook.java b/src/main/java/org/apache/xmlbeans/XmlFactoryHook.java new file mode 100644 index 0000000..5c28509 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlFactoryHook.java @@ -0,0 +1,131 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Node; + +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.lang.ref.SoftReference; + +/** + * A hook for the XML Bean Factory mechanism. + * Provided for advanced users who wish to provide their own + * implementation of the Factory.parse methods. This is used, for example, + * to defer reading XML streams until needed. + *

+ * To use the hook, call XmlFactoryHook.ThreadContext.setHook(), passing + * your own XmlFactoryHook implementation. Then every call to a Factory + * method will be delgated to your hook. + * + *

+ * MyHook hook = new MyHook();
+ * XmlFactoryHook.ThreadContext.setHook(hook);
+ * // this results in a call to hook.parse(...)
+ * XmlObject.Factory.parse(new File("test.xml"));
+ * 
+ *

+ * If the hook needs to turn around and invoke the built-in parsers, then + * it should do so by calling the appropriate method on the passed + * SchemaTypeLoader. Since SchemaTypeLoader.parse() methods delegate + * to the registered hook, a hook that wishes to actually invoke the + * default parser without having itself called back again should + * unregister itself before calling loader.parse(), and then re-register + * itself again after the call. + *

+ * void parse(SchemaTypeLoader loader, ...)
+ * {
+ *     XmlFactoryHook remember = XmlFactoryHook.ThreadContext.getHook();
+ *     XmlFactoryHook.ThreadContext.setHook(null);
+ *     loader.parse(...); // isn't hooked.
+ *     XmlFactoryHook.ThreadContext.setHook(remember);
+ * }
+ * 
+ */ +public interface XmlFactoryHook { + /** + * Hooks Factory.newInstance calls + */ + XmlObject newInstance(SchemaTypeLoader loader, SchemaType type, XmlOptions options); + + /** + * Hooks Factory.parse calls + */ + XmlObject parse(SchemaTypeLoader loader, String xmlText, SchemaType type, XmlOptions options) throws XmlException; + + /** + * Hooks Factory.parse calls + */ + XmlObject parse(SchemaTypeLoader loader, InputStream jiois, SchemaType type, XmlOptions options) throws XmlException, IOException; + + /** + * Hooks Factory.parse calls + */ + XmlObject parse(SchemaTypeLoader loader, XMLStreamReader xsr, SchemaType type, XmlOptions options) throws XmlException; + + /** + * Hooks Factory.parse calls + */ + XmlObject parse(SchemaTypeLoader loader, Reader jior, SchemaType type, XmlOptions options) throws XmlException, IOException; + + /** + * Hooks Factory.parse calls + */ + XmlObject parse(SchemaTypeLoader loader, Node node, SchemaType type, XmlOptions options) throws XmlException; + + /** + * Hooks Factory.newXmlSaxHandler calls + */ + XmlSaxHandler newXmlSaxHandler(SchemaTypeLoader loader, SchemaType type, XmlOptions options); + + /** + * Hooks Factory.newDomImplementation calls + */ + DOMImplementation newDomImplementation(SchemaTypeLoader loader, XmlOptions options); + + /** + * Used to manage the XmlFactoryHook for the current thread. + */ + final class ThreadContext { + private static final ThreadLocal> threadHook = new ThreadLocal<>(); + + public static void clearThreadLocals() { + threadHook.remove(); + } + + /** + * Returns the current thread's hook, or null if none. + */ + public static XmlFactoryHook getHook() { + SoftReference softRef = threadHook.get(); + return softRef == null ? null : softRef.get(); + } + + /** + * Sets the hook for the current thread. + */ + public static void setHook(XmlFactoryHook hook) { + threadHook.set(new SoftReference<>(hook)); + } + + // provided to prevent unwanted construction + private ThreadContext() { + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/XmlFloat.java b/src/main/java/org/apache/xmlbeans/XmlFloat.java new file mode 100644 index 0000000..a100bc2 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlFloat.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:float type. + *

+ * Naturally, convertible to a Java float. + */ +public interface XmlFloat extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_float"); + + /** + * Returns this value as a float + */ + float getFloatValue(); + + /** + * Sets this value as a float + */ + void setFloatValue(float v); + + /** + * A class with methods for creating instances + * of {@link XmlFloat}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlFloat} + */ + public static XmlFloat newInstance() { + return (XmlFloat) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlFloat} + */ + public static XmlFloat newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlFloat) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlFloat} value + */ + public static XmlFloat newValue(Object obj) { + return (XmlFloat) type.newValue(obj); + } + + /** + * Parses a {@link XmlFloat} fragment from a String. For example: "<xml-fragment>12.34e+5</xml-fragment>". + */ + public static XmlFloat parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from a String. For example: "<xml-fragment>12.34e+5</xml-fragment>". + */ + public static XmlFloat parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlFloat} fragment from a File. + */ + public static XmlFloat parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from a File. + */ + public static XmlFloat parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlFloat} fragment from a URL. + */ + public static XmlFloat parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from a URL. + */ + public static XmlFloat parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlFloat} fragment from an InputStream. + */ + public static XmlFloat parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from an InputStream. + */ + public static XmlFloat parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlFloat} fragment from a Reader. + */ + public static XmlFloat parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from a Reader. + */ + public static XmlFloat parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlFloat} fragment from a DOM Node. + */ + public static XmlFloat parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from a DOM Node. + */ + public static XmlFloat parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlFloat} fragment from an XMLStreamReader. + */ + public static XmlFloat parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlFloat} fragment from an XMLStreamReader. + */ + public static XmlFloat parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlFloat) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlGDay.java b/src/main/java/org/apache/xmlbeans/XmlGDay.java new file mode 100644 index 0000000..09effa7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlGDay.java @@ -0,0 +1,196 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; + + +/** + * Corresponds to the XML Schema + * xs:gDay type. + * A gDay specifies only a day-of-month. + *

+ * Convertible to {@link Calendar}, {@link GDate}, or an int. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlGDay extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gDay"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * Returns this value as an int from 1-31 + */ + int getIntValue(); + + /** + * Sets this value as an int from 1-31 + */ + void setIntValue(int v); + + /** + * A class with methods for creating instances + * of {@link XmlGDay}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlGDay} + */ + public static XmlGDay newInstance() { + return (XmlGDay) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlGDay} + */ + public static XmlGDay newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlGDay) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlGDay} value + */ + public static XmlGDay newValue(Object obj) { + return (XmlGDay) type.newValue(obj); + } + + /** + * Parses a {@link XmlGDay} fragment from a String. For example: "<xml-fragment>---14</xml-fragment>". + */ + public static XmlGDay parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from a String. For example: "<xml-fragment>---14</xml-fragment>". + */ + public static XmlGDay parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlGDay} fragment from a File. + */ + public static XmlGDay parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from a File. + */ + public static XmlGDay parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlGDay} fragment from a URL. + */ + public static XmlGDay parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from a URL. + */ + public static XmlGDay parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlGDay} fragment from an InputStream. + */ + public static XmlGDay parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from an InputStream. + */ + public static XmlGDay parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlGDay} fragment from a Reader. + */ + public static XmlGDay parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from a Reader. + */ + public static XmlGDay parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlGDay} fragment from a DOM Node. + */ + public static XmlGDay parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from a DOM Node. + */ + public static XmlGDay parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlGDay} fragment from an XMLStreamReader. + */ + public static XmlGDay parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlGDay} fragment from an XMLStreamReader. + */ + public static XmlGDay parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGDay) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlGMonth.java b/src/main/java/org/apache/xmlbeans/XmlGMonth.java new file mode 100644 index 0000000..bb44425 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlGMonth.java @@ -0,0 +1,196 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; + + +/** + * Corresponds to the XML Schema + * xs:gMonth type. + * A gMonth specifies only a month-of-year. + *

+ * Convertible to {@link Calendar}, {@link GDate}, or an int. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlGMonth extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gMonth"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * Returns this value as an int from 1-12 + */ + int getIntValue(); + + /** + * Sets this value as an int from 1-12 + */ + void setIntValue(int v); + + /** + * A class with methods for creating instances + * of {@link XmlGMonth}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlGMonth} + */ + public static XmlGMonth newInstance() { + return (XmlGMonth) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlGMonth} + */ + public static XmlGMonth newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlGMonth) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlGMonth} value + */ + public static XmlGMonth newValue(Object obj) { + return (XmlGMonth) type.newValue(obj); + } + + /** + * Parses a {@link XmlGMonth} fragment from a String. For example: "<xml-fragment>--06</xml-fragment>". + */ + public static XmlGMonth parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from a String. For example: "<xml-fragment>--06</xml-fragment>". + */ + public static XmlGMonth parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlGMonth} fragment from a File. + */ + public static XmlGMonth parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from a File. + */ + public static XmlGMonth parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlGMonth} fragment from a URL. + */ + public static XmlGMonth parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from a URL. + */ + public static XmlGMonth parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlGMonth} fragment from an InputStream. + */ + public static XmlGMonth parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from an InputStream. + */ + public static XmlGMonth parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlGMonth} fragment from a Reader. + */ + public static XmlGMonth parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from a Reader. + */ + public static XmlGMonth parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlGMonth} fragment from a DOM Node. + */ + public static XmlGMonth parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from a DOM Node. + */ + public static XmlGMonth parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlGMonth} fragment from an XMLStreamReader. + */ + public static XmlGMonth parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlGMonth} fragment from an XMLStreamReader. + */ + public static XmlGMonth parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGMonth) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlGMonthDay.java b/src/main/java/org/apache/xmlbeans/XmlGMonthDay.java new file mode 100644 index 0000000..0ceaeb3 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlGMonthDay.java @@ -0,0 +1,186 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; + + +/** + * Corresponds to the XML Schema + * xs:gMonthDay type. + * A gMonthDay specifies a day of a specific month without specifying the year. + *

+ * Convertible to {@link Calendar} or {@link GDate}. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlGMonthDay extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gMonthDay"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * A class with methods for creating instances + * of {@link XmlGMonthDay}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlGMonthDay} + */ + public static XmlGMonthDay newInstance() { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlGMonthDay} + */ + public static XmlGMonthDay newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlGMonthDay} value + */ + public static XmlGMonthDay newValue(Object obj) { + return (XmlGMonthDay) type.newValue(obj); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a String. For example: "<xml-fragment>--06-14</xml-fragment>". + */ + public static XmlGMonthDay parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a String. For example: "<xml-fragment>--06-14</xml-fragment>". + */ + public static XmlGMonthDay parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a File. + */ + public static XmlGMonthDay parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a File. + */ + public static XmlGMonthDay parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a URL. + */ + public static XmlGMonthDay parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a URL. + */ + public static XmlGMonthDay parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from an InputStream. + */ + public static XmlGMonthDay parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from an InputStream. + */ + public static XmlGMonthDay parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a Reader. + */ + public static XmlGMonthDay parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a Reader. + */ + public static XmlGMonthDay parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a DOM Node. + */ + public static XmlGMonthDay parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from a DOM Node. + */ + public static XmlGMonthDay parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from an XMLStreamReader. + */ + public static XmlGMonthDay parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlGMonthDay} fragment from an XMLStreamReader. + */ + public static XmlGMonthDay parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlGYear.java b/src/main/java/org/apache/xmlbeans/XmlGYear.java new file mode 100644 index 0000000..6ae72b8 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlGYear.java @@ -0,0 +1,196 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; + + +/** + * Corresponds to the XML Schema + * xs:gYear type. + * A gYear specifies a Gregorian year (AD). + *

+ * Convertible to {@link Calendar}, {@link GDate}, or an int. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlGYear extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gYear"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * Returns this value as an int from 1-31 + */ + int getIntValue(); + + /** + * Sets this value as an int from 1-31 + */ + void setIntValue(int v); + + /** + * A class with methods for creating instances + * of {@link XmlGYear}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlGYear} + */ + public static XmlGYear newInstance() { + return (XmlGYear) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlGYear} + */ + public static XmlGYear newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlGYear) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlGYear} value + */ + public static XmlGYear newValue(Object obj) { + return (XmlGYear) type.newValue(obj); + } + + /** + * Parses a {@link XmlGYear} fragment from a String. For example: "<xml-fragment>2003</xml-fragment>". + */ + public static XmlGYear parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from a String. For example: "<xml-fragment>2003</xml-fragment>". + */ + public static XmlGYear parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlGYear} fragment from a File. + */ + public static XmlGYear parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from a File. + */ + public static XmlGYear parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlGYear} fragment from a URL. + */ + public static XmlGYear parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from a URL. + */ + public static XmlGYear parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlGYear} fragment from an InputStream. + */ + public static XmlGYear parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from an InputStream. + */ + public static XmlGYear parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlGYear} fragment from a Reader. + */ + public static XmlGYear parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from a Reader. + */ + public static XmlGYear parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlGYear} fragment from a DOM Node. + */ + public static XmlGYear parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from a DOM Node. + */ + public static XmlGYear parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlGYear} fragment from an XMLStreamReader. + */ + public static XmlGYear parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlGYear} fragment from an XMLStreamReader. + */ + public static XmlGYear parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGYear) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlGYearMonth.java b/src/main/java/org/apache/xmlbeans/XmlGYearMonth.java new file mode 100644 index 0000000..8e318ce --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlGYearMonth.java @@ -0,0 +1,186 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; + + +/** + * Corresponds to the XML Schema + * xs:gYearMonth type. + * A gYearMonth specifies a month in a specific year. + *

+ * Convertible to {@link Calendar}, {@link GDate}. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlGYearMonth extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gYearMonth"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * A class with methods for creating instances + * of {@link XmlGYearMonth}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlGYearMonth} + */ + public static XmlGYearMonth newInstance() { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlGYearMonth} + */ + public static XmlGYearMonth newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlGYearMonth} value + */ + public static XmlGYearMonth newValue(Object obj) { + return (XmlGYearMonth) type.newValue(obj); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a String. For example: "<xml-fragment>2003-06</xml-fragment>". + */ + public static XmlGYearMonth parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a String. For example: "<xml-fragment>2003-06</xml-fragment>". + */ + public static XmlGYearMonth parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a File. + */ + public static XmlGYearMonth parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a File. + */ + public static XmlGYearMonth parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a URL. + */ + public static XmlGYearMonth parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a URL. + */ + public static XmlGYearMonth parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from an InputStream. + */ + public static XmlGYearMonth parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from an InputStream. + */ + public static XmlGYearMonth parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a Reader. + */ + public static XmlGYearMonth parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a Reader. + */ + public static XmlGYearMonth parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a DOM Node. + */ + public static XmlGYearMonth parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from a DOM Node. + */ + public static XmlGYearMonth parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from an XMLStreamReader. + */ + public static XmlGYearMonth parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlGYearMonth} fragment from an XMLStreamReader. + */ + public static XmlGYearMonth parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlHexBinary.java b/src/main/java/org/apache/xmlbeans/XmlHexBinary.java new file mode 100644 index 0000000..acc9487 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlHexBinary.java @@ -0,0 +1,170 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:hexBinary type. + *

+ * Convertible to a byte array. + */ +public interface XmlHexBinary extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_hexBinary"); + + /** + * Returns this value as a byte array. + **/ + byte[] getByteArrayValue(); + + /** + * Sets this value as a byte array. + */ + void setByteArrayValue(byte[] ba); + + + /** + * A class with methods for creating instances + * of {@link XmlHexBinary}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlHexBinary} + */ + public static XmlHexBinary newInstance() { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlHexBinary} + */ + public static XmlHexBinary newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlHexBinary} value + */ + public static XmlHexBinary newValue(Object obj) { + return (XmlHexBinary) type.newValue(obj); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a String. For example: "<xml-fragment>68656c6c6f</xml-fragment>". + */ + public static XmlHexBinary parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a String. For example: "<xml-fragment>68656c6c6f</xml-fragment>". + */ + public static XmlHexBinary parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a File. + */ + public static XmlHexBinary parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a File. + */ + public static XmlHexBinary parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a URL. + */ + public static XmlHexBinary parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a URL. + */ + public static XmlHexBinary parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlHexBinary} fragment from an InputStream. + */ + public static XmlHexBinary parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from an InputStream. + */ + public static XmlHexBinary parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a Reader. + */ + public static XmlHexBinary parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a Reader. + */ + public static XmlHexBinary parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a DOM Node. + */ + public static XmlHexBinary parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from a DOM Node. + */ + public static XmlHexBinary parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlHexBinary} fragment from an XMLStreamReader. + */ + public static XmlHexBinary parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlHexBinary} fragment from an XMLStreamReader. + */ + public static XmlHexBinary parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlID.java b/src/main/java/org/apache/xmlbeans/XmlID.java new file mode 100644 index 0000000..ef56e1c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlID.java @@ -0,0 +1,162 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:ID type. + *

+ * When validated, IDs must be unique within a document. An element + * may not have more than one attribute whose type is ID. + *

+ * Convertible to a {@link String}. + */ +public interface XmlID extends XmlNCName { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_ID"); + + /** + * A class with methods for creating instances + * of {@link XmlID}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlID} + */ + public static XmlID newInstance() { + return (XmlID) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlID} + */ + public static XmlID newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlID) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlID} value + */ + public static XmlID newValue(Object obj) { + return (XmlID) type.newValue(obj); + } + + /** + * Parses a {@link XmlID} fragment from a String. For example: "<xml-fragment>n1</xml-fragment>". + */ + public static XmlID parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlID} fragment from a String. For example: "<xml-fragment>n1</xml-fragment>". + */ + public static XmlID parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlID} fragment from a File. + */ + public static XmlID parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlID} fragment from a File. + */ + public static XmlID parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlID} fragment from a URL. + */ + public static XmlID parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlID} fragment from a URL. + */ + public static XmlID parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlID} fragment from an InputStream. + */ + public static XmlID parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlID} fragment from an InputStream. + */ + public static XmlID parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlID} fragment from a Reader. + */ + public static XmlID parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlID} fragment from a Reader. + */ + public static XmlID parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlID} fragment from a DOM Node. + */ + public static XmlID parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlID} fragment from a DOM Node. + */ + public static XmlID parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlID} fragment from an XMLStreamReader. + */ + public static XmlID parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlID} fragment from an XMLStreamReader. + */ + public static XmlID parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlID) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlIDREF.java b/src/main/java/org/apache/xmlbeans/XmlIDREF.java new file mode 100644 index 0000000..5d5f99f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlIDREF.java @@ -0,0 +1,163 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:IDREF type. + *

+ * When validated, IDREF values must match an ID value that is present within + * the document. This rule is only verified when a whole document is validated + * at once. + *

+ * Convertible to a {@link String}. + */ +public interface XmlIDREF extends XmlNCName { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_IDREF"); + + /** + * A class with methods for creating instances + * of {@link XmlIDREF}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlIDREF} + */ + public static XmlIDREF newInstance() { + return (XmlIDREF) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlIDREF} + */ + public static XmlIDREF newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlIDREF) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlIDREF} value + */ + public static XmlIDREF newValue(Object obj) { + return (XmlIDREF) type.newValue(obj); + } + + /** + * Parses a {@link XmlIDREF} fragment from a String. + */ + public static XmlIDREF parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from a String. + */ + public static XmlIDREF parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlIDREF} fragment from a File. + */ + public static XmlIDREF parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from a File. + */ + public static XmlIDREF parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlIDREF} fragment from a URL. + */ + public static XmlIDREF parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from a URL. + */ + public static XmlIDREF parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlIDREF} fragment from an InputStream. + */ + public static XmlIDREF parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from an InputStream. + */ + public static XmlIDREF parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlIDREF} fragment from a Reader. + */ + public static XmlIDREF parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from a Reader. + */ + public static XmlIDREF parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlIDREF} fragment from a DOM Node. + */ + public static XmlIDREF parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from a DOM Node. + */ + public static XmlIDREF parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlIDREF} fragment from an XMLStreamReader. + */ + public static XmlIDREF parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlIDREF} fragment from an XMLStreamReader. + */ + public static XmlIDREF parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlIDREF) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlIDREFS.java b/src/main/java/org/apache/xmlbeans/XmlIDREFS.java new file mode 100644 index 0000000..71592bd --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlIDREFS.java @@ -0,0 +1,182 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.List; + + +/** + * Corresponds to the XML Schema + * xs:IDREFS type, + * a list type. + *

+ * When validated, IDREF values must match an ID value that is present within + * the document. This rule is only verified when a whole document is validated + * at once. + *

+ * Convertible to a {@link List}. + */ +public interface XmlIDREFS extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_IDREFS"); + + /** + * Returns the value as a {@link List} of {@link String} values + */ + List getListValue(); + + /** + * Returns the value as a {@link List} of {@link XmlIDREF} values + */ + List xgetListValue(); + + /** + * Sets the value as a {@link List} + */ + void setListValue(List l); + + /** + * A class with methods for creating instances + * of {@link XmlIDREFS}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlIDREFS} + */ + public static XmlIDREFS newInstance() { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlIDREFS} + */ + public static XmlIDREFS newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlIDREFS} value + */ + public static XmlIDREFS newValue(Object obj) { + return (XmlIDREFS) type.newValue(obj); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a String. + */ + public static XmlIDREFS parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a String. + */ + public static XmlIDREFS parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a File. + */ + public static XmlIDREFS parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a File. + */ + public static XmlIDREFS parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a URL. + */ + public static XmlIDREFS parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a URL. + */ + public static XmlIDREFS parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlIDREFS} fragment from an InputStream. + */ + public static XmlIDREFS parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from an InputStream. + */ + public static XmlIDREFS parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a Reader. + */ + public static XmlIDREFS parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a Reader. + */ + public static XmlIDREFS parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a DOM Node. + */ + public static XmlIDREFS parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from a DOM Node. + */ + public static XmlIDREFS parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlIDREFS} fragment from an XMLStreamReader. + */ + public static XmlIDREFS parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlIDREFS} fragment from an XMLStreamReader. + */ + public static XmlIDREFS parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlInt.java b/src/main/java/org/apache/xmlbeans/XmlInt.java new file mode 100644 index 0000000..0052fe7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlInt.java @@ -0,0 +1,170 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:int type. + * One of the derived types based on xs:decimal. + *

+ * Naturally, convertible to a Java int. + */ +public interface XmlInt extends XmlLong { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_int"); + + /** + * Returns this value as an int + */ + int getIntValue(); + + /** + * Sets this value as an int + */ + void setIntValue(int v); + + /** + * A class with methods for creating instances + * of {@link XmlInt}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlInt} + */ + public static XmlInt newInstance() { + return (XmlInt) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlInt} + */ + public static XmlInt newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlInt) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlInt} value + */ + public static XmlInt newValue(Object obj) { + return (XmlInt) type.newValue(obj); + } + + /** + * Parses a {@link XmlInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". + */ + public static XmlInt parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". + */ + public static XmlInt parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlInt} fragment from a File. + */ + public static XmlInt parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from a File. + */ + public static XmlInt parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlInt} fragment from a URL. + */ + public static XmlInt parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from a URL. + */ + public static XmlInt parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlInt} fragment from an InputStream. + */ + public static XmlInt parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from an InputStream. + */ + public static XmlInt parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlInt} fragment from a Reader. + */ + public static XmlInt parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from a Reader. + */ + public static XmlInt parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlInt} fragment from a DOM Node. + */ + public static XmlInt parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from a DOM Node. + */ + public static XmlInt parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlInt} fragment from an XMLStreamReader. + */ + public static XmlInt parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlInt} fragment from an XMLStreamReader. + */ + public static XmlInt parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlInt) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlInteger.java b/src/main/java/org/apache/xmlbeans/XmlInteger.java new file mode 100644 index 0000000..93fed93 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlInteger.java @@ -0,0 +1,176 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.math.BigInteger; + +/** + * Corresponds to the XML Schema + * xs:integer type. + * One of the derived types based on xs:decimal. + *

+ * This type should not be confused with xs:int + * or Java {@link Integer}. This type represents an arbitrary-precision integer with + * any number of digits, while a Java int or an xs:int is a 32-bit finite-precision integer. + *

+ * Convertible to a Java {@link BigInteger}. + */ +public interface XmlInteger extends XmlDecimal { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_integer"); + + /** + * Returns this value as a {@link BigInteger} + */ + BigInteger getBigIntegerValue(); + + /** + * Sets this value as a {@link BigInteger} + */ + void setBigIntegerValue(BigInteger bi); + + /** + * A class with methods for creating instances + * of {@link XmlInteger}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlInteger} + */ + public static XmlInteger newInstance() { + return (XmlInteger) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlInteger} + */ + public static XmlInteger newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlInteger) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlInteger} value + */ + public static XmlInteger newValue(Object obj) { + return (XmlInteger) type.newValue(obj); + } + + /** + * Parses a {@link XmlInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". + */ + public static XmlInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". + */ + public static XmlInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlInteger} fragment from a File. + */ + public static XmlInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from a File. + */ + public static XmlInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlInteger} fragment from a URL. + */ + public static XmlInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from a URL. + */ + public static XmlInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlInteger} fragment from an InputStream. + */ + public static XmlInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from an InputStream. + */ + public static XmlInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlInteger} fragment from a Reader. + */ + public static XmlInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from a Reader. + */ + public static XmlInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlInteger} fragment from a DOM Node. + */ + public static XmlInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from a DOM Node. + */ + public static XmlInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlInteger} fragment from an XMLStreamReader. + */ + public static XmlInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlInteger} fragment from an XMLStreamReader. + */ + public static XmlInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlLanguage.java b/src/main/java/org/apache/xmlbeans/XmlLanguage.java new file mode 100644 index 0000000..b936311 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlLanguage.java @@ -0,0 +1,161 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:language type. + *

+ * This type is intended to represent an standard ISO language code string. + *

+ * Convertible to a Java {@link String}. + */ +public interface XmlLanguage extends XmlToken { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_language"); + + /** + * A class with methods for creating instances + * of {@link XmlLanguage}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlLanguage} + */ + public static XmlLanguage newInstance() { + return (XmlLanguage) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlLanguage} + */ + public static XmlLanguage newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlLanguage) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlLanguage} value + */ + public static XmlLanguage newValue(Object obj) { + return (XmlLanguage) type.newValue(obj); + } + + /** + * Parses a {@link XmlLanguage} fragment from a String. For example: "<xml-fragment>en-us</xml-fragment>". + */ + public static XmlLanguage parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from a String. For example: "<xml-fragment>en-us</xml-fragment>". + */ + public static XmlLanguage parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlLanguage} fragment from a File. + */ + public static XmlLanguage parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from a File. + */ + public static XmlLanguage parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlLanguage} fragment from a URL. + */ + public static XmlLanguage parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from a URL. + */ + public static XmlLanguage parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlLanguage} fragment from an InputStream. + */ + public static XmlLanguage parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from an InputStream. + */ + public static XmlLanguage parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlLanguage} fragment from a Reader. + */ + public static XmlLanguage parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from a Reader. + */ + public static XmlLanguage parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlLanguage} fragment from a DOM Node. + */ + public static XmlLanguage parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from a DOM Node. + */ + public static XmlLanguage parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlLanguage} fragment from an XMLStreamReader. + */ + public static XmlLanguage parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlLanguage} fragment from an XMLStreamReader. + */ + public static XmlLanguage parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlLanguage) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlLineNumber.java b/src/main/java/org/apache/xmlbeans/XmlLineNumber.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/XmlLineNumber.java rename to src/main/java/org/apache/xmlbeans/XmlLineNumber.java diff --git a/src/main/java/org/apache/xmlbeans/XmlLong.java b/src/main/java/org/apache/xmlbeans/XmlLong.java new file mode 100644 index 0000000..0a9bce8 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlLong.java @@ -0,0 +1,170 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:long type. + * One of the derived types based on xs:decimal. + *

+ * Naturally, convertible to a Java long. + */ +public interface XmlLong extends XmlInteger { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_long"); + + /** + * Returns this value as a long + */ + long getLongValue(); + + /** + * Sets this value as a long + */ + void setLongValue(long v); + + /** + * A class with methods for creating instances + * of {@link XmlLong}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlLong} + */ + public static XmlLong newInstance() { + return (XmlLong) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlLong} + */ + public static XmlLong newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlLong) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlLong} value + */ + public static XmlLong newValue(Object obj) { + return (XmlLong) type.newValue(obj); + } + + /** + * Parses a {@link XmlLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". + */ + public static XmlLong parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". + */ + public static XmlLong parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlLong} fragment from a File. + */ + public static XmlLong parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from a File. + */ + public static XmlLong parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlLong} fragment from a URL. + */ + public static XmlLong parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from a URL. + */ + public static XmlLong parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlLong} fragment from an InputStream. + */ + public static XmlLong parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from an InputStream. + */ + public static XmlLong parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlLong} fragment from a Reader. + */ + public static XmlLong parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from a Reader. + */ + public static XmlLong parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlLong} fragment from a DOM Node. + */ + public static XmlLong parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from a DOM Node. + */ + public static XmlLong parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlLong} fragment from an XMLStreamReader. + */ + public static XmlLong parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlLong} fragment from an XMLStreamReader. + */ + public static XmlLong parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlLong) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNCName.java b/src/main/java/org/apache/xmlbeans/XmlNCName.java new file mode 100644 index 0000000..4f52fca --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNCName.java @@ -0,0 +1,165 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:Name type. + * One of the derived types based on xs:string. + *

+ * This kind of string is the same as the non-colonized strings that are used + * for XML localnames and prefixes, "my-href.2". It is just a physical + * string, however, and it should NOT be confused with {@link XmlQName}, + * which is a logical combination of localname and namespace URI. + *

+ * Convertible to {@link String}. + */ +public interface XmlNCName extends XmlName { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NCName"); + + /** + * A class with methods for creating instances + * of {@link XmlNCName}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNCName} + */ + public static XmlNCName newInstance() { + return (XmlNCName) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNCName} + */ + public static XmlNCName newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNCName) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNCName} value + */ + public static XmlNCName newValue(Object obj) { + return (XmlNCName) type.newValue(obj); + } + + /** + * Parses a {@link XmlNCName} fragment from a String. For example: "<xml-fragment>My-Name</xml-fragment>". + */ + public static XmlNCName parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from a String. For example: "<xml-fragment>My-Name</xml-fragment>". + */ + public static XmlNCName parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNCName} fragment from a File. + */ + public static XmlNCName parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from a File. + */ + public static XmlNCName parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNCName} fragment from a URL. + */ + public static XmlNCName parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from a URL. + */ + public static XmlNCName parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNCName} fragment from an InputStream. + */ + public static XmlNCName parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from an InputStream. + */ + public static XmlNCName parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNCName} fragment from a Reader. + */ + public static XmlNCName parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from a Reader. + */ + public static XmlNCName parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNCName} fragment from a DOM Node. + */ + public static XmlNCName parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from a DOM Node. + */ + public static XmlNCName parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNCName} fragment from an XMLStreamReader. + */ + public static XmlNCName parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNCName} fragment from an XMLStreamReader. + */ + public static XmlNCName parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNCName) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNMTOKEN.java b/src/main/java/org/apache/xmlbeans/XmlNMTOKEN.java new file mode 100644 index 0000000..dfccff4 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNMTOKEN.java @@ -0,0 +1,164 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:NMTOKEN type. + * One of the derived types based on xs:string. + *

+ * An NMTOKEN is XML's closest concept to an "identifier"; for example, + * it does not permit spaces and only limited punctuation. So NMTOKEN is + * commonly used to describe a single token or enumerated string value. + *

+ * Convertible to {@link String}. + */ +public interface XmlNMTOKEN extends XmlToken { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NMTOKEN"); + + /** + * A class with methods for creating instances + * of {@link XmlNMTOKEN}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNMTOKEN} + */ + public static XmlNMTOKEN newInstance() { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNMTOKEN} + */ + public static XmlNMTOKEN newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNMTOKEN} value + */ + public static XmlNMTOKEN newValue(Object obj) { + return (XmlNMTOKEN) type.newValue(obj); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a String. For example: "<xml-fragment>sample-1.2</xml-fragment>". + */ + public static XmlNMTOKEN parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a String. For example: "<xml-fragment>sample-1.2</xml-fragment>". + */ + public static XmlNMTOKEN parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a File. + */ + public static XmlNMTOKEN parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a File. + */ + public static XmlNMTOKEN parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a URL. + */ + public static XmlNMTOKEN parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a URL. + */ + public static XmlNMTOKEN parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from an InputStream. + */ + public static XmlNMTOKEN parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from an InputStream. + */ + public static XmlNMTOKEN parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a Reader. + */ + public static XmlNMTOKEN parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a Reader. + */ + public static XmlNMTOKEN parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a DOM Node. + */ + public static XmlNMTOKEN parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from a DOM Node. + */ + public static XmlNMTOKEN parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from an XMLStreamReader. + */ + public static XmlNMTOKEN parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNMTOKEN} fragment from an XMLStreamReader. + */ + public static XmlNMTOKEN parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNMTOKENS.java b/src/main/java/org/apache/xmlbeans/XmlNMTOKENS.java new file mode 100644 index 0000000..9cf6fbb --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNMTOKENS.java @@ -0,0 +1,178 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.List; + + +/** + * Corresponds to the XML Schema + * xs:NMTOKENS type, + * a list type. + *

+ * Convertible to {@link List}. + */ +public interface XmlNMTOKENS extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NMTOKENS"); + + /** + * Returns the value as a {@link List} of {@link String} values + */ + List getListValue(); + + /** + * Returns the value as a {@link List} of {@link XmlNMTOKEN} values + */ + List xgetListValue(); + + /** + * Sets the value as a {@link List} + */ + void setListValue(List l); + + /** + * A class with methods for creating instances + * of {@link XmlNMTOKENS}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNMTOKENS} + */ + public static XmlNMTOKENS newInstance() { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNMTOKENS} + */ + public static XmlNMTOKENS newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNMTOKENS} value + */ + public static XmlNMTOKENS newValue(Object obj) { + return (XmlNMTOKENS) type.newValue(obj); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a String. For example: "<xml-fragment>sample-1.1 sample-1.2 sample-1.3</xml-fragment>". + */ + public static XmlNMTOKENS parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a String. For example: "<xml-fragment>sample-1.1 sample-1.2 sample-1.3</xml-fragment>". + */ + public static XmlNMTOKENS parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a File. + */ + public static XmlNMTOKENS parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a File. + */ + public static XmlNMTOKENS parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a URL. + */ + public static XmlNMTOKENS parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a URL. + */ + public static XmlNMTOKENS parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from an InputStream. + */ + public static XmlNMTOKENS parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from an InputStream. + */ + public static XmlNMTOKENS parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a Reader. + */ + public static XmlNMTOKENS parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a Reader. + */ + public static XmlNMTOKENS parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a DOM Node. + */ + public static XmlNMTOKENS parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from a DOM Node. + */ + public static XmlNMTOKENS parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from an XMLStreamReader. + */ + public static XmlNMTOKENS parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNMTOKENS} fragment from an XMLStreamReader. + */ + public static XmlNMTOKENS parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNOTATION.java b/src/main/java/org/apache/xmlbeans/XmlNOTATION.java new file mode 100644 index 0000000..6b56eaa --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNOTATION.java @@ -0,0 +1,163 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:NOTATION type. + *

+ * NOTATIONs are a mechanism in XML Schema that is provided + * for partial backward compatibility with NOTATIONs in DTDs. XML Schema + * users should almost never have any reason to use this data type. + *

+ * Convertible to {@link String}. + */ +public interface XmlNOTATION extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NOTATION"); + + /** + * A class with methods for creating instances + * of {@link XmlNOTATION}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNOTATION} + */ + public static XmlNOTATION newInstance() { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNOTATION} + */ + public static XmlNOTATION newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNOTATION} value + */ + public static XmlNOTATION newValue(Object obj) { + return (XmlNOTATION) type.newValue(obj); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a String. + */ + public static XmlNOTATION parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a String. + */ + public static XmlNOTATION parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a File. + */ + public static XmlNOTATION parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a File. + */ + public static XmlNOTATION parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a URL. + */ + public static XmlNOTATION parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a URL. + */ + public static XmlNOTATION parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNOTATION} fragment from an InputStream. + */ + public static XmlNOTATION parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from an InputStream. + */ + public static XmlNOTATION parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a Reader. + */ + public static XmlNOTATION parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a Reader. + */ + public static XmlNOTATION parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a DOM Node. + */ + public static XmlNOTATION parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from a DOM Node. + */ + public static XmlNOTATION parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNOTATION} fragment from an XMLStreamReader. + */ + public static XmlNOTATION parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNOTATION} fragment from an XMLStreamReader. + */ + public static XmlNOTATION parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlName.java b/src/main/java/org/apache/xmlbeans/XmlName.java new file mode 100644 index 0000000..1bd945d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlName.java @@ -0,0 +1,165 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:Name type. + * One of the derived types based on xs:string. + *

+ * This kind of string is the same as the lexical representation used for XML 1.0 + * element and attribute names, e.g., "pre:a-b.cdef". It is just a physical + * string, however, and it should NOT be confused with {@link XmlQName}, + * which is a logical combination of localname and namespace URI. + *

+ * Convertible to {@link String}. + */ +public interface XmlName extends XmlToken { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_Name"); + + /** + * A class with methods for creating instances + * of {@link XmlName}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlName} + */ + public static XmlName newInstance() { + return (XmlName) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlName} + */ + public static XmlName newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlName) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlName} value + */ + public static XmlName newValue(Object obj) { + return (XmlName) type.newValue(obj); + } + + /** + * Parses a {@link XmlName} fragment from a String. For example: "<xml-fragment>My:Name</xml-fragment>". + */ + public static XmlName parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlName} fragment from a String. For example: "<xml-fragment>My:Name</xml-fragment>". + */ + public static XmlName parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlName} fragment from a File. + */ + public static XmlName parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlName} fragment from a File. + */ + public static XmlName parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlName} fragment from a URL. + */ + public static XmlName parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlName} fragment from a URL. + */ + public static XmlName parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlName} fragment from an InputStream. + */ + public static XmlName parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlName} fragment from an InputStream. + */ + public static XmlName parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlName} fragment from a Reader. + */ + public static XmlName parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlName} fragment from a Reader. + */ + public static XmlName parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlName} fragment from a DOM Node. + */ + public static XmlName parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlName} fragment from a DOM Node. + */ + public static XmlName parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlName} fragment from an XMLStreamReader. + */ + public static XmlName parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlName} fragment from an XMLStreamReader. + */ + public static XmlName parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlName) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNegativeInteger.java b/src/main/java/org/apache/xmlbeans/XmlNegativeInteger.java new file mode 100644 index 0000000..ee7aa7c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNegativeInteger.java @@ -0,0 +1,162 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:negativeInteger type. + * One of the derived types based on xs:decimal. + *

+ * Verified to be negative when validating. + *

+ * Convertible to {@link java.math.BigInteger}. + */ +public interface XmlNegativeInteger extends XmlNonPositiveInteger { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_negativeInteger"); + + /** + * A class with methods for creating instances + * of {@link XmlNegativeInteger}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNegativeInteger} + */ + public static XmlNegativeInteger newInstance() { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNegativeInteger} + */ + public static XmlNegativeInteger newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNegativeInteger} value + */ + public static XmlNegativeInteger newValue(Object obj) { + return (XmlNegativeInteger) type.newValue(obj); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". + */ + public static XmlNegativeInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". + */ + public static XmlNegativeInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a File. + */ + public static XmlNegativeInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a File. + */ + public static XmlNegativeInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a URL. + */ + public static XmlNegativeInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a URL. + */ + public static XmlNegativeInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from an InputStream. + */ + public static XmlNegativeInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from an InputStream. + */ + public static XmlNegativeInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a Reader. + */ + public static XmlNegativeInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a Reader. + */ + public static XmlNegativeInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a DOM Node. + */ + public static XmlNegativeInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from a DOM Node. + */ + public static XmlNegativeInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from an XMLStreamReader. + */ + public static XmlNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNegativeInteger} fragment from an XMLStreamReader. + */ + public static XmlNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNonNegativeInteger.java b/src/main/java/org/apache/xmlbeans/XmlNonNegativeInteger.java new file mode 100644 index 0000000..0179f4e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNonNegativeInteger.java @@ -0,0 +1,162 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:nonNegativeInteger type. + * One of the derived types based on xs:decimal. + *

+ * Verified to be zero or positive when validating. + *

+ * Convertible to {@link java.math.BigInteger}. + */ +public interface XmlNonNegativeInteger extends XmlInteger { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_nonNegativeInteger"); + + /** + * A class with methods for creating instances + * of {@link XmlNonNegativeInteger}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNonNegativeInteger} + */ + public static XmlNonNegativeInteger newInstance() { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNonNegativeInteger} + */ + public static XmlNonNegativeInteger newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNonNegativeInteger} value + */ + public static XmlNonNegativeInteger newValue(Object obj) { + return (XmlNonNegativeInteger) type.newValue(obj); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". + */ + public static XmlNonNegativeInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". + */ + public static XmlNonNegativeInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a File. + */ + public static XmlNonNegativeInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a File. + */ + public static XmlNonNegativeInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a URL. + */ + public static XmlNonNegativeInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a URL. + */ + public static XmlNonNegativeInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from an InputStream. + */ + public static XmlNonNegativeInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from an InputStream. + */ + public static XmlNonNegativeInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a Reader. + */ + public static XmlNonNegativeInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a Reader. + */ + public static XmlNonNegativeInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a DOM Node. + */ + public static XmlNonNegativeInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from a DOM Node. + */ + public static XmlNonNegativeInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from an XMLStreamReader. + */ + public static XmlNonNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNonNegativeInteger} fragment from an XMLStreamReader. + */ + public static XmlNonNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNonPositiveInteger.java b/src/main/java/org/apache/xmlbeans/XmlNonPositiveInteger.java new file mode 100644 index 0000000..6333e88 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNonPositiveInteger.java @@ -0,0 +1,162 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:nonPositiveInteger type. + * One of the derived types based on xs:decimal. + *

+ * Verified to be zero or negative when validating. + *

+ * Convertible to {@link java.math.BigInteger}. + */ +public interface XmlNonPositiveInteger extends XmlInteger { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_nonPositiveInteger"); + + /** + * A class with methods for creating instances + * of {@link XmlNonPositiveInteger}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNonPositiveInteger} + */ + public static XmlNonPositiveInteger newInstance() { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNonPositiveInteger} + */ + public static XmlNonPositiveInteger newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNonPositiveInteger} value + */ + public static XmlNonPositiveInteger newValue(Object obj) { + return (XmlNonPositiveInteger) type.newValue(obj); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". + */ + public static XmlNonPositiveInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". + */ + public static XmlNonPositiveInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a File. + */ + public static XmlNonPositiveInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a File. + */ + public static XmlNonPositiveInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a URL. + */ + public static XmlNonPositiveInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a URL. + */ + public static XmlNonPositiveInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from an InputStream. + */ + public static XmlNonPositiveInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from an InputStream. + */ + public static XmlNonPositiveInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a Reader. + */ + public static XmlNonPositiveInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a Reader. + */ + public static XmlNonPositiveInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a DOM Node. + */ + public static XmlNonPositiveInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from a DOM Node. + */ + public static XmlNonPositiveInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from an XMLStreamReader. + */ + public static XmlNonPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNonPositiveInteger} fragment from an XMLStreamReader. + */ + public static XmlNonPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlNormalizedString.java b/src/main/java/org/apache/xmlbeans/XmlNormalizedString.java new file mode 100644 index 0000000..98fe1c5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlNormalizedString.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:normalizedString type. + * One of the derived types based on xs:string. + *

+ * An normalizedString simply is a string where all the carriage return, + * linefeed, and tab characters have been normalized (switched to) ordinary + * space characters. Use normalizedString for long strings to make them + * insensitive to line breaking. If you wish to often be insensitive to + * runs of whitespace (as is often the case), use + * xs:token + * (aka {@link XmlToken}) instead. + *

+ * Convertible to {@link String}. When obtaining the stringValue, the + * whitespace-normalized value is returned. + */ +public interface XmlNormalizedString extends XmlString { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_normalizedString"); + + /** + * A class with methods for creating instances + * of {@link XmlNormalizedString}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlNormalizedString} + */ + public static XmlNormalizedString newInstance() { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlNormalizedString} + */ + public static XmlNormalizedString newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlNormalizedString} value + */ + public static XmlNormalizedString newValue(Object obj) { + return (XmlNormalizedString) type.newValue(obj); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a String. For example: "<xml-fragment> string to normalize </xml-fragment>". + */ + public static XmlNormalizedString parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a String. For example: "<xml-fragment> string to normalize </xml-fragment>". + */ + public static XmlNormalizedString parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a File. + */ + public static XmlNormalizedString parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a File. + */ + public static XmlNormalizedString parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a URL. + */ + public static XmlNormalizedString parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a URL. + */ + public static XmlNormalizedString parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from an InputStream. + */ + public static XmlNormalizedString parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from an InputStream. + */ + public static XmlNormalizedString parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a Reader. + */ + public static XmlNormalizedString parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a Reader. + */ + public static XmlNormalizedString parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a DOM Node. + */ + public static XmlNormalizedString parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from a DOM Node. + */ + public static XmlNormalizedString parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from an XMLStreamReader. + */ + public static XmlNormalizedString parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlNormalizedString} fragment from an XMLStreamReader. + */ + public static XmlNormalizedString parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlObject.java b/src/main/java/org/apache/xmlbeans/XmlObject.java similarity index 79% rename from src/xmlpublic/org/apache/xmlbeans/XmlObject.java rename to src/main/java/org/apache/xmlbeans/XmlObject.java index 3a29b59..d99f151 100644 --- a/src/xmlpublic/org/apache/xmlbeans/XmlObject.java +++ b/src/main/java/org/apache/xmlbeans/XmlObject.java @@ -15,19 +15,15 @@ package org.apache.xmlbeans; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLStreamException; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.namespace.QName; - -import org.w3c.dom.Node; import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Node; -import java.io.InputStream; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; import java.io.File; -import java.io.Reader; import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; /** * Corresponds to the XML Schema @@ -59,7 +55,7 @@ *

  • It is also simple to copy an XmlObject instance to or from a standard * DOM tree or SAX stream. Use {@link XmlObject.Factory#parse(Node)}, * for example, to load from DOM; use {@link XmlObject.Factory#newXmlSaxHandler} - * to load from SAX; use {@link #newDomNode()} to save to DOM; and use + * to load from SAX; use {@link #newDomNode()} to save to DOM; and use * {@link #save(org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)} * to save to SAX. *
  • Use {@link #validate} to validate the subtree of XML under this @@ -69,7 +65,7 @@ *
  • Use {@link #newCursor} to access the full XML infoset, for example, * if you need to determine interleaved element order or manipulate * annotations, comments, or mixed content. You can get an element name with - * a cursor by calling {@link XmlCursor#getName() cursor.getName()} when the + * a cursor by calling {@link XmlCursor#getName() cursor.getName()} when the * cursor is positioned at an element's START token. See {@link XmlCursor}. *
  • Use {@link #selectPath} to find other XmlObjects in the subtree underneath * this XmlObject using relative XPaths. (In selectPath, "." indicates @@ -131,12 +127,13 @@ * If you need to implement XmlObject yourself, you should subclass * FilterXmlObject in order to delegate to another underlying XmlObject * implementation. This technique will allow you to use your code unchanged - * with future versions of XMLBeans that add additional methods on XmlObject. - */ -public interface XmlObject extends XmlTokenSource -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_anyType"); + * with future versions of XMLBeans that add additional methods on XmlObject. + */ +public interface XmlObject extends XmlTokenSource { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_anyType"); /** * @return The schema type for this instance. This is a permanent, @@ -161,16 +158,16 @@ public interface XmlObject extends XmlTokenSource * use the {@link XmlOptions#setErrorListener} method. With that method, * you can specify an object in which to store messages related to validation. * The following is a simple example.

    - * + * *
          * // Create an XmlOptions instance and set the error listener.
          * XmlOptions validateOptions = new XmlOptions();
          * ArrayList errorList = new ArrayList();
          * validateOptions.setErrorListener(errorList);
    -     * 
    +     *
          * // Validate the XML.
          * boolean isValid = newEmp.validate(validateOptions);
    -     * 
    +     *
          * // If the XML isn't valid, loop through the listener's contents,
          * // printing contained messages.
          * if (!isValid)
    @@ -178,18 +175,17 @@ public interface XmlObject extends XmlTokenSource
          *      for (int i = 0; i < errorList.size(); i++)
          *      {
          *          XmlError error = (XmlError)errorList.get(i);
    -     *          
    +     *
          *          System.out.println("\n");
          *          System.out.println("Message: " + error.getMessage() + "\n");
    -     *          System.out.println("Location of invalid XML: " + 
    +     *          System.out.println("Location of invalid XML: " +
          *              error.getCursorLocation().xmlText() + "\n");
          *      }
          * }
          * 
    * * @param options An object that implements the {@link java.util.Collection - * Collection} interface. - * + * Collection} interface. * @return true if the contents of this object are valid * accoring to schemaType(). */ @@ -198,19 +194,19 @@ public interface XmlObject extends XmlTokenSource /** * Selects a path. Path can be a string or precompiled path String. *

    - * + *

    * The path must be a relative path, where "." represents the * element or attribute containg this XmlObject, and it must select * only other elements or attributes. If a non-element or non-attribute * is selected, an unchecked exception is thrown. *

    - * + *

    * The array that is returned contains all the selected * XmlObjects, within the same document, listed in document * order. The actual array type of the result is inferred * from the closest common base type of selected results. *

    - * + *

    * Here is an example of usage. Suppose we have a global * element definition for "owner" whose type is "person": * @@ -222,7 +218,7 @@ public interface XmlObject extends XmlTokenSource * </complexType> * </schema> * - * + *

    * and suppose "owner" tags can be scattered throughout the * document. Then we can write the following code to find * them all: @@ -237,7 +233,7 @@ public interface XmlObject extends XmlTokenSource * "declare namespace s='http://www.openuri.org/sample' " + * ".//s:owner"); * - * + *

    * Notice the way in which namespace declarations are done in XPath 2.0. * Since XPath can only navigate within an XML document - it cannot * construct new XML - the resulting XmlObjects all reside in @@ -246,19 +242,18 @@ public interface XmlObject extends XmlTokenSource * @param path the xpath * @return an array of all selected XmlObjects */ - XmlObject[] selectPath ( String path ); + XmlObject[] selectPath(String path); /** * Selects a path, applying options. * - * @param path the xpath + * @param path the xpath * @param options the options used to execute the xpath * @return an array of all selected XmlObjects - * * @see #selectPath(String) */ - XmlObject[] selectPath ( String path, XmlOptions options ); - + XmlObject[] selectPath(String path, XmlOptions options); + /** * Executes a query. Query can be a string or precompiled query String. @@ -273,16 +268,15 @@ public interface XmlObject extends XmlTokenSource * * @param query The XQuery expression * @return an array of all selected XmlObjects - * * @see #selectPath(String) */ - XmlObject[] execQuery ( String query ); + XmlObject[] execQuery(String query); /** * Executes a query with options. - * + *

    * Use the options parameter to specify the following:

    - * + * * * * @@ -315,7 +309,7 @@ public interface XmlObject extends XmlTokenSource * * * - * * * @@ -323,17 +317,15 @@ public interface XmlObject extends XmlTokenSource * * * - *
    To specify thisUse this method
    {@link XmlOptions#setLoadAdditionalNamespaces}
    To trim the underlying XML text buffer immediately after constructing + * To trim the underlying XML text buffer immediately after constructing * a document, resulting in a smaller memory footprint.{@link XmlOptions#setLoadTrimTextBuffer}
    Whether value facets should be checked as they are set.{@link XmlOptions#setValidateOnSet}
    - * - * @param query The XQuery expression. - * @param options Options as described. + * * + * @param query The XQuery expression. + * @param options Options as described. * @return an array of all selected XmlObjects - * * @see #execQuery(String) */ - XmlObject[] execQuery ( String query, XmlOptions options ); - + XmlObject[] execQuery(String query, XmlOptions options); + /** * Changes the schema type associated with this data and @@ -354,7 +346,7 @@ public interface XmlObject extends XmlTokenSource * any other XmlObject instances in the subtree are permanently * invalidated and should not be used. (They will return * XmlValueDisconnectedException if you try to use them.) - * + *

    * If a type change is done on the interior of an Xml * tree, then xsi:type attributes are updated as needed. * @@ -385,9 +377,8 @@ public interface XmlObject extends XmlTokenSource * * @param newName the new name * @param newType the new type - * * @return an XmlObject instance whose schemaType is the - * new type and container name is the new name + * new type and container name is the new name */ XmlObject substitute(QName newName, SchemaType newType); @@ -447,11 +438,12 @@ public interface XmlObject extends XmlTokenSource * the XML document underneath the current object. Note that * any parts of the XML document above or outside this XmlObject are * not copied. - * + *

    * Note: The result object will be in the same synchronization domain as the source, * and additional synchronization is required for concurent access. * To use a different synchronization domain use setCopyUseNewSynchronizationDomain * option with copy(XmlOptions) method. + * * @see #copy(XmlOptions) * @see org.apache.xmlbeans.XmlOptions#setCopyUseNewSynchronizationDomain(boolean) */ @@ -463,11 +455,12 @@ public interface XmlObject extends XmlTokenSource * the XML document underneath the current object. Note that * any parts of the XML document above or outside this XmlObject are * not copied. - * + *

    * Note: The result object will be in the same synchronization domain as the source, * and additional synchronization is required for concurent access. * To use a different synchronization domain use setCopyUseNewSynchronizationDomain * option when creating the original XmlObject. + * * @see org.apache.xmlbeans.XmlOptions#setCopyUseNewSynchronizationDomain(boolean) */ XmlObject copy(XmlOptions options); @@ -524,20 +517,29 @@ public interface XmlObject extends XmlTokenSource */ int compareValue(XmlObject obj); - /** LESS_THAN is -1. See {@link #compareValue}. */ + /** + * LESS_THAN is -1. See {@link #compareValue}. + */ static final int LESS_THAN = -1; - /** EQUAL is 0. See {@link #compareValue}. */ + /** + * EQUAL is 0. See {@link #compareValue}. + */ static final int EQUAL = 0; - /** GREATER_THAN is 1. See {@link #compareValue}. */ + /** + * GREATER_THAN is 1. See {@link #compareValue}. + */ static final int GREATER_THAN = 1; - /** NOT_EQUAL is 2. See {@link #compareValue}. */ + /** + * NOT_EQUAL is 2. See {@link #compareValue}. + */ static final int NOT_EQUAL = 2; /** * Selects the contents of the children elements with the given name. + * * @param elementName The name of the elements to be selected. * @return Returns the contents of the selected elements. */ @@ -545,7 +547,8 @@ public interface XmlObject extends XmlTokenSource /** * Selects the contents of the children elements with the given name. - * @param elementUri The URI of the elements to be selected. + * + * @param elementUri The URI of the elements to be selected. * @param elementLocalName The local name of the elements to be selected. * @return Returns the contents of the selected elements. */ @@ -553,6 +556,7 @@ public interface XmlObject extends XmlTokenSource /** * Selects the contents of the children elements that are contained in the elementNameSet. + * * @param elementNameSet Set of element names to be selected. * @return Returns the contents of the selected elements. * @see SchemaType#qnameSetForWildcardElements() @@ -562,6 +566,7 @@ public interface XmlObject extends XmlTokenSource /** * Selects the content of the attribute with the given name. + * * @param attributeName The name of the attribute to be selected. * @return Returns the contents of the selected attribute. */ @@ -569,7 +574,8 @@ public interface XmlObject extends XmlTokenSource /** * Selects the content of the attribute with the given name. - * @param attributeUri The URI of the attribute to be selected. + * + * @param attributeUri The URI of the attribute to be selected. * @param attributeLocalName The local name of the attribute to be selected. * @return Returns the content of the selected attribute. */ @@ -577,6 +583,7 @@ public interface XmlObject extends XmlTokenSource /** * Selects the contents of the attributes that are contained in the elementNameSet. + * * @param attributeNameSet Set of attribute names to be selected. * @return Returns the contents of the selected attributes. * @see SchemaType#qnameSetForWildcardAttributes() @@ -591,21 +598,21 @@ public interface XmlObject extends XmlTokenSource * returned by a factory will have the inferred type. Otherwise * the Factory will returned an untyped document. */ - public static final class Factory - { + final class Factory { /** * Creates a new, completely empty instance. - */ - public static XmlObject newInstance ( ) { - return XmlBeans.getContextTypeLoader().newInstance( null, null ); } - + */ + public static XmlObject newInstance() { + return XmlBeans.getContextTypeLoader().newInstance(null, null); + } + /** *

    Creates a new, completely empty instance, specifying options * for the root element's document type and/or whether to validate * value facets as they are set.

    - * + *

    * Use the options parameter to specify the following:

    - * + * * * * @@ -616,33 +623,38 @@ public static XmlObject newInstance ( ) { * * * - *
    To specify thisUse this method
    Whether value facets should be checked as they are set.{@link XmlOptions#setValidateOnSet}
    - * - * @param options Options specifying root document type and/or value facet - * checking. + * + * + * @param options Options specifying root document type and/or value facet + * checking. * @return A new, empty instance of XmlObject.
  • - */ - public static XmlObject newInstance ( XmlOptions options ) { - return XmlBeans.getContextTypeLoader().newInstance( null, options ); } - + */ + public static XmlObject newInstance(XmlOptions options) { + return XmlBeans.getContextTypeLoader().newInstance(null, options); + } + /** * Creates a new immutable value. - */ - /** Creates an immutable {@link XmlObject} value */ - public static XmlObject newValue ( Object obj ) { - return type.newValue( obj ); } - + */ + /** + * Creates an immutable {@link XmlObject} value + */ + public static XmlObject newValue(Object obj) { + return type.newValue(obj); + } + /** * Parses the given {@link String} as XML. - */ - public static XmlObject parse ( String xmlAsString ) throws XmlException { - return XmlBeans.getContextTypeLoader().parse( xmlAsString, null, null ); } - + */ + public static XmlObject parse(String xmlAsString) throws XmlException { + return XmlBeans.getContextTypeLoader().parse(xmlAsString, null, null); + } + /** * Parses the given {@link String} as XML. - * + *

    * Use the options parameter to specify the following:

    - * + * * * * @@ -678,60 +690,67 @@ public static XmlObject parse ( String xmlAsString ) throws XmlException { * * * - * * * - *
    To specify thisUse this method
    {@link XmlOptions#setLoadAdditionalNamespaces}
    To trim the underlying XML text buffer immediately after parsing + * To trim the underlying XML text buffer immediately after parsing * a document, resulting in a smaller memory footprint.{@link XmlOptions#setLoadTrimTextBuffer}
    - * + * + * * @param xmlAsString The string to parse. - * @param options Options as specified. + * @param options Options as specified. * @return A new instance containing the specified XML. - */ - public static XmlObject parse ( String xmlAsString, XmlOptions options ) throws XmlException { - return XmlBeans.getContextTypeLoader().parse( xmlAsString, null, options ); } - + */ + public static XmlObject parse(String xmlAsString, XmlOptions options) throws XmlException { + return XmlBeans.getContextTypeLoader().parse(xmlAsString, null, options); + } + /** * Parses the given {@link File} as XML. - */ - public static XmlObject parse ( File file ) throws XmlException, IOException { - return XmlBeans.getContextTypeLoader().parse( file, null, null ); } + */ + public static XmlObject parse(File file) throws XmlException, IOException { + return XmlBeans.getContextTypeLoader().parse(file, null, null); + } /** * Parses the given {@link File} as XML. - */ - public static XmlObject parse ( File file, XmlOptions options ) throws XmlException, IOException { - return XmlBeans.getContextTypeLoader().parse( file, null, options ); } - + */ + public static XmlObject parse(File file, XmlOptions options) throws XmlException, IOException { + return XmlBeans.getContextTypeLoader().parse(file, null, options); + } + /** * Downloads the given {@link java.net.URL} as XML. - */ + */ public static XmlObject parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return XmlBeans.getContextTypeLoader().parse( u, null, null ); } + return XmlBeans.getContextTypeLoader().parse(u, null, null); + } /** * Downloads the given {@link java.net.URL} as XML. - */ + */ public static XmlObject parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return XmlBeans.getContextTypeLoader().parse( u, null, options ); } + return XmlBeans.getContextTypeLoader().parse(u, null, options); + } /** * Decodes and parses the given {@link InputStream} as XML. - */ - public static XmlObject parse ( InputStream is ) throws XmlException, IOException { - return XmlBeans.getContextTypeLoader().parse( is, null, null ); } - + */ + public static XmlObject parse(InputStream is) throws XmlException, IOException { + return XmlBeans.getContextTypeLoader().parse(is, null, null); + } + /** * Decodes and parses the given {@link XMLStreamReader} as XML. - */ - public static XmlObject parse ( XMLStreamReader xsr ) throws XmlException { - return XmlBeans.getContextTypeLoader().parse( xsr, null, null ); } - + */ + public static XmlObject parse(XMLStreamReader xsr) throws XmlException { + return XmlBeans.getContextTypeLoader().parse(xsr, null, null); + } + /** * Decodes and parses the given {@link InputStream} as XML. - * + *

    * Use the options parameter to specify the following:

    - * + * * * * @@ -771,116 +790,83 @@ public static XmlObject parse ( XMLStreamReader xsr ) throws XmlException { * * * - * * * - *
    To specify thisUse this method
    {@link XmlOptions#setLoadAdditionalNamespaces}
    Trim the underlying XML text buffer immediately after parsing + * Trim the underlying XML text buffer immediately after parsing * a document, resulting in a smaller memory footprint.{@link XmlOptions#setLoadTrimTextBuffer}
    - */ - public static XmlObject parse ( InputStream is, XmlOptions options ) throws XmlException, IOException { - return XmlBeans.getContextTypeLoader().parse( is, null, options ); } - + * + */ + public static XmlObject parse(InputStream is, XmlOptions options) throws XmlException, IOException { + return XmlBeans.getContextTypeLoader().parse(is, null, options); + } + /** * Parses the given {@link XMLStreamReader} as XML. - */ - public static XmlObject parse ( XMLStreamReader xsr, XmlOptions options ) throws XmlException { - return XmlBeans.getContextTypeLoader().parse( xsr, null, options ); } - + */ + public static XmlObject parse(XMLStreamReader xsr, XmlOptions options) throws XmlException { + return XmlBeans.getContextTypeLoader().parse(xsr, null, options); + } + /** * Parses the given {@link Reader} as XML. - */ - public static XmlObject parse ( Reader r ) throws XmlException, IOException { - return XmlBeans.getContextTypeLoader().parse( r, null, null ); } - + */ + public static XmlObject parse(Reader r) throws XmlException, IOException { + return XmlBeans.getContextTypeLoader().parse(r, null, null); + } + /** * Parses the given {@link Reader} as XML. - */ - public static XmlObject parse ( Reader r, XmlOptions options ) throws XmlException, IOException { - return XmlBeans.getContextTypeLoader().parse( r, null, options ); } - - /** - * Converts the given DOM {@link Node} into an XmlObject. - */ - public static XmlObject parse ( Node node ) throws XmlException { - return XmlBeans.getContextTypeLoader().parse( node, null, null ); } - + */ + public static XmlObject parse(Reader r, XmlOptions options) throws XmlException, IOException { + return XmlBeans.getContextTypeLoader().parse(r, null, options); + } + /** * Converts the given DOM {@link Node} into an XmlObject. - */ - public static XmlObject parse ( Node node, XmlOptions options ) throws XmlException { - return XmlBeans.getContextTypeLoader().parse( node, null, options ); } - - /** - * Loads the given {@link XMLInputStream} into an XmlObject. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. */ - public static XmlObject parse ( XMLInputStream xis ) throws XmlException, XMLStreamException { - return XmlBeans.getContextTypeLoader().parse( xis, null, null ); } - + public static XmlObject parse(Node node) throws XmlException { + return XmlBeans.getContextTypeLoader().parse(node, null, null); + } + /** - * Loads the given {@link XMLInputStream} into an XmlObject. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. + * Converts the given DOM {@link Node} into an XmlObject. */ - public static XmlObject parse ( XMLInputStream xis, XmlOptions options ) throws XmlException, XMLStreamException { - return XmlBeans.getContextTypeLoader().parse( xis, null, options ); } + public static XmlObject parse(Node node, XmlOptions options) throws XmlException { + return XmlBeans.getContextTypeLoader().parse(node, null, options); + } /** * Returns an {@link XmlSaxHandler} that can load an XmlObject from SAX events. - */ - public static XmlSaxHandler newXmlSaxHandler ( ) { - return XmlBeans.getContextTypeLoader().newXmlSaxHandler( null, null ); } - + */ + public static XmlSaxHandler newXmlSaxHandler() { + return XmlBeans.getContextTypeLoader().newXmlSaxHandler(null, null); + } + /** * Returns an {@link XmlSaxHandler} that can load an XmlObject from SAX events. - */ - public static XmlSaxHandler newXmlSaxHandler ( XmlOptions options ) { - return XmlBeans.getContextTypeLoader().newXmlSaxHandler( null, options ); } - + */ + public static XmlSaxHandler newXmlSaxHandler(XmlOptions options) { + return XmlBeans.getContextTypeLoader().newXmlSaxHandler(null, options); + } + /** * Creates a new DOMImplementation object - */ - public static DOMImplementation newDomImplementation ( ) { - return XmlBeans.getContextTypeLoader().newDomImplementation( null ); } - - /** - * Creates a new DOMImplementation object, taking options - */ - public static DOMImplementation newDomImplementation ( XmlOptions options ) { - return XmlBeans.getContextTypeLoader().newDomImplementation( options ); } - - /** - * Returns a new validating {@link XMLInputStream} that throws exceptions when the input is not valid. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. */ - public static XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis ) throws XmlException, XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, null, null ); } - + public static DOMImplementation newDomImplementation() { + return XmlBeans.getContextTypeLoader().newDomImplementation(null); + } + /** - * Returns a new validating {@link XMLInputStream} that throws exceptions - * when the input is not valid, specifying options - * for the root element's document type and/or the collection object to use - * as an error listener while validating.

    - * - *

    Use the options parameter to specify the following:

    - * - *
      - *
    • A collection instance that should be used as an error listener during - * compilation, as described in {@link XmlOptions#setErrorListener}.
    • - *
    • The document type for the root element, as described in - * {@link XmlOptions#setDocumentType(SchemaType)}.
    • - *
    - * - * @param xis The basis for the new XMLInputStream. - * @param options Options specifying root document type and/or an error listener. - * @return A new validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. + * Creates a new DOMImplementation object, taking options */ - public static XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, XmlOptions options ) throws XmlException, XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, null, options ); } - + public static DOMImplementation newDomImplementation(XmlOptions options) { + return XmlBeans.getContextTypeLoader().newDomImplementation(options); + } + /** * Instances cannot be created. - */ - private Factory() { } + */ + private Factory() { + } } } diff --git a/src/main/java/org/apache/xmlbeans/XmlOptionCharEscapeMap.java b/src/main/java/org/apache/xmlbeans/XmlOptionCharEscapeMap.java new file mode 100644 index 0000000..76ecdc7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlOptionCharEscapeMap.java @@ -0,0 +1,134 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.HashMap; +import java.util.Map; + +/** + * Corresponds to the Saver and XmlOptions. + *

    + * This class is used to set up a map containing characters to be escaped. + * Characters can be escaped as hex, decimal or as a predefined entity (this + * latter option applies only to the 5 characters defined as predefined entities + * in the XML Spec). + *

    + *

      + * For example: + *
      + *      XmlOptionCharEscapeMap escapes = new XmlOptionCharEscapeMap();
      + *      escapes.addMapping('A', XmlOptionCharEscapeMap.HEXADECIMAL);
      + *      escapes.addMapping('B', XmlOptionCharEscapeMap.DECIMAL);
      + *      escapes.addMapping('>', XmlOptionCharEscapeMap.PREDEF_ENTITY);
      + *
      + *      XmlOptions opts = new XmlOptions();
      + *      opts.setSaveSubstituteCharacters(escapes);
      + *      System.out.println(myXml.xmlText(opts));
      + *
      + *      will result in:
      + *      A being printed as A
      + *      B being printed as B
      + *      > being printed as >
      + *
      + * 
      + */ +public class XmlOptionCharEscapeMap { + public static final int PREDEF_ENTITY = 0; + public static final int DECIMAL = 1; + public static final int HEXADECIMAL = 2; + + // map of Character to String which will represent it in the output document + private final Map _charMap; + + // internal HashMap just for predefined entities + private static final Map _predefEntities = new HashMap<>(); + + static { + _predefEntities.put('<', "<"); + _predefEntities.put('>', ">"); + _predefEntities.put('&', "&"); + _predefEntities.put('\'', "'"); + _predefEntities.put('"', """); + } + + /** + * Construct a new XmlOptionCharEncoder. + */ + public XmlOptionCharEscapeMap() { + _charMap = new HashMap<>(); + } + + /** + * @return whether a character encoding exists for this character + */ + public boolean containsChar(char ch) { + return _charMap.containsKey(ch); + } + + /** + * set up this character to be escaped in output documents + * according to the given mode + */ + public void addMapping(char ch, int mode) throws XmlException { + Character theChar = ch; + switch (mode) { + case PREDEF_ENTITY: + String replString = _predefEntities.get(theChar); + if (replString == null) { + throw new XmlException("XmlOptionCharEscapeMap.addMapping(): " + + "the PREDEF_ENTITY mode can only be used for the following " + + "characters: <, >, &, \" and '"); + } + _charMap.put(theChar, replString); + break; + + case DECIMAL: + _charMap.put(theChar, "&#" + (int) ch + ";"); + break; + + case HEXADECIMAL: + String hexCharPoint = Integer.toHexString(ch); + _charMap.put(theChar, "&#x" + hexCharPoint + ";"); + break; + + default: + throw new XmlException("XmlOptionCharEscapeMap.addMapping(): " + + "mode must be PREDEF_ENTITY, DECIMAL or HEXADECIMAL"); + } + } + + /** + * set up this contiguous set of characters to be escaped in + * output documents according to the given mode + */ + public void addMappings(char ch1, char ch2, int mode) throws XmlException { + if (ch1 > ch2) { + throw new XmlException("XmlOptionCharEscapeMap.addMappings(): " + + "ch1 must be <= ch2"); + } + + for (char c = ch1; c <= ch2; c++) { + addMapping(c, mode); + } + } + + /** + * returns the escaped String for the character + */ + public String getEscapedString(char ch) { + return _charMap.get(ch); + } +} diff --git a/src/main/java/org/apache/xmlbeans/XmlOptions.java b/src/main/java/org/apache/xmlbeans/XmlOptions.java new file mode 100644 index 0000000..ff6b2e5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlOptions.java @@ -0,0 +1,1440 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import org.apache.xmlbeans.impl.store.Saaj; +import org.xml.sax.EntityResolver; +import org.xml.sax.XMLReader; + +import javax.xml.namespace.QName; +import java.net.URI; +import java.util.*; + +/** + * Used to supply options for loading, saving, and compiling, and validating. + *

      + * There are two styles for using XmlOptions: multiline setup, and single-line use. + * Here are two examples. First, multiline style: + *

      + * XmlOptions opts = new XmlOptions();
      + * opts.setSavePrettyPrint();
      + * opts.setSavePrettyPrintIndent(4);
      + * System.out.println(xobj.xmlText(opts));
      + * 
      + *

      + * The alternative is single-line usage: + *

      + * System.out.println(xobj.xmlText(
      + *     new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(4)));
      + * 
      + *

      + * Table showing where each option gets used. + * Note that: + *

        + *
      • options available for newInstance methods will also + * apply for parse methods
      • + *
      • options used for validate methods are also used for + * compile methods, since compilation usually implies + * validation against Schema for Schemas
      • + *
      + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
      newInstance methodsparse methodsvalidate methodscompile methodssave and xmlTextmethods
      setDocumentType
      + * setDocumentSourceName
      + * setValidateOnSet
      + * setUnsynchronized
      setLoad***
      + * setEntityResolver
      setErrorListener
      + * setValidateTreatLaxAsSkip + * setValidateStrict
      setErrorListener
      + * setCompile***
      + * setEntityResolver
      + * setBaseURI
      + * setGenerateJavaVersion
      setSave***
      + * setUseDefaultNamespace
      + * setCharacterEncoding
      + */ +public class XmlOptions implements java.io.Serializable { + // + // Complete set of XmlOption's + // + + // TODO - Add selectPath option to track the seletion (default is to clean selections fast). + public enum XmlOptionsKeys { + SAVE_NAMESPACES_FIRST, + SAVE_SYNTHETIC_DOCUMENT_ELEMENT, + SAVE_PRETTY_PRINT, + SAVE_PRETTY_PRINT_INDENT, + SAVE_PRETTY_PRINT_OFFSET, + SAVE_AGGRESSIVE_NAMESPACES, + SAVE_USE_DEFAULT_NAMESPACE, + SAVE_IMPLICIT_NAMESPACES, + SAVE_SUGGESTED_PREFIXES, + SAVE_FILTER_PROCINST, + SAVE_USE_OPEN_FRAGMENT, + SAVE_OUTER, + SAVE_INNER, + SAVE_NO_XML_DECL, + SAVE_SUBSTITUTE_CHARACTERS, + SAVE_OPTIMIZE_FOR_SPEED, + SAVE_CDATA_LENGTH_THRESHOLD, + SAVE_CDATA_ENTITY_COUNT_THRESHOLD, + SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES, + LOAD_REPLACE_DOCUMENT_ELEMENT, + LOAD_STRIP_WHITESPACE, + LOAD_STRIP_COMMENTS, + LOAD_STRIP_PROCINSTS, + LOAD_LINE_NUMBERS, + LOAD_LINE_NUMBERS_END_ELEMENT, + LOAD_SAVE_CDATA_BOOKMARKS, + LOAD_SUBSTITUTE_NAMESPACES, + LOAD_TRIM_TEXT_BUFFER, + LOAD_ADDITIONAL_NAMESPACES, + LOAD_MESSAGE_DIGEST, + LOAD_USE_DEFAULT_RESOLVER, + LOAD_USE_XMLREADER, + XQUERY_CURRENT_NODE_VAR, + XQUERY_VARIABLE_MAP, + CHARACTER_ENCODING, + ERROR_LISTENER, + DOCUMENT_TYPE, + DOCUMENT_SOURCE_NAME, + COMPILE_SUBSTITUTE_NAMES, + COMPILE_NO_VALIDATION, + COMPILE_NO_UPA_RULE, + COMPILE_NO_PVR_RULE, + COMPILE_NO_ANNOTATIONS, + COMPILE_DOWNLOAD_URLS, + COMPILE_MDEF_NAMESPACES, + COMPILE_PARTIAL_TYPESYSTEM, + VALIDATE_ON_SET, + VALIDATE_TREAT_LAX_AS_SKIP, + VALIDATE_STRICT, + VALIDATE_TEXT_ONLY, + UNSYNCHRONIZED, + ENTITY_RESOLVER, + BASE_URI, + SCHEMA_CODE_PRINTER, + GENERATE_JAVA_VERSION, + USE_SAME_LOCALE, + COPY_USE_NEW_SYNC_DOMAIN, + LOAD_ENTITY_BYTES_LIMIT, + ENTITY_EXPANSION_LIMIT, + LOAD_DTD_GRAMMAR, + LOAD_EXTERNAL_DTD, + SAAJ_IMPL, + LOAD_USE_LOCALE_CHAR_UTIL, + XPATH_USE_SAXON, + XPATH_USE_XMLBEANS, + ATTTRIBUTE_VALIDATION_COMPAT_MODE + } + + + public static final int DEFAULT_ENTITY_EXPANSION_LIMIT = 2048; + + private static final XmlOptions EMPTY_OPTIONS; + + static { + EMPTY_OPTIONS = new XmlOptions(); + EMPTY_OPTIONS._map = Collections.unmodifiableMap(EMPTY_OPTIONS._map); + } + + + private static final long serialVersionUID = 1L; + + private Map _map = new HashMap<>(); + + + /** + * Construct a new blank XmlOptions. + */ + public XmlOptions() { + } + + /** + * Construct a new XmlOptions, copying the options. + */ + public XmlOptions(XmlOptions other) { + if (other != null) { + _map.putAll(other._map); + } + } + + // + // Handy-dandy helper methods for setting some options + // + + /** + * This option will cause the saver to save namespace attributes first. + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveNamespacesFirst() { + return setSaveNamespacesFirst(true); + } + + public XmlOptions setSaveNamespacesFirst(boolean b) { + return set(XmlOptionsKeys.SAVE_NAMESPACES_FIRST, b); + } + + public boolean isSaveNamespacesFirst() { + return hasOption(XmlOptionsKeys.SAVE_NAMESPACES_FIRST); + } + + + /** + * This option will cause the saver to reformat white space for easier reading. + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSavePrettyPrint() { + return setSavePrettyPrint(true); + } + + public XmlOptions setSavePrettyPrint(boolean b) { + return set(XmlOptionsKeys.SAVE_PRETTY_PRINT, b); + } + + public boolean isSavePrettyPrint() { + return hasOption(XmlOptionsKeys.SAVE_PRETTY_PRINT); + } + + + /** + * When used with setSavePrettyPrint this sets the indent + * amount to use. + * + * @param indent the indent amount to use + * @see #setSavePrettyPrint + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSavePrettyPrintIndent(int indent) { + return set(XmlOptionsKeys.SAVE_PRETTY_PRINT_INDENT, indent); + } + + public Integer getSavePrettyPrintIndent() { + return (Integer) get(XmlOptionsKeys.SAVE_PRETTY_PRINT_INDENT); + } + + /** + * When used with setSavePrettyPrint this sets the offset + * amount to use. + * + * @param offset the offset amount to use + * @see #setSavePrettyPrint + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSavePrettyPrintOffset(int offset) { + return set(XmlOptionsKeys.SAVE_PRETTY_PRINT_OFFSET, offset); + } + + public Integer getSavePrettyPrintOffset() { + return (Integer) get(XmlOptionsKeys.SAVE_PRETTY_PRINT_OFFSET); + } + + /** + * When writing a document, this sets the character + * encoding to use. + * + * @param encoding the character encoding + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + * @see XmlTokenSource#save(java.io.File, XmlOptions) + */ + public XmlOptions setCharacterEncoding(String encoding) { + return set(XmlOptionsKeys.CHARACTER_ENCODING, encoding); + } + + public String getCharacterEncoding() { + return (String) get(XmlOptionsKeys.CHARACTER_ENCODING); + } + + /** + * When parsing a document, this sets the type of the root + * element. If this is set, the parser will not try to guess + * the type based on the document's QName. + * + * @param type The root element's document type. + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setDocumentType(SchemaType type) { + return set(XmlOptionsKeys.DOCUMENT_TYPE, type); + } + + public SchemaType getDocumentType() { + return (SchemaType) get(XmlOptionsKeys.DOCUMENT_TYPE); + } + + + /** + *

      Sets a collection object for collecting {@link XmlError} objects + * during parsing, validation, and compilation. When set, the collection + * will contain all the errors after the operation takes place. Notice that + * the errors will only have line numbers if the document was + * loaded with line numbers enabled.

      + * + *

      The following simple example illustrates using an error listener + * during validation.

      + * + *
      +     * // Create an XmlOptions instance and set the error listener.
      +     * XmlOptions validateOptions = new XmlOptions();
      +     * ArrayList errorList = new ArrayList();
      +     * validateOptions.setErrorListener(errorList);
      +     *
      +     * // Validate the XML.
      +     * boolean isValid = newEmp.validate(validateOptions);
      +     *
      +     * // If the XML isn't valid, loop through the listener's contents,
      +     * // printing contained messages.
      +     * if (!isValid)
      +     * {
      +     *      for (int i = 0; i < errorList.size(); i++)
      +     *      {
      +     *          XmlError error = (XmlError)errorList.get(i);
      +     *
      +     *          System.out.println("\n");
      +     *          System.out.println("Message: " + error.getMessage() + "\n");
      +     *          System.out.println("Location of invalid XML: " +
      +     *              error.getCursorLocation().xmlText() + "\n");
      +     *      }
      +     * }
      +     * 
      + * + * @param c A collection that will be filled with {@link XmlError} objects + * via {@link Collection#add} + * @see XmlError + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + * @see XmlObject#validate(XmlOptions) + * @see XmlBeans#compileXsd + * @see XmlOptions#setLoadLineNumbers + */ + public XmlOptions setErrorListener(Collection c) { + return set(XmlOptionsKeys.ERROR_LISTENER, c); + } + + @SuppressWarnings("unchecked") + public Collection getErrorListener() { + return (Collection) get(XmlOptionsKeys.ERROR_LISTENER); + } + + /** + * Causes the saver to reduce the number of namespace prefix declarations. + * The saver will do this by passing over the document twice, first to + * collect the set of needed namespace declarations, and then second + * to actually save the document with the declarations collected + * at the root. + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveAggressiveNamespaces() { + return setSaveAggressiveNamespaces(true); + } + + public XmlOptions setSaveAggressiveNamespaces(boolean b) { + return set(XmlOptionsKeys.SAVE_AGGRESSIVE_NAMESPACES, b); + } + + public boolean isSaveAggressiveNamespaces() { + return hasOption(XmlOptionsKeys.SAVE_AGGRESSIVE_NAMESPACES); + } + + + /** + * This option causes the saver to wrap the current fragment in + * an element with the given name. + * + * @param name the name to use for the top level element + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveSyntheticDocumentElement(QName name) { + return set(XmlOptionsKeys.SAVE_SYNTHETIC_DOCUMENT_ELEMENT, name); + } + + public QName getSaveSyntheticDocumentElement() { + return (QName) get(XmlOptionsKeys.SAVE_SYNTHETIC_DOCUMENT_ELEMENT); + } + + + /** + * If this option is set, the saver will try to use the default + * namespace for the most commonly used URI. If it is not set + * the saver will always created named prefixes. + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setUseDefaultNamespace() { + return setUseDefaultNamespace(true); + } + + public XmlOptions setUseDefaultNamespace(boolean b) { + return set(XmlOptionsKeys.SAVE_USE_DEFAULT_NAMESPACE, b); + } + + public boolean isUseDefaultNamespace() { + return hasOption(XmlOptionsKeys.SAVE_USE_DEFAULT_NAMESPACE); + } + + /** + * If namespaces have already been declared outside the scope of the + * fragment being saved, this allows those mappings to be passed + * down to the saver, so the prefixes are not re-declared. + * + * @param implicitNamespaces a map of prefixes to uris that can be + * used by the saver without being declared + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveImplicitNamespaces(Map implicitNamespaces) { + return set(XmlOptionsKeys.SAVE_IMPLICIT_NAMESPACES, implicitNamespaces); + } + + @SuppressWarnings("unchecked") + public Map getSaveImplicitNamespaces() { + return (Map) get(XmlOptionsKeys.SAVE_IMPLICIT_NAMESPACES); + } + + /** + * A map of hints to pass to the saver for which prefixes to use + * for which namespace URI. + * + * @param suggestedPrefixes a map from URIs to prefixes + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveSuggestedPrefixes(Map suggestedPrefixes) { + return set(XmlOptionsKeys.SAVE_SUGGESTED_PREFIXES, suggestedPrefixes); + } + + @SuppressWarnings("unchecked") + public Map getSaveSuggestedPrefixes() { + return (Map) get(XmlOptionsKeys.SAVE_SUGGESTED_PREFIXES); + } + + /** + * This option causes the saver to filter a Processing Instruction + * with the given target + * + * @param filterProcinst the name of a Processing Instruction to filter + * on save + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveFilterProcinst(String filterProcinst) { + return set(XmlOptionsKeys.SAVE_FILTER_PROCINST, filterProcinst); + } + + public String getSaveFilterProcinst() { + return (String) get(XmlOptionsKeys.SAVE_FILTER_PROCINST); + } + + /** + * This option causes the saver to replace characters with other values in + * the output stream. It is intended to be used for escaping non-standard + * characters during output. + * + * @param characterReplacementMap is an XmlOptionCharEscapeMap containing + * the characters to be escaped. + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + * @see XmlOptionCharEscapeMap + */ + public XmlOptions setSaveSubstituteCharacters( + XmlOptionCharEscapeMap characterReplacementMap) { + return set(XmlOptionsKeys.SAVE_SUBSTITUTE_CHARACTERS, characterReplacementMap); + } + + public XmlOptionCharEscapeMap getSaveSubstituteCharacters() { + return (XmlOptionCharEscapeMap) get(XmlOptionsKeys.SAVE_SUBSTITUTE_CHARACTERS); + } + + /** + * When saving a fragment, this option changes the qname of the synthesized + * root element. Normally <xml-fragment> is used. + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveUseOpenFrag() { + return setSaveUseOpenFrag(true); + } + + public XmlOptions setSaveUseOpenFrag(boolean b) { + return set(XmlOptionsKeys.SAVE_USE_OPEN_FRAGMENT, b); + } + + public boolean isSaveUseOpenFrag() { + return hasOption(XmlOptionsKeys.SAVE_USE_OPEN_FRAGMENT); + } + + /** + * This option controls whether saving begins on the element or its contents + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveOuter() { + return setSaveOuter(true); + } + + public XmlOptions setSaveOuter(boolean b) { + return set(XmlOptionsKeys.SAVE_OUTER, b); + } + + public boolean isSaveOuter() { + return hasOption(XmlOptionsKeys.SAVE_OUTER); + } + + /** + * This option controls whether saving begins on the element or its contents + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveInner() { + return setSaveInner(true); + } + + public XmlOptions setSaveInner(boolean b) { + return set(XmlOptionsKeys.SAVE_INNER, b); + } + + public boolean isSaveInner() { + return hasOption(XmlOptionsKeys.SAVE_INNER); + } + + /** + * This option controls whether saving saves out the XML + * declaration ( + * + * @see XmlTokenSource#save(java.io.File, XmlOptions) + * @see XmlTokenSource#xmlText(XmlOptions) + */ + public XmlOptions setSaveNoXmlDecl() { + return setSaveNoXmlDecl(true); + } + + public XmlOptions setSaveNoXmlDecl(boolean b) { + return set(XmlOptionsKeys.SAVE_NO_XML_DECL, b); + } + + public boolean isSaveNoXmlDecl() { + return hasOption(XmlOptionsKeys.SAVE_NO_XML_DECL); + } + + + /** + * This option controls when saving will use CDATA blocks. + * CDATA will be used if the folowing condition is true: + *
      textLength > cdataLengthThreshold && entityCount > cdataEntityCountThreshold + *
      The default value of cdataLengthThreshold is 32. + *
      + *
      Use the folowing values for these cases: + * + * + * + * + * + * + * + *
      Scenario cdataLengthThreshold cdataEntityCountThreshold
      Every text is CDATA 0 -1
      Only text that has an entity is CDATA 0 0
      Only text longer than x chars is CDATA x -1
      Only text that has y entitazable chars is CDATA 0 y
      Only text longer than x chars and has y entitazable chars is CDATA x y
      + * + * @see XmlOptions#setSaveCDataEntityCountThreshold(int) + */ + public XmlOptions setSaveCDataLengthThreshold(int cdataLengthThreshold) { + return set(XmlOptionsKeys.SAVE_CDATA_LENGTH_THRESHOLD, cdataLengthThreshold); + } + + public Integer getSaveCDataLengthThreshold() { + return (Integer) get(XmlOptionsKeys.SAVE_CDATA_LENGTH_THRESHOLD); + } + + + /** + * This option controls when saving will use CDATA blocks. + * CDATA will be used if the folowing condition is true: + *
      textLength > cdataLengthThreshold && entityCount > cdataEntityCountThreshold + *
      The default value of cdataEntityCountThreshold is 5. + * + * @see XmlOptions#setSaveCDataLengthThreshold(int) + */ + public XmlOptions setSaveCDataEntityCountThreshold(int cdataEntityCountThreshold) { + return set(XmlOptionsKeys.SAVE_CDATA_ENTITY_COUNT_THRESHOLD, cdataEntityCountThreshold); + } + + public Integer getSaveCDataEntityCountThreshold() { + return (Integer) get(XmlOptionsKeys.SAVE_CDATA_ENTITY_COUNT_THRESHOLD); + } + + /** + *

      Use this option when parsing and saving XML documents.

      + * + *

      For parsing this option will annotate the text fields in the store with CDataBookmark.

      + * + *

      For saving this option will save the text fields annotated with CDataBookmark as + * CDATA XML text.
      + * Note: The SaveCDataEntityCountThreshold and SaveCDataLengthThreshold options and + * their default values still apply.

      + * + *

      Note: Due to the store representation, a CDATA will not be recognized + * if it is imediately after non CDATA text and all text following it will + * be considered CDATA.
      + * Example:
      + *

      +     * <a><![CDATA[cdata text]]></a>               - is considered as: <a><![CDATA[cdata text]]></a>
      +     * <b><![CDATA[cdata text]]> regular text</b>  - is considered as: <b><![CDATA[cdata text regular text]]></b>
      +     * <c>text <![CDATA[cdata text]]></c>          - is considered as: <c>text cdata text</c>
      +     * 
      + *

      + * + *

      Sample code: + *

      +     * String xmlText = "<a>\n" +
      +     * "<a><![CDATA[cdata text]]></a>\n" +
      +     * "<b><![CDATA[cdata text]]> regular text</b>\n" +
      +     * "<c>text <![CDATA[cdata text]]></c>\n" +
      +     * "</a>";
      +     * System.out.println(xmlText);
      +     *
      +     * XmlOptions opts = new XmlOptions();
      +     * opts.setUseCDataBookmarks();
      +     *
      +     * XmlObject xo = XmlObject.Factory.parse( xmlText , opts);
      +     *
      +     * System.out.println("xo1:\n" + xo.xmlText(opts));
      +     * System.out.println("\n");
      +     *
      +     * opts.setSavePrettyPrint();
      +     * System.out.println("xo2:\n" + xo.xmlText(opts));
      +     * 
      + *

      + * + * @see CDataBookmark + * @see CDataBookmark#CDATA_BOOKMARK + */ + public XmlOptions setUseCDataBookmarks() { + return set(XmlOptionsKeys.LOAD_SAVE_CDATA_BOOKMARKS); + } + + public boolean isUseCDataBookmarks() { + return hasOption(XmlOptionsKeys.LOAD_SAVE_CDATA_BOOKMARKS); + } + + /** + * This option controls whether namespace declarations are included as attributes in the + * startElement event. By default, up to and including XMLBeans 2.3.0 they were included, in + * subsequent versions, they are no longer included. + */ + public XmlOptions setSaveSaxNoNSDeclsInAttributes() { + return setSaveSaxNoNSDeclsInAttributes(true); + } + + public XmlOptions setSaveSaxNoNSDeclsInAttributes(boolean b) { + return set(XmlOptionsKeys.SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES, b); + } + + public boolean isSaveSaxNoNSDeclsInAttributes() { + return hasOption(XmlOptionsKeys.SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES); + } + + + /** + * If this option is set, the document element is replaced with the + * given QName when parsing. If null is supplied, the document element + * is removed. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadReplaceDocumentElement(QName replacement) { + return set(XmlOptionsKeys.LOAD_REPLACE_DOCUMENT_ELEMENT, replacement); + } + + public QName getLoadReplaceDocumentElement() { + return (QName) get(XmlOptionsKeys.LOAD_REPLACE_DOCUMENT_ELEMENT); + } + + /** + * If this option is set, all insignificant whitespace is stripped + * when parsing a document. Can be used to save memory on large + * documents when you know there is no mixed content. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadStripWhitespace() { + return setLoadStripWhitespace(true); + } + + public XmlOptions setLoadStripWhitespace(boolean b) { + return set(XmlOptionsKeys.LOAD_STRIP_WHITESPACE, b); + } + + public boolean isSetLoadStripWhitespace() { + return hasOption(XmlOptionsKeys.LOAD_STRIP_WHITESPACE); + } + + /** + * If this option is set, all comments are stripped when parsing + * a document. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadStripComments() { + return setLoadStripComments(true); + } + + public XmlOptions setLoadStripComments(boolean b) { + return set(XmlOptionsKeys.LOAD_STRIP_COMMENTS, b); + } + + public boolean isLoadStripComments() { + return hasOption(XmlOptionsKeys.LOAD_STRIP_COMMENTS); + } + + /** + * If this option is set, all processing instructions + * are stripped when parsing a document. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadStripProcinsts() { + return setLoadStripProcinsts(true); + } + + public XmlOptions setLoadStripProcinsts(boolean b) { + return set(XmlOptionsKeys.LOAD_STRIP_PROCINSTS, b); + } + + public boolean isLoadStripProcinsts() { + return hasOption(XmlOptionsKeys.LOAD_STRIP_PROCINSTS); + } + + /** + * If this option is set, line number annotations are placed + * in the store when parsing a document. This is particularly + * useful when you want {@link XmlError} objects to contain + * line numbers. + *
      Note: This adds line numbers info only for start tags. + * For line number info on end tags use: + * {@link XmlOptions#setLoadLineNumbersEndElement()} + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + * @see XmlError + */ + public XmlOptions setLoadLineNumbers() { + return setLoadLineNumbers(true); + } + + public XmlOptions setLoadLineNumbers(boolean b) { + return set(XmlOptionsKeys.LOAD_LINE_NUMBERS, b); + } + + public boolean isLoadLineNumbers() { + return hasOption(XmlOptionsKeys.LOAD_LINE_NUMBERS); + } + + + /** + * If this option is set, line number annotations are placed + * in the store when parsing a document. This is particularly + * useful when you want {@link XmlError} objects to contain + * line numbers. Use the option to load line numbers at the end of an element. + */ + public XmlOptions setLoadLineNumbersEndElement() { + return setLoadLineNumbersEndElement(true); + } + + public XmlOptions setLoadLineNumbersEndElement(boolean b) { + setLoadLineNumbers(true); + return set(XmlOptionsKeys.LOAD_LINE_NUMBERS_END_ELEMENT, b); + } + + public boolean isLoadLineNumbersEndElement() { + return hasOption(XmlOptionsKeys.LOAD_LINE_NUMBERS_END_ELEMENT); + } + + /** + * This option sets a map of namespace uri substitutions that happen + * when parsing a document. + *

      + * This is particularly useful if you + * have documents that use no namespace, but you wish to avoid + * the name collision problems that occur when you introduce + * schema definitions without a target namespace. + *

      + * By mapping the empty string "" (the absence of a URI) to a specific + * namespace, you can force the parser to behave as if a no-namespace + * document were actually in the specified namespace. This allows you + * to type the instance according to a schema in a nonempty namespace, + * and therefore avoid the problematic practice of using schema + * definitions without a target namespace. + * + * @param substNamespaces a map of document URIs to replacement URIs + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadSubstituteNamespaces(Map substNamespaces) { + return set(XmlOptionsKeys.LOAD_SUBSTITUTE_NAMESPACES, substNamespaces); + } + + @SuppressWarnings("unchecked") + public Map getLoadSubstituteNamespaces() { + return (Map) get(XmlOptionsKeys.LOAD_SUBSTITUTE_NAMESPACES); + } + + /** + * If this option is set, the underlying xml text buffer is trimmed + * immediately after parsing a document resulting in a smaller memory + * footprint. Use this option if you are loading a large number + * of unchanging documents that will stay in memory for some time. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadTrimTextBuffer() { + return setLoadTrimTextBuffer(true); + } + + public XmlOptions setLoadTrimTextBuffer(boolean b) { + return set(XmlOptionsKeys.LOAD_TRIM_TEXT_BUFFER, b); + } + + public boolean isLoadTrimTextBuffer() { + return hasOption(XmlOptionsKeys.LOAD_TRIM_TEXT_BUFFER); + } + + /** + * Set additional namespace mappings to be added when parsing + * a document. + * + * @param nses additional namespace mappings + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadAdditionalNamespaces(Map nses) { + return set(XmlOptionsKeys.LOAD_ADDITIONAL_NAMESPACES, nses); + } + + @SuppressWarnings("unchecked") + public Map getLoadAdditionalNamespaces() { + return (Map) get(XmlOptionsKeys.LOAD_ADDITIONAL_NAMESPACES); + } + + /** + * If this option is set when loading from an InputStream or File, then + * the loader will compute a 160-bit SHA-1 message digest of the XML + * file while loading it and make it available via + * XmlObject.documentProperties().getMessageDigest(); + *
      + * The schema compiler uses message digests to detect and eliminate + * duplicate imported xsd files. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadMessageDigest() { + return setLoadMessageDigest(true); + } + + public XmlOptions setLoadMessageDigest(boolean b) { + return set(XmlOptionsKeys.LOAD_MESSAGE_DIGEST, b); + } + + public boolean isLoadMessageDigest() { + return hasOption(XmlOptionsKeys.LOAD_MESSAGE_DIGEST); + } + + /** + * By default, XmlBeans does not resolve entities when parsing xml + * documents (unless an explicit entity resolver is specified). + * Use this option to turn on entity resolving by default. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadUseDefaultResolver() { + return setLoadUseDefaultResolver(true); + } + + public XmlOptions setLoadUseDefaultResolver(boolean b) { + return set(XmlOptionsKeys.LOAD_USE_DEFAULT_RESOLVER, b); + } + + public boolean isLoadUseDefaultResolver() { + return hasOption(XmlOptionsKeys.LOAD_USE_DEFAULT_RESOLVER); + } + + + /** + * By default, XmlBeans creates a JAXP parser, + * other parsers can be used by providing an XMLReader. + * For using the default JDK's SAX parser use: + * xmlOptions.setLoadUseXMLReader( SAXParserFactory.newInstance().newSAXParser().getXMLReader() ); + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setLoadUseXMLReader(XMLReader xmlReader) { + return set(XmlOptionsKeys.LOAD_USE_XMLREADER, xmlReader); + } + + public XMLReader getLoadUseXMLReader() { + return (XMLReader) get(XmlOptionsKeys.LOAD_USE_XMLREADER); + } + + /** + * Sets the name of the variable that represents + * the current node in a query expression. + * + * @param varName The new variable name to use for the query. + * @see XmlObject#execQuery + * @see XmlCursor#execQuery + */ + public XmlOptions setXqueryCurrentNodeVar(String varName) { + return set(XmlOptionsKeys.XQUERY_CURRENT_NODE_VAR, varName); + } + + public String getXqueryCurrentNodeVar() { + return (String) get(XmlOptionsKeys.XQUERY_CURRENT_NODE_VAR); + } + + /** + * Map the names and values of external variables in an xquery + * expression. The keys of the map are the variable names + * in the query without the '$' prefix. The values of the map + * are objects and can be any of the primitive wrapper classes, + * String, XmlObject, or XmlCursor. The mapping only applies to + * xquery and has no effect on xpath expressions. + * + * @param varMap a map from Strings to variable instances. + * @see XmlObject#execQuery + * @see XmlCursor#execQuery + */ + public XmlOptions setXqueryVariables(Map varMap) { + return set(XmlOptionsKeys.XQUERY_VARIABLE_MAP, varMap); + } + + @SuppressWarnings("unchecked") + public Map getXqueryVariables() { + return (Map) get(XmlOptionsKeys.XQUERY_VARIABLE_MAP); + } + + /** + * This option sets the document source name into the xml store + * when parsing a document. If a document is parsed from a + * File or URI, it is automatically set to the URI of the + * source; otherwise, for example, when parsing a String, + * you can use this option to specify the source name yourself. + * + * @see XmlObject.Factory#parse(java.lang.String, XmlOptions) + */ + public XmlOptions setDocumentSourceName(String documentSourceName) { + return set(XmlOptionsKeys.DOCUMENT_SOURCE_NAME, documentSourceName); + } + + public String getDocumentSourceName() { + return (String) get(XmlOptionsKeys.DOCUMENT_SOURCE_NAME); + } + + /** + * This option allows for QName substitution during schema compilation. + * + * @param nameMap a map from QNames to substitute QNames. + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileSubstituteNames(Map nameMap) { + return set(XmlOptionsKeys.COMPILE_SUBSTITUTE_NAMES, nameMap); + } + + @SuppressWarnings("unchecked") + public Map getCompileSubstituteNames() { + return (Map) get(XmlOptionsKeys.COMPILE_SUBSTITUTE_NAMES); + } + + /** + * If this option is set, validation is not done on the Schema XmlBeans + * when building a SchemaTypeSystem + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileNoValidation() { + return set(XmlOptionsKeys.COMPILE_NO_VALIDATION); + } + + public boolean isCompileNoValidation() { + return hasOption(XmlOptionsKeys.COMPILE_NO_VALIDATION); + } + + /** + * If this option is set, the unique particle attribution rule is not + * enforced when building a SchemaTypeSystem. See + * Appendix H of the XML Schema specification + * for information on the UPA rule. + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileNoUpaRule() { + return setCompileNoUpaRule(true); + } + + public XmlOptions setCompileNoUpaRule(boolean b) { + return set(XmlOptionsKeys.COMPILE_NO_UPA_RULE, b); + } + + public boolean isCompileNoUpaRule() { + return hasOption(XmlOptionsKeys.COMPILE_NO_UPA_RULE); + } + + /** + * If this option is set, the particle valid (restriciton) rule is not + * enforced when building a SchemaTypeSystem. See + * Section 3.9.6 of the XML Schema specification + * for information on the PVR rule. + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileNoPvrRule() { + return setCompileNoPvrRule(true); + } + + public XmlOptions setCompileNoPvrRule(boolean b) { + return set(XmlOptionsKeys.COMPILE_NO_PVR_RULE, b); + } + + public boolean isCompileNoPvrRule() { + return hasOption(XmlOptionsKeys.COMPILE_NO_PVR_RULE); + } + + /** + * if this option is set, the schema compiler will skip annotations when + * processing Schema components. + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileNoAnnotations() { + return setCompileNoAnnotations(true); + } + + public XmlOptions setCompileNoAnnotations(boolean b) { + return set(XmlOptionsKeys.COMPILE_NO_ANNOTATIONS, b); + } + + public boolean isCompileNoAnnotations() { + return hasOption(XmlOptionsKeys.COMPILE_NO_ANNOTATIONS); + } + + /** + * If this option is set, then the schema compiler will try to download + * schemas that appear in imports and includes from network based URLs. + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileDownloadUrls() { + return setCompileDownloadUrls(true); + } + + public XmlOptions setCompileDownloadUrls(boolean b) { + return set(XmlOptionsKeys.COMPILE_DOWNLOAD_URLS, b); + } + + public boolean isCompileDownloadUrls() { + return hasOption(XmlOptionsKeys.COMPILE_DOWNLOAD_URLS); + } + + /** + * If this option is set, then the schema compiler will permit and + * ignore multiple definitions of the same component (element, attribute, + * type, etc) names in the given namespaces. If multiple definitions + * with the same name appear, the definitions that happen to be processed + * last will be ignored. + * + * @param mdefNamespaces a set of namespace URIs as Strings + * @see XmlBeans#compileXsd + */ + public XmlOptions setCompileMdefNamespaces(Set mdefNamespaces) { + return set(XmlOptionsKeys.COMPILE_MDEF_NAMESPACES, mdefNamespaces); + } + + @SuppressWarnings("unchecked") + public Set getCompileMdefNamespaces() { + return (Set) get(XmlOptionsKeys.COMPILE_MDEF_NAMESPACES); + } + + public XmlOptions setCompilePartialTypesystem() { + return setCompilePartialTypesystem(true); + } + + public XmlOptions setCompilePartialTypesystem(boolean compilePartialTypesystem) { + return set(XmlOptionsKeys.COMPILE_PARTIAL_TYPESYSTEM, compilePartialTypesystem); + } + + public boolean isCompilePartialTypesystem() { + Boolean flag = (Boolean) get(XmlOptionsKeys.COMPILE_PARTIAL_TYPESYSTEM); + return flag != null && flag; + } + + /** + * If this option is set when an instance is created, then value + * facets will be checked on each call to a setter or getter + * method on instances of XmlObject within the instance document. + * If the facets are not satisfied, then an unchecked exception is + * thrown immediately. This option is useful for finding code that + * is introducing invalid values in an XML document, but it + * slows performance. + * + * @see XmlObject.Factory#parse(java.io.File, XmlOptions) + */ + public XmlOptions setValidateOnSet() { + return setValidateOnSet(true); + } + + public XmlOptions setValidateOnSet(boolean b) { + return set(XmlOptionsKeys.VALIDATE_ON_SET, b); + } + + public boolean isValidateOnSet() { + return hasOption(XmlOptionsKeys.VALIDATE_ON_SET); + } + + /** + * Instructs the validator to skip elements matching an + * particle with contentModel="lax". This is useful because, + * in certain situations, XmlBeans will find types on the + * classpath that the document author did not anticipate. + */ + public XmlOptions setValidateTreatLaxAsSkip() { + return setValidateTreatLaxAsSkip(true); + } + + public XmlOptions setValidateTreatLaxAsSkip(boolean b) { + return set(XmlOptionsKeys.VALIDATE_TREAT_LAX_AS_SKIP, b); + } + + public boolean isValidateTreatLaxAsSkip() { + return hasOption(XmlOptionsKeys.VALIDATE_TREAT_LAX_AS_SKIP); + } + + /** + * Performs additional validation checks that are disabled by + * default for better compatibility. + */ + public XmlOptions setValidateStrict() { + return setValidateStrict(true); + } + + public XmlOptions setValidateStrict(boolean b) { + return set(XmlOptionsKeys.VALIDATE_STRICT, b); + } + + public boolean isValidateStrict() { + return hasOption(XmlOptionsKeys.VALIDATE_STRICT); + } + + public XmlOptions setValidateTextOnly() { + return setValidateTextOnly(true); + } + + public XmlOptions setValidateTextOnly(boolean b) { + return set(XmlOptionsKeys.VALIDATE_TEXT_ONLY, b); + } + + public boolean isValidateTextOnly() { + return hasOption(XmlOptionsKeys.VALIDATE_TEXT_ONLY); + } + + + /** + * This option controls whether or not operations on XmlBeans are + * thread safe. When not on, all XmlBean operations will be syncronized. + * This provides for multiple thread the ability to access a single + * XmlBeans simultainously, but has a perf impact. If set, then + * only one thread may access an XmlBean. + */ + public XmlOptions setUnsynchronized() { + return setUnsynchronized(true); + } + + public XmlOptions setUnsynchronized(boolean b) { + return set(XmlOptionsKeys.UNSYNCHRONIZED, b); + } + + public boolean isUnsynchronized() { + return hasOption(XmlOptionsKeys.UNSYNCHRONIZED); + } + + /** + * If this option is set when compiling a schema, then the given + * EntityResolver will be consulted in order to resolve any + * URIs while downloading imported schemas. + *

      + * EntityResolvers are currently only used by compileXsd; they + * are not consulted by other functions, for example, parse. + * This will likely change in the future. + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setEntityResolver(EntityResolver resolver) { + return set(XmlOptionsKeys.ENTITY_RESOLVER, resolver); + } + + public EntityResolver getEntityResolver() { + return (EntityResolver) get(XmlOptionsKeys.ENTITY_RESOLVER); + } + + /** + * If this option is set when compiling a schema, then the given + * URI will be considered as base URI when deciding the directory + * structure for saving the sources inside the generated JAR file. + * + * @param baseURI the URI to be considered as "base" + * @see XmlBeans#compileXsd + */ + public XmlOptions setBaseURI(URI baseURI) { + return set(XmlOptionsKeys.BASE_URI, baseURI); + } + + public URI getBaseURI() { + return (URI) get(XmlOptionsKeys.BASE_URI); + } + + /** + * If this option is set when compiling a schema, then the given + * SchemaTypeCodePrinter.Printer will be used to generate the + * Java code. + * + * @see XmlBeans#compileXsd + */ + public XmlOptions setSchemaCodePrinter(SchemaCodePrinter printer) { + return set(XmlOptionsKeys.SCHEMA_CODE_PRINTER, printer); + } + + public SchemaCodePrinter getSchemaCodePrinter() { + return (SchemaCodePrinter) get(XmlOptionsKeys.SCHEMA_CODE_PRINTER); + } + + /** + * If this option is set to true, the return of XmlObject.copy() method will + * return an object in it's own synchronization domain, otherwise both objects + * will share the same synchronization domain, requiring explicit synchronization + * when concurent accessing the two objects. + * + * @param useNewSyncDomain A flag representing the usage of new domain + * @see XmlObject#copy() + */ + public XmlOptions setCopyUseNewSynchronizationDomain(boolean useNewSyncDomain) { + return set(XmlOptionsKeys.COPY_USE_NEW_SYNC_DOMAIN, useNewSyncDomain); + } + + public boolean isCopyUseNewSynchronizationDomain() { + Boolean flag = (Boolean) get(XmlOptionsKeys.COPY_USE_NEW_SYNC_DOMAIN); + return flag != null && flag; + } + + public XmlOptions setUseSameLocale(Object localeOrXmlTokenSource) { + return set(XmlOptionsKeys.USE_SAME_LOCALE, localeOrXmlTokenSource); + } + + public Object getUseSameLocale() { + return get(XmlOptionsKeys.USE_SAME_LOCALE); + } + + + /** + * Sets the maximum number of bytes allowed when an Entity is expanded during parsing. + * The default value is 10240 bytes. + * + * @param entityBytesLimit the maximum number of bytes allowed when an Entity is expanded during parsing + * @return this + */ + public XmlOptions setLoadEntityBytesLimit(int entityBytesLimit) { + return set(XmlOptionsKeys.LOAD_ENTITY_BYTES_LIMIT, entityBytesLimit); + } + + public Integer getLoadEntityBytesLimit() { + return (Integer) get(XmlOptionsKeys.LOAD_ENTITY_BYTES_LIMIT); + } + + + /** + * Sets the maximum number of entity expansions allowed during parsing. + * The default value is 2048. + * + * @param entityExpansionLimit the maximum number of entity expansions allowed during parsing + * @return this + */ + public XmlOptions setEntityExpansionLimit(int entityExpansionLimit) { + return set(XmlOptionsKeys.ENTITY_EXPANSION_LIMIT, entityExpansionLimit); + } + + public int getEntityExpansionLimit() { + Integer limit = (Integer) get(XmlOptionsKeys.ENTITY_EXPANSION_LIMIT); + return limit == null ? DEFAULT_ENTITY_EXPANSION_LIMIT : limit; + } + + /** + * Controls whether DTD grammar is loaded during parsing. + * The default value is false. + * + * @param loadDTDGrammar {@code true}, if DTD grammar is loaded during parsing + * @return this + */ + public XmlOptions setLoadDTDGrammar(boolean loadDTDGrammar) { + return set(XmlOptionsKeys.LOAD_DTD_GRAMMAR, loadDTDGrammar); + } + + public boolean isLoadDTDGrammar() { + Boolean flag = (Boolean) get(XmlOptionsKeys.LOAD_DTD_GRAMMAR); + return flag != null && flag; + } + + /** + * Controls whether external DTDs are loaded during parsing. + * The default value is false. + * + * @param loadExternalDTD {@code true}, if external DTDs are loaded during parsing + * @return this + */ + public XmlOptions setLoadExternalDTD(boolean loadExternalDTD) { + return set(XmlOptionsKeys.LOAD_EXTERNAL_DTD, loadExternalDTD); + } + + public boolean isLoadExternalDTD() { + Boolean flag = (Boolean) get(XmlOptionsKeys.LOAD_EXTERNAL_DTD); + return flag != null && flag; + } + + public XmlOptions setSaveOptimizeForSpeed(boolean saveOptimizeForSpeed) { + return set(XmlOptionsKeys.SAVE_OPTIMIZE_FOR_SPEED, saveOptimizeForSpeed); + } + + public boolean isSaveOptimizeForSpeed() { + Boolean flag = (Boolean) get(XmlOptionsKeys.SAVE_OPTIMIZE_FOR_SPEED); + return flag != null && flag; + } + + // Use in XmlOptions to enable SAAJ support in store + public XmlOptions setSaaj(Saaj saaj) { + return set(XmlOptionsKeys.SAAJ_IMPL, saaj); + } + + public Saaj getSaaj() { + return (Saaj) get(XmlOptionsKeys.SAAJ_IMPL); + } + + public XmlOptions setLoadUseLocaleCharUtil(boolean useCharUtil) { + return set(XmlOptionsKeys.LOAD_USE_LOCALE_CHAR_UTIL, useCharUtil); + } + + public boolean isLoadUseLocaleCharUtil() { + Boolean flag = (Boolean) get(XmlOptionsKeys.LOAD_USE_LOCALE_CHAR_UTIL); + return flag != null && flag; + } + + public XmlOptions setXPathUseSaxon() { + return setXPathUseSaxon(true); + } + + public XmlOptions setXPathUseSaxon(boolean xpathUseSaxon) { + return set(XmlOptionsKeys.XPATH_USE_SAXON, xpathUseSaxon); + } + + public boolean isXPathUseSaxon() { + Boolean flag = (Boolean) get(XmlOptionsKeys.XPATH_USE_SAXON); + return flag != null && flag; + } + + public XmlOptions setXPathUseXmlBeans() { + return setXPathUseSaxon(true); + } + + public XmlOptions setXPathUseXmlBeans(boolean xpathUseXmlBeans) { + return set(XmlOptionsKeys.XPATH_USE_XMLBEANS, xpathUseXmlBeans); + } + + public boolean isXPathUseXmlBeans() { + Boolean flag = (Boolean) get(XmlOptionsKeys.XPATH_USE_XMLBEANS); + return flag != null && flag; + } + + public XmlOptions setAttributeValidationCompatMode(boolean attributeValidationCompatMode) { + return set(XmlOptionsKeys.ATTTRIBUTE_VALIDATION_COMPAT_MODE, attributeValidationCompatMode); + } + + public boolean isAttributeValidationCompatMode() { + Boolean flag = (Boolean) get(XmlOptionsKeys.ATTTRIBUTE_VALIDATION_COMPAT_MODE); + return flag != null && flag; + } + + /** + * If passed null, returns an empty options object. Otherwise, returns its argument. + */ + public static XmlOptions maskNull(XmlOptions o) { + return (o == null) ? EMPTY_OPTIONS : o; + } + + + private XmlOptions set(XmlOptionsKeys option) { + return set(option, true); + } + + private XmlOptions set(XmlOptionsKeys option, Object value) { + _map.put(option, value); + return this; + } + + private XmlOptions set(XmlOptionsKeys option, int value) { + return set(option, (Integer)value); + } + + private XmlOptions set(XmlOptionsKeys option, boolean value) { + if (value) { + set(option, Boolean.TRUE); + } else { + remove(option); + } + return this; + } + + /** + * Used to test a generic option + */ + public boolean hasOption(XmlOptionsKeys option) { + return _map.containsKey(option); + } + + /** + * Used to get a generic option + */ + public Object get(XmlOptionsKeys option) { + return _map.get(option); + } + + public void remove(XmlOptionsKeys option) { + _map.remove(option); + } +} diff --git a/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java b/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java new file mode 100644 index 0000000..7ab1a51 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java @@ -0,0 +1,39 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Same as {@link XmlOptions} but adhering to JavaBean conventions + * + * @deprecated use XmlOptions instead + */ +@Deprecated +public class XmlOptionsBean extends XmlOptions { + /** + * Construct a new blank XmlOptions. + */ + public XmlOptionsBean() { + } + + /** + * Construct a new XmlOptions, copying the options. + * + * @param other the source XmlOptions object + */ + public XmlOptionsBean(XmlOptions other) { + super(other); + } +} diff --git a/src/main/java/org/apache/xmlbeans/XmlPositiveInteger.java b/src/main/java/org/apache/xmlbeans/XmlPositiveInteger.java new file mode 100644 index 0000000..cfa2679 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlPositiveInteger.java @@ -0,0 +1,162 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:positiveInteger type. + * One of the derived types based on xs:decimal. + *

      + * Verified to be positive when validating. + *

      + * Convertible to {@link java.math.BigInteger}. + */ +public interface XmlPositiveInteger extends XmlNonNegativeInteger { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_positiveInteger"); + + /** + * A class with methods for creating instances + * of {@link XmlPositiveInteger}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlPositiveInteger} + */ + public static XmlPositiveInteger newInstance() { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlPositiveInteger} + */ + public static XmlPositiveInteger newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlPositiveInteger} value + */ + public static XmlPositiveInteger newValue(Object obj) { + return (XmlPositiveInteger) type.newValue(obj); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". + */ + public static XmlPositiveInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". + */ + public static XmlPositiveInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a File. + */ + public static XmlPositiveInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a File. + */ + public static XmlPositiveInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a URL. + */ + public static XmlPositiveInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a URL. + */ + public static XmlPositiveInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from an InputStream. + */ + public static XmlPositiveInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from an InputStream. + */ + public static XmlPositiveInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a Reader. + */ + public static XmlPositiveInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a Reader. + */ + public static XmlPositiveInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a DOM Node. + */ + public static XmlPositiveInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from a DOM Node. + */ + public static XmlPositiveInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from an XMLStreamReader. + */ + public static XmlPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlPositiveInteger} fragment from an XMLStreamReader. + */ + public static XmlPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlQName.java b/src/main/java/org/apache/xmlbeans/XmlQName.java new file mode 100644 index 0000000..7c648c5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlQName.java @@ -0,0 +1,179 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import javax.xml.namespace.QName; + + +/** + * Corresponds to the XML Schema + * xs:QName type. + *

      + * A QName is the logical combination of an XML namespace URI and a localName. + * Although in an XML instance document, a QName appears as "prefix:localName", + * the logical value of a QName does NOT contain any information about the + * prefix, only the namespace URI to which the prefix maps. For example, + * two QNames "a:hello" and "b:hello" are perfectly equivalent if "a:" in + * the first instance maps to the same URI as "b:" in the second instance. + *

      + * Convertible to {@link javax.xml.namespace.QName}. + */ +public interface XmlQName extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_QName"); + + /** + * Returns this value as a {@link QName} + */ + QName getQNameValue(); + + /** + * Sets this value as a {@link QName} + */ + void setQNameValue(QName name); + + /** + * A class with methods for creating instances + * of {@link XmlQName}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlQName} + */ + public static XmlQName newInstance() { + return (XmlQName) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlQName} + */ + public static XmlQName newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlQName) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlQName} value + */ + public static XmlQName newValue(Object obj) { + return (XmlQName) type.newValue(obj); + } + + /** + * Parses a {@link XmlQName} fragment from a String. For example: "<xml-fragment xmlns:x="http://openuri.org/">x:sample</xml-fragment>". + */ + public static XmlQName parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from a String. For example: "<xml-fragment xmlns:x="http://openuri.org/">x:sample</xml-fragment>". + */ + public static XmlQName parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlQName} fragment from a File. + */ + public static XmlQName parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from a File. + */ + public static XmlQName parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlQName} fragment from a URL. + */ + public static XmlQName parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from a URL. + */ + public static XmlQName parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlQName} fragment from an InputStream. + */ + public static XmlQName parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from an InputStream. + */ + public static XmlQName parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlQName} fragment from a Reader. + */ + public static XmlQName parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from a Reader. + */ + public static XmlQName parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlQName} fragment from a DOM Node. + */ + public static XmlQName parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from a DOM Node. + */ + public static XmlQName parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlQName} fragment from an XMLStreamReader. + */ + public static XmlQName parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlQName} fragment from an XMLStreamReader. + */ + public static XmlQName parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlQName) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java b/src/main/java/org/apache/xmlbeans/XmlRuntimeException.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java rename to src/main/java/org/apache/xmlbeans/XmlRuntimeException.java diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlSaxHandler.java b/src/main/java/org/apache/xmlbeans/XmlSaxHandler.java similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/XmlSaxHandler.java rename to src/main/java/org/apache/xmlbeans/XmlSaxHandler.java diff --git a/src/main/java/org/apache/xmlbeans/XmlShort.java b/src/main/java/org/apache/xmlbeans/XmlShort.java new file mode 100644 index 0000000..45b362d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlShort.java @@ -0,0 +1,170 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:short type. + * One of the derived types based on xs:decimal. + *

      + * Naturally, convertible to a Java short. + */ +public interface XmlShort extends XmlInt { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_short"); + + /** + * Returns this value as a short + */ + short getShortValue(); + + /** + * Sets this value as a short + */ + void setShortValue(short s); + + /** + * A class with methods for creating instances + * of {@link XmlShort}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlShort} + */ + public static XmlShort newInstance() { + return (XmlShort) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlShort} + */ + public static XmlShort newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlShort) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlShort} value + */ + public static XmlShort newValue(Object obj) { + return (XmlShort) type.newValue(obj); + } + + /** + * Parses a {@link XmlShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". + */ + public static XmlShort parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". + */ + public static XmlShort parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlShort} fragment from a File. + */ + public static XmlShort parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from a File. + */ + public static XmlShort parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlShort} fragment from a URL. + */ + public static XmlShort parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from a URL. + */ + public static XmlShort parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlShort} fragment from an InputStream. + */ + public static XmlShort parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from an InputStream. + */ + public static XmlShort parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlShort} fragment from a Reader. + */ + public static XmlShort parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from a Reader. + */ + public static XmlShort parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlShort} fragment from a DOM Node. + */ + public static XmlShort parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from a DOM Node. + */ + public static XmlShort parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlShort} fragment from an XMLStreamReader. + */ + public static XmlShort parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlShort} fragment from an XMLStreamReader. + */ + public static XmlShort parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlShort) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlSimpleList.java b/src/main/java/org/apache/xmlbeans/XmlSimpleList.java new file mode 100644 index 0000000..5ad4222 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlSimpleList.java @@ -0,0 +1,321 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.*; + +/** + * The immutable {@link List} returned for XML simple list values. + *

      + * XmlSimpleList implements an equals() and hashCode() that compare list + * contents, so two XmlSimpleLists are the same if they have the same + * values in the same order. + */ +public class XmlSimpleList implements List, java.io.Serializable { + private static final long serialVersionUID = 1L; + + private final List underlying; + + /** + * Constructs an immutable XmlSimpleList that wraps (does not copy) + * the given {@link List}. All non-mutating methods delegate to + * the underlying List instance. + */ + public XmlSimpleList(List list) { + this.underlying = list; + } + + /** + * Returns the number of elements in this list. + */ + public int size() { + return underlying.size(); + } + + /** + * True if the list is empty. + */ + public boolean isEmpty() { + return underlying.isEmpty(); + } + + /** + * True if the list is contains an object equal to o. + */ + public boolean contains(Object o) { + return underlying.contains(o); + } + + /** + * True if the list is contains all the objects in the given collection. + */ + public boolean containsAll(Collection coll) { + return underlying.containsAll(coll); + } + + /** + * Copies the collection to an array. + */ + public Object[] toArray() { + return underlying.toArray(new Object[0]); + } + + /** + * Copies the collection to an array of a specified type. + */ + @SuppressWarnings("SuspiciousToArrayCall") + public X[] toArray(X[] a) { + return underlying.toArray(a); + } + + /** + * Unsupported because this list is immutable. + */ + public boolean add(Object o) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public boolean addAll(Collection coll) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public boolean remove(Object o) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public boolean removeAll(Collection coll) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public boolean retainAll(Collection coll) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public void clear() { + throw new UnsupportedOperationException(); + } + + /** + * Returns the object at the specified position in this list. + */ + public T get(int index) { + return underlying.get(index); + } + + /** + * Unsupported because this list is immutable. + */ + public T set(int index, T element) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public void add(int index, Object element) { + throw new UnsupportedOperationException(); + } + + /** + * Unsupported because this list is immutable. + */ + public T remove(int index) { + throw new UnsupportedOperationException(); + } + + /** + * Returns index of the first occurance of an object equal to o. + */ + public int indexOf(Object o) { + return underlying.indexOf(o); + } + + /** + * Returns index of the last occurance of an object equal to o. + */ + public int lastIndexOf(Object o) { + return underlying.lastIndexOf(o); + } + + /** + * Unsupported because this list is immutable. + */ + public boolean addAll(int index, Collection c) { + throw new UnsupportedOperationException(); + } + + /** + * Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. + */ + public List subList(int from, int to) { + return new XmlSimpleList<>(underlying.subList(from, to)); + } + + /** + * Returns an iterator over the elements in this list in proper sequence. + */ + public Iterator iterator() { + return new Iterator() { + final Iterator i = underlying.iterator(); + + public boolean hasNext() { + return i.hasNext(); + } + + public T next() { + return i.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + /** + * Returns a list iterator of the elements in this list in proper sequence. + */ + public ListIterator listIterator() { + return listIterator(0); + } + + /** + * Returns a list iterator of the elements in this list in proper sequence, starting at the specified position in this list. + */ + public ListIterator listIterator(final int index) { + return new ListIterator() { + final ListIterator i = underlying.listIterator(index); + + public boolean hasNext() { + return i.hasNext(); + } + + public T next() { + return i.next(); + } + + public boolean hasPrevious() { + return i.hasPrevious(); + } + + public T previous() { + return i.previous(); + } + + public int nextIndex() { + return i.nextIndex(); + } + + public int previousIndex() { + return i.previousIndex(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public void set(Object o) { + throw new UnsupportedOperationException(); + } + + public void add(Object o) { + throw new UnsupportedOperationException(); + } + }; + } + + private String stringValue(Object o) { + if (o instanceof SimpleValue) { + return ((SimpleValue) o).getStringValue(); + } + return o.toString(); + } + + /** + * Returns a space-separated list of the string representations of all + * the items in the list. For most lists, this is a valid xml lexical + * value for the list. (The notable exception is a list of QNames.) + */ + public String toString() { + int size = underlying.size(); + if (size == 0) { + return ""; + } + String first = stringValue(underlying.get(0)); + if (size == 1) { + return first; + } + StringBuilder result = new StringBuilder(first); + for (int i = 1; i < size; i++) { + result.append(' '); + result.append(stringValue(underlying.get(i))); + } + return result.toString(); + } + + /** + * Two XmlSimpleLists are equal if all their items are equal. + * (They must have the same number of items, and the items must be in + * the same order.) + */ + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof XmlSimpleList)) { + return false; + } + final XmlSimpleList xmlSimpleList = (XmlSimpleList) o; + List underlying2 = xmlSimpleList.underlying; + int size = underlying.size(); + if (size != underlying2.size()) { + return false; + } + for (int i = 0; i < size; i++) { + if (!Objects.equals(underlying.get(i), underlying2.get(i))) { + return false; + } + } + return true; + } + + /** + * Combines the hash codes of all the list items. + */ + public int hashCode() { + int hash = 0; + for (Object item : underlying) { + hash *= 19; + hash += item.hashCode(); + } + return hash; + } +} diff --git a/src/main/java/org/apache/xmlbeans/XmlString.java b/src/main/java/org/apache/xmlbeans/XmlString.java new file mode 100644 index 0000000..b05a72e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlString.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:string type. + *

      + * A basic string in XML schema is not whitespace normalized. If you + * want your string type to be insensitive to variations in runs of + * whitespace, consider using + * xs:token + * (aka {@link XmlToken}) instead. + * To forbid whitespace and permit just alphanumeric and other + * common identifier characters consider + * xs:NMTOKEN + * (aka {@link XmlNMTOKEN}) instead. + *

      + * Convertible to {@link String}. + */ +public interface XmlString extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_string"); + + /** + * A class with methods for creating instances + * of {@link XmlString}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlString} + */ + public static XmlString newInstance() { + return (XmlString) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlString} + */ + public static XmlString newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlString) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlString} value + */ + public static XmlString newValue(Object obj) { + return (XmlString) type.newValue(obj); + } + + /** + * Parses a {@link XmlString} fragment from a String. For example: "<xml-fragment> arbitrary string </xml-fragment>". + */ + public static XmlString parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlString} fragment from a String. For example: "<xml-fragment> arbitrary string </xml-fragment>". + */ + public static XmlString parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlString} fragment from a File. + */ + public static XmlString parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlString} fragment from a File. + */ + public static XmlString parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlString} fragment from a URL. + */ + public static XmlString parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlString} fragment from a URL. + */ + public static XmlString parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlString} fragment from an InputStream. + */ + public static XmlString parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlString} fragment from an InputStream. + */ + public static XmlString parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlString} fragment from a Reader. + */ + public static XmlString parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlString} fragment from a Reader. + */ + public static XmlString parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlString} fragment from a DOM Node. + */ + public static XmlString parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlString} fragment from a DOM Node. + */ + public static XmlString parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlString} fragment from an XMLStreamReader. + */ + public static XmlString parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlString} fragment from an XMLStreamReader. + */ + public static XmlString parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlString) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlTime.java b/src/main/java/org/apache/xmlbeans/XmlTime.java new file mode 100644 index 0000000..c3a1aeb --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlTime.java @@ -0,0 +1,186 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.util.Calendar; + + +/** + * Corresponds to the XML Schema + * xs:time type. + * A gDay specifies only a day-of-month. + *

      + * Convertible to {@link Calendar} or {@link GDate}. + * + * @see XmlCalendar + * @see GDate + */ +public interface XmlTime extends XmlAnySimpleType { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_time"); + + /** + * Returns this value as a {@link Calendar} + */ + Calendar getCalendarValue(); + + /** + * Sets this value as a {@link Calendar} + */ + void setCalendarValue(Calendar c); + + /** + * Returns this value as a {@link GDate} + */ + GDate getGDateValue(); + + /** + * Sets this value as a {@link GDateSpecification} + */ + void setGDateValue(GDate gd); + + /** + * A class with methods for creating instances + * of {@link XmlTime}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlTime} + */ + public static XmlTime newInstance() { + return (XmlTime) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlTime} + */ + public static XmlTime newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlTime) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlTime} value + */ + public static XmlTime newValue(Object obj) { + return (XmlTime) type.newValue(obj); + } + + /** + * Parses a {@link XmlTime} fragment from a String. For example: "<xml-fragment>12:00:00</xml-fragment>". + */ + public static XmlTime parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from a String. For example: "<xml-fragment>12:00:00</xml-fragment>". + */ + public static XmlTime parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlTime} fragment from a File. + */ + public static XmlTime parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from a File. + */ + public static XmlTime parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlTime} fragment from a URL. + */ + public static XmlTime parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from a URL. + */ + public static XmlTime parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlTime} fragment from an InputStream. + */ + public static XmlTime parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from an InputStream. + */ + public static XmlTime parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlTime} fragment from a Reader. + */ + public static XmlTime parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from a Reader. + */ + public static XmlTime parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlTime} fragment from a DOM Node. + */ + public static XmlTime parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from a DOM Node. + */ + public static XmlTime parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlTime} fragment from an XMLStreamReader. + */ + public static XmlTime parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlTime} fragment from an XMLStreamReader. + */ + public static XmlTime parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlTime) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlToken.java b/src/main/java/org/apache/xmlbeans/XmlToken.java new file mode 100644 index 0000000..f209dd1 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlToken.java @@ -0,0 +1,173 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:token type. + * One of the derived types based on xs:string. + *

      + * A token is XML's best representation for a "whitespace insensitive string." + * All carriage returns, linefeeds, and tabs are converted to ordinary space + * characters (as with xs:normalizedString), + * and furthermore, all contiguous runs of space are collapsed to single spaces, + * and leading and trailing spaces are trimmed. + *

      + * If you want "  high  priority  " + * to be equivalent to "high priority", you should consider + * using xs:token or a subtype of xs:token. + *

      + * When the {@link #getStringValue()} is obtained from an XmlToken, the normalized, + * trimmed, whitespace collapsed value is returned. + *

      + * Convertible to {@link String}. + */ +public interface XmlToken extends XmlNormalizedString { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_token"); + + /** + * A class with methods for creating instances + * of {@link XmlToken}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlToken} + */ + public static XmlToken newInstance() { + return (XmlToken) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlToken} + */ + public static XmlToken newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlToken) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlToken} value + */ + public static XmlToken newValue(Object obj) { + return (XmlToken) type.newValue(obj); + } + + /** + * Parses a {@link XmlToken} fragment from a String. For example: "<xml-fragment>string to collapse</xml-fragment>". + */ + public static XmlToken parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from a String. For example: "<xml-fragment>string to collapse</xml-fragment>". + */ + public static XmlToken parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlToken} fragment from a File. + */ + public static XmlToken parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from a File. + */ + public static XmlToken parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlToken} fragment from a URL. + */ + public static XmlToken parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from a URL. + */ + public static XmlToken parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlToken} fragment from an InputStream. + */ + public static XmlToken parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from an InputStream. + */ + public static XmlToken parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlToken} fragment from a Reader. + */ + public static XmlToken parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from a Reader. + */ + public static XmlToken parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlToken} fragment from a DOM Node. + */ + public static XmlToken parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from a DOM Node. + */ + public static XmlToken parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlToken} fragment from an XMLStreamReader. + */ + public static XmlToken parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlToken} fragment from an XMLStreamReader. + */ + public static XmlToken parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlToken) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlTokenSource.java b/src/main/java/org/apache/xmlbeans/XmlTokenSource.java similarity index 85% rename from src/xmlpublic/org/apache/xmlbeans/XmlTokenSource.java rename to src/main/java/org/apache/xmlbeans/XmlTokenSource.java index 2c57fd1..8082863 100644 --- a/src/xmlpublic/org/apache/xmlbeans/XmlTokenSource.java +++ b/src/main/java/org/apache/xmlbeans/XmlTokenSource.java @@ -15,22 +15,13 @@ package org.apache.xmlbeans; -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.io.File; -import java.io.IOException; - -import javax.xml.stream.XMLStreamReader; - import org.w3c.dom.Node; - import org.xml.sax.ContentHandler; -import org.xml.sax.ext.LexicalHandler; import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +import javax.xml.stream.XMLStreamReader; +import java.io.*; /** * Represents a holder of XML that can return an {@link XmlCursor} @@ -39,12 +30,11 @@ * Both {@link XmlObject} * (and thus all XML Beans) and {@link XmlCursor} are * XmlTokenSource implementations. - * + * * @see XmlObject * @see XmlCursor - */ -public interface XmlTokenSource -{ + */ +public interface XmlTokenSource { /** * Returns the synchronization object for the document. If concurrent * multithreaded access to a document is required, the access should should @@ -52,7 +42,7 @@ public interface XmlTokenSource * monitor per XML document tree. */ Object monitor(); - + /** * Returns the XmlDocumentProperties object for the document this token * source is associated with. @@ -61,46 +51,29 @@ public interface XmlTokenSource /** * Returns a new XML cursor. - * + *

      * A cursor provides random access to all the tokens in the XML * data, plus the ability to extract strongly-typed XmlObjects * for the data. If the data is not read-only, the XML cursor * also allows modifications to the data. - * + *

      * Using a cursor for the first time typically forces the XML * document into memory. */ XmlCursor newCursor(); - /** - * Returns a new XmlInputStream. - * - * The stream starts at the current begin-tag or begin-document - * position and ends at the matching end-tag or end-document. - * - * This is a fail-fast stream, so if the underlying data is changed - * while the stream is being read, the stream throws a - * ConcurrentModificationException. - * - * Throws an IllegalStateException if the XmlTokenSource is not - * positioned at begin-tag or begin-document (e.g., if it is at - * an attribute). - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - XMLInputStream newXMLInputStream(); - /** * Returns a new XMLStreamReader. - * + *

      * The stream starts at the current begin-tag or begin-document * position and ends at the matching end-tag or end-document. - * + *

      * This is a fail-fast stream, so if the underlying data is changed * while the stream is being read, the stream throws a * ConcurrentModificationException. */ XMLStreamReader newXMLStreamReader(); - + /** * Returns standard XML text. *

      @@ -113,8 +86,8 @@ public interface XmlTokenSource * positioned at begin-tag or begin-document (e.g., if it is at * an attribute). *

      - * Note that this method does not produce XML with the XML declaration, - * including the encoding information. To save the XML declaration with + * Note that this method does not produce XML with the XML declaration, + * including the encoding information. To save the XML declaration with * the XML, see {@link #save(OutputStream)} or {@link #save(OutputStream, XmlOptions)}. */ String xmlText(); @@ -122,16 +95,16 @@ public interface XmlTokenSource /** * Returns a new stream containing standard XML text, encoded * according to the given encoding. - * + *

      * The byte stream contains contents starting at the current * begin-tag or begin-document and ending at the matching * end-tag or end-document. The specified encoding is used * and also emitted in a PI at the beginning of the stream. - * + *

      * This is a fail-fast stream, so if the underlying data is changed * while the stream is being read, the stream throws a * ConcurrentModificationException. - * + *

      * Throws an IllegalStateException if the XmlTokenSource is not * positioned at begin-tag or begin-document (e.g., if it is at * an attribute). @@ -140,22 +113,22 @@ public interface XmlTokenSource /** * Returns a new character reader containing XML text. - * + *

      * The contents of the reader represents the document contents * starting at the current begin-tag or begin-document and ending at * the matching end-tag or end-document. No encoding annotation * will be made in the text itself. - * + *

      * This is a fail-fast reader, so if the underlying data is changed * while the reader is being read, the reader throws a * ConcurrentModificationException. - * + *

      * Throws an IllegalStateException if the XmlTokenSource is not * positioned at begin-tag or begin-document (e.g., if it is at * an attribute). */ Reader newReader(); - + /** * Returns a W3C DOM Node containing the XML * represented by this source. This is a copy of the XML, it is @@ -177,38 +150,48 @@ public interface XmlTokenSource /** * Writes the XML represented by this source to the given SAX content and * lexical handlers. - * Note that this method does not save the XML declaration, including the encoding information. - * To save the XML declaration with the XML, see {@link #save(OutputStream)}, + * Note that this method does not save the XML declaration, including the encoding information. + * To save the XML declaration with the XML, see {@link #save(OutputStream)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ - void save ( ContentHandler ch, LexicalHandler lh ) throws SAXException; - + void save(ContentHandler ch, LexicalHandler lh) throws SAXException; + /** * Writes the XML represented by this source to the given File. * This method will save the XML declaration, including encoding information, * with the XML. */ - void save ( File file ) throws IOException; - + void save(File file) throws IOException; + /** * Writes the XML represented by this source to the given output stream. * This method will save the XML declaration, including encoding information, * with the XML. */ - void save ( OutputStream os ) throws IOException; + void save(OutputStream os) throws IOException; /** * Writes the XML represented by this source to the given output. - * Note that this method does not save the XML declaration, including the encoding information. - * To save the XML declaration with the XML, see {@link #save(OutputStream)}, + * Note that this method does not save the XML declaration, including the encoding information. + * To save the XML declaration with the XML, see {@link #save(OutputStream)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ - void save ( Writer w ) throws IOException; + void save(Writer w) throws IOException; /** - *

      Just like newXMLInputStream() but with any of a number of options. Use the - * options parameter to specify the following:

      - * + * Returns a new XMLStreamReader. + *

      + * The stream starts at the current begin-tag or begin-document + * position and ends at the matching end-tag or end-document. + *

      + * This is a fail-fast stream, so if the underlying data is changed + * while the stream is being read, the stream throws a + * ConcurrentModificationException. + *

      + * Throws an IllegalStateException if the XmlTokenSource is not + * positioned at begin-tag or begin-document (e.g., if it is at + * an attribute). + * * * * @@ -219,8 +202,8 @@ public interface XmlTokenSource * * * * @@ -235,12 +218,12 @@ public interface XmlTokenSource * * * - * * * * - * * * @@ -250,14 +233,14 @@ public interface XmlTokenSource * * * - * - * + * * * * * * @@ -266,8 +249,8 @@ public interface XmlTokenSource * * * - * * * @@ -285,87 +268,80 @@ public interface XmlTokenSource * * *
      To specify thisUse this method
      Prefix-to-namespace mappings that should be assumed * when saving this XML. This is useful when the resulting - * XML will be part of a larger XML document, ensuring that this - * inner document will take advantage of namespaces defined in + * XML will be part of a larger XML document, ensuring that this + * inner document will take advantage of namespaces defined in * the outer document.{@link XmlOptions#setSaveImplicitNamespaces}
      {@link XmlOptions#setSaveNamespacesFirst}
      The XML should be pretty printed when saved. Note that this + * The XML should be pretty printed when saved. Note that this * should only be used for debugging.{@link XmlOptions#setSavePrettyPrint}
      The number of spaces to use when indenting for pretty printing. + * The number of spaces to use when indenting for pretty printing. * The default is 2.{@link XmlOptions#setSavePrettyPrintIndent}
      {@link XmlOptions#setSavePrettyPrintOffset}
      To minimize the number of namespace attributes generated for the + * To minimize the number of namespace attributes generated for the * saved XML. Note that this can reduce performance significantly.{@link XmlOptions#setSaveAggresiveNamespaces}{@link XmlOptions#setSaveAggressiveNamespaces}
      To reduce the size of the saved document - * by allowing the use of the default namespace. Note that this can - * potentially change the semantic meaning of the XML if unprefixed QNames are + * by allowing the use of the default namespace. Note that this can + * potentially change the semantic meaning of the XML if unprefixed QNames are * present as the value of an attribute or element.{@link XmlOptions#setUseDefaultNamespace}
      {@link XmlOptions#setSaveFilterProcinst}
      Change the QName of the synthesized root element when saving. This - * replaces "xml-fragment" with "fragment" in the namespace + * Change the QName of the synthesized root element when saving. This + * replaces "xml-fragment" with "fragment" in the namespace * http://www.openuri.org/fragment{@link XmlOptions#setSaveUseOpenFrag}
      {@link XmlOptions#setSaveSyntheticDocumentElement}
      - * - * @see XmlOptions - * - * @param options Any of the described options. - * @return A new validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - XMLInputStream newXMLInputStream(XmlOptions options); - - /** - * Just like newXMLInputStream() but with options. - * Options map may be null. + * + * @param options Any of the described options. Options map may be null. + * @return A new validating XMLStreamReader. * @see XmlOptions */ XMLStreamReader newXMLStreamReader(XmlOptions options); - + /** * Just like xmlText() but with options. * Options map may be null. *

      - * Note that this method does not produce XML with the XML declaration, - * including the encoding information. To save the XML declaration with + * Note that this method does not produce XML with the XML declaration, + * including the encoding information. To save the XML declaration with * the XML, see {@link #save(OutputStream)} or {@link #save(OutputStream, XmlOptions)}. * * @see XmlOptions */ String xmlText(XmlOptions options); - + /** - * * Just like newInputStream(String encoding) but with options. * Options map may be null. + * * @see XmlOptions */ InputStream newInputStream(XmlOptions options); - + /** * Just like newReader() but with options. * Options map may be null. + * * @see XmlOptions */ Reader newReader(XmlOptions options); - + /** * Just like newDomNode() but with options. * Options map may be null. + * * @see XmlOptions */ Node newDomNode(XmlOptions options); - + /** * Writes the XML represented by this source to the given SAX content and * lexical handlers. - * Note that this method does not save the XML declaration, including the encoding information. - * To save the XML declaration with the XML, see {@link #save(OutputStream)}, + * Note that this method does not save the XML declaration, including the encoding information. + * To save the XML declaration with the XML, see {@link #save(OutputStream)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ - void save ( ContentHandler ch, LexicalHandler lh, XmlOptions options ) throws SAXException; - + void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException; + /** * Writes the XML represented by this source to the given File. * This method will save the XML declaration, including encoding information, * with the XML. */ - void save ( File file, XmlOptions options ) throws IOException; - + void save(File file, XmlOptions options) throws IOException; + /** * Writes the XML represented by this source to the given output stream. * This method will save the XML declaration, including encoding information, * with the XML. */ - void save ( OutputStream os, XmlOptions options ) throws IOException; + void save(OutputStream os, XmlOptions options) throws IOException; /** * Writes the XML represented by this source to the given output. - * Note that this method does not save the XML declaration, including the encoding information. - * To save the XML declaration with the XML, see {@link #save(OutputStream)}, + * Note that this method does not save the XML declaration, including the encoding information. + * To save the XML declaration with the XML, see {@link #save(OutputStream)}, * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}. */ - void save ( Writer w, XmlOptions options ) throws IOException; + void save(Writer w, XmlOptions options) throws IOException; /** * Prints to stdout the state of the document in which this token source is positioned. @@ -374,5 +350,5 @@ public interface XmlTokenSource * XML text which only approximates the actual state of the document. */ - void dump ( ); + void dump(); } diff --git a/src/main/java/org/apache/xmlbeans/XmlUnsignedByte.java b/src/main/java/org/apache/xmlbeans/XmlUnsignedByte.java new file mode 100644 index 0000000..32f3e67 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlUnsignedByte.java @@ -0,0 +1,173 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:unsignedByte type. + * One of the derived types based on xs:decimal. + *

      + * Verified to be in the range 0..255 when validating. + *

      + * As suggested by JAXB, convertible to Java short. + */ +public interface XmlUnsignedByte extends XmlUnsignedShort { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedByte"); + + /** + * Returns this value as a short + */ + short getShortValue(); + + /** + * Sets this value as a short + */ + void setShortValue(short s); + + + /** + * A class with methods for creating instances + * of {@link XmlUnsignedByte}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlUnsignedByte} + */ + public static XmlUnsignedByte newInstance() { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlUnsignedByte} + */ + public static XmlUnsignedByte newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlUnsignedByte} value + */ + public static XmlUnsignedByte newValue(Object obj) { + return (XmlUnsignedByte) type.newValue(obj); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". + */ + public static XmlUnsignedByte parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". + */ + public static XmlUnsignedByte parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a File. + */ + public static XmlUnsignedByte parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a File. + */ + public static XmlUnsignedByte parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a URL. + */ + public static XmlUnsignedByte parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a URL. + */ + public static XmlUnsignedByte parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from an InputStream. + */ + public static XmlUnsignedByte parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from an InputStream. + */ + public static XmlUnsignedByte parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a Reader. + */ + public static XmlUnsignedByte parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a Reader. + */ + public static XmlUnsignedByte parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a DOM Node. + */ + public static XmlUnsignedByte parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from a DOM Node. + */ + public static XmlUnsignedByte parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from an XMLStreamReader. + */ + public static XmlUnsignedByte parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlUnsignedByte} fragment from an XMLStreamReader. + */ + public static XmlUnsignedByte parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlUnsignedInt.java b/src/main/java/org/apache/xmlbeans/XmlUnsignedInt.java new file mode 100644 index 0000000..d1869e0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlUnsignedInt.java @@ -0,0 +1,172 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:unsignedInt type. + * One of the derived types based on xs:decimal. + *

      + * Verified to be in the range 0..4294967295 when validating. + *

      + * Convertible to Java long. + */ +public interface XmlUnsignedInt extends XmlUnsignedLong { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedInt"); + + /** + * Returns this value as a long + */ + long getLongValue(); + + /** + * Sets this value as a long + */ + void setLongValue(long v); + + /** + * A class with methods for creating instances + * of {@link XmlUnsignedInt}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlUnsignedInt} + */ + public static XmlUnsignedInt newInstance() { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlUnsignedInt} + */ + public static XmlUnsignedInt newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlUnsignedInt} value + */ + public static XmlUnsignedInt newValue(Object obj) { + return (XmlUnsignedInt) type.newValue(obj); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". + */ + public static XmlUnsignedInt parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". + */ + public static XmlUnsignedInt parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a File. + */ + public static XmlUnsignedInt parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a File. + */ + public static XmlUnsignedInt parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a URL. + */ + public static XmlUnsignedInt parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a URL. + */ + public static XmlUnsignedInt parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from an InputStream. + */ + public static XmlUnsignedInt parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from an InputStream. + */ + public static XmlUnsignedInt parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a Reader. + */ + public static XmlUnsignedInt parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a Reader. + */ + public static XmlUnsignedInt parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a DOM Node. + */ + public static XmlUnsignedInt parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from a DOM Node. + */ + public static XmlUnsignedInt parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from an XMLStreamReader. + */ + public static XmlUnsignedInt parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlUnsignedInt} fragment from an XMLStreamReader. + */ + public static XmlUnsignedInt parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlUnsignedLong.java b/src/main/java/org/apache/xmlbeans/XmlUnsignedLong.java new file mode 100644 index 0000000..8b55954 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlUnsignedLong.java @@ -0,0 +1,165 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +import java.math.BigInteger; + + +/** + * Corresponds to the XML Schema + * xs:unsignedLong type. + * One of the derived types based on xs:decimal. + *

      + * Verified to be in the range 0..264-1 when validating. + *

      + * Convertible to {@link BigInteger}. + */ +public interface XmlUnsignedLong extends XmlNonNegativeInteger { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedLong"); + + /** + * A class with methods for creating instances + * of {@link XmlUnsignedLong}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlUnsignedLong} + */ + public static XmlUnsignedLong newInstance() { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlUnsignedLong} + */ + public static XmlUnsignedLong newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlUnsignedLong} value + */ + public static XmlUnsignedLong newValue(Object obj) { + return (XmlUnsignedLong) type.newValue(obj); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". + */ + public static XmlUnsignedLong parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". + */ + public static XmlUnsignedLong parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a File. + */ + public static XmlUnsignedLong parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a File. + */ + public static XmlUnsignedLong parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a URL. + */ + public static XmlUnsignedLong parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a URL. + */ + public static XmlUnsignedLong parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from an InputStream. + */ + public static XmlUnsignedLong parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from an InputStream. + */ + public static XmlUnsignedLong parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a Reader. + */ + public static XmlUnsignedLong parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a Reader. + */ + public static XmlUnsignedLong parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a DOM Node. + */ + public static XmlUnsignedLong parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from a DOM Node. + */ + public static XmlUnsignedLong parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from an XMLStreamReader. + */ + public static XmlUnsignedLong parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlUnsignedLong} fragment from an XMLStreamReader. + */ + public static XmlUnsignedLong parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/XmlUnsignedShort.java b/src/main/java/org/apache/xmlbeans/XmlUnsignedShort.java new file mode 100644 index 0000000..05c21dc --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/XmlUnsignedShort.java @@ -0,0 +1,172 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans; + +/** + * Corresponds to the XML Schema + * xs:unsignedShort type. + * One of the derived types based on xs:decimal. + *

      + * Verified to be in the range 0..65535 when validating. + *

      + * Convertible to a Java int. + */ +public interface XmlUnsignedShort extends XmlUnsignedInt { + /** + * The constant {@link SchemaType} object representing this schema type. + */ + SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedShort"); + + /** + * Returns this value as an int + */ + int getIntValue(); + + /** + * Sets this value as an int + */ + void setIntValue(int v); + + /** + * A class with methods for creating instances + * of {@link XmlUnsignedShort}. + */ + final class Factory { + /** + * Creates an empty instance of {@link XmlUnsignedShort} + */ + public static XmlUnsignedShort newInstance() { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().newInstance(type, null); + } + + /** + * Creates an empty instance of {@link XmlUnsignedShort} + */ + public static XmlUnsignedShort newInstance(org.apache.xmlbeans.XmlOptions options) { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().newInstance(type, options); + } + + /** + * Creates an immutable {@link XmlUnsignedShort} value + */ + public static XmlUnsignedShort newValue(Object obj) { + return (XmlUnsignedShort) type.newValue(obj); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". + */ + public static XmlUnsignedShort parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(s, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". + */ + public static XmlUnsignedShort parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(s, type, options); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a File. + */ + public static XmlUnsignedShort parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(f, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a File. + */ + public static XmlUnsignedShort parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(f, type, options); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a URL. + */ + public static XmlUnsignedShort parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(u, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a URL. + */ + public static XmlUnsignedShort parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(u, type, options); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from an InputStream. + */ + public static XmlUnsignedShort parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(is, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from an InputStream. + */ + public static XmlUnsignedShort parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(is, type, options); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a Reader. + */ + public static XmlUnsignedShort parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(r, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a Reader. + */ + public static XmlUnsignedShort parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(r, type, options); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a DOM Node. + */ + public static XmlUnsignedShort parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(node, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from a DOM Node. + */ + public static XmlUnsignedShort parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(node, type, options); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from an XMLStreamReader. + */ + public static XmlUnsignedShort parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(xsr, type, null); + } + + /** + * Parses a {@link XmlUnsignedShort} fragment from an XMLStreamReader. + */ + public static XmlUnsignedShort parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { + return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse(xsr, type, options); + } + + private Factory() { + // No instance of this class allowed + } + } +} + diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlValidationError.java b/src/main/java/org/apache/xmlbeans/XmlValidationError.java similarity index 99% rename from src/xmlpublic/org/apache/xmlbeans/XmlValidationError.java rename to src/main/java/org/apache/xmlbeans/XmlValidationError.java index 74a6776..518f70d 100644 --- a/src/xmlpublic/org/apache/xmlbeans/XmlValidationError.java +++ b/src/main/java/org/apache/xmlbeans/XmlValidationError.java @@ -235,7 +235,7 @@ public String getMessage() if (_fieldQName != null) { String msg = super.getMessage(); - StringBuffer sb = new StringBuffer(msg.length() + 100); + StringBuilder sb = new StringBuilder(msg.length() + 100); sb.append(msg); diff --git a/src/main/java/org/apache/xmlbeans/impl/common/DefaultClassLoaderResourceLoader.java b/src/main/java/org/apache/xmlbeans/impl/common/DefaultClassLoaderResourceLoader.java new file mode 100755 index 0000000..f11cd49 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/DefaultClassLoaderResourceLoader.java @@ -0,0 +1,43 @@ +/* Copyright 2019 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import java.io.InputStream; + +import org.apache.xmlbeans.ResourceLoader; + +public class DefaultClassLoaderResourceLoader implements ResourceLoader +{ + public InputStream getResourceAsStream(String resourceName) { + InputStream in = null; + try { + in = getResourceAsStream(Thread.currentThread().getContextClassLoader(), resourceName); + } catch (SecurityException securityexception) {} + if (in == null) { + in = getResourceAsStream(DefaultClassLoaderResourceLoader.class.getClassLoader(), resourceName); + } + if (in == null) { + in = DefaultClassLoaderResourceLoader.class.getResourceAsStream(resourceName); + } + return in; + } + + public void close() {} + + private InputStream getResourceAsStream(ClassLoader loader, String resourceName) { + return loader == null ? null : loader.getResourceAsStream(resourceName); + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/DocumentHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java similarity index 94% rename from src/common/org/apache/xmlbeans/impl/common/DocumentHelper.java rename to src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java index 7dd0bbf..f6e873a 100644 --- a/src/common/org/apache/xmlbeans/impl/common/DocumentHelper.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/DocumentHelper.java @@ -15,27 +15,24 @@ package org.apache.xmlbeans.impl.common; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.stream.events.Namespace; - import org.apache.xmlbeans.XmlOptionsBean; import org.w3c.dom.Document; -import org.w3c.dom.Element; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; + public final class DocumentHelper { - private static XBLogger logger = XBLogFactory.getLogger(DocumentHelper.class); + private static final XBLogger logger = XBLogFactory.getLogger(DocumentHelper.class); private static long lastLog; private DocumentHelper() {} @@ -58,7 +55,7 @@ public void fatalError(SAXParseException exception) throws SAXException { /** Prints the error message. */ private void printError(int type, SAXParseException ex) { StringBuilder sb = new StringBuilder(); - + String systemId = ex.getSystemId(); if (systemId != null) { int index = systemId.lastIndexOf('/'); @@ -76,7 +73,7 @@ private void printError(int type, SAXParseException ex) { logger.log(type, sb.toString(), ex); } } - + /** * Creates a new document builder, with sensible defaults * @@ -84,7 +81,7 @@ private void printError(int type, SAXParseException ex) { * @throws IllegalStateException If creating the DocumentBuilder fails, e.g. * due to {@link ParserConfigurationException}. */ - public static synchronized DocumentBuilder newDocumentBuilder(XmlOptionsBean xmlOptions) { + public static DocumentBuilder newDocumentBuilder(XmlOptionsBean xmlOptions) { try { DocumentBuilder documentBuilder = documentBuilderFactory(xmlOptions).newDocumentBuilder(); documentBuilder.setEntityResolver(SAXHelper.IGNORING_ENTITY_RESOLVER); @@ -115,7 +112,7 @@ private static void trySetFeature(DocumentBuilderFactory dbf, String feature, bo logger.log(XBLogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame); } } - + private static void trySetXercesSecurityManager(DocumentBuilderFactory dbf, XmlOptionsBean options) { // Try built-in JVM one first, standalone if not for (String securityManagerClassName : new String[]{ @@ -123,7 +120,7 @@ private static void trySetXercesSecurityManager(DocumentBuilderFactory dbf, XmlO "org.apache.xerces.util.SecurityManager" }) { try { - Object mgr = Class.forName(securityManagerClassName).newInstance(); + Object mgr = Class.forName(securityManagerClassName).getDeclaredConstructor().newInstance(); Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE); setLimit.invoke(mgr, options.getEntityExpansionLimit()); dbf.setAttribute(XMLBeansConstants.SECURITY_MANAGER, mgr); @@ -154,7 +151,7 @@ private static void trySetXercesSecurityManager(DocumentBuilderFactory dbf, XmlO * Parses the given stream via the default (sensible) * DocumentBuilder * @param inp Stream to read the XML data from - * @return the parsed Document + * @return the parsed Document */ public static Document readDocument(XmlOptionsBean xmlOptions, InputStream inp) throws IOException, SAXException { return newDocumentBuilder(xmlOptions).parse(inp); @@ -164,7 +161,7 @@ public static Document readDocument(XmlOptionsBean xmlOptions, InputStream inp) * Parses the given stream via the default (sensible) * DocumentBuilder * @param inp sax source to read the XML data from - * @return the parsed Document + * @return the parsed Document */ public static Document readDocument(XmlOptionsBean xmlOptions, InputSource inp) throws IOException, SAXException { return newDocumentBuilder(xmlOptions).parse(inp); @@ -176,7 +173,7 @@ public static Document readDocument(XmlOptionsBean xmlOptions, InputSource inp) /** * Creates a new DOM Document */ - public static synchronized Document createDocument() { + public static Document createDocument() { return documentBuilderSingleton.newDocument(); } } diff --git a/src/main/java/org/apache/xmlbeans/impl/common/EncodingMap.java b/src/main/java/org/apache/xmlbeans/impl/common/EncodingMap.java new file mode 100644 index 0000000..654982c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/EncodingMap.java @@ -0,0 +1,422 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class EncodingMap { + public static String getJava2IANAMapping(String java) { + String iana = _java_to_iana.get(java.toUpperCase(Locale.ROOT)); + if (iana != null) { + return iana; + } + // Try to use the information in the JDK to see if it is an encoding it supports + if (Charset.isSupported(java)) { + try { + iana = Charset.forName(java).name(); + return iana; + } catch (IllegalArgumentException iae) { + return null; + } + } + return null; + } + + public static String getIANA2JavaMapping(String iana) { + String java = _iana_to_java.get(iana.toUpperCase(Locale.ROOT)); + if (java != null) { + return java; + } else if (Charset.isSupported(iana)) { + return iana; + } else { + return null; + } + } + + private EncodingMap() { + } + + private final static Map _iana_to_java = new HashMap<>(); + private final static HashMap _java_to_iana = new HashMap<>(); + + private static void addMapping( + String java, String iana, boolean isDefault) { + assert !_iana_to_java.containsKey(iana); + assert java.toUpperCase(Locale.ROOT).equals(java); + assert iana.toUpperCase(Locale.ROOT).equals(iana); + + _iana_to_java.put(iana, java); + + if (isDefault) { + assert !_java_to_iana.containsKey(java); + _java_to_iana.put(java, iana); + } + } + + private static boolean completeMappings() { + HashMap m = new HashMap<>(); + + for (String s : _iana_to_java.keySet()) { + m.put(_iana_to_java.get(s), null); + } + + for (String k : m.keySet()) { + assert _java_to_iana.containsKey(k) : k; + } + + return true; + } + + static { + addMapping("ASCII", "ANSI_X3.4-1986", false); + addMapping("ASCII", "ASCII", true); + addMapping("ASCII", "CP367", false); + addMapping("ASCII", "CSASCII", false); + addMapping("ASCII", "IBM-367", false); + addMapping("ASCII", "IBM367", false); + addMapping("ASCII", "ISO-IR-6", false); + addMapping("ASCII", "ISO646-US", false); + addMapping("ASCII", "ISO_646.IRV:1991", false); + addMapping("ASCII", "US", false); + addMapping("ASCII", "US-ASCII", false); + addMapping("BIG5", "BIG5", true); + addMapping("BIG5", "CSBIG5", false); + addMapping("CP037", "CP037", false); + addMapping("CP037", "CSIBM037", false); + addMapping("CP037", "EBCDIC-CP-CA", false); + addMapping("CP037", "EBCDIC-CP-NL", false); + addMapping("CP037", "EBCDIC-CP-US", true); + addMapping("CP037", "EBCDIC-CP-WT", false); + addMapping("CP037", "IBM-37", false); + addMapping("CP037", "IBM037", false); + addMapping("CP1026", "CP1026", false); + addMapping("CP1026", "CSIBM1026", false); + addMapping("CP1026", "IBM-1026", false); + addMapping("CP1026", "IBM1026", true); + addMapping("CP1047", "CP1047", false); + addMapping("CP1047", "IBM-1047", false); + addMapping("CP1047", "IBM1047", true); + addMapping("CP1140", "CCSID01140", false); + addMapping("CP1140", "CP01140", false); + addMapping("CP1140", "IBM-1140", false); + addMapping("CP1140", "IBM01140", true); + addMapping("CP1141", "CCSID01141", false); + addMapping("CP1141", "CP01141", false); + addMapping("CP1141", "IBM-1141", false); + addMapping("CP1141", "IBM01141", true); + addMapping("CP1142", "CCSID01142", false); + addMapping("CP1142", "CP01142", false); + addMapping("CP1142", "IBM-1142", false); + addMapping("CP1142", "IBM01142", true); + addMapping("CP1143", "CCSID01143", false); + addMapping("CP1143", "CP01143", false); + addMapping("CP1143", "IBM-1143", false); + addMapping("CP1143", "IBM01143", true); + addMapping("CP1144", "CCSID01144", false); + addMapping("CP1144", "CP01144", false); + addMapping("CP1144", "IBM-1144", false); + addMapping("CP1144", "IBM01144", true); + addMapping("CP1145", "CCSID01145", false); + addMapping("CP1145", "CP01145", false); + addMapping("CP1145", "IBM-1145", false); + addMapping("CP1145", "IBM01145", true); + addMapping("CP1146", "CCSID01146", false); + addMapping("CP1146", "CP01146", false); + addMapping("CP1146", "IBM-1146", false); + addMapping("CP1146", "IBM01146", true); + addMapping("CP1147", "CCSID01147", false); + addMapping("CP1147", "CP01147", false); + addMapping("CP1147", "IBM-1147", false); + addMapping("CP1147", "IBM01147", true); + addMapping("CP1148", "CCSID01148", false); + addMapping("CP1148", "CP01148", false); + addMapping("CP1148", "IBM-1148", false); + addMapping("CP1148", "IBM01148", true); + addMapping("CP1149", "CCSID01149", false); + addMapping("CP1149", "CP01149", false); + addMapping("CP1149", "IBM-1149", false); + addMapping("CP1149", "IBM01149", true); + addMapping("CP1250", "WINDOWS-1250", true); + addMapping("CP1251", "WINDOWS-1251", true); + addMapping("CP1252", "WINDOWS-1252", true); + addMapping("CP1253", "WINDOWS-1253", true); + addMapping("CP1254", "WINDOWS-1254", true); + addMapping("CP1255", "WINDOWS-1255", true); + addMapping("CP1256", "WINDOWS-1256", true); + addMapping("CP1257", "WINDOWS-1257", true); + addMapping("CP1258", "WINDOWS-1258", true); + addMapping("CP273", "CP273", false); + addMapping("CP273", "CSIBM273", false); + addMapping("CP273", "IBM-273", false); + addMapping("CP273", "IBM273", true); + addMapping("CP277", "CP277", false); + addMapping("CP277", "CSIBM277", false); + addMapping("CP277", "EBCDIC-CP-DK", true); + addMapping("CP277", "EBCDIC-CP-NO", false); + addMapping("CP277", "IBM-277", false); + addMapping("CP277", "IBM277", false); + addMapping("CP278", "CP278", false); + addMapping("CP278", "CSIBM278", false); + addMapping("CP278", "EBCDIC-CP-FI", true); + addMapping("CP278", "EBCDIC-CP-SE", false); + addMapping("CP278", "IBM-278", false); + addMapping("CP278", "IBM278", false); + addMapping("CP280", "CP280", false); + addMapping("CP280", "CSIBM280", false); + addMapping("CP280", "EBCDIC-CP-IT", true); + addMapping("CP280", "IBM-280", false); + addMapping("CP280", "IBM280", false); + addMapping("CP284", "CP284", false); + addMapping("CP284", "CSIBM284", false); + addMapping("CP284", "EBCDIC-CP-ES", true); + addMapping("CP284", "IBM-284", false); + addMapping("CP284", "IBM284", false); + addMapping("CP285", "CP285", false); + addMapping("CP285", "CSIBM285", false); + addMapping("CP285", "EBCDIC-CP-GB", true); + addMapping("CP285", "IBM-285", false); + addMapping("CP285", "IBM285", false); + addMapping("CP290", "CP290", false); + addMapping("CP290", "CSIBM290", false); + addMapping("CP290", "EBCDIC-JP-KANA", true); + addMapping("CP290", "IBM-290", false); + addMapping("CP290", "IBM290", false); + addMapping("CP297", "CP297", false); + addMapping("CP297", "CSIBM297", false); + addMapping("CP297", "EBCDIC-CP-FR", true); + addMapping("CP297", "IBM-297", false); + addMapping("CP297", "IBM297", false); + addMapping("CP420", "CP420", false); + addMapping("CP420", "CSIBM420", false); + addMapping("CP420", "EBCDIC-CP-AR1", true); + addMapping("CP420", "IBM-420", false); + addMapping("CP420", "IBM420", false); + addMapping("CP424", "CP424", false); + addMapping("CP424", "CSIBM424", false); + addMapping("CP424", "EBCDIC-CP-HE", true); + addMapping("CP424", "IBM-424", false); + addMapping("CP424", "IBM424", false); + addMapping("CP437", "437", false); + addMapping("CP437", "CP437", false); + addMapping("CP437", "CSPC8CODEPAGE437", false); + addMapping("CP437", "IBM-437", false); + addMapping("CP437", "IBM437", true); + addMapping("CP500", "CP500", false); + addMapping("CP500", "CSIBM500", false); + addMapping("CP500", "EBCDIC-CP-BE", false); + addMapping("CP500", "EBCDIC-CP-CH", true); + addMapping("CP500", "IBM-500", false); + addMapping("CP500", "IBM500", false); + addMapping("CP775", "CP775", false); + addMapping("CP775", "CSPC775BALTIC", false); + addMapping("CP775", "IBM-775", false); + addMapping("CP775", "IBM775", true); + addMapping("CP850", "850", false); + addMapping("CP850", "CP850", false); + addMapping("CP850", "CSPC850MULTILINGUAL", false); + addMapping("CP850", "IBM-850", false); + addMapping("CP850", "IBM850", true); + addMapping("CP852", "852", false); + addMapping("CP852", "CP852", false); + addMapping("CP852", "CSPCP852", false); + addMapping("CP852", "IBM-852", false); + addMapping("CP852", "IBM852", true); + addMapping("CP855", "855", false); + addMapping("CP855", "CP855", false); + addMapping("CP855", "CSIBM855", false); + addMapping("CP855", "IBM-855", false); + addMapping("CP855", "IBM855", true); + addMapping("CP857", "857", false); + addMapping("CP857", "CP857", false); + addMapping("CP857", "CSIBM857", false); + addMapping("CP857", "IBM-857", false); + addMapping("CP857", "IBM857", true); + addMapping("CP858", "CCSID00858", false); + addMapping("CP858", "CP00858", false); + addMapping("CP858", "IBM-858", false); + addMapping("CP858", "IBM00858", true); + addMapping("CP860", "860", false); + addMapping("CP860", "CP860", false); + addMapping("CP860", "CSIBM860", false); + addMapping("CP860", "IBM-860", false); + addMapping("CP860", "IBM860", true); + addMapping("CP861", "861", false); + addMapping("CP861", "CP-IS", false); + addMapping("CP861", "CP861", false); + addMapping("CP861", "CSIBM861", false); + addMapping("CP861", "IBM-861", false); + addMapping("CP861", "IBM861", true); + addMapping("CP862", "862", false); + addMapping("CP862", "CP862", false); + addMapping("CP862", "CSPC862LATINHEBREW", false); + addMapping("CP862", "IBM-862", false); + addMapping("CP862", "IBM862", true); + addMapping("CP863", "863", false); + addMapping("CP863", "CP863", false); + addMapping("CP863", "CSIBM863", false); + addMapping("CP863", "IBM-863", false); + addMapping("CP863", "IBM863", true); + addMapping("CP864", "CP864", false); + addMapping("CP864", "CSIBM864", false); + addMapping("CP864", "IBM-864", false); + addMapping("CP864", "IBM864", true); + addMapping("CP865", "865", false); + addMapping("CP865", "CP865", false); + addMapping("CP865", "CSIBM865", false); + addMapping("CP865", "IBM-865", false); + addMapping("CP865", "IBM865", true); + addMapping("CP866", "866", false); + addMapping("CP866", "CP866", false); + addMapping("CP866", "CSIBM866", false); + addMapping("CP866", "IBM-866", false); + addMapping("CP866", "IBM866", true); + addMapping("CP868", "CP-AR", false); + addMapping("CP868", "CP868", false); + addMapping("CP868", "CSIBM868", false); + addMapping("CP868", "IBM-868", false); + addMapping("CP868", "IBM868", true); + addMapping("CP869", "CP-GR", false); + addMapping("CP869", "CP869", false); + addMapping("CP869", "CSIBM869", false); + addMapping("CP869", "IBM-869", false); + addMapping("CP869", "IBM869", true); + addMapping("CP870", "CP870", false); + addMapping("CP870", "CSIBM870", false); + addMapping("CP870", "EBCDIC-CP-ROECE", true); + addMapping("CP870", "EBCDIC-CP-YU", false); + addMapping("CP870", "IBM-870", false); + addMapping("CP870", "IBM870", false); + addMapping("CP871", "CP871", false); + addMapping("CP871", "CSIBM871", false); + addMapping("CP871", "EBCDIC-CP-IS", true); + addMapping("CP871", "IBM-871", false); + addMapping("CP871", "IBM871", false); + addMapping("CP918", "CP918", false); + addMapping("CP918", "CSIBM918", false); + addMapping("CP918", "EBCDIC-CP-AR2", true); + addMapping("CP918", "IBM-918", false); + addMapping("CP918", "IBM918", false); + addMapping("CP924", "CCSID00924", false); + addMapping("CP924", "CP00924", false); + addMapping("CP924", "EBCDIC-LATIN9--EURO", false); + addMapping("CP924", "IBM-924", false); + addMapping("CP924", "IBM00924", true); + addMapping("CP936", "GBK", true); + addMapping("CP936", "CP936", false); + addMapping("CP936", "MS936", false); + addMapping("CP936", "WINDOWS-936", false); + addMapping("EUCJIS", "CSEUCPKDFMTJAPANESE", false); + addMapping("EUCJIS", "EUC-JP", true); + addMapping("EUCJIS", "EXTENDED_UNIX_CODE_PACKED_FORMAT_FOR_JAPANESE", false); + addMapping("GB18030", "GB18030", true); + addMapping("GB2312", "CSGB2312", false); + addMapping("GB2312", "GB2312", true); + addMapping("ISO2022CN", "ISO-2022-CN", true); + addMapping("ISO2022KR", "CSISO2022KR", false); + addMapping("ISO2022KR", "ISO-2022-KR", true); + addMapping("ISO8859_1", "CP819", false); + addMapping("ISO8859_1", "CSISOLATIN1", false); + addMapping("ISO8859_1", "IBM-819", false); + addMapping("ISO8859_1", "IBM819", false); + addMapping("ISO8859_1", "ISO-8859-1", true); + addMapping("ISO8859_1", "ISO-IR-100", false); + addMapping("ISO8859_1", "ISO_8859-1", false); + addMapping("ISO8859_1", "L1", false); + addMapping("ISO8859_1", "LATIN1", false); + addMapping("ISO8859_2", "CSISOLATIN2", false); + addMapping("ISO8859_2", "ISO-8859-2", true); + addMapping("ISO8859_2", "ISO-IR-101", false); + addMapping("ISO8859_2", "ISO_8859-2", false); + addMapping("ISO8859_2", "L2", false); + addMapping("ISO8859_2", "LATIN2", false); + addMapping("ISO8859_3", "CSISOLATIN3", false); + addMapping("ISO8859_3", "ISO-8859-3", true); + addMapping("ISO8859_3", "ISO-IR-109", false); + addMapping("ISO8859_3", "ISO_8859-3", false); + addMapping("ISO8859_3", "L3", false); + addMapping("ISO8859_3", "LATIN3", false); + addMapping("ISO8859_4", "CSISOLATIN4", false); + addMapping("ISO8859_4", "ISO-8859-4", true); + addMapping("ISO8859_4", "ISO-IR-110", false); + addMapping("ISO8859_4", "ISO_8859-4", false); + addMapping("ISO8859_4", "L4", false); + addMapping("ISO8859_4", "LATIN4", false); + addMapping("ISO8859_5", "CSISOLATINCYRILLIC", false); + addMapping("ISO8859_5", "CYRILLIC", false); + addMapping("ISO8859_5", "ISO-8859-5", true); + addMapping("ISO8859_5", "ISO-IR-144", false); + addMapping("ISO8859_5", "ISO_8859-5", false); + addMapping("ISO8859_6", "ARABIC", false); + addMapping("ISO8859_6", "ASMO-708", false); + addMapping("ISO8859_6", "CSISOLATINARABIC", false); + addMapping("ISO8859_6", "ECMA-114", false); + addMapping("ISO8859_6", "ISO-8859-6", true); + addMapping("ISO8859_6", "ISO-IR-127", false); + addMapping("ISO8859_6", "ISO_8859-6", false); + addMapping("ISO8859_7", "CSISOLATINGREEK", false); + addMapping("ISO8859_7", "ECMA-118", false); + addMapping("ISO8859_7", "ELOT_928", false); + addMapping("ISO8859_7", "GREEK", false); + addMapping("ISO8859_7", "GREEK8", false); + addMapping("ISO8859_7", "ISO-8859-7", true); + addMapping("ISO8859_7", "ISO-IR-126", false); + addMapping("ISO8859_7", "ISO_8859-7", false); + addMapping("ISO8859_8", "CSISOLATINHEBREW", false); + addMapping("ISO8859_8", "HEBREW", false); + addMapping("ISO8859_8", "ISO-8859-8", true); + addMapping("ISO8859_8", "ISO-8859-8-I", false); + addMapping("ISO8859_8", "ISO-IR-138", false); + addMapping("ISO8859_8", "ISO_8859-8", false); + addMapping("ISO8859_9", "CSISOLATIN5", false); + addMapping("ISO8859_9", "ISO-8859-9", true); + addMapping("ISO8859_9", "ISO-IR-148", false); + addMapping("ISO8859_9", "ISO_8859-9", false); + addMapping("ISO8859_9", "L5", false); + addMapping("ISO8859_9", "LATIN5", false); + addMapping("JIS", "CSISO2022JP", false); + addMapping("JIS", "ISO-2022-JP", true); + addMapping("JIS0201", "CSISO13JISC6220JP", false); + addMapping("JIS0201", "X0201", true); + addMapping("JIS0208", "CSISO87JISX0208", false); + addMapping("JIS0208", "ISO-IR-87", false); + addMapping("JIS0208", "X0208", true); + addMapping("JIS0208", "X0208DBIJIS_X0208-1983", false); + addMapping("JIS0212", "CSISO159JISX02121990", false); + addMapping("JIS0212", "ISO-IR-159", true); + addMapping("JIS0212", "X0212", false); + addMapping("KOI8_R", "CSKOI8R", false); + addMapping("KOI8_R", "KOI8-R", true); + addMapping("KSC5601", "EUC-KR", true); + addMapping("MS932", "CSWINDOWS31J", false); + addMapping("MS932", "WINDOWS-31J", true); + addMapping("SJIS", "CSSHIFTJIS", false); + addMapping("SJIS", "MS_KANJI", false); + addMapping("SJIS", "SHIFT_JIS", true); + addMapping("TIS620", "TIS-620", true); + addMapping("UNICODE", "UTF-16", true); + addMapping("UTF-16BE", "UTF-16BE", true); + addMapping("UTF-16BE", "UTF_16BE", false); + addMapping("ISO-10646-UCS-2", "ISO-10646-UCS-2", true); + addMapping("UTF-16LE", "UTF-16LE", true); + addMapping("UTF-16LE", "UTF_16LE", false); + addMapping("UTF8", "UTF-8", true); + + assert completeMappings(); + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/GlobalLock.java b/src/main/java/org/apache/xmlbeans/impl/common/GlobalLock.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/GlobalLock.java rename to src/main/java/org/apache/xmlbeans/impl/common/GlobalLock.java diff --git a/src/common/org/apache/xmlbeans/impl/common/IOUtil.java b/src/main/java/org/apache/xmlbeans/impl/common/IOUtil.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/IOUtil.java rename to src/main/java/org/apache/xmlbeans/impl/common/IOUtil.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java b/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java new file mode 100644 index 0000000..55242e6 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java @@ -0,0 +1,664 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.ValidatorListener.Event; +import org.apache.xmlbeans.impl.xpath.XPath; +import org.apache.xmlbeans.impl.xpath.XPathExecutionContext; + +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import java.util.*; + +/** + * Identity constraint engine. Performs streaming validation of identity constraints. + * This includes key, keyref, & unique, as well as ID & IDRef. + */ +public class IdentityConstraint { + + private ConstraintState _constraintStack; + private ElementState _elementStack; + private Collection _errorListener; + private boolean _invalid; + private boolean _trackIdrefs; // We only track idrefs if validating from the root element + + public IdentityConstraint(Collection errorListener, boolean trackIdrefs) { + _errorListener = errorListener; + _trackIdrefs = trackIdrefs; + } + + public void element(Event e, SchemaType st, SchemaIdentityConstraint[] ics) { + + // Construct a new state for the element + newState(); + + // First dispatch this element event + for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) { + cs.element(e, st); + } + + // Create a new SelectorState for each new Identity Constraint + + for (int i = 0; ics != null && i < ics.length; i++) { + newConstraintState(ics[i], e, st); + } + } + + public void endElement(Event e) { + // Pop the element state stack and any constraints at this depth + if (_elementStack._hasConstraints) { + for (ConstraintState cs = _constraintStack; cs != null && cs != _elementStack._savePoint; cs = cs._next) { + cs.remove(e); + } + + _constraintStack = _elementStack._savePoint; + } + + _elementStack = _elementStack._next; + + // Dispatch the event + for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) { + cs.endElement(e); + } + + } + + public void attr(Event e, QName name, SchemaType st, String value) { + for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) { + cs.attr(e, name, st, value); + } + } + + public void text(Event e, SchemaType st, String value, boolean emptyContent) { + for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) { + cs.text(e, st, value, emptyContent); + } + } + + public boolean isValid() { + return !_invalid; + } + + private void newConstraintState(SchemaIdentityConstraint ic, Event e, SchemaType st) { + if (ic.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) { + new KeyrefState(ic, e, st); + } else { + new SelectorState(ic, e, st); + } + } + + private void buildIdStates() { + // Construct states to hold the values for IDs and IDRefs + IdState ids = new IdState(); + if (_trackIdrefs) { + new IdRefState(ids); + } + } + + private void newState() { + boolean firstTime = _elementStack == null; + + ElementState st = new ElementState(); + st._next = _elementStack; + _elementStack = st; + + if (firstTime) { + buildIdStates(); + } + } + + private void emitError(Event event, String code, Object[] args) { + _invalid = true; + + if (_errorListener != null) { + assert event != null; + + _errorListener.add(errorForEvent(code, args, XmlError.SEVERITY_ERROR, event)); + } + } + + public static XmlError errorForEvent(String code, Object[] args, int severity, Event event) { + XmlCursor loc = event.getLocationAsCursor(); + XmlError error; + if (loc != null) { + error = XmlError.forCursor(code, args, severity, loc); + } else { + Location location = event.getLocation(); + if (location != null) { + error = XmlError.forLocation(code, args, severity, + location.getSystemId(), location.getLineNumber(), + location.getColumnNumber(), location.getCharacterOffset()); + } else { + error = XmlError.forMessage(code, args, severity); + } + } + return error; + } + + private void emitError(Event event, String msg) { + _invalid = true; + + if (_errorListener != null) { + assert event != null; + + _errorListener.add(errorForEvent(msg, XmlError.SEVERITY_ERROR, event)); + } + } + + public static XmlError errorForEvent(String msg, int severity, Event event) { + XmlCursor loc = event.getLocationAsCursor(); + XmlError error; + if (loc != null) { + error = XmlError.forCursor(msg, severity, loc); + } else { + Location location = event.getLocation(); + if (location != null) { + error = XmlError.forLocation(msg, severity, + location.getSystemId(), location.getLineNumber(), + location.getColumnNumber(), location.getCharacterOffset()); + } else { + error = XmlError.forMessage(msg, severity); + } + } + return error; + } + + private void setSavePoint(ConstraintState cs) { + if (!_elementStack._hasConstraints) { + _elementStack._savePoint = cs; + } + + _elementStack._hasConstraints = true; + } + + private static XmlObject newValue(SchemaType st, String value) { + try { + return st.newValue(value); + } catch (IllegalArgumentException e) { + // This is a bit hacky. newValue throws XmlValueOutOfRangeException which is + // unchecked and declared in typeimpl. I can only catch its parent class, + // typeimpl is built after common. + + // Ignore these exceptions. Assume that validation will catch them. + return null; + } + } + + /** + * Return the simple type for schema type. If the schema type is already + * simple, just return it. If it is a complex type with simple content, + * return the simple type it extends. + */ + static SchemaType getSimpleType(SchemaType st) { + assert st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT : + st + " does not have simple content."; + + while (!st.isSimpleType()) { + st = st.getBaseType(); + } + + return st; + } + + static boolean hasSimpleContent(SchemaType st) { + return st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT; + } + + public abstract class ConstraintState { + ConstraintState _next; + + ConstraintState() { + setSavePoint(_constraintStack); + _next = _constraintStack; + _constraintStack = this; + } + + abstract void element(Event e, SchemaType st); + + abstract void endElement(Event e); + + abstract void attr(Event e, QName name, SchemaType st, String value); + + abstract void text(Event e, SchemaType st, String value, boolean emptyContent); + + abstract void remove(Event e); + + } + + public class SelectorState extends ConstraintState { + SchemaIdentityConstraint _constraint; + Set _values = new LinkedHashSet(); + XPathExecutionContext _context; + + SelectorState(SchemaIdentityConstraint constraint, Event e, SchemaType st) { + _constraint = constraint; + _context = new XPathExecutionContext(); + _context.init((XPath) _constraint.getSelectorPath()); + + if ((_context.start() & XPathExecutionContext.HIT) != 0) { + createFieldState(e, st); + } + } + + void addFields(XmlObjectList fields, Event e) { + if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) { + _values.add(fields); + } else if (_values.contains(fields)) { + if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_UNIQUE) { + emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_UNIQUE, + new Object[]{fields, QNameHelper.pretty(_constraint.getName())}); + } else { + emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_KEY, + new Object[]{fields, QNameHelper.pretty(_constraint.getName())}); + } + } else { + _values.add(fields); + } + } + + void element(Event e, SchemaType st) { + if ((_context.element(e.getName()) & XPathExecutionContext.HIT) != 0) { + createFieldState(e, st); + } + } + + void endElement(Event e) { + _context.end(); + } + + void createFieldState(Event e, SchemaType st) { + new FieldState(this, e, st); + } + + void remove(Event e) { + // Bubble up key, unique values to keyrefs + for (ConstraintState cs = _next; cs != null; cs = cs._next) { + if (cs instanceof KeyrefState) { + KeyrefState kr = (KeyrefState) cs; + if (kr._constraint.getReferencedKey() == this._constraint) { + kr.addKeyValues(_values, true); + } + } + } + } + + void attr(Event e, QName name, SchemaType st, String value) { + } + + void text(Event e, SchemaType st, String value, boolean emptyContent) { + } + } + + public class KeyrefState extends SelectorState { + Map _keyValues = new HashMap(); + private Object CHILD_ADDED = new Object(); + private Object CHILD_REMOVED = new Object(); + private Object SELF_ADDED = new Object(); + + KeyrefState(SchemaIdentityConstraint constraint, Event e, SchemaType st) { + super(constraint, e, st); + } + + void addKeyValues(final Set values, boolean child) { + /** If the key values are added by children, then if two or + more children add the same value, the value dissapears from the map + but if is added by the element in question directly then it will + be present in the map regardless of what children contained */ + for (Iterator it = values.iterator(); it.hasNext(); ) { + Object key = it.next(); + Object value = _keyValues.get(key); + if (value == null) { + _keyValues.put(key, child ? CHILD_ADDED : SELF_ADDED); + } else if (value == CHILD_ADDED) { + if (child) { + _keyValues.put(key, CHILD_REMOVED); + } else { + _keyValues.put(key, SELF_ADDED); + } + } else if (value == CHILD_REMOVED) { + if (!child) { + _keyValues.put(key, SELF_ADDED); + } + } + } + } + + private boolean hasKeyValue(Object key) { + Object value = _keyValues.get(key); + return value != null && value != CHILD_REMOVED; + } + + void remove(Event e) { + // First check if there are any keys at the same stack level as this + // that may contribute key values to me + for (ConstraintState cs = _next; cs != null && cs != _elementStack._savePoint; cs = cs._next) { + if (cs instanceof SelectorState) { + SelectorState sel = (SelectorState) cs; + if (sel._constraint == _constraint.getReferencedKey()) { + addKeyValues(sel._values, false); + } + } + } + + + // validate all values have been seen + for (Iterator it = _values.iterator(); it.hasNext(); ) { + + XmlObjectList fields = (XmlObjectList) it.next(); + if (fields.unfilled() < 0 && !hasKeyValue(fields)) { + // KHK: cvc-identity-constraint.4.3 ? + emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$KEYREF_KEY_NOT_FOUND, + new Object[]{fields, QNameHelper.pretty(_constraint.getName())}); + return; + } + } + } + } + + public class FieldState extends ConstraintState { + SelectorState _selector; + XPathExecutionContext[] _contexts; + boolean[] _needsValue; + XmlObjectList _value; + + FieldState(SelectorState selector, Event e, SchemaType st) { + + // System.out.println("Creating new Field State for: " + e.getName()); + + _selector = selector; + SchemaIdentityConstraint ic = selector._constraint; + + int fieldCount = ic.getFields().length; + _contexts = new XPathExecutionContext[fieldCount]; + _needsValue = new boolean[fieldCount]; + _value = new XmlObjectList(fieldCount); + + for (int i = 0; i < fieldCount; i++) { + _contexts[i] = new XPathExecutionContext(); + _contexts[i].init((XPath) ic.getFieldPath(i)); + if ((_contexts[i].start() & XPathExecutionContext.HIT) != 0) { + // System.out.println("hit for element: " + e.getName()); + + if (!hasSimpleContent(st)) + // KHK: cvc-identity-constraint.3 + { + emitError(e, "Identity constraint field must have simple content"); + } else { + _needsValue[i] = true; + } + } + } + + } + + void element(Event e, SchemaType st) { + for (int i = 0; i < _contexts.length; i++) { + if (_needsValue[i]) { + // KHK: cvc-identity-constraint.3 + emitError(e, "Identity constraint field must have simple content"); + _needsValue[i] = false; + } + } + + for (int i = 0; i < _contexts.length; i++) { + if ((_contexts[i].element(e.getName()) & XPathExecutionContext.HIT) != 0) { + if (!hasSimpleContent(st)) { + // KHK: cvc-identity-constraint.3 + emitError(e, "Identity constraint field must have simple content"); + } else { + _needsValue[i] = true; + } + } + } + } + + void attr(Event e, QName name, SchemaType st, String value) { + + // Null value indicates previously reported validation problem + if (value == null) { + return; + } + + for (int i = 0; i < _contexts.length; i++) { + if (_contexts[i].attr(name)) { + XmlObject o = newValue(st, value); + + // Ignore invalid values. Assume that validation catches these + if (o == null) { + return; + } + + boolean set = _value.set(o, i); + + // KHK: ? + if (!set) { + emitError(e, "Multiple instances of field with xpath: '" + + _selector._constraint.getFields()[i] + "' for a selector"); + } + } + + } + } + + + void text(Event e, SchemaType st, String value, boolean emptyContent) { + + // Null value indicates previously reported validation problem + if (value == null && !emptyContent) { + return; + } + + for (int i = 0; i < _contexts.length; i++) { + if (_needsValue[i]) { + + if (emptyContent || !hasSimpleContent(st)) { + // KHK: cvc-identity-constraint.3 + emitError(e, "Identity constraint field must have simple content"); + return; + } + + SchemaType simpleType = getSimpleType(st); + XmlObject o = newValue(simpleType, value); + + // Ignore invalid values. Assume that validation catches these + if (o == null) { + return; + } + + boolean set = _value.set(o, i); + + // KHK: ? + if (!set) { + emitError(e, "Multiple instances of field with xpath: '" + + _selector._constraint.getFields()[i] + "' for a selector"); + } + } + } + } + + void endElement(Event e) { + // reset any _needsValue flags + // assume that if we didn't see the text, it was because of another validation + // error, so don't emit another one. + for (int i = 0; i < _needsValue.length; i++) { + _contexts[i].end(); + _needsValue[i] = false; + } + + } + + void remove(Event e) { + + if (_selector._constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEY && + _value.unfilled() >= 0) { + // KHK: cvc-identity-constraint.4.2.1 ? + // keys must have all values supplied + emitError(e, "Key " + QNameHelper.pretty(_selector._constraint.getName()) + " is missing field with xpath: '" + _selector._constraint.getFields()[_value.unfilled()] + "'"); + } else { + // Finished. Add these fields to the selector state + _selector.addFields(_value, e); + } + } + + } + + public class IdState extends ConstraintState { + Set _values = new LinkedHashSet(); + + IdState() { + } + + void attr(Event e, QName name, SchemaType st, String value) { + handleValue(e, st, value); + } + + void text(Event e, SchemaType st, String value, boolean emptyContent) { + if (emptyContent) { + return; + } + + handleValue(e, st, value); + } + + private void handleValue(Event e, SchemaType st, String value) { + + // Null value indicates previously reported validation problem + if (value == null) { + return; + } + + if (st == null || st.isNoType()) { + // ignore invalid values. Assume that validation catches these + return; + } + + if (XmlID.type.isAssignableFrom(st)) { + XmlObjectList xmlValue = new XmlObjectList(1); + XmlObject o = newValue(XmlID.type, value); + + // Ignore invalid values. Assume that validation catches these + if (o == null) { + return; + } + + xmlValue.set(o, 0); + + if (_values.contains(xmlValue)) { + emitError(e, XmlErrorCodes.ID_VALID$DUPLICATE, new Object[]{value}); + } else { + _values.add(xmlValue); + } + } + } + + void element(Event e, SchemaType st) { + } + + void endElement(Event e) { + } + + void remove(Event e) { + } + + } + + public class IdRefState extends ConstraintState { + IdState _ids; + List _values; + + IdRefState(IdState ids) { + _ids = ids; + _values = new ArrayList(); + } + + private void handleValue(Event e, SchemaType st, String value) { + // Null value indicates previously reported validation problem + if (value == null) { + return; + } + + if (st == null || st.isNoType()) { + // ignore invalid values. Assume that validation catches these + return; + } + if (XmlIDREFS.type.isAssignableFrom(st)) { + XmlIDREFS lv = (XmlIDREFS) newValue(XmlIDREFS.type, value); + + // Ignore invalid values. Assume that validation catches these + if (lv == null) { + return; + } + + List l = lv.xgetListValue(); + + // Add one value for each idref in the list + for (int i = 0; i < l.size(); i++) { + XmlObjectList xmlValue = new XmlObjectList(1); + XmlIDREF idref = (XmlIDREF) l.get(i); + xmlValue.set(idref, 0); + _values.add(xmlValue); + } + } else if (XmlIDREF.type.isAssignableFrom(st)) { + XmlObjectList xmlValue = new XmlObjectList(1); + XmlIDREF idref = (XmlIDREF) st.newValue(value); + + // Ignore invalid values. Assume that validation catches these + if (idref == null) { + return; + } + + xmlValue.set(idref, 0); + _values.add(xmlValue); + } + } + + void attr(Event e, QName name, SchemaType st, String value) { + handleValue(e, st, value); + } + + void text(Event e, SchemaType st, String value, boolean emptyContent) { + if (emptyContent) { + return; + } + + handleValue(e, st, value); + } + + void remove(Event e) { + // Validate each ref has a corresponding ID + for (Iterator it = _values.iterator(); it.hasNext(); ) { + Object o = it.next(); + if (!_ids._values.contains(o)) { + // KHK: cvc-id.1 + emitError(e, "ID not found for IDRef value '" + o + "'"); + } + } + } + + void element(Event e, SchemaType st) { + } + + void endElement(Event e) { + } + } + + private static class ElementState { + ElementState _next; + boolean _hasConstraints; + ConstraintState _savePoint; + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/InvalidLexicalValueException.java b/src/main/java/org/apache/xmlbeans/impl/common/InvalidLexicalValueException.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/InvalidLexicalValueException.java rename to src/main/java/org/apache/xmlbeans/impl/common/InvalidLexicalValueException.java diff --git a/src/common/org/apache/xmlbeans/impl/common/JarHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/JarHelper.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/JarHelper.java rename to src/main/java/org/apache/xmlbeans/impl/common/JarHelper.java diff --git a/src/common/org/apache/xmlbeans/impl/common/Levenshtein.java b/src/main/java/org/apache/xmlbeans/impl/common/Levenshtein.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/Levenshtein.java rename to src/main/java/org/apache/xmlbeans/impl/common/Levenshtein.java diff --git a/src/common/org/apache/xmlbeans/impl/common/LoadSaveUtils.java b/src/main/java/org/apache/xmlbeans/impl/common/LoadSaveUtils.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/LoadSaveUtils.java rename to src/main/java/org/apache/xmlbeans/impl/common/LoadSaveUtils.java diff --git a/src/common/org/apache/xmlbeans/impl/common/Mutex.java b/src/main/java/org/apache/xmlbeans/impl/common/Mutex.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/Mutex.java rename to src/main/java/org/apache/xmlbeans/impl/common/Mutex.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java b/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java new file mode 100644 index 0000000..c0e7c8a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java @@ -0,0 +1,777 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import javax.xml.namespace.QName; +import java.util.*; + +public class NameUtil { + // punctuation characters + public final static char HYPHEN = '\u002D'; + public final static char PERIOD = '\u002E'; + public final static char COLON = '\u003A'; + public final static char USCORE = '\u005F'; + public final static char DOT = '\u00B7'; + public final static char TELEIA = '\u0387'; + public final static char AYAH = '\u06DD'; + public final static char ELHIZB = '\u06DE'; + + private final static Set javaWords = new HashSet<>(Arrays.asList( + "assert", + "abstract", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "default", + "do", + "double", + "else", + "enum", // since JDK1.5 + "extends", + "false", // not a keyword + "final", + "finally", + "float", + "for", + "goto", + "if", + "implements", + "import", + "instanceof", + "int", + "interface", + "long", + "native", + "new", + "null", // not a keyword + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "strictfp", + "super", + "switch", + "synchronized", + "this", + "threadsafe", + "throw", + "throws", + "transient", + "true", // not a keyword + "try", + "void", + "volatile", + "while")); + + private final static Set extraWords = new HashSet<>(Arrays.asList( + "i", // used for indexes + "target", // used for parameter + "org", // used for package names + "com" // used for package names + )); + + /* + private final static Set javaNames = new HashSet(Arrays.asList( + new String[] + { + "CharSequence", + "Cloneable", + "Comparable", + "Runnable", + + "Boolean", + "Byte", + "Character", + "Class", + "ClassLoader", + "Compiler", + "Double", + "Float", + "InheritableThreadLocal", + "Integer", + "Long", + "Math", + "Number", + "Object", + "Package", + "Process", + "Runtime", + "RuntimePermission", + "SecurityManager", + "Short", + "StackTraceElement", + "StrictMath", + "String", + "StringBuffer", + "System", + "Thread", + "ThreadGroup", + "ThreadLocal", + "Throwable", + "Void", + + "ArithmeticException", + "ArrayIndexOutOfBoundsException", + "ArrayStoreException", + "ClassCastException", + "ClassNotFoundException", + "CloneNotSupportedException", + "Exception", + "IllegalAccessException", + "IllegalArgumentException", + "IllegalMonitorStateException", + "IllegalStateException", + "IllegalThreadStateException", + "IndexOutOfBoundsException", + "InstantiationException", + "InterruptedException", + "NegativeArraySizeException", + "NoSuchFieldException", + "NoSuchMethodException", + "NullPointerException", + "NumberFormatException", + "RuntimeException", + "SecurityException", + "StringIndexOutOfBoundsException", + "UnsupportedOperationException", + + "AbstractMethodError", + "AssertionError", + "ClassCircularityError", + "ClassFormatError", + "Error", + "ExceptionInInitializerError", + "IllegalAccessError", + "IncompatibleClassChangeError", + "InstantiationError", + "InternalError", + "LinkageError", + "NoClassDefFoundError", + "NoSuchFieldError", + "NoSuchMethodError", + "OutOfMemoryError", + "StackOverflowError", + "ThreadDeath", + "UnknownError", + "UnsatisfiedLinkError", + "UnsupportedClassVersionError", + "VerifyError", + "VirtualMachineError", + } + )); + */ + + private final static Set javaNames = new HashSet<>(Arrays.asList( + // 1. all the Java.lang classes [1.4.1 JDK]. + "CharSequence", + "Cloneable", + "Comparable", + "Runnable", + + "Boolean", + "Byte", + "Character", + "Class", + "ClassLoader", + "Compiler", + "Double", + "Float", + "InheritableThreadLocal", + "Integer", + "Long", + "Math", + "Number", + "Object", + "Package", + "Process", + "Runtime", + "RuntimePermission", + "SecurityManager", + "Short", + "StackTraceElement", + "StrictMath", + "String", + "StringBuffer", + "System", + "Thread", + "ThreadGroup", + "ThreadLocal", + "Throwable", + "Void", + + "ArithmeticException", + "ArrayIndexOutOfBoundsException", + "ArrayStoreException", + "ClassCastException", + "ClassNotFoundException", + "CloneNotSupportedException", + "Exception", + "IllegalAccessException", + "IllegalArgumentException", + "IllegalMonitorStateException", + "IllegalStateException", + "IllegalThreadStateException", + "IndexOutOfBoundsException", + "InstantiationException", + "InterruptedException", + "NegativeArraySizeException", + "NoSuchFieldException", + "NoSuchMethodException", + "NullPointerException", + "NumberFormatException", + "RuntimeException", + "SecurityException", + "StringIndexOutOfBoundsException", + "UnsupportedOperationException", + + "AbstractMethodError", + "AssertionError", + "ClassCircularityError", + "ClassFormatError", + "Error", + "ExceptionInInitializerError", + "IllegalAccessError", + "IncompatibleClassChangeError", + "InstantiationError", + "InternalError", + "LinkageError", + "NoClassDefFoundError", + "NoSuchFieldError", + "NoSuchMethodError", + "OutOfMemoryError", + "StackOverflowError", + "ThreadDeath", + "UnknownError", + "UnsatisfiedLinkError", + "UnsupportedClassVersionError", + "VerifyError", + "VirtualMachineError", + + // 2. other classes used as primitive types by xml beans + "BigInteger", + "BigDecimal", + "Enum", + "Date", + "GDate", + "GDuration", + "QName", + "List", + + // 3. the top few org.apache.xmlbeans names + "XmlObject", + "XmlCursor", + "XmlBeans", + "SchemaType")); + + public static boolean isValidJavaIdentifier(String id) { + if (id == null) { + throw new IllegalArgumentException("id cannot be null"); + } + + int len = id.length(); + if (len == 0) { + return false; + } + + if (javaWords.contains(id)) { + return false; + } + + if (!Character.isJavaIdentifierStart(id.charAt(0))) { + return false; + } + + for (int i = 1; i < len; i++) { + if (!Character.isJavaIdentifierPart(id.charAt(i))) { + return false; + } + } + + return true; + } + + public static String getClassNameFromQName(QName qname) { + return getClassNameFromQName(qname, false); + } + + public static String getClassNameFromQName(QName qname, boolean useJaxRpcRules) { + String java_type = upperCamelCase(qname.getLocalPart(), useJaxRpcRules); + + String uri = qname.getNamespaceURI(); + + String java_pkg = getPackageFromNamespace(uri, useJaxRpcRules); + + if (java_pkg != null) { + return java_pkg + "." + java_type; + } else { + return java_type; + } + } + + private static final String JAVA_NS_PREFIX = "java:"; + + public static String getNamespaceFromPackage(final Class clazz) { + Class curr_clazz = clazz; + + while (curr_clazz.isArray()) { + curr_clazz = curr_clazz.getComponentType(); + } + + String fullname = clazz.getName(); + int lastdot = fullname.lastIndexOf('.'); + String pkg_name = lastdot < 0 ? "" : fullname.substring(0, lastdot); + + //special case for builtin types + /* + if (curr_clazz.isPrimitive()) + { + pkg_name = c.getJavaLanguageNamespaceUri(); + } + else if (pkg_name.startsWith(LANG_PREFIX)) + { + final String rem_str = pkg_name.substring(LANG_PREFIX.length()); + pkg_name = c.getJavaLanguageNamespaceUri() + "." + rem_str; + } + */ + return JAVA_NS_PREFIX + pkg_name; + } + + private static boolean isUriSchemeChar(char ch) { + return (ch >= 'a' && ch <= 'z' || + ch >= 'A' && ch <= 'Z' || + ch >= '0' && ch <= '9' || + ch == '-' || ch == '.' || ch == '+'); + } + + private static boolean isUriAlphaChar(char ch) { + return (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'); + } + + private static int findSchemeColon(String uri) { + int len = uri.length(); + if (len == 0) { + return -1; + } + if (!isUriAlphaChar(uri.charAt(0))) { + return -1; + } + int i; + for (i = 1; i < len; i++) { + if (!isUriSchemeChar(uri.charAt(i))) { + break; + } + } + if (i == len) { + return -1; + } + if (uri.charAt(i) != ':') { + return -1; + } + // consume consecutive colons + for (; i < len; i++) { + if (uri.charAt(i) != ':') { + break; + } + } + // for the "scheme:::" case, return len-1 + return i - 1; + } + + private static String jls77String(String name) { + StringBuilder buf = new StringBuilder(name); + for (int i = 0; i < name.length(); i++) { + // We need to also make sure that our package names don't contain the + // "$" character in them, which, although a valid Java identifier part, + // would create confusion when trying to generate fully-qualified names + if (!Character.isJavaIdentifierPart(buf.charAt(i)) || '$' == buf.charAt(i)) { + buf.setCharAt(i, '_'); + } + } + if (buf.length() == 0 || !Character.isJavaIdentifierStart(buf.charAt(0))) { + buf.insert(0, '_'); + } + if (isJavaReservedWord(name)) { + buf.append('_'); + } + return buf.toString(); + } + + private static List splitDNS(String dns) { + // JAXB says: only split+reverse DNS if TLD matches known TLDs or ISO 3166 + // We are ignoring this now (TH) + + List result = new ArrayList<>(); + + int end = dns.length(); + int begin = dns.lastIndexOf('.'); + for (; begin != -1; begin--) { + if (dns.charAt(begin) == '.') { + result.add(jls77String(dns.substring(begin + 1, end))); + end = begin; + } + } + result.add(jls77String(dns.substring(0, end))); + + // JAXB draft example implies removal of www + if (result.size() >= 3 && + result.get(result.size() - 1).toLowerCase(Locale.ROOT).equals("www")) { + result.remove(result.size() - 1); + } + + return result; + } + + private static String processFilename(String filename) { + // JAXB says: strip 2 or 3 letter extension or ".html" + + int i = filename.lastIndexOf('.'); + if (i > 0 && ( + i + 1 + 2 == filename.length() || + i + 1 + 3 == filename.length() || + "html".equals(filename.substring(i + 1).toLowerCase(Locale.ROOT)))) { + return filename.substring(0, i); + } + + return filename; + } + + public static String getPackageFromNamespace(String uri) { + return getPackageFromNamespace(uri, false); + } + + public static String getPackageFromNamespace(String uri, boolean useJaxRpcRules) { + // special case: no namespace -> package "noNamespace" + if (uri == null || uri.length() == 0) { + return "noNamespace"; + } + + // apply draft JAXB rules + int len = uri.length(); + int i = findSchemeColon(uri); + List result; + + if (i == len - 1) { + // XMLBEANS-57: colon is at end so just use scheme as the package name + result = new ArrayList<>(); + result.add(uri.substring(0, i)); + } else if (i >= 0 && uri.substring(0, i).equals("java")) { + result = Arrays.asList(uri.substring(i + 1).split("\\.")); + } else { + result = new ArrayList<>(); + outer: + for (i = i + 1; i < len; ) { + while (uri.charAt(i) == '/') { + if (++i >= len) { + break outer; + } + } + int start = i; + while (uri.charAt(i) != '/') { + if (++i >= len) { + break; + } + } + int end = i; + result.add(uri.substring(start, end)); + } + if (result.size() > 1) { + result.set(result.size() - 1, processFilename(result.get(result.size() - 1))); + } + + if (result.size() > 0) { + List splitdns = splitDNS(result.get(0)); + result.remove(0); + result.addAll(0, splitdns); + } + } + + StringBuilder buf = new StringBuilder(); + for (String s : result) { + String part = nonJavaKeyword(lowerCamelCase(s, useJaxRpcRules, true)); + if (part.length() > 0) { + buf.append(part); + buf.append('.'); + } + } + if (buf.length() == 0) { + return "noNamespace"; + } + if (useJaxRpcRules) { + return buf.substring(0, buf.length() - 1).toLowerCase(Locale.ROOT); + } + return buf.substring(0, buf.length() - 1); // chop off extra dot + } + + public static void main(String[] args) { + for (String arg : args) { + System.out.println(upperCaseUnderbar(arg)); + } + } + + /** + * Returns a upper-case-and-underbar string using the JAXB rules. + * Always starts with a capital letter that is a valid + * java identifier start. (If JAXB rules don't produce + * one, then "X_" is prepended.) + */ + public static String upperCaseUnderbar(String xml_name) { + StringBuilder buf = new StringBuilder(); + List words = splitWords(xml_name, false); + + final int sz = words.size() - 1; + if (sz >= 0 && !Character.isJavaIdentifierStart(words.get(0).charAt(0))) { + buf.append("X_"); + } + + for (int i = 0; i < sz; i++) { + buf.append(words.get(i)); + buf.append(USCORE); + } + + if (sz >= 0) { + buf.append(words.get(sz)); + } + + //upcase entire buffer + final int len = buf.length(); + for (int j = 0; j < len; j++) { + char c = buf.charAt(j); + buf.setCharAt(j, Character.toUpperCase(c)); + } + + return buf.toString(); + } + + /** + * Returns a camel-cased string using the JAXB rules. + * Always starts with a capital letter that is a valid + * java identifier start. (If JAXB rules don't produce + * one, then "X" is prepended.) + */ + public static String upperCamelCase(String xml_name) { + return upperCamelCase(xml_name, false); + } + + /** + * Returns a camel-cased string, but either JAXB or JAX-RPC rules + * are used + */ + public static String upperCamelCase(String xml_name, boolean useJaxRpcRules) { + StringBuilder buf = new StringBuilder(); + List words = splitWords(xml_name, useJaxRpcRules); + + if (words.size() > 0) { + if (!Character.isJavaIdentifierStart(words.get(0).charAt(0))) { + buf.append("X"); + } + + for (String word : words) { + buf.append(word); + } + } + return buf.toString(); + } + + /** + * Returns a camel-cased string using the JAXB rules, + * where the first component is lowercased. Note that + * if the first component is an acronym, the whole + * thigns gets lowercased. + * Always starts with a lowercase letter that is a valid + * java identifier start. (If JAXB rules don't produce + * one, then "x" is prepended.) + */ + public static String lowerCamelCase(String xml_name) { + return lowerCamelCase(xml_name, false, true); + } + + /** + * Returns a camel-cased string using the JAXB or JAX-RPC rules + */ + public static String lowerCamelCase(String xml_name, boolean useJaxRpcRules, + boolean fixGeneratedName) { + StringBuilder buf = new StringBuilder(); + List words = splitWords(xml_name, useJaxRpcRules); + + if (words.size() > 0) { + String first = words.get(0).toLowerCase(Locale.ROOT); + char f = first.charAt(0); + if (!Character.isJavaIdentifierStart(f) && fixGeneratedName) { + buf.append("x"); + } + buf.append(first); + + Iterator itr = words.iterator(); + itr.next(); // skip already-lowercased word + while (itr.hasNext()) { + buf.append(itr.next()); + } + } + return buf.toString(); + } + + public static String upperCaseFirstLetter(String s) { + if (s.length() == 0 || Character.isUpperCase(s.charAt(0))) { + return s; + } + + StringBuilder buf = new StringBuilder(s); + buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); + return buf.toString(); + } + + + /** + * split an xml name into words via JAXB approach, upcasing first + * letter of each word as needed, if upcase is true + *

      + * ncname is xml ncname (i.e. no colons). + */ + private static void addCapped(List list, String str) { + if (str.length() > 0) { + list.add(upperCaseFirstLetter(str)); + } + } + + public static List splitWords(String name, boolean useJaxRpcRules) { + List list = new ArrayList<>(); + int len = name.length(); + int start = 0; + int prefix = START; + for (int i = 0; i < len; i++) { + int current = getCharClass(name.charAt(i), useJaxRpcRules); + if (prefix != PUNCT && current == PUNCT) { + addCapped(list, name.substring(start, i)); + while ((current = getCharClass(name.charAt(i), useJaxRpcRules)) == PUNCT) { + if (++i >= len) { + return list; + } + } + start = i; + } else if ((prefix == DIGIT) != (current == DIGIT) || + (prefix == LOWER && current != LOWER) || + (isLetter(prefix) != isLetter(current))) { + addCapped(list, name.substring(start, i)); + start = i; + } else if (prefix == UPPER && current == LOWER && i > start + 1) { + addCapped(list, name.substring(start, i - 1)); + start = i - 1; + } + prefix = current; + } + addCapped(list, name.substring(start)); + return list; + } + + //char classes + private final static int START = 0; + private final static int PUNCT = 1; + private final static int DIGIT = 2; + private final static int MARK = 3; + private final static int UPPER = 4; + private final static int LOWER = 5; + private final static int NOCASE = 6; + + public static int getCharClass(char c, boolean useJaxRpcRules) { + //ordering is important here. + if (isPunctuation(c, useJaxRpcRules)) { + return PUNCT; + } else if (Character.isDigit(c)) { + return DIGIT; + } else if (Character.isUpperCase(c)) { + return UPPER; + } else if (Character.isLowerCase(c)) { + return LOWER; + } else if (Character.isLetter(c)) { + return NOCASE; + } else if (Character.isJavaIdentifierPart(c)) { + return MARK; + } else { + return PUNCT; // not covered by JAXB: treat it as punctuation + } + } + + private static boolean isLetter(int state) { + return (state == UPPER + || state == LOWER + || state == NOCASE); + } + + public static boolean isPunctuation(char c, boolean useJaxRpcRules) { + return (c == HYPHEN + || c == PERIOD + || c == COLON + || c == DOT + || (c == USCORE && !useJaxRpcRules) + || c == TELEIA + || c == AYAH + || c == ELHIZB); + } + + /** + * Intended to be applied to a lowercase-starting identifier that + * may collide with a Java keyword. If it does collide, this + * prepends the letter "x". + */ + public static String nonJavaKeyword(String word) { + if (isJavaReservedWord(word)) { + return 'x' + word; + } + return word; + } + + /** + * Intended to be applied to a lowercase-starting identifier that + * may collide with a Java keyword. If it does collide, this + * prepends the letter "x". + */ + public static String nonExtraKeyword(String word) { + return isExtraReservedWord(word) ? word + "Value" : word; + } + + /** + * Intended to be applied to an uppercase-starting identifier that + * may collide with a java.lang.* classname. If it does collide, this + * prepends the letter "X". + */ + public static String nonJavaCommonClassName(String name) { + if (isJavaCommonClassName(name)) { + return "X" + name; + } + return name; + } + + private static boolean isJavaReservedWord(String word) { + return javaWords.contains(word.toLowerCase(Locale.ROOT)); + } + + private static boolean isExtraReservedWord(String word) { + return extraWords.contains(word.toLowerCase(Locale.ROOT)); + } + + public static boolean isJavaCommonClassName(String word) { + return javaNames.contains(word); + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/NullLogger.java b/src/main/java/org/apache/xmlbeans/impl/common/NullLogger.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/NullLogger.java rename to src/main/java/org/apache/xmlbeans/impl/common/NullLogger.java diff --git a/src/common/org/apache/xmlbeans/impl/common/PrefixResolver.java b/src/main/java/org/apache/xmlbeans/impl/common/PrefixResolver.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/PrefixResolver.java rename to src/main/java/org/apache/xmlbeans/impl/common/PrefixResolver.java diff --git a/src/common/org/apache/xmlbeans/impl/common/PushedInputStream.java b/src/main/java/org/apache/xmlbeans/impl/common/PushedInputStream.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/PushedInputStream.java rename to src/main/java/org/apache/xmlbeans/impl/common/PushedInputStream.java diff --git a/src/common/org/apache/xmlbeans/impl/common/QNameHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java similarity index 96% rename from src/common/org/apache/xmlbeans/impl/common/QNameHelper.java rename to src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java index b6c4458..7617aaf 100644 --- a/src/common/org/apache/xmlbeans/impl/common/QNameHelper.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/QNameHelper.java @@ -15,18 +15,18 @@ package org.apache.xmlbeans.impl.common; -import javax.xml.namespace.QName; +import org.apache.xmlbeans.SchemaField; +import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.xml.stream.XMLName; +import javax.xml.namespace.QName; +import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.Map; -import java.util.HashMap; import java.util.Collections; -import java.io.UnsupportedEncodingException; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaField; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; public class QNameHelper { @@ -36,10 +36,10 @@ public static XMLName getXMLName(QName qname) { if (qname == null) return null; - + return XMLNameHelper.forLNS( qname.getLocalPart(), qname.getNamespaceURI() ); } - + public static QName forLNS(String localname, String uri) { if (uri == null) @@ -67,7 +67,7 @@ public static String pretty(QName name) if (name.getNamespaceURI() == null || name.getNamespaceURI().length() == 0) return name.getLocalPart(); - + return name.getLocalPart() + "@" + name.getNamespaceURI(); } @@ -102,13 +102,13 @@ private static boolean isSafe(int c) // // The reason for the "shortening" is to avoid filenames longer than about // 256 characters, which are prohibited on Windows NT. - + public static final int MAX_NAME_LENGTH = 64; public static final String URI_SHA1_PREFIX = "URI_SHA_1_"; public static String hexsafe(String s) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); @@ -136,11 +136,11 @@ public static String hexsafe(String s) } } } - + // short enough? Done! if (result.length() <= MAX_NAME_LENGTH) return result.toString(); - + // too long? use SHA1 try { @@ -157,7 +157,7 @@ public static String hexsafe(String s) } byte[] digest = md.digest(inputBytes); assert(digest.length == 20); // SHA1 160 bits == 20 bytes - result = new StringBuffer(URI_SHA1_PREFIX); + result = new StringBuilder(URI_SHA1_PREFIX); for (int j = 0; j < digest.length; j++) { result.append(hexdigits[(digest[j] >> 4) & 0xF]); @@ -201,25 +201,25 @@ public static String readable(SchemaType sType, Map nsPrefix) { return readable(sType.getName(), nsPrefix); } - + if (sType.isAttributeType()) { return "attribute type " + readable(sType.getAttributeTypeAttributeName(), nsPrefix); } - + if (sType.isDocumentType()) { return "document type " + readable(sType.getDocumentElementName(), nsPrefix); } - + if (sType.isNoType() || sType.getOuterType() == null) { return "invalid type"; } - + SchemaType outerType = sType.getOuterType(); SchemaField container = sType.getContainerField(); - + if (outerType.isAttributeType()) { return "type of attribute " + readable(container.getName(), nsPrefix); @@ -228,7 +228,7 @@ else if (outerType.isDocumentType()) { return "type of element " + readable(container.getName(), nsPrefix); } - + if (container != null) { if (container.isAttribute()) @@ -240,7 +240,7 @@ else if (outerType.isDocumentType()) return "type of " + container.getName().getLocalPart() + " element in " + readable(outerType, nsPrefix); } } - + if (outerType.getBaseType() == sType) return "base type of " + readable(outerType, nsPrefix); else if (outerType.getSimpleVariety() == SchemaType.LIST) @@ -248,9 +248,9 @@ else if (outerType.getSimpleVariety() == SchemaType.LIST) else if (outerType.getSimpleVariety() == SchemaType.UNION) return "member type " + sType.getAnonymousUnionMemberOrdinal() + " of " + readable(outerType, nsPrefix); else - return "inner type in " + readable(outerType, nsPrefix); + return "inner type in " + readable(outerType, nsPrefix); } - + public static String readable(QName name) { return readable(name, WELL_KNOWN_PREFIXES); @@ -265,13 +265,13 @@ public static String readable(QName name, Map prefixes) return prefix + ":" + name.getLocalPart(); return name.getLocalPart() + " in namespace " + name.getNamespaceURI(); } - + public static String suggestPrefix(String namespace) { String result = (String)WELL_KNOWN_PREFIXES.get(namespace); if (result != null) return result; - + int len = namespace.length(); int i = namespace.lastIndexOf('/'); if (i > 0 && i == namespace.length() - 1) @@ -279,21 +279,21 @@ public static String suggestPrefix(String namespace) len = i; i = namespace.lastIndexOf('/', i - 1); } - + i += 1; // skip '/', also covers -1 case. - + if (namespace.startsWith("www.", i)) { i += 4; // "www.".length() } - + while (i < len) { if (XMLChar.isNCNameStart(namespace.charAt(i))) break; i += 1; } - + for (int end = i + 1; end < len; end += 1) { if (!XMLChar.isNCName(namespace.charAt(end)) || !Character.isLetterOrDigit(namespace.charAt(end))) @@ -302,7 +302,7 @@ public static String suggestPrefix(String namespace) break; } } - + // prefixes starting with "xml" are forbidden, so change "xmls" -> "xs" if (namespace.length() >= i + 3 && startsWithXml(namespace, i)) { @@ -310,7 +310,7 @@ public static String suggestPrefix(String namespace) return "x" + Character.toLowerCase(namespace.charAt(i + 3)); return "ns"; } - + if (len - i > 4) // four or less? leave it. { if (isVowel(namespace.charAt(i + 2)) && !isVowel(namespace.charAt(i + 3))) @@ -318,28 +318,28 @@ public static String suggestPrefix(String namespace) else len = i + 3; // more than four? truncate to 3. } - + if (len - i == 0) return "ns"; - - return namespace.substring(i, len).toLowerCase(); + + return namespace.substring(i, len).toLowerCase(Locale.ROOT); } - + private static boolean startsWithXml(String s, int i) { if (s.length() < i + 3) return false; - + if (s.charAt(i) != 'X' && s.charAt(i) != 'x') return false; if (s.charAt(i + 1) != 'M' && s.charAt(i + 1) != 'm') return false; if (s.charAt(i + 2) != 'L' && s.charAt(i + 2) != 'l') return false; - + return true; } - + private static boolean isVowel(char ch) { switch (ch) @@ -359,7 +359,7 @@ private static boolean isVowel(char ch) return false; } } - + public static String namespace(SchemaType sType) { while (sType != null) diff --git a/src/common/org/apache/xmlbeans/impl/common/ReaderInputStream.java b/src/main/java/org/apache/xmlbeans/impl/common/ReaderInputStream.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/ReaderInputStream.java rename to src/main/java/org/apache/xmlbeans/impl/common/ReaderInputStream.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/ResolverUtil.java b/src/main/java/org/apache/xmlbeans/impl/common/ResolverUtil.java new file mode 100644 index 0000000..391cd5c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/ResolverUtil.java @@ -0,0 +1,68 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import org.apache.xmlbeans.SystemProperties; +import org.xml.sax.EntityResolver; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +/** + * Author: Cezar Andrei (cezar.andrei at bea.com) + * Date: Dec 3, 2003 + */ +public class ResolverUtil { + private static EntityResolver _entityResolver = null; + + static { + try { + String erClassName = SystemProperties.getProperty("xmlbean.entityResolver"); + if (erClassName != null) { + Object o = Class.forName(erClassName).getDeclaredConstructor().newInstance(); + _entityResolver = (EntityResolver) o; + } + } catch (Exception e) { + _entityResolver = null; + } + } + + public static EntityResolver getGlobalEntityResolver() { + return _entityResolver; + } + + public static EntityResolver resolverForCatalog(String catalogFile) { + if (catalogFile == null) { + return null; + } + + try { + Class cmClass = Class.forName("org.apache.xml.resolver.CatalogManager"); + Constructor cstrCm = cmClass.getDeclaredConstructor(); + Object cmObj = cstrCm.newInstance(); + Method cmMethod = cmClass.getMethod("setCatalogFiles", String.class); + cmMethod.invoke(cmObj, catalogFile); + + Class crClass = Class.forName("org.apache.xml.resolver.tools.CatalogResolver"); + Constructor cstrCr = crClass.getDeclaredConstructor(cmClass); + Object crObj = cstrCr.newInstance(cmObj); + + return (EntityResolver) crObj; + } catch (Exception e) { + return null; + } + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/SAXHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java similarity index 87% rename from src/common/org/apache/xmlbeans/impl/common/SAXHelper.java rename to src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java index e3040c9..366cd86 100644 --- a/src/common/org/apache/xmlbeans/impl/common/SAXHelper.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java @@ -15,21 +15,21 @@ package org.apache.xmlbeans.impl.common; -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - -import javax.xml.XMLConstants; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; - +import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlOptionsBean; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; +import javax.xml.XMLConstants; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; + /** * Provides handy methods for working with SAX parsers and readers */ @@ -37,23 +37,24 @@ public final class SAXHelper { private static final XBLogger logger = XBLogFactory.getLogger(SAXHelper.class); private static long lastLog; - private SAXHelper() {} + private SAXHelper() { + } /** * Creates a new SAX XMLReader, with sensible defaults */ - public static XMLReader newXMLReader(XmlOptionsBean options) throws SAXException, ParserConfigurationException { + public static XMLReader newXMLReader(XmlOptions options) throws SAXException, ParserConfigurationException { XMLReader xmlReader = saxFactory(options).newSAXParser().getXMLReader(); xmlReader.setEntityResolver(IGNORING_ENTITY_RESOLVER); trySetSAXFeature(xmlReader, XMLConstants.FEATURE_SECURE_PROCESSING); trySetXercesSecurityManager(xmlReader, options); return xmlReader; } - + public static final EntityResolver IGNORING_ENTITY_RESOLVER = new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { + throws SAXException, IOException { return new InputSource(new StringReader("")); } }; @@ -62,7 +63,7 @@ static SAXParserFactory saxFactory() { return saxFactory(new XmlOptionsBean()); } - static SAXParserFactory saxFactory(XmlOptionsBean options) { + static SAXParserFactory saxFactory(XmlOptions options) { SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setValidating(false); saxFactory.setNamespaceAware(true); @@ -91,15 +92,15 @@ private static void trySetSAXFeature(XMLReader xmlReader, String feature) { logger.log(XBLogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame); } } - - private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptionsBean options) { + + private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptions options) { // Try built-in JVM one first, standalone if not - for (String securityManagerClassName : new String[] { - //"com.sun.org.apache.xerces.internal.util.SecurityManager", - "org.apache.xerces.util.SecurityManager" + for (String securityManagerClassName : new String[]{ + //"com.sun.org.apache.xerces.internal.util.SecurityManager", + "org.apache.xerces.util.SecurityManager" }) { try { - Object mgr = Class.forName(securityManagerClassName).newInstance(); + Object mgr = Class.forName(securityManagerClassName).getDeclaredConstructor().newInstance(); Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE); setLimit.invoke(mgr, options.getEntityExpansionLimit()); xmlReader.setProperty(XMLBeansConstants.SECURITY_MANAGER, mgr); @@ -107,7 +108,7 @@ private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptionsB return; } catch (Throwable e) { // NOSONAR - also catch things like NoClassDefError here // throttle the log somewhat as it can spam the log otherwise - if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { + if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { logger.log(XBLogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e); lastLog = System.currentTimeMillis(); } @@ -119,7 +120,7 @@ private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptionsB xmlReader.setProperty(XMLBeansConstants.ENTITY_EXPANSION_LIMIT, options.getEntityExpansionLimit()); } catch (SAXException e) { // NOSONAR - also catch things like NoClassDefError here // throttle the log somewhat as it can spam the log otherwise - if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { + if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { logger.log(XBLogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e); lastLog = System.currentTimeMillis(); } diff --git a/src/common/org/apache/xmlbeans/impl/common/Sax2Dom.java b/src/main/java/org/apache/xmlbeans/impl/common/Sax2Dom.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/Sax2Dom.java rename to src/main/java/org/apache/xmlbeans/impl/common/Sax2Dom.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java new file mode 100644 index 0000000..6f2a4eb --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java @@ -0,0 +1,283 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import java.io.*; +import java.nio.charset.Charset; + +public class SniffedXmlInputStream extends BufferedInputStream { + // We don't sniff more than 192 bytes. + public static final int MAX_SNIFFED_BYTES = 192; + + public SniffedXmlInputStream(InputStream stream) throws IOException { + super(stream); + + // read byte order marks and detect EBCDIC etc + _encoding = sniffFourBytes(); + + if (_encoding != null && _encoding.equals("IBM037")) { + // First four bytes suggest EBCDIC with + // assuming we can read it as UTF-8. + _encoding = sniffForXmlDecl("UTF-8"); + } + + if (_encoding == null) { + // The XML spec says these two things: + + // (1) "In the absence of external character encoding information + // (such as MIME headers), parsed entities which are stored in an + // encoding other than UTF-8 or UTF-16 must begin with a text + // declaration (see 4.3.1 The Text Declaration) containing an + // encoding declaration:" + + // (2) "In the absence of information provided by an external + // transport protocol (e.g. HTTP or MIME), it is an error + // for an entity including an encoding declaration to be + // presented to the XML processor in an encoding other than + // that named in the declaration, or for an entity which begins + // with neither a Byte Order Mark nor an encoding declaration + // to use an encoding other than UTF-8." + + // Since we're using a sniffed stream, we do not have external + // character encoding information. + + // Since we're here, we also don't have a recognized byte order + // mark or an explicit encoding declaration that can be read in + // either ASCII or EBDIC style. + + // Therefore, we must use UTF-8. + + _encoding = "UTF-8"; + } + } + + private int readAsMuchAsPossible(byte[] buf, int startAt, int len) throws IOException { + int total = 0; + while (total < len) { + int count = read(buf, startAt + total, len - total); + if (count < 0) { + break; + } + total += count; + } + return total; + } + + private String sniffFourBytes() throws IOException { + mark(4); + int skip = 0; + try { + byte[] buf = new byte[4]; + if (readAsMuchAsPossible(buf, 0, 4) < 4) { + return null; + } + long result = 0xFF000000 & (buf[0] << 24) | 0x00FF0000 & (buf[1] << 16) | 0x0000FF00 & (buf[2] << 8) | 0x000000FF & buf[3]; + + if (result == 0x0000FEFF) { + return "UCS-4"; + } else if (result == 0xFFFE0000) { + return "UCS-4"; + } else if (result == 0x0000003C) { + return "UCS-4BE"; + } else if (result == 0x3C000000) { + return "UCS-4LE"; + } else if (result == 0x003C003F) { + return "UTF-16BE"; + } else if (result == 0x3C003F00) { + return "UTF-16LE"; + } else if (result == 0x3C3F786D) { + return null; // looks like US-ASCII with = 0) { + int i = xmlpi + 5; + ScannedAttribute attr = new ScannedAttribute(); + while (i < limit) { + i = scanAttribute(buf, i, limit, attr); + if (i < 0) { + return null; + } + if (attr.name.equals("encoding")) { + return attr.value; + } + } + } + return null; + } + + private static int firstIndexOf(String s, char[] buf, int startAt, int limit) { + assert (s.length() > 0); + char[] lookFor = s.toCharArray(); + + char firstchar = lookFor[0]; + searching: + for (limit -= lookFor.length; startAt < limit; startAt++) { + if (buf[startAt] == firstchar) { + for (int i = 1; i < lookFor.length; i++) { + if (buf[startAt + i] != lookFor[i]) { + continue searching; + } + } + return startAt; + } + } + + return -1; + } + + private static int nextNonmatchingByte(char[] lookFor, char[] buf, int startAt, int limit) { + searching: + for (; startAt < limit; startAt++) { + int thischar = buf[startAt]; + for (int i = 0; i < lookFor.length; i++) { + if (thischar == lookFor[i]) { + continue searching; + } + } + return startAt; + } + return -1; + } + + private static int nextMatchingByte(char[] lookFor, char[] buf, int startAt, int limit) { + searching: + for (; startAt < limit; startAt++) { + int thischar = buf[startAt]; + for (int i = 0; i < lookFor.length; i++) { + if (thischar == lookFor[i]) { + return startAt; + } + } + } + return -1; + } + + private static int nextMatchingByte(char lookFor, char[] buf, int startAt, int limit) { + searching: + for (; startAt < limit; startAt++) { + if (buf[startAt] == lookFor) { + return startAt; + } + } + return -1; + } + + private static char[] WHITESPACE = new char[]{' ', '\r', '\t', '\n'}; + private static char[] NOTNAME = new char[]{'=', ' ', '\r', '\t', '\n', '?', '>', '<', '\'', '\"'}; + + private static class ScannedAttribute { + public String name; + public String value; + } + + private static int scanAttribute(char[] buf, int startAt, int limit, ScannedAttribute attr) { + int nameStart = nextNonmatchingByte(WHITESPACE, buf, startAt, limit); + if (nameStart < 0) { + return -1; + } + int nameEnd = nextMatchingByte(NOTNAME, buf, nameStart, limit); + if (nameEnd < 0) { + return -1; + } + int equals = nextNonmatchingByte(WHITESPACE, buf, nameEnd, limit); + if (equals < 0) { + return -1; + } + if (buf[equals] != '=') { + return -1; + } + int valQuote = nextNonmatchingByte(WHITESPACE, buf, equals + 1, limit); + if (buf[valQuote] != '\'' && buf[valQuote] != '\"') { + return -1; + } + int valEndquote = nextMatchingByte(buf[valQuote], buf, valQuote + 1, limit); + if (valEndquote < 0) { + return -1; + } + attr.name = new String(buf, nameStart, nameEnd - nameStart); + attr.value = new String(buf, valQuote + 1, valEndquote - valQuote - 1); + return valEndquote + 1; + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java similarity index 82% rename from src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java rename to src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java index b497814..214ec4d 100644 --- a/src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java @@ -15,30 +15,27 @@ package org.apache.xmlbeans.impl.common; +import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; -import java.io.BufferedReader; import java.nio.charset.Charset; -public class SniffedXmlReader extends BufferedReader -{ +public class SniffedXmlReader extends BufferedReader { // We don't sniff more than 192 bytes. - public static int MAX_SNIFFED_CHARS = 192; + public static final int MAX_SNIFFED_CHARS = 192; - public SniffedXmlReader(Reader reader) throws IOException - { + public SniffedXmlReader(Reader reader) throws IOException { super(reader); _encoding = sniffForXmlDecl(); } - private int readAsMuchAsPossible(char[] buf, int startAt, int len) throws IOException - { + private int readAsMuchAsPossible(char[] buf, int startAt, int len) throws IOException { int total = 0; - while (total < len) - { + while (total < len) { int count = read(buf, startAt + total, len - total); - if (count < 0) + if (count < 0) { break; + } total += count; } return total; @@ -56,25 +53,20 @@ private int readAsMuchAsPossible(char[] buf, int startAt, int len) throws IOExce private static Charset dummy7 = Charset.forName("Cp1252"); - private String sniffForXmlDecl() throws IOException - { + private String sniffForXmlDecl() throws IOException { mark(MAX_SNIFFED_CHARS); - try - { + try { char[] buf = new char[MAX_SNIFFED_CHARS]; int limit = readAsMuchAsPossible(buf, 0, MAX_SNIFFED_CHARS); return SniffedXmlInputStream.extractXmlDeclEncoding(buf, 0, limit); - } - finally - { + } finally { reset(); } } private String _encoding; - public String getXmlEncoding() - { + public String getXmlEncoding() { return _encoding; } } diff --git a/src/common/org/apache/xmlbeans/impl/common/SoftCache.java b/src/main/java/org/apache/xmlbeans/impl/common/SoftCache.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/SoftCache.java rename to src/main/java/org/apache/xmlbeans/impl/common/SoftCache.java diff --git a/src/common/org/apache/xmlbeans/impl/common/StaxHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/StaxHelper.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/StaxHelper.java rename to src/main/java/org/apache/xmlbeans/impl/common/StaxHelper.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java b/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java new file mode 100644 index 0000000..a6d6f47 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/SystemCache.java @@ -0,0 +1,97 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.xmlbeans.impl.common; + +import org.apache.xmlbeans.SchemaTypeLoader; +import org.apache.xmlbeans.SystemProperties; + +import java.lang.ref.SoftReference; +import java.lang.reflect.InvocationTargetException; + +/** + * This class encapsulates the caching strategy for XmlBeans. + * By subclassing this, a client of XmlBeans can implement caches that are + * more suitable for different applications using information that XmlBeans + * cannot know. + *

      + * This class works as a singleton and as a default implementation for the cache. + * You can set a particular implementation using the "xmlbean.systemcacheimpl" + * system property or using the static {@link #set(SystemCache)} method. + * Subclasses of this need to be thread-safe. An implementation can be replaced + * at any time, so use of static variables is discouraged to ensure proper cleanup. + */ +public class SystemCache { + private static SystemCache INSTANCE = new SystemCache(); + + static { + String cacheClass = SystemProperties.getProperty("xmlbean.systemcacheimpl"); + Object impl = null; + if (cacheClass != null) { + try { + impl = Class.forName(cacheClass).getDeclaredConstructor().newInstance(); + if (!(impl instanceof SystemCache)) { + throw new ClassCastException("Value for system property " + + "\"xmlbean.systemcacheimpl\" points to a class (" + cacheClass + + ") which does not derive from SystemCache"); + } + } catch (ClassNotFoundException cnfe) { + throw new RuntimeException("Cache class " + cacheClass + + " specified by \"xmlbean.systemcacheimpl\" was not found.", + cnfe); + } catch (InstantiationException | NoSuchMethodException | InvocationTargetException ie) { + throw new RuntimeException("Could not instantiate class " + + cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." + + " An empty constructor may be missing.", ie); + } catch (IllegalAccessException iae) { + throw new RuntimeException("Could not instantiate class " + + cacheClass + " as specified by \"xmlbean.systemcacheimpl\"." + + " A public empty constructor may be missing.", iae); + } + } + if (impl != null) { + INSTANCE = (SystemCache) impl; + } + } + + public static synchronized void set(SystemCache instance) { + INSTANCE = instance; + } + + public static SystemCache get() { + return INSTANCE; + } + + public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) { + return null; + } + + public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) { + } + + private ThreadLocal tl_saxLoaders = new ThreadLocal<>(); + + public void clearThreadLocals() { + tl_saxLoaders.remove(); + } + + public Object getSaxLoader() { + SoftReference s = tl_saxLoaders.get(); + return s == null ? null : s.get(); + } + + public void setSaxLoader(Object saxLoader) { + tl_saxLoaders.set(new SoftReference(saxLoader)); + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/ValidationContext.java b/src/main/java/org/apache/xmlbeans/impl/common/ValidationContext.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/ValidationContext.java rename to src/main/java/org/apache/xmlbeans/impl/common/ValidationContext.java diff --git a/src/common/org/apache/xmlbeans/impl/common/ValidatorListener.java b/src/main/java/org/apache/xmlbeans/impl/common/ValidatorListener.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/ValidatorListener.java rename to src/main/java/org/apache/xmlbeans/impl/common/ValidatorListener.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XBLogFactory.java b/src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java similarity index 97% rename from src/common/org/apache/xmlbeans/impl/common/XBLogFactory.java rename to src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java index 0afac4d..f0b8840 100644 --- a/src/common/org/apache/xmlbeans/impl/common/XBLogFactory.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/XBLogFactory.java @@ -101,7 +101,7 @@ public static XBLogger getLogger(final String cat) { @SuppressWarnings("unchecked") Class loggerClass = (Class) Class.forName(_loggerClassName); - logger = loggerClass.newInstance(); + logger = loggerClass.getDeclaredConstructor().newInstance(); logger.initialize(cat); } catch(Exception e) { // Give up and use the null logger diff --git a/src/common/org/apache/xmlbeans/impl/common/XBLogger.java b/src/main/java/org/apache/xmlbeans/impl/common/XBLogger.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XBLogger.java rename to src/main/java/org/apache/xmlbeans/impl/common/XBLogger.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java b/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java new file mode 100644 index 0000000..b2b62af --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java @@ -0,0 +1,100 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import org.apache.xmlbeans.SystemProperties; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; + +public class XBeanDebug { + public static final int TRACE_SCHEMA_LOADING = 0x0001; + public static final String traceProp = "org.apache.xmlbeans.impl.debug"; + public static final String defaultProp = ""; // "TRACE_SCHEMA_LOADING"; + + private static int _enabled = initializeBitsFromProperty(); + private static int _indent = 0; + + private static int initializeBitsFromProperty() { + String prop = SystemProperties.getProperty(traceProp, defaultProp); + return (prop.contains("TRACE_SCHEMA_LOADING")) ? TRACE_SCHEMA_LOADING : 0; + } + + public static void enable(int bits) { + _enabled = _enabled | bits; + } + + public static void disable(int bits) { + _enabled = _enabled & ~bits; + } + + public static void trace(int bits, String message, int indent) { + if (test(bits)) { + synchronized (XBeanDebug.class) { + if (indent < 0) { + _indent += indent; + } + + String _indentspace = " "; + String spaces = _indent < 0 ? "" : _indent > _indentspace.length() ? _indentspace : _indentspace.substring(0, _indent); + String logmessage = Thread.currentThread().getName() + ": " + spaces + message + "\n"; + System.err.print(logmessage); + + if (indent > 0) { + _indent += indent; + } + } + } + } + + public static boolean test(int bits) { + return (_enabled & bits) != 0; + } + + static PrintStream _err; + + public static String log(String message) { + log(message, null); + return message; + } + + public static String logStackTrace(String message) { + log(message, new Throwable()); + return message; + } + + private synchronized static String log(String message, Throwable stackTrace) { + if (_err == null) { + try { + File diagnosticFile = File.createTempFile("xmlbeandebug", ".log"); + _err = new PrintStream(diagnosticFile, "UTF-8"); + System.err.println("Diagnostic XML Bean debug log file created: " + diagnosticFile); + } catch (IOException e) { + _err = System.err; + } + } + _err.println(message); + if (stackTrace != null) { + stackTrace.printStackTrace(_err); + } + return message; + } + + public static void logException(Throwable t) { + log(t.getMessage(), t); + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/XMLBeansConstants.java b/src/main/java/org/apache/xmlbeans/impl/common/XMLBeansConstants.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XMLBeansConstants.java rename to src/main/java/org/apache/xmlbeans/impl/common/XMLBeansConstants.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XMLChar.java b/src/main/java/org/apache/xmlbeans/impl/common/XMLChar.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XMLChar.java rename to src/main/java/org/apache/xmlbeans/impl/common/XMLChar.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XMLNameHelper.java b/src/main/java/org/apache/xmlbeans/impl/common/XMLNameHelper.java similarity index 98% rename from src/common/org/apache/xmlbeans/impl/common/XMLNameHelper.java rename to src/main/java/org/apache/xmlbeans/impl/common/XMLNameHelper.java index 505c76c..eceeec7 100644 --- a/src/common/org/apache/xmlbeans/impl/common/XMLNameHelper.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/XMLNameHelper.java @@ -76,7 +76,7 @@ private static boolean isSafe(int c) public static String hexsafe(String s) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java new file mode 100644 index 0000000..2183252 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java @@ -0,0 +1,54 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import org.apache.xmlbeans.XmlError; + +import java.net.URI; +import java.util.AbstractCollection; +import java.util.Collections; +import java.util.Iterator; + +public class XmlErrorPrinter extends AbstractCollection { + private final boolean _noisy; + private final URI _baseURI; + + public XmlErrorPrinter(boolean noisy, URI baseURI) { + _noisy = noisy; + _baseURI = baseURI; + } + + public boolean add(XmlError err) { + if (err != null) { + if (err.getSeverity() == XmlError.SEVERITY_ERROR || + err.getSeverity() == XmlError.SEVERITY_WARNING) { + System.err.println(err.toString(_baseURI)); + } else if (_noisy) { + System.out.println(err.toString(_baseURI)); + } + } + return false; + } + + public Iterator iterator() { + return Collections.emptyIterator(); + } + + public int size() { + return 0; + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java new file mode 100644 index 0000000..b13ab5e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java @@ -0,0 +1,66 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.common; + +import org.apache.xmlbeans.XmlError; + +import java.util.AbstractCollection; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; + +public class XmlErrorWatcher extends AbstractCollection { + private final Collection _underlying; + private XmlError _firstError; + + public XmlErrorWatcher(Collection underlying) { + _underlying = underlying; + } + + public boolean add(XmlError o) { + if (_firstError == null && o != null && o.getSeverity() == XmlError.SEVERITY_ERROR) { + _firstError = o; + } + if (_underlying == null) { + return false; + } + return _underlying.add(o); + } + + public Iterator iterator() { + if (_underlying == null) { + return Collections.emptyIterator(); + } + + return _underlying.iterator(); + } + + public int size() { + if (_underlying == null) { + return 0; + } + + return _underlying.size(); + } + + public boolean hasError() { + return _firstError != null; + } + + public XmlError firstError() { + return _firstError; + } +} diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlEventBase.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlEventBase.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlEventBase.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlEventBase.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlLocale.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlLocale.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlLocale.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlLocale.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlNameImpl.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlNameImpl.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlNameImpl.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlNameImpl.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlObjectList.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlObjectList.java similarity index 98% rename from src/common/org/apache/xmlbeans/impl/common/XmlObjectList.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlObjectList.java index ca8970e..cce6f24 100644 --- a/src/common/org/apache/xmlbeans/impl/common/XmlObjectList.java +++ b/src/main/java/org/apache/xmlbeans/impl/common/XmlObjectList.java @@ -120,7 +120,7 @@ private static String prettytrim(String s) } public String toString() { - StringBuffer b = new StringBuffer(); + StringBuilder b = new StringBuilder(); for (int i = 0 ; i < _objects.length ; i++) { diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlReaderToWriter.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlReaderToWriter.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlReaderToWriter.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlReaderToWriter.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlStreamUtils.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlStreamUtils.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlStreamUtils.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlStreamUtils.java diff --git a/src/common/org/apache/xmlbeans/impl/common/XmlWhitespace.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlWhitespace.java similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/XmlWhitespace.java rename to src/main/java/org/apache/xmlbeans/impl/common/XmlWhitespace.java diff --git a/src/common/org/apache/xmlbeans/impl/common/readme.txt b/src/main/java/org/apache/xmlbeans/impl/common/readme.txt similarity index 100% rename from src/common/org/apache/xmlbeans/impl/common/readme.txt rename to src/main/java/org/apache/xmlbeans/impl/common/readme.txt diff --git a/src/main/java/org/apache/xmlbeans/impl/config/BindingConfigImpl.java b/src/main/java/org/apache/xmlbeans/impl/config/BindingConfigImpl.java new file mode 100755 index 0000000..08d87a7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/config/BindingConfigImpl.java @@ -0,0 +1,331 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.config; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.schema.StscState; +import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument.Config; +import org.apache.xmlbeans.impl.xb.xmlconfig.*; + +import javax.xml.namespace.QName; +import java.io.File; +import java.util.*; + +/** + * An implementation of BindingConfig + */ +public class BindingConfigImpl extends BindingConfig { + private final Map _packageMap = new LinkedHashMap(); + private final Map _prefixMap = new LinkedHashMap(); + private final Map _suffixMap = new LinkedHashMap(); + // uri prefix -> package + private final Map _packageMapByUriPrefix = new LinkedHashMap<>(); + // uri prefix -> name prefix + private final Map _prefixMapByUriPrefix = new LinkedHashMap<>(); + // uri prefix -> name suffix + private final Map _suffixMapByUriPrefix = new LinkedHashMap<>(); + private final Map _qnameTypeMap = new LinkedHashMap<>(); + private final Map _qnameDocTypeMap = new LinkedHashMap<>(); + private final Map _qnameElemMap = new LinkedHashMap<>(); + private final Map _qnameAttMap = new LinkedHashMap<>(); + + private final List _interfaceExtensions = new ArrayList<>(); + private final List _prePostExtensions = new ArrayList<>(); + private final Map _userTypes = new LinkedHashMap<>(); + + public static BindingConfig forConfigDocuments(Config[] configs, File[] javaFiles, File[] classpath) { + return new BindingConfigImpl(configs, javaFiles, classpath); + } + + private BindingConfigImpl(Config[] configs, File[] javaFiles, File[] classpath) { + for (Config config : configs) { + Nsconfig[] nsa = config.getNamespaceArray(); + for (Nsconfig nsconfig : nsa) { + recordNamespaceSetting(nsconfig.getUri(), nsconfig.getPackage(), _packageMap); + recordNamespaceSetting(nsconfig.getUri(), nsconfig.getPrefix(), _prefixMap); + recordNamespaceSetting(nsconfig.getUri(), nsconfig.getSuffix(), _suffixMap); + recordNamespacePrefixSetting(nsconfig.getUriprefix(), nsconfig.getPackage(), _packageMapByUriPrefix); + recordNamespacePrefixSetting(nsconfig.getUriprefix(), nsconfig.getPrefix(), _prefixMapByUriPrefix); + recordNamespacePrefixSetting(nsconfig.getUriprefix(), nsconfig.getSuffix(), _suffixMapByUriPrefix); + } + + Qnameconfig[] qnc = config.getQnameArray(); + for (Qnameconfig qnameconfig : qnc) { + List applyto = qnameconfig.xgetTarget().xgetListValue(); + QName name = qnameconfig.getName(); + String javaname = qnameconfig.getJavaname(); + for (Object o : applyto) { + Qnametargetenum a = (Qnametargetenum) o; + switch (a.getEnumValue().intValue()) { + case Qnametargetenum.INT_TYPE: + _qnameTypeMap.put(name, javaname); + break; + case Qnametargetenum.INT_DOCUMENT_TYPE: + _qnameDocTypeMap.put(name, javaname); + break; + case Qnametargetenum.INT_ACCESSOR_ELEMENT: + _qnameElemMap.put(name, javaname); + break; + case Qnametargetenum.INT_ACCESSOR_ATTRIBUTE: + _qnameAttMap.put(name, javaname); + break; + } + } + } + + Extensionconfig[] ext = config.getExtensionArray(); + for (Extensionconfig extensionconfig : ext) { + recordExtensionSetting(javaFiles, classpath, extensionconfig); + } + + Usertypeconfig[] utypes = config.getUsertypeArray(); + for (Usertypeconfig utype : utypes) { + recordUserTypeSetting(javaFiles, classpath, utype); + } + } + + secondPhaseValidation(); + //todo normalize(); + } + + void addInterfaceExtension(InterfaceExtensionImpl ext) { + if (ext == null) { + return; + } + + _interfaceExtensions.add(ext); + } + + void addPrePostExtension(PrePostExtensionImpl ext) { + if (ext == null) { + return; + } + + _prePostExtensions.add(ext); + } + + void secondPhaseValidation() { + // validate interface methods collisions + Map methodSignatures = new HashMap<>(); + + for (InterfaceExtensionImpl extension : _interfaceExtensions) { + + InterfaceExtensionImpl.MethodSignatureImpl[] methods = (InterfaceExtensionImpl.MethodSignatureImpl[]) extension.getMethods(); + for (InterfaceExtensionImpl.MethodSignatureImpl ms : methods) { + if (methodSignatures.containsKey(ms)) { + + InterfaceExtensionImpl.MethodSignatureImpl ms2 = (InterfaceExtensionImpl.MethodSignatureImpl) methodSignatures.get(ms); + if (!ms.getReturnType().equals(ms2.getReturnType())) { + BindingConfigImpl.error("Colliding methods '" + ms.getSignature() + "' in interfaces " + + ms.getInterfaceName() + " and " + ms2.getInterfaceName() + ".", null); + } + + return; + } + + // store it into hashmap + methodSignatures.put(ms, ms); + } + } + + // validate that PrePostExtension-s do not intersect + for (int i = 0; i < _prePostExtensions.size() - 1; i++) { + PrePostExtensionImpl a = _prePostExtensions.get(i); + for (int j = 1; j < _prePostExtensions.size(); j++) { + PrePostExtensionImpl b = _prePostExtensions.get(j); + if (a.hasNameSetIntersection(b)) { + BindingConfigImpl.error("The applicable domain for handler '" + a.getHandlerNameForJavaSource() + + "' intersects with the one for '" + b.getHandlerNameForJavaSource() + "'.", null); + } + } + } + } + + private static void recordNamespaceSetting(Object key, String value, Map result) { + if (value == null) { + return; + } + if (key == null) { + result.put("", value); + } else if (key instanceof String && "##any".equals(key)) { + result.put(key, value); + } else if (key instanceof List) { + // map uris to value + ((List) key).forEach(o -> result.put("##local".equals(o) ? "" : o, value)); + } + } + + private static void recordNamespacePrefixSetting(List list, String value, Map result) { + if (value == null) { + return; + } + if (list == null) { + return; + } + list.forEach(o -> result.put(o, value)); + } + + private void recordExtensionSetting(File[] javaFiles, File[] classpath, Extensionconfig ext) { + NameSet xbeanSet = null; + Object key = ext.getFor(); + + + if (key instanceof String && "*".equals(key)) { + xbeanSet = NameSet.EVERYTHING; + } else if (key instanceof List) { + NameSetBuilder xbeanSetBuilder = new NameSetBuilder(); + for (Object o : (List) key) { + String xbeanName = (String) o; + xbeanSetBuilder.add(xbeanName); + } + xbeanSet = xbeanSetBuilder.toNameSet(); + } + + if (xbeanSet == null) { + error("Invalid value of attribute 'for' : '" + key + "'.", ext); + } + + Extensionconfig.Interface[] intfXO = ext.getInterfaceArray(); + Extensionconfig.PrePostSet ppXO = ext.getPrePostSet(); + + Parser loader = new Parser(javaFiles, classpath); + + if (intfXO.length > 0 || ppXO != null) { + for (Extensionconfig.Interface anInterface : intfXO) { + addInterfaceExtension(InterfaceExtensionImpl.newInstance(loader, xbeanSet, anInterface)); + } + + addPrePostExtension(PrePostExtensionImpl.newInstance(loader, xbeanSet, ppXO)); + } + } + + private void recordUserTypeSetting(File[] javaFiles, File[] classpath, Usertypeconfig usertypeconfig) { + Parser loader = new Parser(javaFiles, classpath); + UserTypeImpl userType = UserTypeImpl.newInstance(loader, usertypeconfig); + _userTypes.put(userType.getName(), userType); + } + + + private String lookup(Map map, Map mapByUriPrefix, String uri) { + if (uri == null) { + uri = ""; + } + String result = (String) map.get(uri); + if (result != null) { + return result; + } + if (mapByUriPrefix != null) { + result = lookupByUriPrefix(mapByUriPrefix, uri); + if (result != null) { + return result; + } + } + + return (String) map.get("##any"); + } + + private String lookupByUriPrefix(Map mapByUriPrefix, String uri) { + if (uri == null) { + return null; + } + if (!mapByUriPrefix.isEmpty()) { + String uriprefix = null; + for (Object o : mapByUriPrefix.keySet()) { + String nextprefix = (String) o; + if (uriprefix != null && nextprefix.length() < uriprefix.length()) { + continue; + } + if (uri.startsWith(nextprefix)) { + uriprefix = nextprefix; + } + } + + if (uriprefix != null) { + return (String) mapByUriPrefix.get(uriprefix); + } + } + return null; + } + + //package methods + static void warning(String s, XmlObject xo) { + StscState.get().error(s, XmlError.SEVERITY_WARNING, xo); + } + + static void error(String s, XmlObject xo) { + StscState.get().error(s, XmlError.SEVERITY_ERROR, xo); + } + + //public methods + + public String lookupPackageForNamespace(String uri) { + return lookup(_packageMap, _packageMapByUriPrefix, uri); + } + + public String lookupPrefixForNamespace(String uri) { + return lookup(_prefixMap, _prefixMapByUriPrefix, uri); + } + + public String lookupSuffixForNamespace(String uri) { + return lookup(_suffixMap, _suffixMapByUriPrefix, uri); + } + + /** + * @deprecated replaced with {@link #lookupJavanameForQName(QName, int)} + */ + public String lookupJavanameForQName(QName qname) { + String result = _qnameTypeMap.get(qname); + return result != null ? result : _qnameDocTypeMap.get(qname); + } + + public String lookupJavanameForQName(QName qname, int kind) { + switch (kind) { + case QNAME_TYPE: + return _qnameTypeMap.get(qname); + case QNAME_DOCUMENT_TYPE: + return _qnameDocTypeMap.get(qname); + case QNAME_ACCESSOR_ELEMENT: + return _qnameElemMap.get(qname); + case QNAME_ACCESSOR_ATTRIBUTE: + return _qnameAttMap.get(qname); + } + return null; + } + + public UserType lookupUserTypeForQName(QName qname) { + return qname == null ? null : _userTypes.get(qname); + } + + public InterfaceExtension[] getInterfaceExtensions() { + return _interfaceExtensions.toArray(new InterfaceExtension[0]); + } + + public InterfaceExtension[] getInterfaceExtensions(String fullJavaName) { + return _interfaceExtensions.stream(). + filter(i -> i.contains(fullJavaName)). + toArray(InterfaceExtension[]::new); + } + + public PrePostExtension[] getPrePostExtensions() { + return _prePostExtensions.toArray(new PrePostExtension[0]); + } + + public PrePostExtension getPrePostExtension(String fullJavaName) { + return _prePostExtensions.stream(). + filter(p -> p.contains(fullJavaName)). + findFirst().orElse(null); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/config/InterfaceExtensionImpl.java b/src/main/java/org/apache/xmlbeans/impl/config/InterfaceExtensionImpl.java new file mode 100755 index 0000000..66ec046 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/config/InterfaceExtensionImpl.java @@ -0,0 +1,304 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.config; + +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.type.ReferenceType; +import org.apache.xmlbeans.InterfaceExtension; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; + +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Stream; + +public class InterfaceExtensionImpl implements InterfaceExtension { + private NameSet _xbeanSet; + private String _interfaceClassName; + private String _delegateToClassName; + private MethodSignatureImpl[] _methods; + + static InterfaceExtensionImpl newInstance(Parser loader, NameSet xbeanSet, Extensionconfig.Interface intfXO) { + InterfaceExtensionImpl result = new InterfaceExtensionImpl(); + + result._xbeanSet = xbeanSet; + + ClassOrInterfaceDeclaration interfaceJClass = validateInterface(loader, intfXO.getName(), intfXO); + + + if (interfaceJClass == null) + { + BindingConfigImpl.error("Interface '" + intfXO.getStaticHandler() + "' not found.", intfXO); + return null; + } + + result._interfaceClassName = interfaceJClass.getFullyQualifiedName().get(); + + result._delegateToClassName = intfXO.getStaticHandler(); + ClassOrInterfaceDeclaration delegateJClass = validateClass(loader, result._delegateToClassName, intfXO); + + if (delegateJClass == null) { + // no HandlerClass + BindingConfigImpl.warning("Handler class '" + intfXO.getStaticHandler() + "' not found on classpath, skip validation.", intfXO); + return result; + } + + if (!result.validateMethods(interfaceJClass, delegateJClass, intfXO)) + return null; + + return result; + } + + private static ClassOrInterfaceDeclaration validateInterface(Parser loader, String intfStr, XmlObject loc) { + return validateJava(loader, intfStr, true, loc); + } + + static ClassOrInterfaceDeclaration validateClass(Parser loader, String clsStr, XmlObject loc) { + return validateJava(loader, clsStr, false, loc); + } + + static ClassOrInterfaceDeclaration validateJava(Parser loader, String clsStr, boolean isInterface, XmlObject loc) { + if (loader==null) { + return null; + } + + final String ent = isInterface ? "Interface" : "Class"; + ClassOrInterfaceDeclaration cls = loader.loadSource(clsStr); + + if (cls==null) { + BindingConfigImpl.error(ent + " '" + clsStr + "' not found.", loc); + return null; + } + + if ( isInterface != cls.isInterface() ) { + BindingConfigImpl.error("'" + clsStr + "' must be " + (isInterface ? "an interface" : "a class") + ".", loc); + } + + if (!cls.isPublic()) { + BindingConfigImpl.error(ent + " '" + clsStr + "' is not public.", loc); + } + + return cls; + } + + private boolean validateMethods(ClassOrInterfaceDeclaration interfaceJClass, ClassOrInterfaceDeclaration delegateJClass, XmlObject loc) { + _methods = interfaceJClass.getMethods().stream() + .map(m -> validateMethod(interfaceJClass, delegateJClass, m, loc)) + .map(m -> m == null ? null : new MethodSignatureImpl(getStaticHandler(), m)) + .toArray(MethodSignatureImpl[]::new); + + return Stream.of(_methods).allMatch(Objects::nonNull); + } + + private MethodDeclaration validateMethod(ClassOrInterfaceDeclaration interfaceJClass, + ClassOrInterfaceDeclaration delegateJClass, MethodDeclaration method, XmlObject loc) { + + String methodName = method.getName().asString(); + + String[] delegateParams = Stream.concat( + Stream.of("org.apache.xmlbeans.XmlObject"), + Stream.of(paramStrings(method.getParameters())) + ).toArray(String[]::new); + + MethodDeclaration handlerMethod = getMethod(delegateJClass, methodName, delegateParams); + + String delegateFQN = delegateJClass.getFullyQualifiedName().orElse(""); + String methodFQN = methodName + "(" + method.getParameters().toString() + ")"; + String interfaceFQN = interfaceJClass.getFullyQualifiedName().orElse(""); + + if (handlerMethod == null) { + BindingConfigImpl.error("Handler class '" + delegateFQN + "' does not contain method " + methodFQN, loc); + return null; + } + + // check for throws exceptions + if (!Arrays.equals(exceptionStrings(method), exceptionStrings(handlerMethod))) { + BindingConfigImpl.error("Handler method '" + delegateFQN + "." + methodName + "' must declare the same " + + "exceptions as the interface method '" + interfaceFQN + "." + methodFQN, loc); + return null; + } + + if (!handlerMethod.isPublic() || !handlerMethod.isStatic()) { + BindingConfigImpl.error("Method '" + delegateJClass.getFullyQualifiedName() + "." + + methodFQN + "' must be declared public and static.", loc); + return null; + } + + String returnType = method.getTypeAsString(); + if (!returnType.equals(handlerMethod.getTypeAsString())) { + BindingConfigImpl.error("Return type for method '" + returnType + " " + delegateFQN + "." + methodName + + "(...)' does not match the return type of the interface method :'" + returnType + "'.", loc); + return null; + } + + return method; + } + + static MethodDeclaration getMethod(ClassOrInterfaceDeclaration cls, String name, String[] paramTypes) { + // cls.getMethodsBySignature only checks the type name as-is ... i.e. if the type name is imported + // only the simple name is checked, otherwise the full qualified name + return cls.getMethodsByName(name).stream() + .filter(m -> parameterMatches(paramStrings(m.getParameters()), paramTypes)) + .findFirst().orElse(null); + } + + private static String[] paramStrings(NodeList params) { + return params.stream().map(Parameter::getTypeAsString).toArray(String[]::new); + } + + private static String[] exceptionStrings(MethodDeclaration method) { + return method.getThrownExceptions().stream().map(ReferenceType::asString).toArray(String[]::new); + } + + private static boolean parameterMatches(String[] params1, String[] params2) { + // compare all parameters type strings + // a type string can be a simple name (e.g. "XmlObject") or + // fully qualified name ("org.apache.xmlbeans.XmlObject") + // try to loosely match the names + if (params1.length != params2.length) { + return false; + } + for (int i=0; i _finiteSet; + + private NameSet(boolean isFinite, Set finiteSet) { + _isFinite = isFinite; + _finiteSet = finiteSet; + } + + static NameSet newInstance(boolean isFinite, Set finiteSet) { + if (finiteSet.size() == 0) { + if (isFinite) { + return NameSet.EMPTY; + } else { + return NameSet.EVERYTHING; + } + } else { + Set fs = new HashSet<>(); + fs.addAll(finiteSet); + return new NameSet(isFinite, fs); + } + } + + private static Set intersectFiniteSets(Set a, Set b) { + Set intersection = new HashSet<>(); + //compute the intersection of _finiteSet with withSet + while (a.iterator().hasNext()) { + String name = (String) a.iterator().next(); + if (b.contains(name)) { + intersection.add(name); + } + } + return intersection; + } + + /** + * Returns the union of this NameSet with the 'with' NameSet. + */ + public NameSet union(NameSet with) { + if (_isFinite) { + if (with._isFinite) { + Set union = new HashSet<>(); + union.addAll(_finiteSet); + union.addAll(with._finiteSet); + return newInstance(true, union); + } else { + Set subst = new HashSet<>(); + subst.addAll(with._finiteSet); + subst.removeAll(_finiteSet); + return newInstance(false, subst); + } + } else { + if (with._isFinite) { + Set subst = new HashSet<>(); + subst.addAll(_finiteSet); + subst.removeAll(with._finiteSet); + return newInstance(false, subst); + } else { + return newInstance(false, intersectFiniteSets(_finiteSet, with._finiteSet)); + } + } + } + + /** + * Returns the intersection of this NameSet with the 'with' NameSet + */ + public NameSet intersect(NameSet with) { + if (_isFinite) { + if (with._isFinite) { + return newInstance(true, intersectFiniteSets(_finiteSet, with._finiteSet)); + } else { + Set subst = new HashSet<>(); + subst.addAll(_finiteSet); + subst.removeAll(with._finiteSet); + return newInstance(false, subst); + } + } else { + if (with._isFinite) { + Set subst = new HashSet<>(); + subst.addAll(with._finiteSet); + subst.removeAll(_finiteSet); + return newInstance(true, subst); + } else { + Set union = new HashSet<>(); + union.addAll(_finiteSet); + union.addAll(with._finiteSet); + return newInstance(false, union); + } + } + } + + /** + * Returns the result of substracting this NameSet from 'from' NameSet + * + * @see NameSet#substract + */ + public NameSet substractFrom(NameSet from) { + return from.substract(this); + } + + /** + * Returns the result of substracting 'what' NameSet from this NameSet + * + * @see NameSet#substractFrom + */ + public NameSet substract(NameSet what) { + if (_isFinite) { + if (what._isFinite) { + // it's the subst of _finiteSet with what._finiteSet + Set subst = new HashSet<>(); + subst.addAll(_finiteSet); + subst.removeAll(what._finiteSet); + return newInstance(true, subst); + } else { + return newInstance(true, intersectFiniteSets(_finiteSet, what._finiteSet)); + } + } else { + if (what._isFinite) { + // it's the union of _finiteSet with what._finiteSet + Set union = new HashSet<>(); + union.addAll(_finiteSet); + union.addAll(what._finiteSet); + return newInstance(false, union); + } else { + // what's in thisSet and it's not in whatSet + Set subst = new HashSet<>(); + subst.addAll(what._finiteSet); + subst.removeAll(_finiteSet); + return newInstance(true, subst); + } + } + } + + /** + * Returns an inversion of this NameSet + */ + public NameSet invert() { + return newInstance(!_isFinite, _finiteSet); + } + + public boolean contains(String name) { + if (_isFinite) { + return _finiteSet.contains(name); + } else { + return !_finiteSet.contains(name); + } + } +} diff --git a/src/xmlconfig/org/apache/xmlbeans/impl/config/NameSetBuilder.java b/src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java similarity index 76% rename from src/xmlconfig/org/apache/xmlbeans/impl/config/NameSetBuilder.java rename to src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java index da61a08..582b19f 100644 --- a/src/xmlconfig/org/apache/xmlbeans/impl/config/NameSetBuilder.java +++ b/src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java @@ -18,25 +18,16 @@ */ package org.apache.xmlbeans.impl.config; -import java.util.Set; import java.util.HashSet; +import java.util.Set; /** * Used to build {@link NameSet NameSets}. */ public class NameSetBuilder { - private boolean _isFinite; - private Set _finiteSet; - - /** - * Creates an empty builder for a NameSet. - */ - public NameSetBuilder() - { - _isFinite = true; - _finiteSet = new HashSet(); - } + private boolean _isFinite = true; + private final Set _finiteSet = new HashSet<>(); /** * Inverts the representing NameSet @@ -50,26 +41,28 @@ public void invert() * Adds a name to the representing NameSet * @param name */ - public void add(String name) - { - if (_isFinite ) + public void add(String name) { + if (_isFinite) { _finiteSet.add(name); - else + } else { _finiteSet.remove(name); + } } /** * Creates a new NameSet with the current state. + * * @return created NameSet */ - public NameSet toNameSet() - { - if ( _finiteSet.size()==0 ) - if ( _isFinite ) + public NameSet toNameSet() { + if (_finiteSet.size() == 0) { + if (_isFinite) { return NameSet.EMPTY; - else + } else { return NameSet.EVERYTHING; - else + } + } else { return NameSet.newInstance(_isFinite, _finiteSet); + } } } \ No newline at end of file diff --git a/src/main/java/org/apache/xmlbeans/impl/config/Parser.java b/src/main/java/org/apache/xmlbeans/impl/config/Parser.java new file mode 100644 index 0000000..8142aa9 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/config/Parser.java @@ -0,0 +1,66 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.config; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.utils.SourceRoot; + +import java.io.File; +import java.io.IOException; +import java.util.function.Predicate; + +class Parser { + final File[] javaFiles; + final File[] classpath; + + + public Parser(File[] javaFiles, File[] classpath) { + this.javaFiles = (javaFiles != null) ? javaFiles.clone() : new File[0]; + this.classpath = (classpath != null) ? classpath.clone() : new File[0]; + } + + public ClassOrInterfaceDeclaration loadSource(String className) { + final String fileName = className.replace('.','/') +".java"; + for (File f : javaFiles) { + final String filePath = f.getPath(); + if (filePath.replace('\\','/').endsWith(fileName)) { + // remove filename from path - don't use replace because of different path separator + final String rootPath = filePath.substring(0, filePath.length()-fileName.length()); + final String startPackage = className.indexOf('.') == -1 ? "" : className.substring(0, className.lastIndexOf('.')); + final String simpleName = startPackage.isEmpty() ? className : className.substring(startPackage.length()+1); + SourceRoot sourceRoot = new SourceRoot(new File(rootPath).toPath()); + try { + ParseResult pcu = sourceRoot.tryToParse(startPackage, simpleName+".java"); + ClassOrInterfaceDeclaration cls = pcu.getResult().flatMap(cu -> cu.getTypes().stream() + .filter(matchType(className)) + .map(t -> (ClassOrInterfaceDeclaration) t).findFirst()).orElse(null); + return cls; + } catch (IOException e) { + return null; + } + } + } + return null; + } + + private static Predicate> matchType(String className) { + return (t) -> t instanceof ClassOrInterfaceDeclaration && + t.getFullyQualifiedName().map(fqn -> fqn.equals(className)).orElse(false); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/config/PrePostExtensionImpl.java b/src/main/java/org/apache/xmlbeans/impl/config/PrePostExtensionImpl.java new file mode 100755 index 0000000..e598052 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/config/PrePostExtensionImpl.java @@ -0,0 +1,128 @@ +/* Copyright 2004 The Apache Software Foundation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.xmlbeans.impl.config; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.type.PrimitiveType; +import org.apache.xmlbeans.PrePostExtension; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; + + +public class PrePostExtensionImpl implements PrePostExtension { + + private static final String[] PARAMTYPES_STRING = { + "int", "org.apache.xmlbeans.XmlObject", "javax.xml.namespace.QName", "boolean", "int" + }; + private static final String SIGNATURE = "(" + String.join(", ", PARAMTYPES_STRING) + ")"; + + private NameSet _xbeanSet; + private ClassOrInterfaceDeclaration _delegateToClass; + private String _delegateToClassName; + private MethodDeclaration _preSet; + private MethodDeclaration _postSet; + + static PrePostExtensionImpl newInstance(Parser loader, NameSet xbeanSet, Extensionconfig.PrePostSet prePostXO) + { + if (prePostXO==null) + return null; + + PrePostExtensionImpl result = new PrePostExtensionImpl(); + + result._xbeanSet = xbeanSet; + result._delegateToClassName = prePostXO.getStaticHandler(); + result._delegateToClass = InterfaceExtensionImpl.validateClass(loader, result._delegateToClassName, prePostXO); + + if ( result._delegateToClass==null ) // no HandlerClass + { + BindingConfigImpl.warning("Handler class '" + prePostXO.getStaticHandler() + "' not found on classpath, skip validation.", prePostXO); + return result; + } + + if (!result.lookAfterPreAndPost(loader, prePostXO)) + return null; + + return result; + } + + private boolean lookAfterPreAndPost(Parser loader, XmlObject loc) { + assert (_delegateToClass!=null) : "Delegate to class handler expected."; + boolean valid = true; + + _preSet = InterfaceExtensionImpl.getMethod(_delegateToClass, "preSet", PARAMTYPES_STRING); + // _preSet==null is ok + + if (_preSet!=null && !_preSet.getType().equals(PrimitiveType.booleanType())) { + // just emit an warning and don't remember as a preSet + BindingConfigImpl.warning("Method '" + _delegateToClass.getNameAsString() + + ".preSet" + SIGNATURE + "' " + + "should return boolean to be considered for a preSet handler.", loc); + _preSet = null; + } + + _postSet = InterfaceExtensionImpl.getMethod(_delegateToClass, "postSet", PARAMTYPES_STRING); + // _postSet==null is ok + + if (_preSet==null && _postSet==null) + { + BindingConfigImpl.error("prePostSet handler specified '" + _delegateToClass.getNameAsString() + + "' but no preSet" + SIGNATURE + " or postSet" + SIGNATURE + " methods found.", loc); + valid = false; + } + + return valid; + } + + // public methods + public NameSet getNameSet() + { + return _xbeanSet; + } + + public boolean contains(String fullJavaName) + { + return _xbeanSet.contains(fullJavaName); + } + + public boolean hasPreCall() + { + return _preSet!=null; + } + + public boolean hasPostCall() + { + return _postSet!=null; + } + + public String getStaticHandler() + { + return _delegateToClassName; + } + + /** + * Returns the name of the handler in a form that can be put in a java source. + */ + public String getHandlerNameForJavaSource() { + return (_delegateToClass == null) ? null : _delegateToClass.getNameAsString(); + } + + boolean hasNameSetIntersection(PrePostExtensionImpl ext) + { + return !NameSet.EMPTY.equals(_xbeanSet.intersect(ext._xbeanSet)); + } + +} diff --git a/src/xmlconfig/org/apache/xmlbeans/impl/config/UserTypeImpl.java b/src/main/java/org/apache/xmlbeans/impl/config/UserTypeImpl.java similarity index 90% rename from src/xmlconfig/org/apache/xmlbeans/impl/config/UserTypeImpl.java rename to src/main/java/org/apache/xmlbeans/impl/config/UserTypeImpl.java index 738d619..72e3b79 100644 --- a/src/xmlconfig/org/apache/xmlbeans/impl/config/UserTypeImpl.java +++ b/src/main/java/org/apache/xmlbeans/impl/config/UserTypeImpl.java @@ -15,12 +15,11 @@ package org.apache.xmlbeans.impl.config; -import javax.xml.namespace.QName; - import org.apache.xmlbeans.UserType; -import org.apache.xmlbeans.impl.jam.JamClassLoader; import org.apache.xmlbeans.impl.xb.xmlconfig.Usertypeconfig; +import javax.xml.namespace.QName; + public class UserTypeImpl implements UserType { private QName _name; @@ -28,7 +27,7 @@ public class UserTypeImpl implements UserType private String _staticHandler; - static UserTypeImpl newInstance(JamClassLoader loader, Usertypeconfig cfgXO) + static UserTypeImpl newInstance(Parser loader, Usertypeconfig cfgXO) { UserTypeImpl result = new UserTypeImpl(); @@ -44,7 +43,7 @@ static UserTypeImpl newInstance(JamClassLoader loader, Usertypeconfig cfgXO) } - public String getJavaName() + public String getJavaName() { return _javaName; } diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/Inst2Xsd.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/Inst2Xsd.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/Inst2Xsd.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/Inst2Xsd.java diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/Inst2XsdOptions.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/Inst2XsdOptions.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/Inst2XsdOptions.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/Inst2XsdOptions.java diff --git a/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java new file mode 100644 index 0000000..75279b6 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java @@ -0,0 +1,756 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.xmlbeans.impl.inst2xsd; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.common.XmlWhitespace; +import org.apache.xmlbeans.impl.inst2xsd.util.Attribute; +import org.apache.xmlbeans.impl.inst2xsd.util.Element; +import org.apache.xmlbeans.impl.inst2xsd.util.Type; +import org.apache.xmlbeans.impl.inst2xsd.util.TypeSystemHolder; +import org.apache.xmlbeans.impl.util.XsTypeConverter; +import org.apache.xmlbeans.impl.values.*; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Cezar Andrei ( cezar.andrei at bea.com ) + * Date: Jul 26, 2004 + */ +public class RussianDollStrategy + implements XsdGenStrategy { + static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance"; + + static final QName _xsiNil = new QName(_xsi, "nil", "xsi"); + + public void processDoc(XmlObject[] instances, Inst2XsdOptions options, TypeSystemHolder typeSystemHolder) { + for (XmlObject instance : instances) { + XmlCursor xc = instance.newCursor(); + // xc on start doc + + StringBuilder comment = new StringBuilder(); + + while (!xc.isStart()) { + xc.toNextToken(); + if (xc.isComment()) { + comment.append(xc.getTextValue()); + } else if (xc.isEnddoc()) { + return; + } + } + // xc now on the root element + + Element withElem = processElement(xc, comment.toString(), options, typeSystemHolder); + withElem.setGlobal(true); + + addGlobalElement(withElem, typeSystemHolder, options); + } + } + + protected Element addGlobalElement(Element withElem, TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) { + assert withElem.isGlobal(); + Element intoElem = typeSystemHolder.getGlobalElement(withElem.getName()); + + if (intoElem == null) { + typeSystemHolder.addGlobalElement(withElem); + return withElem; + } else { + combineTypes(intoElem.getType(), withElem.getType(), options); + combineElementComments(intoElem, withElem); + return intoElem; + } + } + + protected Element processElement(XmlCursor xc, String comment, + Inst2XsdOptions options, TypeSystemHolder typeSystemHolder) { + assert xc.isStart(); + Element element = new Element(); + element.setName(xc.getName()); + element.setGlobal(false); + + Type elemType = Type.createUnnamedType(Type.SIMPLE_TYPE_SIMPLE_CONTENT); //assume simple, set later + element.setType(elemType); + + StringBuilder textBuff = new StringBuilder(); + StringBuilder commentBuff = new StringBuilder(); + List children = new ArrayList<>(); + List attributes = new ArrayList<>(); + + loop: + do { + XmlCursor.TokenType tt = xc.toNextToken(); + switch (tt.intValue()) { + case XmlCursor.TokenType.INT_ATTR: + // todo check for xsi:type + // ignore xsi:... attributes other than xsi:nil + QName attName = xc.getName(); + if (!_xsiNil.getNamespaceURI().equals(attName.getNamespaceURI())) { + attributes.add(processAttribute(xc, options, element.getName().getNamespaceURI(), typeSystemHolder)); + } else if (_xsiNil.equals(attName)) { + element.setNillable(true); + } + + break; + + case XmlCursor.TokenType.INT_START: + children.add(processElement(xc, commentBuff.toString(), options, typeSystemHolder)); + commentBuff.delete(0, commentBuff.length()); + break; + + case XmlCursor.TokenType.INT_TEXT: + textBuff.append(xc.getChars()); + break; + + case XmlCursor.TokenType.INT_COMMENT: + commentBuff.append(xc.getTextValue()); + break; + + case XmlCursor.TokenType.INT_NAMESPACE: + // ignore, + // each element and attribute will take care to define itself in the right targetNamespace + break; + + case XmlCursor.TokenType.INT_END: + break loop; + + case XmlCursor.TokenType.INT_PROCINST: + // ignore + break; + + case XmlCursor.TokenType.INT_ENDDOC: + break loop; + + case XmlCursor.TokenType.INT_NONE: + break loop; + + case XmlCursor.TokenType.INT_STARTDOC: + throw new IllegalStateException(); + + default: + throw new IllegalStateException("Unknown TokenType."); + } + } + while (true); + + String collapsedText = XmlWhitespace.collapse(textBuff.toString(), XmlWhitespace.WS_COLLAPSE); + + String commnetStr = (comment == null ? + (commentBuff.length() == 0 ? null : commentBuff.toString()) : + (commentBuff.length() == 0 ? comment : commentBuff.insert(0, comment).toString())); + element.setComment(commnetStr); + + if (children.size() > 0) { + // complex content + if (collapsedText.length() > 0) { + elemType.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT); + } else { + elemType.setContentType(Type.COMPLEX_TYPE_COMPLEX_CONTENT); + } + processElementsInComplexType(elemType, children, element.getName().getNamespaceURI(), typeSystemHolder, options); + processAttributesInComplexType(elemType, attributes); + } else { + // simple content + // hack workaround for being able to call xc.getNamespaceForPrefix() + XmlCursor xcForNamespaces = xc.newCursor(); + xcForNamespaces.toParent(); + + if (attributes.size() > 0) { + elemType.setContentType(Type.COMPLEX_TYPE_SIMPLE_CONTENT); + + Type extendedType = Type.createNamedType( + processSimpleContentType(textBuff.toString(), options, xcForNamespaces), Type.SIMPLE_TYPE_SIMPLE_CONTENT); + elemType.setExtensionType(extendedType); + + processAttributesInComplexType(elemType, attributes); + } else { + elemType.setContentType(Type.SIMPLE_TYPE_SIMPLE_CONTENT); + elemType.setName(processSimpleContentType(textBuff.toString(), options, xcForNamespaces)); + + // add enumeration value + String enumValue = XmlString.type.getName().equals(elemType.getName()) ? textBuff.toString() : collapsedText; + elemType.addEnumerationValue(enumValue, xcForNamespaces); + } + + xcForNamespaces.dispose(); // end hack + } + + checkIfReferenceToGlobalTypeIsNeeded(element, typeSystemHolder, options); + + return element; + } + + protected void processElementsInComplexType(Type elemType, List children, String parentNamespace, + TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) { + Map elemNamesToElements = new HashMap<>(); + Element currentElem = null; + + for (Element child : children) { + if (currentElem == null) { // first element in this type + checkIfElementReferenceIsNeeded(child, parentNamespace, typeSystemHolder, options); + elemType.addElement(child); + elemNamesToElements.put(child.getName(), child); + currentElem = child; + continue; + } + + if (currentElem.getName() == child.getName()) { // same contiguos element + combineTypes(currentElem.getType(), child.getType(), options); // unify types + combineElementComments(currentElem, child); + // minOcc=0 maxOcc=unbounded + currentElem.setMinOccurs(0); + currentElem.setMaxOccurs(Element.UNBOUNDED); + } else { + Element sameElem = elemNamesToElements.get(child.getName()); + if (sameElem == null) { // new element name + checkIfElementReferenceIsNeeded(child, parentNamespace, typeSystemHolder, options); + elemType.addElement(child); + elemNamesToElements.put(child.getName(), child); + } else { //same non contiguos + combineTypes(currentElem.getType(), child.getType(), options); + combineElementComments(currentElem, child); + elemType.setTopParticleForComplexOrMixedContent(Type.PARTICLE_CHOICE_UNBOUNDED); + } + currentElem = child; + } + } + } + + protected void checkIfElementReferenceIsNeeded(Element child, String parentNamespace, + TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) { + if (!child.getName().getNamespaceURI().equals(parentNamespace)) { + Element referencedElem = new Element(); + referencedElem.setGlobal(true); + referencedElem.setName(child.getName()); + referencedElem.setType(child.getType()); + + if (child.isNillable()) { + referencedElem.setNillable(true); + child.setNillable(false); + } + + referencedElem = addGlobalElement(referencedElem, typeSystemHolder, options); + + child.setRef(referencedElem); // clears child's type + } + } + + protected void checkIfReferenceToGlobalTypeIsNeeded(Element elem, TypeSystemHolder typeSystemHolder, + Inst2XsdOptions options) { + // RussianDollDesign doesn't define global types + } + + protected void processAttributesInComplexType(Type elemType, List attributes) { + assert elemType.isComplexType(); + for (Attribute att : attributes) { + elemType.addAttribute(att); + } + } + + protected Attribute processAttribute(XmlCursor xc, Inst2XsdOptions options, String parentNamespace, + TypeSystemHolder typeSystemHolder) { + assert xc.isAttr() : "xc not on attribute"; + Attribute attribute = new Attribute(); + QName attName = xc.getName(); + + attribute.setName(attName); + + XmlCursor parent = xc.newCursor(); + parent.toParent(); + + Type simpleContentType = Type.createNamedType( + processSimpleContentType(xc.getTextValue(), options, parent), Type.SIMPLE_TYPE_SIMPLE_CONTENT); + + parent.dispose(); + + attribute.setType(simpleContentType); + + checkIfAttributeReferenceIsNeeded(attribute, parentNamespace, typeSystemHolder); + + return attribute; + } + + protected void checkIfAttributeReferenceIsNeeded(Attribute attribute, String parentNamespace, TypeSystemHolder typeSystemHolder) { + if (!attribute.getName().getNamespaceURI().equals("") && + !attribute.getName().getNamespaceURI().equals(parentNamespace)) { + // make attribute be a reference to a top level attribute in a different targetNamespace + Attribute referencedAtt = new Attribute(); + referencedAtt.setGlobal(true); + referencedAtt.setName(attribute.getName()); + referencedAtt.setType(attribute.getType()); + + typeSystemHolder.addGlobalAttribute(referencedAtt); + + attribute.setRef(referencedAtt); + } + } + + protected static class SCTValidationContext + implements ValidationContext { + protected boolean valid = true; + + public boolean isValid() { + return valid; + } + + public void resetToValid() { + valid = true; + } + + public void invalid(String message) { + valid = false; + } + + public void invalid(String code, Object[] args) { + valid = false; + } + } + + private final SCTValidationContext _validationContext = new SCTValidationContext(); + + + // List of precedence for smart simple primitive type determination + // byte, short, int, long, integer, float, double, decimal, + // boolean + // date, dateTime, time, gDuration, + // QName ?, + // anyUri ? - triggered only for http:// or www. constructs, + // list types ? + // string + protected QName processSimpleContentType(String lexicalValue, Inst2XsdOptions options, final XmlCursor xc) { + // check options and return xsd:string or if smart is enabled, look for a better type + if (options.getSimpleContentTypes() == Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING) { + return XmlString.type.getName(); + } + + if (options.getSimpleContentTypes() != Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART) { + throw new IllegalArgumentException("Unknown value for Inst2XsdOptions.getSimpleContentTypes() :" + options.getSimpleContentTypes()); + } + + // Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART case + + + try { + XsTypeConverter.lexByte(lexicalValue); + return XmlByte.type.getName(); + } catch (Exception ignored) { + } + + try { + XsTypeConverter.lexShort(lexicalValue); + return XmlShort.type.getName(); + } catch (Exception ignored) { + } + + try { + XsTypeConverter.lexInt(lexicalValue); + return XmlInt.type.getName(); + } catch (Exception ignored) { + } + + try { + XsTypeConverter.lexLong(lexicalValue); + return XmlLong.type.getName(); + } catch (Exception ignored) { + } + + try { + XsTypeConverter.lexInteger(lexicalValue); + return XmlInteger.type.getName(); + } catch (Exception ignored) { + } + + try { + XsTypeConverter.lexFloat(lexicalValue); + return XmlFloat.type.getName(); + } catch (Exception ignored) { + } + +// // this not needed because it's lexical space is covered by float +// try +// { +// XsTypeConverter.lexDouble(lexicalValue); +// return XmlDouble.type.getName(); +// } +// catch (Exception e) {} +// +// try +// { +// XsTypeConverter.lexDecimal(lexicalValue); +// return XmlDecimal.type.getName(); +// } +// catch (Exception e) {} + + XmlDateImpl.validateLexical(lexicalValue, XmlDate.type, _validationContext); + if (_validationContext.isValid()) { + return XmlDate.type.getName(); + } + _validationContext.resetToValid(); + + XmlDateTimeImpl.validateLexical(lexicalValue, XmlDateTime.type, _validationContext); + if (_validationContext.isValid()) { + return XmlDateTime.type.getName(); + } + _validationContext.resetToValid(); + + XmlTimeImpl.validateLexical(lexicalValue, XmlTime.type, _validationContext); + if (_validationContext.isValid()) { + return XmlTime.type.getName(); + } + _validationContext.resetToValid(); + + XmlDurationImpl.validateLexical(lexicalValue, XmlDuration.type, _validationContext); + if (_validationContext.isValid()) { + return XmlDuration.type.getName(); + } + _validationContext.resetToValid(); + + // check for uri + if (lexicalValue.startsWith("http://") || lexicalValue.startsWith("www.")) { + XmlAnyUriImpl.validateLexical(lexicalValue, _validationContext); + if (_validationContext.isValid()) { + return XmlAnyURI.type.getName(); + } + _validationContext.resetToValid(); + } + + // check for QName + int idx = lexicalValue.indexOf(':'); + if (idx >= 0 && idx == lexicalValue.lastIndexOf(':') && idx + 1 < lexicalValue.length()) { + XmlQNameImpl.validateLexical(lexicalValue, _validationContext, xc::namespaceForPrefix); + if (_validationContext.isValid()) { + return XmlQName.type.getName(); + } + _validationContext.resetToValid(); + } + + //the check for lists is probably too expensive + + return XmlString.type.getName(); + } + + + protected void combineTypes(Type into, Type with, Inst2XsdOptions options) { + if (into == with) { + return; + } + + if (into.isGlobal() && with.isGlobal() && into.getName().equals(with.getName())) { + return; + } + + + if (into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT && + with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT) { + combineSimpleTypes(into, with, options); + return; + } + + if ((into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT || + into.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT) && + (with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT || + with.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT)) { + // take the extension name if it's a complex type + QName intoTypeName = into.isComplexType() ? into.getExtensionType().getName() : into.getName(); + QName withTypeName = with.isComplexType() ? with.getExtensionType().getName() : with.getName(); + + //complex type simple content + into.setContentType(Type.COMPLEX_TYPE_SIMPLE_CONTENT); + + QName moreGeneralTypeName = combineToMoreGeneralSimpleType(intoTypeName, withTypeName); + if (into.isComplexType()) { + Type extendedType = Type.createNamedType(moreGeneralTypeName, Type.SIMPLE_TYPE_SIMPLE_CONTENT); + into.setExtensionType(extendedType); + } else { + into.setName(moreGeneralTypeName); + } + + combineAttributesOfTypes(into, with); + return; + } + + if (into.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT && + with.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT) { + combineAttributesOfTypes(into, with); + combineElementsOfTypes(into, with, options); + return; + } + + if (into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT || + into.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT || + with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT || + with.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT) { + into.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT); + combineAttributesOfTypes(into, with); + combineElementsOfTypes(into, with, options); + return; + } + + if ((into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT || + into.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT || + into.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT || + into.getContentType() == Type.COMPLEX_TYPE_MIXED_CONTENT) && + (with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT || + with.getContentType() == Type.COMPLEX_TYPE_SIMPLE_CONTENT || + with.getContentType() == Type.COMPLEX_TYPE_COMPLEX_CONTENT || + with.getContentType() == Type.COMPLEX_TYPE_MIXED_CONTENT)) { + into.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT); + combineAttributesOfTypes(into, with); + combineElementsOfTypes(into, with, options); + return; + } + + throw new IllegalArgumentException("Unknown content type."); + } + + protected void combineSimpleTypes(Type into, Type with, Inst2XsdOptions options) { + assert (into.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT && + with.getContentType() == Type.SIMPLE_TYPE_SIMPLE_CONTENT) : "Invalid arguments"; + + //simple type simple content + into.setName(combineToMoreGeneralSimpleType(into.getName(), with.getName())); + + // take care of enumeration values + if (options.isUseEnumerations()) { + into.addAllEnumerationsFrom(with); + + if (into.getEnumerationValues().size() > options.getUseEnumerations()) { + into.closeEnumeration(); + } + } + } + + protected QName combineToMoreGeneralSimpleType(QName t1, QName t2) { + if (t1.equals(t2)) { + return t1; + } + + if (t2.equals(XmlShort.type.getName()) && t1.equals(XmlByte.type.getName())) { + return t2; + } + if (t1.equals(XmlShort.type.getName()) && t2.equals(XmlByte.type.getName())) { + return t1; + } + + if (t2.equals(XmlInt.type.getName()) && + (t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) { + return t2; + } + if (t1.equals(XmlInt.type.getName()) && + (t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) { + return t1; + } + + if (t2.equals(XmlLong.type.getName()) && + (t1.equals(XmlInt.type.getName()) || t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) { + return t2; + } + if (t1.equals(XmlLong.type.getName()) && + (t2.equals(XmlInt.type.getName()) || t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) { + return t1; + } + + if (t2.equals(XmlInteger.type.getName()) && + (t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) || + t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) { + return t2; + } + if (t1.equals(XmlInteger.type.getName()) && + (t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) || + t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) { + return t1; + } + + if (t2.equals(XmlFloat.type.getName()) && + (t1.equals(XmlInteger.type.getName()) || + t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) || + t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName()))) { + return t2; + } + if (t1.equals(XmlFloat.type.getName()) && + (t2.equals(XmlInteger.type.getName()) || + t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) || + t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName()))) { + return t1; + } + + //double, decimal will never get here since they don't get generated + + //the rest of the combinations are not compatible, so they will combine in xsd:string + return XmlString.type.getName(); + } + + protected void combineAttributesOfTypes(Type into, Type from) { + // loop through attributes: add fromAtt if they don't exist, combine them if they exist + outterLoop: + for (int i = 0; i < from.getAttributes().size(); i++) { + Attribute fromAtt = from.getAttributes().get(i); + for (int j = 0; j < into.getAttributes().size(); j++) { + Attribute intoAtt = into.getAttributes().get(j); + if (intoAtt.getName().equals(fromAtt.getName())) { + intoAtt.getType().setName( + combineToMoreGeneralSimpleType(intoAtt.getType().getName(), fromAtt.getType().getName())); + continue outterLoop; + } + } + // fromAtt doesn't exist in into type, will add it right now + into.addAttribute(fromAtt); + } + + //optional attributes: if there are atts in into that are not in from, make them optional + for (int i = 0; i < into.getAttributes().size(); i++) { + Attribute intoAtt = into.getAttributes().get(i); + for (int j = 0; j < from.getAttributes().size(); j++) { + Attribute fromAtt = from.getAttributes().get(j); + if (fromAtt.getName().equals(intoAtt.getName())) { + continue; + } + } + // intoAtt doesn't exist in into type, will add it right now + intoAtt.setOptional(true); + } + } + + protected void combineElementsOfTypes(Type into, Type from, Inst2XsdOptions options) { + boolean needsUnboundedChoice = false; + + if (into.getTopParticleForComplexOrMixedContent() != Type.PARTICLE_SEQUENCE || + from.getTopParticleForComplexOrMixedContent() != Type.PARTICLE_SEQUENCE) { + needsUnboundedChoice = true; + } + + List res = new ArrayList<>(); + + int fromStartingIndex = 0; + int fromMatchedIndex = -1; + int intoMatchedIndex = -1; + + // for each element in into + for (int i = 0; !needsUnboundedChoice && i < into.getElements().size(); i++) { + // try to find one with same name in from + Element intoElement = into.getElements().get(i); + for (int j = fromStartingIndex; j < from.getElements().size(); j++) { + Element fromElement = from.getElements().get(j); + if (intoElement.getName().equals(fromElement.getName())) { + fromMatchedIndex = j; + break; + } + } + + // if not found, it's safe to add this one to result 'res' (as optional) and continue + if (fromMatchedIndex < fromStartingIndex) { + res.add(intoElement); + intoElement.setMinOccurs(0); + continue; + } + + // else try out all from elemens between fromStartingIndex to fromMatchedIndex + // to see if they match one of the into elements + intoMatchingLoop: + for (int j2 = fromStartingIndex; j2 < fromMatchedIndex; j2++) { + Element fromCandidate = from.getElements().get(j2); + + for (int i2 = i + 1; i2 < into.getElements().size(); i2++) { + Element intoCandidate = into.getElements().get(i2); + if (fromCandidate.getName().equals(intoCandidate.getName())) { + intoMatchedIndex = i2; + break intoMatchingLoop; + } + } + } + + if (intoMatchedIndex < i) { + // if none matched they are safe to be added to res as optional + for (int j3 = fromStartingIndex; j3 < fromMatchedIndex; j3++) { + Element fromCandidate = from.getElements().get(j3); + res.add(fromCandidate); + fromCandidate.setMinOccurs(0); + } + // also since into[i] == from[fromMatchedIndex] add it only once + res.add(intoElement); + Element fromMatchedElement = from.getElements().get(fromMatchedIndex); + + if (fromMatchedElement.getMinOccurs() <= 0) { + intoElement.setMinOccurs(0); + } + if (fromMatchedElement.getMaxOccurs() == Element.UNBOUNDED) { + intoElement.setMaxOccurs(Element.UNBOUNDED); + } + + combineTypes(intoElement.getType(), fromMatchedElement.getType(), options); + combineElementComments(intoElement, fromMatchedElement); + + fromStartingIndex = fromMatchedIndex + 1; + } else { + // if matched it means into type will transform into a choice unbounded type + needsUnboundedChoice = true; + } + } + + for (int j = fromStartingIndex; j < from.getElements().size(); j++) { + Element remainingFromElement = from.getElements().get(j); + res.add(remainingFromElement); + remainingFromElement.setMinOccurs(0); + } + + // if choice was detected + if (needsUnboundedChoice) { + into.setTopParticleForComplexOrMixedContent(Type.PARTICLE_CHOICE_UNBOUNDED); + + outterLoop: + for (int j = 0; j < from.getElements().size(); j++) { + Element fromElem = from.getElements().get(j); + for (int i = 0; i < into.getElements().size(); i++) { + Element intoElem = into.getElements().get(i); + intoElem.setMinOccurs(1); + intoElem.setMaxOccurs(1); + + if (intoElem == fromElem) { + continue outterLoop; + } + + if (intoElem.getName().equals(fromElem.getName())) { + combineTypes(intoElem.getType(), fromElem.getType(), options); + combineElementComments(intoElem, fromElem); + + continue outterLoop; + } + } + + // fromElem doesn't exist in into type, will add it right now + into.addElement(fromElem); + fromElem.setMinOccurs(1); + fromElem.setMaxOccurs(1); + } + } else { + // into remains sequence but will contain the new list of elements res + into.setElements(res); + } + } + + protected void combineElementComments(Element into, Element with) { + if (with.getComment() != null && with.getComment().length() > 0) { + if (into.getComment() == null) { + into.setComment(with.getComment()); + } else { + into.setComment(into.getComment() + with.getComment()); + } + } + } +} diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/SalamiSliceStrategy.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/SalamiSliceStrategy.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/SalamiSliceStrategy.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/SalamiSliceStrategy.java diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/VenetianBlindStrategy.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/VenetianBlindStrategy.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/VenetianBlindStrategy.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/VenetianBlindStrategy.java diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/XsdGenStrategy.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/XsdGenStrategy.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/XsdGenStrategy.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/XsdGenStrategy.java diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Attribute.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Attribute.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Attribute.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Attribute.java diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Element.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Element.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Element.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Element.java diff --git a/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java new file mode 100644 index 0000000..e9d3a8e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/Type.java @@ -0,0 +1,277 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.xmlbeans.impl.inst2xsd.util; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlQName; +import org.apache.xmlbeans.impl.values.XmlQNameImpl; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Cezar Andrei (cezar.andrei at bea.com) Date: Jul 16, 2004 + */ +public class Type { + private QName _name; + + private int _kind = SIMPLE_TYPE_SIMPLE_CONTENT; + // _kind value space + public static final int SIMPLE_TYPE_SIMPLE_CONTENT = 1; // ie no atts, no elems, just text + public static final int COMPLEX_TYPE_SIMPLE_CONTENT = 2; // ie atts*, no elems, text* - simple type extension + public static final int COMPLEX_TYPE_COMPLEX_CONTENT = 3; // ie atts*, elems, no text + public static final int COMPLEX_TYPE_MIXED_CONTENT = 4; // ie atts*, elems, text + public static final int COMPLEX_TYPE_EMPTY_CONTENT = 5; // no elems, no text, just atts + + private int _topParticleForComplexOrMixedContent = PARTICLE_SEQUENCE; + // _topParticleForComplexOrMixedContent + public static final int PARTICLE_SEQUENCE = 1; + public static final int PARTICLE_CHOICE_UNBOUNDED = 2; + + private List _elements; // size>0 COMPLEX + private List _attributes; // size>0 COMPLEX + + private Type _extensionType; + private boolean _isGlobal = false; + + private List _enumerationValues; + private boolean _acceptsEnumerationValue = true; + private List _enumerationQNames; // This is a special case where the lexical representation + // is not enough for a value, the QNames need to be remembered + // in case the _extensionType is QName + + protected Type() { + } + + public static Type createNamedType(QName name, int contentType) { + assert name != null; + Type type = new Type(); + type.setName(name); + type.setContentType(contentType); + return type; + } + + public static Type createUnnamedType(int contentType) { + assert contentType == SIMPLE_TYPE_SIMPLE_CONTENT || + contentType == COMPLEX_TYPE_SIMPLE_CONTENT || + contentType == COMPLEX_TYPE_COMPLEX_CONTENT || + contentType == COMPLEX_TYPE_MIXED_CONTENT || + contentType == COMPLEX_TYPE_EMPTY_CONTENT : "Unknown contentType: " + contentType; + Type type = new Type(); + type.setContentType(contentType); + return type; + } + + + public QName getName() { + return _name; + } + + public void setName(QName name) { + this._name = name; + } + + /** + * @return SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text + * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension + * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text + * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text + * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts + */ + public int getContentType() { + return _kind; + } + + /** + * @param kind 4 kinds: + * SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text + * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension + * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text + * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text + * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts + */ + public void setContentType(int kind) { + this._kind = kind; + } + + public List getElements() { + ensureElements(); + return _elements; + } + + public void addElement(Element element) { + ensureElements(); + _elements.add(element); + } + + public void setElements(List elements) { + ensureElements(); + _elements.clear(); + _elements.addAll(elements); + } + + private void ensureElements() { + if (_elements == null) { + _elements = new ArrayList<>(); + } + } + + public List getAttributes() { + ensureAttributes(); + return _attributes; + } + + public void addAttribute(Attribute attribute) { + ensureAttributes(); + _attributes.add(attribute); + } + + public Attribute getAttribute(QName name) { + for (Attribute value : _attributes) { + if (value.getName().equals(name)) { + return value; + } + } + return null; + } + + private void ensureAttributes() { + if (_attributes == null) { + _attributes = new ArrayList<>(); + } + } + + public boolean isComplexType() { + return (_kind == COMPLEX_TYPE_COMPLEX_CONTENT || + _kind == COMPLEX_TYPE_MIXED_CONTENT || + _kind == COMPLEX_TYPE_SIMPLE_CONTENT); + } + + public boolean hasSimpleContent() { + return (_kind == SIMPLE_TYPE_SIMPLE_CONTENT || + _kind == COMPLEX_TYPE_SIMPLE_CONTENT); + } + + /** + * @return PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED + */ + public int getTopParticleForComplexOrMixedContent() { + return _topParticleForComplexOrMixedContent; + } + + /** + * @param topParticleForComplexOrMixedContent PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED + */ + public void setTopParticleForComplexOrMixedContent(int topParticleForComplexOrMixedContent) { + this._topParticleForComplexOrMixedContent = topParticleForComplexOrMixedContent; + } + + public boolean isGlobal() { + return _isGlobal; + } + + public void setGlobal(boolean isGlobal) { + assert isGlobal && getName() != null; + _isGlobal = isGlobal; + } + + public Type getExtensionType() { + return _extensionType; + } + + public void setExtensionType(Type extendedType) { + assert _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Extension used only for type which are COMPLEX_TYPE_SIMPLE_CONTENT"; + assert extendedType != null && extendedType.getName() != null : "Extended type must be a named type."; + _extensionType = extendedType; + } + + public List getEnumerationValues() { + ensureEnumerationValues(); + return _enumerationValues; + } + + public List getEnumerationQNames() { + ensureEnumerationValues(); + return _enumerationQNames; + } + + public void addEnumerationValue(String enumerationValue, final XmlCursor xc) { + assert _kind == SIMPLE_TYPE_SIMPLE_CONTENT || _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content"; + ensureEnumerationValues(); + if (_acceptsEnumerationValue && !_enumerationValues.contains(enumerationValue)) { + _enumerationValues.add(enumerationValue); + if (_name.equals(XmlQName.type.getName())) { + // check for QName + QName qname = XmlQNameImpl.validateLexical(enumerationValue, null, xc::namespaceForPrefix); + + assert qname != null : "The check for QName should allready have happened."; + _enumerationQNames.add(qname); + } + } + } + + private void ensureEnumerationValues() { + if (_enumerationValues == null) { + _enumerationValues = new ArrayList<>(); + _enumerationQNames = new ArrayList<>(); + } + } + + public boolean isEnumeration() { + return _acceptsEnumerationValue && _enumerationValues != null && _enumerationValues.size() > 1; + } + + public boolean isQNameEnumeration() { + return isEnumeration() && _name.equals(XmlQName.type.getName()) && _enumerationQNames != null && _enumerationQNames.size() > 1; + } + + public void closeEnumeration() { + _acceptsEnumerationValue = false; + } + + public String toString() { + return "Type{" + + "_name = " + _name + + ", _extensionType = " + _extensionType + + ", _kind = " + _kind + + ", _elements = " + _elements + + ", _attributes = " + _attributes + + "}"; + } + + public void addAllEnumerationsFrom(Type from) { + assert _kind == SIMPLE_TYPE_SIMPLE_CONTENT || _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content"; + ensureEnumerationValues(); + + if (_name.equals(XmlQName.type.getName()) && from._name.equals(XmlQName.type.getName())) { + for (int i = 0; i < from.getEnumerationValues().size(); i++) { + String enumValue = from.getEnumerationValues().get(i); + QName enumQNameValue = from.getEnumerationQNames().get(i); + if (_acceptsEnumerationValue && !_enumerationQNames.contains(enumQNameValue)) { + _enumerationValues.add(enumValue); + _enumerationQNames.add(enumQNameValue); + } + } + } else { + for (int i = 0; i < from.getEnumerationValues().size(); i++) { + String enumValue = from.getEnumerationValues().get(i); + if (_acceptsEnumerationValue && !_enumerationValues.contains(enumValue)) { + _enumerationValues.add(enumValue); + } + } + } + } +} diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/util/TypeSystemHolder.java b/src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/TypeSystemHolder.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/inst2xsd/util/TypeSystemHolder.java rename to src/main/java/org/apache/xmlbeans/impl/inst2xsd/util/TypeSystemHolder.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/BMPattern.java b/src/main/java/org/apache/xmlbeans/impl/regex/BMPattern.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/BMPattern.java rename to src/main/java/org/apache/xmlbeans/impl/regex/BMPattern.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/Match.java b/src/main/java/org/apache/xmlbeans/impl/regex/Match.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/Match.java rename to src/main/java/org/apache/xmlbeans/impl/regex/Match.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/Op.java b/src/main/java/org/apache/xmlbeans/impl/regex/Op.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/Op.java rename to src/main/java/org/apache/xmlbeans/impl/regex/Op.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/ParseException.java b/src/main/java/org/apache/xmlbeans/impl/regex/ParseException.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/ParseException.java rename to src/main/java/org/apache/xmlbeans/impl/regex/ParseException.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/ParserForXMLSchema.java b/src/main/java/org/apache/xmlbeans/impl/regex/ParserForXMLSchema.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/ParserForXMLSchema.java rename to src/main/java/org/apache/xmlbeans/impl/regex/ParserForXMLSchema.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/README.txt b/src/main/java/org/apache/xmlbeans/impl/regex/README.txt similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/README.txt rename to src/main/java/org/apache/xmlbeans/impl/regex/README.txt diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/REUtil.java b/src/main/java/org/apache/xmlbeans/impl/regex/REUtil.java similarity index 98% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/REUtil.java rename to src/main/java/org/apache/xmlbeans/impl/regex/REUtil.java index 089fe88..80a3dc7 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/regex/REUtil.java +++ b/src/main/java/org/apache/xmlbeans/impl/regex/REUtil.java @@ -101,7 +101,7 @@ static final int parseOptions(String opts) throws ParseException { } static final String createOptionString(int options) { - StringBuffer sb = new StringBuffer(9); + StringBuilder sb = new StringBuilder(9); if ((options & RegularExpression.PROHIBIT_FIXED_STRING_OPTIMIZATION) != 0) sb.append((char)'F'); if ((options & RegularExpression.PROHIBIT_HEAD_CHARACTER_OPTIMIZATION) != 0) @@ -129,7 +129,7 @@ static final String createOptionString(int options) { static String stripExtendedComment(String regex) { int len = regex.length(); - StringBuffer buffer = new StringBuffer(len); + StringBuilder buffer = new StringBuilder(len); int offset = 0; while (offset < len) { int ch = regex.charAt(offset++); @@ -298,12 +298,12 @@ public static boolean matches(String regex, String options, String target) throw */ public static String quoteMeta(String literal) { int len = literal.length(); - StringBuffer buffer = null; + StringBuilder buffer = null; for (int i = 0; i < len; i ++) { int ch = literal.charAt(i); if (".*+?{[()|\\^$".indexOf(ch) >= 0) { if (buffer == null) { - buffer = new StringBuffer(i+(len-i)*2); + buffer = new StringBuilder(i+(len-i)*2); if (i > 0) buffer.append(literal.substring(0, i)); } buffer.append((char)'\\'); diff --git a/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java b/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java new file mode 100644 index 0000000..e1d2f97 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java @@ -0,0 +1,656 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.regex; + +/** + * This class represents a character class such as [a-z] or a period. + */ +final class RangeToken extends Token implements java.io.Serializable { + + int[] ranges; + boolean sorted; + boolean compacted; + RangeToken icaseCache = null; + int[] map = null; + int nonMapIndex; + + RangeToken(int type) { + super(type); + this.setSorted(false); + } + + // for RANGE or NRANGE + protected void addRange(int start, int end) { + this.icaseCache = null; + //System.err.println("Token#addRange(): "+start+" "+end); + int r1, r2; + if (start <= end) { + r1 = start; + r2 = end; + } else { + r1 = end; + r2 = start; + } + + if (this.ranges == null) { + this.ranges = new int[2]; + this.ranges[0] = r1; + this.ranges[1] = r2; + this.setSorted(true); + } else { + int pos = this.ranges.length; + if (this.ranges[pos - 1] + 1 == r1) { + this.ranges[pos - 1] = r2; + return; + } + int[] temp = new int[pos + 2]; + System.arraycopy(this.ranges, 0, temp, 0, pos); + this.ranges = temp; + if (this.ranges[pos - 1] >= r1) { + this.setSorted(false); + } + this.ranges[pos++] = r1; + this.ranges[pos] = r2; + if (!this.sorted) { + this.sortRanges(); + } + } + } + + private boolean isSorted() { + return this.sorted; + } + + private void setSorted(boolean sort) { + this.sorted = sort; + if (!sort) { + this.compacted = false; + } + } + + private boolean isCompacted() { + return this.compacted; + } + + private void setCompacted() { + this.compacted = true; + } + + protected void sortRanges() { + if (this.isSorted()) { + return; + } + if (this.ranges == null) { + return; + } + //System.err.println("Do sorting: "+this.ranges.length); + + // Bubble sort + // Why? -- In many cases, + // this.ranges has few elements. + for (int i = this.ranges.length - 4; i >= 0; i -= 2) { + for (int j = 0; j <= i; j += 2) { + if (this.ranges[j] > this.ranges[j + 2] + || this.ranges[j] == this.ranges[j + 2] && this.ranges[j + 1] > this.ranges[j + 3]) { + int tmp; + tmp = this.ranges[j + 2]; + this.ranges[j + 2] = this.ranges[j]; + this.ranges[j] = tmp; + tmp = this.ranges[j + 3]; + this.ranges[j + 3] = this.ranges[j + 1]; + this.ranges[j + 1] = tmp; + } + } + } + this.setSorted(true); + } + + /** + * this.ranges is sorted. + */ + @SuppressWarnings("ConstantConditions") + protected void compactRanges() { + boolean DEBUG = false; + if (this.ranges == null || this.ranges.length <= 2) { + return; + } + if (this.isCompacted()) { + return; + } + int base = 0; // Index of writing point + int target = 0; // Index of processing point + + while (target < this.ranges.length) { + if (base != target) { + this.ranges[base] = this.ranges[target++]; + this.ranges[base + 1] = this.ranges[target++]; + } else { + target += 2; + } + int baseend = this.ranges[base + 1]; + while (target < this.ranges.length) { + if (baseend + 1 < this.ranges[target]) { + break; + } + if (baseend + 1 == this.ranges[target]) { + if (DEBUG) { + System.err.println("Token#compactRanges(): Compaction: [" + this.ranges[base] + + ", " + this.ranges[base + 1] + + "], [" + this.ranges[target] + + ", " + this.ranges[target + 1] + + "] -> [" + this.ranges[base] + + ", " + this.ranges[target + 1] + + "]"); + } + this.ranges[base + 1] = this.ranges[target + 1]; + baseend = this.ranges[base + 1]; + target += 2; + } else if (baseend >= this.ranges[target + 1]) { + if (DEBUG) { + System.err.println("Token#compactRanges(): Compaction: [" + this.ranges[base] + + ", " + this.ranges[base + 1] + + "], [" + this.ranges[target] + + ", " + this.ranges[target + 1] + + "] -> [" + this.ranges[base] + + ", " + this.ranges[base + 1] + + "]"); + } + target += 2; + } else if (baseend < this.ranges[target + 1]) { + if (DEBUG) { + System.err.println("Token#compactRanges(): Compaction: [" + this.ranges[base] + + ", " + this.ranges[base + 1] + + "], [" + this.ranges[target] + + ", " + this.ranges[target + 1] + + "] -> [" + this.ranges[base] + + ", " + this.ranges[target + 1] + + "]"); + } + this.ranges[base + 1] = this.ranges[target + 1]; + baseend = this.ranges[base + 1]; + target += 2; + } else { + throw new RuntimeException("Token#compactRanges(): Internel Error: [" + + this.ranges[base] + + "," + this.ranges[base + 1] + + "] [" + this.ranges[target] + + "," + this.ranges[target + 1] + "]"); + } + } // while + base += 2; + } + + if (base != this.ranges.length) { + int[] result = new int[base]; + System.arraycopy(this.ranges, 0, result, 0, base); + this.ranges = result; + } + this.setCompacted(); + } + + protected void mergeRanges(Token token) { + RangeToken tok = (RangeToken) token; + this.sortRanges(); + tok.sortRanges(); + if (tok.ranges == null) { + return; + } + this.icaseCache = null; + this.setSorted(true); + if (this.ranges == null) { + this.ranges = new int[tok.ranges.length]; + System.arraycopy(tok.ranges, 0, this.ranges, 0, tok.ranges.length); + return; + } + int[] result = new int[this.ranges.length + tok.ranges.length]; + for (int i = 0, j = 0, k = 0; i < this.ranges.length || j < tok.ranges.length; ) { + if (i >= this.ranges.length) { + result[k++] = tok.ranges[j++]; + result[k++] = tok.ranges[j++]; + } else if (j >= tok.ranges.length) { + result[k++] = this.ranges[i++]; + result[k++] = this.ranges[i++]; + } else if (tok.ranges[j] < this.ranges[i] + || tok.ranges[j] == this.ranges[i] && tok.ranges[j + 1] < this.ranges[i + 1]) { + result[k++] = tok.ranges[j++]; + result[k++] = tok.ranges[j++]; + } else { + result[k++] = this.ranges[i++]; + result[k++] = this.ranges[i++]; + } + } + this.ranges = result; + } + + protected void subtractRanges(Token token) { + if (token.type == NRANGE) { + this.intersectRanges(token); + return; + } + RangeToken tok = (RangeToken) token; + if (tok.ranges == null || this.ranges == null) { + return; + } + this.icaseCache = null; + this.sortRanges(); + this.compactRanges(); + tok.sortRanges(); + tok.compactRanges(); + + //System.err.println("Token#substractRanges(): Entry: "+this.ranges.length+", "+tok.ranges.length); + + int[] result = new int[this.ranges.length + tok.ranges.length]; + int wp = 0, src = 0, sub = 0; + while (src < this.ranges.length && sub < tok.ranges.length) { + int srcbegin = this.ranges[src]; + int srcend = this.ranges[src + 1]; + int subbegin = tok.ranges[sub]; + int subend = tok.ranges[sub + 1]; + if (srcend < subbegin) { // Not overlapped + // src: o-----o + // sub: o-----o + // res: o-----o + // Reuse sub + result[wp++] = this.ranges[src++]; + result[wp++] = this.ranges[src++]; + } else if (srcend >= subbegin + && srcbegin <= subend) { // Overlapped + // src: o--------o + // sub: o----o + // sub: o----o + // sub: o----o + // sub: o------------o + if (subbegin <= srcbegin && srcend <= subend) { + // src: o--------o + // sub: o------------o + // res: empty + // Reuse sub + src += 2; + } else if (subbegin <= srcbegin) { + // src: o--------o + // sub: o----o + // res: o-----o + // Reuse src(=res) + this.ranges[src] = subend + 1; + sub += 2; + } else if (srcend <= subend) { + // src: o--------o + // sub: o----o + // res: o-----o + // Reuse sub + result[wp++] = srcbegin; + result[wp++] = subbegin - 1; + src += 2; + } else { + // src: o--------o + // sub: o----o + // res: o-o o-o + // Reuse src(=right res) + result[wp++] = srcbegin; + result[wp++] = subbegin - 1; + this.ranges[src] = subend + 1; + sub += 2; + } + } else if (subend < srcbegin) { + // Not overlapped + // src: o-----o + // sub: o----o + sub += 2; + } else { + throw new RuntimeException("Token#subtractRanges(): Internal Error: [" + this.ranges[src] + + "," + this.ranges[src + 1] + + "] - [" + tok.ranges[sub] + + "," + tok.ranges[sub + 1] + + "]"); + } + } + while (src < this.ranges.length) { + result[wp++] = this.ranges[src++]; + result[wp++] = this.ranges[src++]; + } + this.ranges = new int[wp]; + System.arraycopy(result, 0, this.ranges, 0, wp); + // this.ranges is sorted and compacted. + } + + /** + * @param token Ignore whether it is NRANGE or not. + */ + protected void intersectRanges(Token token) { + RangeToken tok = (RangeToken) token; + if (tok.ranges == null || this.ranges == null) { + return; + } + this.icaseCache = null; + this.sortRanges(); + this.compactRanges(); + tok.sortRanges(); + tok.compactRanges(); + + int[] result = new int[this.ranges.length + tok.ranges.length]; + int wp = 0, src1 = 0, src2 = 0; + while (src1 < this.ranges.length && src2 < tok.ranges.length) { + int src1begin = this.ranges[src1]; + int src1end = this.ranges[src1 + 1]; + int src2begin = tok.ranges[src2]; + int src2end = tok.ranges[src2 + 1]; + if (src1end < src2begin) { // Not overlapped + // src1: o-----o + // src2: o-----o + // res: empty + // Reuse src2 + src1 += 2; + } else if (src1end >= src2begin + && src1begin <= src2end) { // Overlapped + // src1: o--------o + // src2: o----o + // src2: o----o + // src2: o----o + // src2: o------------o + if (src2begin <= src1begin && src1end <= src2end) { + // src1: o--------o + // src2: o------------o + // res: o--------o + // Reuse src2 + result[wp++] = src1begin; + result[wp++] = src1end; + src1 += 2; + } else if (src2begin <= src1begin) { + // src1: o--------o + // src2: o----o + // res: o--o + // Reuse the rest of src1 + result[wp++] = src1begin; + result[wp++] = src2end; + this.ranges[src1] = src2end + 1; + src2 += 2; + } else if (src1end <= src2end) { + // src1: o--------o + // src2: o----o + // res: o--o + // Reuse src2 + result[wp++] = src2begin; + result[wp++] = src1end; + src1 += 2; + } else { + // src1: o--------o + // src2: o----o + // res: o----o + // Reuse the rest of src1 + result[wp++] = src2begin; + result[wp++] = src2end; + this.ranges[src1] = src2end + 1; + } + } else if (src2end < src1begin) { + // Not overlapped + // src1: o-----o + // src2: o----o + src2 += 2; + } else { + throw new RuntimeException("Token#intersectRanges(): Internal Error: [" + + this.ranges[src1] + + "," + this.ranges[src1 + 1] + + "] & [" + tok.ranges[src2] + + "," + tok.ranges[src2 + 1] + + "]"); + } + } + while (src1 < this.ranges.length) { + result[wp++] = this.ranges[src1++]; + result[wp++] = this.ranges[src1++]; + } + this.ranges = new int[wp]; + System.arraycopy(result, 0, this.ranges, 0, wp); + // this.ranges is sorted and compacted. + } + + /** + * for RANGE: Creates complement. + * for NRANGE: Creates the same meaning RANGE. + */ + static Token complementRanges(Token token) { + if (token.type != RANGE && token.type != NRANGE) { + throw new IllegalArgumentException("Token#complementRanges(): must be RANGE: " + token.type); + } + RangeToken tok = (RangeToken) token; + tok.sortRanges(); + tok.compactRanges(); + int len = tok.ranges.length + 2; + if (tok.ranges[0] == 0) { + len -= 2; + } + int last = tok.ranges[tok.ranges.length - 1]; + if (last == UTF16_MAX) { + len -= 2; + } + RangeToken ret = Token.createRange(); + ret.ranges = new int[len]; + int wp = 0; + if (tok.ranges[0] > 0) { + ret.ranges[wp++] = 0; + ret.ranges[wp++] = tok.ranges[0] - 1; + } + for (int i = 1; i < tok.ranges.length - 2; i += 2) { + ret.ranges[wp++] = tok.ranges[i] + 1; + ret.ranges[wp++] = tok.ranges[i + 1] - 1; + } + if (last != UTF16_MAX) { + ret.ranges[wp++] = last + 1; + ret.ranges[wp] = UTF16_MAX; + } + ret.setCompacted(); + return ret; + } + + synchronized RangeToken getCaseInsensitiveToken() { + if (this.icaseCache != null) { + return this.icaseCache; + } + + RangeToken uppers = this.type == Token.RANGE ? Token.createRange() : Token.createNRange(); + for (int i = 0; i < this.ranges.length; i += 2) { + for (int ch = this.ranges[i]; ch <= this.ranges[i + 1]; ch++) { + if (ch > 0xffff) { + uppers.addRange(ch, ch); + } else { + char uch = Character.toUpperCase((char) ch); + uppers.addRange(uch, uch); + } + } + } + RangeToken lowers = this.type == Token.RANGE ? Token.createRange() : Token.createNRange(); + for (int i = 0; i < uppers.ranges.length; i += 2) { + for (int ch = uppers.ranges[i]; ch <= uppers.ranges[i + 1]; ch++) { + if (ch > 0xffff) { + lowers.addRange(ch, ch); + } else { + char uch = Character.toUpperCase((char) ch); + lowers.addRange(uch, uch); + } + } + } + lowers.mergeRanges(uppers); + lowers.mergeRanges(this); + lowers.compactRanges(); + + this.icaseCache = lowers; + return lowers; + } + + boolean match(int ch) { + if (this.map == null) { + this.createMap(); + } + boolean ret; + if (this.type == RANGE) { + if (ch < MAPSIZE) { + return (this.map[ch / 32] & (1 << (ch & 0x1f))) != 0; + } + ret = false; + for (int i = this.nonMapIndex; i < this.ranges.length; i += 2) { + if (this.ranges[i] <= ch && ch <= this.ranges[i + 1]) { + return true; + } + } + } else { + if (ch < MAPSIZE) { + return (this.map[ch / 32] & (1 << (ch & 0x1f))) == 0; + } + ret = true; + for (int i = this.nonMapIndex; i < this.ranges.length; i += 2) { + if (this.ranges[i] <= ch && ch <= this.ranges[i + 1]) { + return false; + } + } + } + return ret; + } + + private static final int MAPSIZE = 256; + + private void createMap() { + int asize = MAPSIZE / 32; // 32 is the number of bits in `int'. + // CHANGE(radup) we need a new map, since this is not synchronized + // and if we init the instance map with 0's it's going to be trouble + // -this.map = new int[asize]; + // -this.nonMapIndex = this.ranges.length; + // -for (int i = 0; i < asize; i++) this.map[i] = 0; + int[] localmap = new int[asize]; // + + int localnonMapIndex = this.ranges.length; // + + for (int i = 0; i < asize; i++) { + localmap[i] = 0; // + redundant + } + for (int i = 0; i < this.ranges.length; i += 2) { + int s = this.ranges[i]; + int e = this.ranges[i + 1]; + if (s < MAPSIZE) { + for (int j = s; j <= e && j < MAPSIZE; j++) { + localmap[j / 32] |= 1 << (j & 0x1f); // s&0x1f : 0-31 + } + } else { + localnonMapIndex = i; + break; + } + if (e >= MAPSIZE) { + localnonMapIndex = i; + break; + } + } + this.nonMapIndex = localnonMapIndex; // + + this.map = localmap; // + + //for (int i = 0; i < asize; i ++) System.err.println("Map: "+Integer.toString(this.map[i], 16)); + } + + public String toString(int options) { + String ret; + if (this.type == RANGE) { + if (this == Token.token_dot) { + ret = "."; + } else if (this == Token.token_0to9) { + ret = "\\d"; + } else if (this == Token.token_wordchars) { + ret = "\\w"; + } else if (this == Token.token_spaces) { + ret = "\\s"; + } else { + StringBuilder sb = new StringBuilder(); + sb.append("["); + for (int i = 0; i < this.ranges.length; i += 2) { + if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0) { + sb.append(","); + } + if (this.ranges[i] == this.ranges[i + 1]) { + sb.append(escapeCharInCharClass(this.ranges[i])); + } else { + sb.append(escapeCharInCharClass(this.ranges[i])); + sb.append('-'); + sb.append(escapeCharInCharClass(this.ranges[i + 1])); + } + } + sb.append("]"); + ret = sb.toString(); + } + } else { + if (this == Token.token_not_0to9) { + ret = "\\D"; + } else if (this == Token.token_not_wordchars) { + ret = "\\W"; + } else if (this == Token.token_not_spaces) { + ret = "\\S"; + } else { + StringBuilder sb = new StringBuilder(); + sb.append("[^"); + for (int i = 0; i < this.ranges.length; i += 2) { + if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0) { + sb.append(","); + } + if (this.ranges[i] == this.ranges[i + 1]) { + sb.append(escapeCharInCharClass(this.ranges[i])); + } else { + sb.append(escapeCharInCharClass(this.ranges[i])); + sb.append('-'); + sb.append(escapeCharInCharClass(this.ranges[i + 1])); + } + } + sb.append("]"); + ret = sb.toString(); + } + } + return ret; + } + + private static String escapeCharInCharClass(int ch) { + String ret; + switch (ch) { + case '[': + case ']': + case '-': + case '^': + case ',': + case '\\': + ret = "\\" + (char) ch; + break; + case '\f': + ret = "\\f"; + break; + case '\n': + ret = "\\n"; + break; + case '\r': + ret = "\\r"; + break; + case '\t': + ret = "\\t"; + break; + case 0x1b: + ret = "\\e"; + break; + //case 0x0b: ret = "\\v"; break; + default: + if (ch < 0x20) { + String pre = "0" + Integer.toHexString(ch); + ret = "\\x" + pre.substring(pre.length() - 2); + } else if (ch >= 0x10000) { + String pre = "0" + Integer.toHexString(ch); + ret = "\\v" + pre.substring(pre.length() - 6); + } else { + ret = "" + (char) ch; + } + } + return ret; + } + +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/RegexParser.java b/src/main/java/org/apache/xmlbeans/impl/regex/RegexParser.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/RegexParser.java rename to src/main/java/org/apache/xmlbeans/impl/regex/RegexParser.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/RegularExpression.java b/src/main/java/org/apache/xmlbeans/impl/regex/RegularExpression.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/RegularExpression.java rename to src/main/java/org/apache/xmlbeans/impl/regex/RegularExpression.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/SchemaRegularExpression.java b/src/main/java/org/apache/xmlbeans/impl/regex/SchemaRegularExpression.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/SchemaRegularExpression.java rename to src/main/java/org/apache/xmlbeans/impl/regex/SchemaRegularExpression.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/Token.java b/src/main/java/org/apache/xmlbeans/impl/regex/Token.java similarity index 99% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/Token.java rename to src/main/java/org/apache/xmlbeans/impl/regex/Token.java index 6d85fb2..16f9ebd 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/regex/Token.java +++ b/src/main/java/org/apache/xmlbeans/impl/regex/Token.java @@ -828,7 +828,7 @@ static protected RangeToken getRange(String name, boolean positive) { //REVISIT: do we really need to support block names as in Unicode 3.1 // or we can just create all the names in IsBLOCKNAME format (XML Schema REC)? // - StringBuffer buffer = new StringBuffer(50); + StringBuilder buffer = new StringBuilder(50); for (int i = 0; i < Token.blockNames.length; i ++) { Token r1 = Token.createRange(); int location; @@ -1441,10 +1441,10 @@ void addChild(Token tok) { //System.err.println("Merge '"+previous+"' and '"+tok+"'."); - StringBuffer buffer; + StringBuilder buffer; int nextMaxLength = (tok.type == CHAR ? 2 : tok.getString().length()); if (previous.type == CHAR) { // Replace previous token by STRING - buffer = new StringBuffer(2 + nextMaxLength); + buffer = new StringBuilder(2 + nextMaxLength); int ch = previous.getChar(); if (ch >= 0x10000) buffer.append(REUtil.decomposeToSurrogates(ch)); @@ -1453,7 +1453,7 @@ void addChild(Token tok) { previous = Token.createString(null); this.children.setElementAt(previous, size-1); } else { // STRING - buffer = new StringBuffer(previous.getString().length() + nextMaxLength); + buffer = new StringBuilder(previous.getString().length() + nextMaxLength); buffer.append(previous.getString()); } @@ -1490,7 +1490,7 @@ public String toString(int options) { } else ret = ch.toString(options)+ch2.toString(options); } else { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.children.size(); i ++) { sb.append(((Token)this.children.elementAt(i)).toString(options)); } @@ -1504,7 +1504,7 @@ public String toString(int options) { && this.getChild(0).type == EMPTY) { ret = this.getChild(1).toString(options)+"??"; } else { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(((Token)this.children.elementAt(0)).toString(options)); for (int i = 1; i < this.children.size(); i ++) { sb.append((char)'|'); diff --git a/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java b/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java new file mode 100644 index 0000000..0d26b03 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/repackage/EditBuildScript.java @@ -0,0 +1,85 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.repackage; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +public class EditBuildScript { + // + // usgae: edit buildfile token new-value + // + + public static void main(String[] args) throws Exception { + if (args.length != 3) { + throw new IllegalArgumentException("Wrong number of arguments"); + } + + args[0] = args[0].replace('/', File.separatorChar); + + File buildFile = new File(args[0]); + + StringBuffer sb = readFile(buildFile); + + String tokenStr = "> _fromPackages; + private List> _toPackages; + + private Pattern _packagePattern; + + private final Repackager _repackager; + + private Map _movedDirs; + private List _moveAlongFiles; + private int _skippedFiles; + + public static void main(String[] args) throws Exception { + new Repackage(args).repackage(); + } + + private Repackage(String[] args) { + String sourceDir = null; + String targetDir = null; + String repackageSpec = null; + boolean failure = false; + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-repackage") && i + 1 < args.length) { + repackageSpec = args[++i]; + } else if (args[i].equals("-f") && i + 1 < args.length) { + sourceDir = args[++i]; + } else if (args[i].equals("-t") && i + 1 < args.length) { + targetDir = args[++i]; + } else { + failure = true; + } + } + + if (failure || repackageSpec == null || (sourceDir == null ^ targetDir == null)) { + throw new RuntimeException("Usage: repackage -repackage [spec] [ -f [sourcedir] -t [targetdir] ]"); + } + + _repackager = new Repackager(repackageSpec); + + //noinspection ConstantConditions + if (sourceDir == null || targetDir == null) { + _sourceBase = _targetBase = null; + } else { + _sourceBase = new File(sourceDir); + _targetBase = new File(targetDir); + } + } + + + public void repackage() throws Exception { + if (_sourceBase == null || _targetBase == null) { + // read from system.in, write on system.out + System.out.println(_repackager.repackage(readInputStream(System.in)).toString()); + return; + } + + _fromPackages = _repackager.getFromPackages(); + _toPackages = _repackager.getToPackages(); + + _packagePattern = Pattern.compile("^\\s*package\\s+((?:\\w|\\.)*)\\s*;", Pattern.MULTILINE); + + _moveAlongFiles = new ArrayList<>(); + _movedDirs = new HashMap<>(); + +// System.out.println( "Deleting repackage dir ..." ); +// recursiveDelete( _targetBase ); + + _targetBase.mkdirs(); + + List files = new ArrayList<>(); + + fillFiles(files, _sourceBase); + + System.out.println("Repackaging " + files.size() + " files ..."); + + int prefixLength = _sourceBase.getCanonicalPath().length(); + + for (File from : files) { + + String name = from.getCanonicalPath().substring(prefixLength + 1); + + repackageFile(name); + } + + finishMovingFiles(); + + if (_skippedFiles > 0) { + System.out.println("Skipped " + _skippedFiles + " unmodified files."); + } + } + + public void repackageFile(String name) + throws IOException { + if (name.endsWith(".java")) { + repackageJavaFile(name); + } else if (name.endsWith(".xsdconfig") || + name.endsWith(".xml") || + name.endsWith(".g")) { + repackageNonJavaFile(name); + } else if (name.startsWith("bin" + File.separatorChar)) { + repackageNonJavaFile(name); + } else { + moveAlongWithJavaFiles(name); + } + } + + public void moveAlongWithJavaFiles(String name) { + _moveAlongFiles.add(name); + } + + public void finishMovingFiles() + throws IOException { + for (String name : _moveAlongFiles) { + String srcDir = Repackager.dirForPath(name); + String toDir = _movedDirs.get(srcDir); + + String toName = (toDir == null) ? name : new File(toDir, new File(name).getName()).toString(); + + if (name.endsWith(".html")) { + repackageNonJavaFile(name, toName); + } else { + justMoveNonJavaFile(name, toName); + } + } + } + + public void repackageNonJavaFile(String name) + throws IOException { + File sourceFile = new File(_sourceBase, name); + File targetFile = new File(_targetBase, name); + + if (sourceFile.lastModified() < targetFile.lastModified()) { + _skippedFiles += 1; + } else { + writeFile(targetFile, _repackager.repackage(readFile(sourceFile))); + } + } + + public void repackageNonJavaFile(String sourceName, String targetName) + throws IOException { + File sourceFile = new File(_sourceBase, sourceName); + File targetFile = new File(_targetBase, targetName); + + if (sourceFile.lastModified() < targetFile.lastModified()) { + _skippedFiles += 1; + } else { + writeFile(targetFile, _repackager.repackage(readFile(sourceFile))); + } + } + + public void justMoveNonJavaFile(String sourceName, String targetName) + throws IOException { + File sourceFile = new File(_sourceBase, sourceName); + File targetFile = new File(_targetBase, targetName); + + if (sourceFile.lastModified() < targetFile.lastModified()) { + _skippedFiles += 1; + } else { + copyFile(sourceFile, targetFile); + } + } + + public void repackageJavaFile(String name) + throws IOException { + File sourceFile = new File(_sourceBase, name); + StringBuffer sb = readFile(sourceFile); + + Matcher packageMatcher = _packagePattern.matcher(sb); + + if (packageMatcher.find()) { + String pkg = packageMatcher.group(1); + int pkgStart = packageMatcher.start(1); + int pkgEnd = packageMatcher.end(1); + + if (packageMatcher.find()) { + throw new RuntimeException("Two package specifications found: " + name); + } + + List filePath = Repackager.splitPath(name, File.separatorChar); + String srcDir = Repackager.dirForPath(name); + + // Sort the repackage spec so that longer from's are first to match + // longest package first + + for (; ; ) { + boolean swapped = false; + + for (int i = 1; i < filePath.size(); i++) { + String spec1 = filePath.get(i - 1); + String spec2 = filePath.get(i); + + if (spec1.indexOf(':') < spec2.indexOf(':')) { + filePath.set(i - 1, spec2); + filePath.set(i, spec1); + + swapped = true; + } + } + + if (!swapped) { + break; + } + } + + List pkgPath = Repackager.splitPath(pkg, '.'); + + int f = filePath.size() - 2; + + if (f < 0 || (filePath.size() - 1) < pkgPath.size()) { + throw new RuntimeException("Package spec differs from file path: " + name); + } + + for (int i = pkgPath.size() - 1; i >= 0; i--) { + if (!pkgPath.get(i).equals(filePath.get(f))) { + throw new RuntimeException("Package spec differs from file path: " + name); + } + f--; + } + + List changeTo = null; + List changeFrom = null; + + from: + for (int i = 0; i < _fromPackages.size(); i++) { + List from = _fromPackages.get(i); + + if (from.size() <= pkgPath.size()) { + for (int j = 0; j < from.size(); j++) { + if (!from.get(j).equals(pkgPath.get(j))) { + continue from; + } + } + + changeFrom = from; + changeTo = _toPackages.get(i); + + break; + } + } + + if (changeTo != null) { + String newPkg = ""; + String newName = ""; + + for (int i = 0; i < changeTo.size(); i++) { + if (i > 0) { + newPkg += "."; + newName += File.separatorChar; + } + + newPkg += changeTo.get(i); + newName += changeTo.get(i); + } + + for (int i = filePath.size() - pkgPath.size() - 2; i >= 0; i--) { + newName = filePath.get(i) + File.separatorChar + newName; + } + + for (int i = changeFrom.size(); i < pkgPath.size(); i++) { + newName += File.separatorChar + pkgPath.get(i); + newPkg += '.' + pkgPath.get(i); + } + + newName += File.separatorChar + filePath.get(filePath.size() - 1); + + sb.replace(pkgStart, pkgEnd, newPkg); + + name = newName; + String newDir = Repackager.dirForPath(name); + + if (!srcDir.equals(newDir)) { + _movedDirs.put(srcDir, newDir); + } + } + } + + File targetFile = new File(_targetBase, name); // new name + + if (sourceFile.lastModified() < targetFile.lastModified()) { + _skippedFiles += 1; + return; + } + + writeFile(new File(_targetBase, name), _repackager.repackage(sb)); + } + + void writeFile(File f, StringBuffer chars) throws IOException { + f.getParentFile().mkdirs(); + + try (Writer w = Files.newBufferedWriter(f.toPath(), StandardCharsets.ISO_8859_1); + Reader r = new StringReader(chars.toString())) { + copy(r, w); + } + } + + StringBuffer readFile(File f) throws IOException { + try (Reader r = Files.newBufferedReader(f.toPath(), StandardCharsets.ISO_8859_1); + StringWriter w = new StringWriter()) { + copy(r, w); + return w.getBuffer(); + } + } + + StringBuffer readInputStream(InputStream is) throws IOException { + try (Reader r = new InputStreamReader(is, StandardCharsets.ISO_8859_1); + StringWriter w = new StringWriter()) { + copy(r, w); + return w.getBuffer(); + } + } + + public static void copyFile(File from, File to) throws IOException { + to.getParentFile().mkdirs(); + + FileInputStream in = new FileInputStream(from); + FileOutputStream out = new FileOutputStream(to); + + copy(in, out); + + out.close(); + in.close(); + } + + public static void copy(InputStream in, OutputStream out) throws IOException { + byte[] buffer = new byte[1024 * 16]; + + for (; ; ) { + int n = in.read(buffer, 0, buffer.length); + + if (n < 0) { + break; + } + + out.write(buffer, 0, n); + } + } + + public static void copy(Reader r, Writer w) throws IOException { + char[] buffer = new char[1024 * 16]; + + for (; ; ) { + int n = r.read(buffer, 0, buffer.length); + + if (n < 0) { + break; + } + + w.write(buffer, 0, n); + } + } + + public void fillFiles(List files, File file) { + if (!file.isDirectory()) { + files.add(file); + return; + } + + // Exclude the build directory + + if (file.getName().equals("build")) { + return; + } + + // Exclude CVS directories + if (file.getName().equals("CVS")) { + return; + } + + String[] entries = file.list(); + if (entries == null) { + throw new RuntimeException("Directory can't be accessed: " + file.toString()); + } + for (String entry : entries) { + fillFiles(files, new File(file, entry)); + } + } + + public void recursiveDelete(File file) { + if (!file.exists()) { + return; + } + + if (file.isDirectory()) { + String[] entries = file.list(); + if (entries == null) { + throw new RuntimeException("Directory can't be accessed: " + file.toString()); + } + + for (String entry : entries) { + recursiveDelete(new File(file, entry)); + } + } + + file.delete(); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java b/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java new file mode 100644 index 0000000..93518e0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/repackage/Repackager.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.repackage; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Repackager { + + private final List> _fromPackages = new ArrayList<>(); + private final List> _toPackages = new ArrayList<>(); + + private Matcher[] _fromMatchers; + private String[] _toPackageNames; + + public Repackager(String repackageSpecs) { + List repackages = splitPath(repackageSpecs, ';'); + + // Sort the repackage spec so that longer from's are first to match + // longest package first + + for (; ; ) { + boolean swapped = false; + + for (int i = 1; i < repackages.size(); i++) { + String spec1 = repackages.get(i - 1); + String spec2 = repackages.get(i); + + if (spec1.indexOf(':') < spec2.indexOf(':')) { + repackages.set(i - 1, spec2); + repackages.set(i, spec1); + + swapped = true; + } + } + + if (!swapped) { + break; + } + } + + for (String repackage : repackages) { + + int j = repackage.indexOf(':'); + + if (j < 0 || repackage.indexOf(':', j + 1) >= 0) { + throw new RuntimeException("Illegal repackage specification: " + repackage); + } + + String from = repackage.substring(0, j); + String to = repackage.substring(j + 1); + + _fromPackages.add(Repackager.splitPath(from, '.')); + _toPackages.add(Repackager.splitPath(to, '.')); + } + + _fromMatchers = new Matcher[_fromPackages.size() * 2]; + _toPackageNames = new String[_fromPackages.size() * 2]; + + addPatterns('.', 0); + addPatterns('/', _fromPackages.size()); + } + + void addPatterns(char sep, int off) { + for (int i = 0; i < _fromPackages.size(); i++) { + List from = _fromPackages.get(i); + List to = _toPackages.get(i); + + String pattern = ""; + + for (int j = 0; j < from.size(); j++) { + if (j > 0) { + pattern += "\\" + sep; + } + + pattern += from.get(j); + } + + String toPackage = ""; + + for (int j = 0; j < to.size(); j++) { + if (j > 0) { + toPackage += sep; + } + + toPackage += to.get(j); + } + + _fromMatchers[off + i] = Pattern.compile(pattern).matcher(""); + _toPackageNames[off + i] = toPackage; + } + } + + public StringBuffer repackage(StringBuffer sb) { + StringBuffer result = null; + + for (int i = 0; i < _fromMatchers.length; i++) { + Matcher m = _fromMatchers[i]; + + m.reset(sb); + + for (boolean found = m.find(); found; found = m.find()) { + if (result == null) { + result = new StringBuffer(); + } + + m.appendReplacement(result, _toPackageNames[i]); + } + + if (result != null) { + m.appendTail(result); + sb = result; + result = null; + } + } + + return sb; + } + + public List> getFromPackages() { + return _fromPackages; + } + + public List> getToPackages() { + return _toPackages; + } + + public static List splitPath(String path, char separator) { + ArrayList components = new ArrayList<>(); + + for (; ; ) { + int i = path.indexOf(separator); + + if (i < 0) { + break; + } + + components.add(path.substring(0, i)); + + path = path.substring(i + 1); + } + + if (path.length() > 0) { + components.add(path); + } + + return components; + } + + public static String dirForPath(String path) { + return new File(path).getParent(); + } +} \ No newline at end of file diff --git a/src/marshal/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExt.java b/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExt.java similarity index 100% rename from src/marshal/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExt.java rename to src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExt.java diff --git a/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java b/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java new file mode 100644 index 0000000..98071f0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java @@ -0,0 +1,1114 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.richParser; + +import org.apache.xmlbeans.GDate; +import org.apache.xmlbeans.GDateBuilder; +import org.apache.xmlbeans.GDuration; +import org.apache.xmlbeans.XmlCalendar; +import org.apache.xmlbeans.impl.common.InvalidLexicalValueException; +import org.apache.xmlbeans.impl.common.XMLChar; +import org.apache.xmlbeans.impl.common.XmlWhitespace; +import org.apache.xmlbeans.impl.util.HexBin; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Date; + +/** + * Author: Cezar Andrei (cezar.andrei at bea.com) + * Date: Nov 17, 2003 + */ +public class XMLStreamReaderExtImpl + implements XMLStreamReaderExt { + private final XMLStreamReader _xmlStream; + private final CharSeqTrimWS _charSeq; + private String _defaultValue; + + public XMLStreamReaderExtImpl(XMLStreamReader xmlStream) { + if (xmlStream == null) { + throw new IllegalArgumentException(); + } + + _xmlStream = xmlStream; + _charSeq = new CharSeqTrimWS(this); + } + + public XMLStreamReader getUnderlyingXmlStream() { + return _xmlStream; + } + + // XMLStreamReaderExt methods + public String getStringValue() + throws XMLStreamException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_PRESERVE); + return _charSeq.toString(); + } + + public String getStringValue(int wsStyle) + throws XMLStreamException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_PRESERVE); + //REVIEW zieg 2004-01-11 - we should write a collapse method + //that takes a CharSequence to void creating this extra String object + return XmlWhitespace.collapse(_charSeq.toString(), wsStyle); + } + + public boolean getBooleanValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexBoolean(_charSeq); + } catch (InvalidLexicalValueException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public byte getByteValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexByte(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public short getShortValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexShort(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public int getIntValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexInt(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public long getLongValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexLong(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public BigInteger getBigIntegerValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexInteger(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public BigDecimal getBigDecimalValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexDecimal(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public float getFloatValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexFloat(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public double getDoubleValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexDouble(_charSeq); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public InputStream getHexBinaryValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + String text = _charSeq.toString(); + byte[] buf = HexBin.decode(text.getBytes(StandardCharsets.ISO_8859_1)); + if (buf != null) { + return new ByteArrayInputStream(buf); + } else { + throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation()); + } + } + + public InputStream getBase64Value() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + String text = _charSeq.toString(); + byte[] buf = Base64.getDecoder().decode(text.getBytes(StandardCharsets.ISO_8859_1)); + if (buf != null) { + return new ByteArrayInputStream(buf); + } else { + throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation()); + } + } + + public XmlCalendar getCalendarValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return new GDateBuilder(_charSeq).getCalendar(); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public Date getDateValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return new GDateBuilder(_charSeq).getDate(); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public GDate getGDateValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexGDate(_charSeq); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public GDuration getGDurationValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return new GDuration(_charSeq); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public QName getQNameValue() + throws XMLStreamException, InvalidLexicalValueException { + _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexQName(_charSeq, _xmlStream.getNamespaceContext()); + } catch (InvalidLexicalValueException e) { + throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation()); + } + } + + public String getAttributeStringValue(int index) throws XMLStreamException { + return _xmlStream.getAttributeValue(index); + } + + public String getAttributeStringValue(int index, int wsStyle) throws XMLStreamException { + return XmlWhitespace.collapse(_xmlStream.getAttributeValue(index), wsStyle); + } + + public boolean getAttributeBooleanValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexBoolean(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (InvalidLexicalValueException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public byte getAttributeByteValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexByte(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public short getAttributeShortValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexShort(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public int getAttributeIntValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexInt(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public long getAttributeLongValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexLong(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public BigInteger getAttributeBigIntegerValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexInteger(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public BigDecimal getAttributeBigDecimalValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexDecimal(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public float getAttributeFloatValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexFloat(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public double getAttributeDoubleValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexDouble(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public InputStream getAttributeHexBinaryValue(int index) throws XMLStreamException { + String text = _charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM).toString(); + byte[] buf = HexBin.decode(text.getBytes(StandardCharsets.ISO_8859_1)); + if (buf != null) { + return new ByteArrayInputStream(buf); + } else { + throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation()); + } + } + + public InputStream getAttributeBase64Value(int index) throws XMLStreamException { + String text = _charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM).toString(); + byte[] buf = Base64.getDecoder().decode(text.getBytes(StandardCharsets.ISO_8859_1)); + if (buf != null) { + return new ByteArrayInputStream(buf); + } else { + throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation()); + } + } + + public XmlCalendar getAttributeCalendarValue(int index) throws XMLStreamException { + try { + return new GDateBuilder(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)). + getCalendar(); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public Date getAttributeDateValue(int index) throws XMLStreamException { + try { + return new GDateBuilder(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)) + .getDate(); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public GDate getAttributeGDateValue(int index) throws XMLStreamException { + try { + return new GDate(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public GDuration getAttributeGDurationValue(int index) throws XMLStreamException { + try { + return new GDuration(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public QName getAttributeQNameValue(int index) throws XMLStreamException { + try { + return XsTypeConverter.lexQName(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM), + _xmlStream.getNamespaceContext()); + } catch (InvalidLexicalValueException e) { + throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation()); + } + } + + public String getAttributeStringValue(String uri, String local) throws XMLStreamException { + return _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_PRESERVE).toString(); + } + + public String getAttributeStringValue(String uri, String local, int wsStyle) throws XMLStreamException { + return XmlWhitespace.collapse(_xmlStream.getAttributeValue(uri, local), wsStyle); + } + + public boolean getAttributeBooleanValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexBoolean(cs); + } catch (InvalidLexicalValueException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public byte getAttributeByteValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexByte(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public short getAttributeShortValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexShort(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public int getAttributeIntValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexInt(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public long getAttributeLongValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexLong(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public BigInteger getAttributeBigIntegerValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexInteger(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public BigDecimal getAttributeBigDecimalValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexDecimal(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public float getAttributeFloatValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexFloat(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public double getAttributeDoubleValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexDouble(cs); + } catch (NumberFormatException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public InputStream getAttributeHexBinaryValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + String text = cs.toString(); + byte[] buf = HexBin.decode(text.getBytes(StandardCharsets.ISO_8859_1)); + if (buf != null) { + return new ByteArrayInputStream(buf); + } else { + throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation()); + } + } + + public InputStream getAttributeBase64Value(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + String text = cs.toString(); + byte[] buf = Base64.getDecoder().decode(text.getBytes(StandardCharsets.ISO_8859_1)); + if (buf != null) { + return new ByteArrayInputStream(buf); + } else { + throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation()); + } + } + + public XmlCalendar getAttributeCalendarValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return new GDateBuilder(cs).getCalendar(); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public Date getAttributeDateValue(String uri, String local) throws XMLStreamException { + try { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + return new GDateBuilder(cs).getDate(); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public GDate getAttributeGDateValue(String uri, String local) throws XMLStreamException { + try { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + return new GDate(cs); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public GDuration getAttributeGDurationValue(String uri, String local) throws XMLStreamException { + try { + return new GDuration(_charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM)); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException(e, _charSeq.getLocation()); + } + } + + public QName getAttributeQNameValue(String uri, String local) throws XMLStreamException { + CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); + try { + return XsTypeConverter.lexQName(cs, _xmlStream.getNamespaceContext()); + } catch (InvalidLexicalValueException e) { + throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation()); + } + } + + public void setDefaultValue(String defaultValue) throws XMLStreamException { + _defaultValue = defaultValue; + } + + /** + * Only trims the XML whaitspace at edges, it should not be used for WS collapse + * Used for int, short, byte + */ + private static class CharSeqTrimWS + implements CharSequence { + final static int XMLWHITESPACE_PRESERVE = 1; + final static int XMLWHITESPACE_TRIM = 2; + + private static int INITIAL_SIZE = 100; + private char[] _buf = new char[INITIAL_SIZE]; + private int _start, _length = 0; + private int _nonWSStart = 0; + private int _nonWSEnd = 0; + private String _toStringValue; + private XMLStreamReaderExtImpl _xmlSteam; + //private boolean _supportForGetTextCharacters = true; + private final ExtLocation _location; + private boolean _hasText; + + CharSeqTrimWS(XMLStreamReaderExtImpl xmlSteam) { + _xmlSteam = xmlSteam; + _location = new ExtLocation(); + } + + void reload(int style) + throws XMLStreamException { + _toStringValue = null; + _location.reset(); + _hasText = false; + + fillBuffer(); + + if (style == XMLWHITESPACE_PRESERVE) { + _nonWSStart = 0; + _nonWSEnd = _length; + + // takes defaultValue only if there wasn't any text + if (!_hasText && _xmlSteam._defaultValue != null) { + _length = 0; + fillBufferFromString(_xmlSteam._defaultValue); + } + } else if (style == XMLWHITESPACE_TRIM) { + for (_nonWSStart = 0; _nonWSStart < _length; _nonWSStart++) { + if (!XMLChar.isSpace(_buf[_nonWSStart])) { + break; + } + } + for (_nonWSEnd = _length; _nonWSEnd > _nonWSStart; _nonWSEnd--) { + if (!XMLChar.isSpace(_buf[_nonWSEnd - 1])) { + break; + } + } + + // takes defaultValue if length after triming is 0 + if (length() == 0 && _xmlSteam._defaultValue != null) { + _length = 0; + fillBufferFromString(_xmlSteam._defaultValue); + + //apply whispace rule on the default value + for (_nonWSStart = 0; _nonWSStart < _length; _nonWSStart++) { + if (!XMLChar.isSpace(_buf[_nonWSStart])) { + break; + } + } + for (_nonWSEnd = _length; _nonWSEnd > _nonWSStart; _nonWSEnd--) { + if (!XMLChar.isSpace(_buf[_nonWSEnd - 1])) { + break; + } + } + } + } + _xmlSteam._defaultValue = null; + } + + private void fillBuffer() + throws XMLStreamException { + _length = 0; + + if (_xmlSteam.getEventType() == XMLStreamReader.START_DOCUMENT) { + _xmlSteam.next(); + } + if (_xmlSteam.isStartElement()) { + _xmlSteam.next(); + } + + int depth = 0; + String error = null; + int eventType = _xmlSteam.getEventType(); + + loop: + while (true) { + switch (eventType) { + case XMLStreamReader.CDATA: + case XMLStreamReader.CHARACTERS: + case XMLStreamReader.SPACE: + _location.set(_xmlSteam.getLocation()); + + if (depth == 0) { + addTextToBuffer(); + } + + break; + + case XMLStreamReader.ATTRIBUTE: + case XMLStreamReader.COMMENT: + case XMLStreamReader.DTD: + case XMLStreamReader.ENTITY_DECLARATION: + case XMLStreamReader.NAMESPACE: + case XMLStreamReader.NOTATION_DECLARATION: + case XMLStreamReader.PROCESSING_INSTRUCTION: + case XMLStreamReader.START_DOCUMENT: + // ignore + break; + + case XMLStreamReader.END_DOCUMENT: + _location.set(_xmlSteam.getLocation()); + + break loop; + + case XMLStreamReader.END_ELEMENT: + _location.set(_xmlSteam.getLocation()); + depth--; + if (depth < 0) { + break loop; + } + break; + + case XMLStreamReader.ENTITY_REFERENCE: + _location.set(_xmlSteam.getLocation()); + + addEntityToBuffer(); + break; + + case XMLStreamReader.START_ELEMENT: + depth++; + error = "Unexpected element '" + _xmlSteam.getName() + "' in text content."; + _location.set(_xmlSteam.getLocation()); + + break; + } + eventType = _xmlSteam.next(); + } + if (error != null) { + throw new XMLStreamException(error); + } + } + + private void ensureBufferLength(int lengthToAdd) { + if (_length + lengthToAdd > _buf.length) { + char[] newBuf = new char[_length + lengthToAdd]; + if (_length > 0) { + System.arraycopy(_buf, 0, newBuf, 0, _length); + } + _buf = newBuf; + } + } + + private void fillBufferFromString(CharSequence value) { + int textLength = value.length(); + ensureBufferLength(textLength); + + for (int i = 0; i < textLength; i++) { + _buf[i] = value.charAt(i); + } + _length = textLength; + } + + private void addTextToBuffer() { + _hasText = true; + int textLength = _xmlSteam.getTextLength(); + ensureBufferLength(textLength); + + /* + Commented out as part of the receipt of the more up to date + jsr173_1.0_ri.jar. getTextCharacters(int, char[], int, int) + used to throw UnsupportedOperationException always. Now it no longer + does, but getTextCharacters(int, char[], int, int) does not return what + we expect. So reverting to always calling getTextCharacters() until + we can work out whether it's us that's wrong or them. + + if (_supportForGetTextCharacters) + try + { + _length = _xmlSteam.getTextCharacters(0, _buf, _length, textLength); + } + catch(Exception e) + { + _supportForGetTextCharacters = false; + } + */ + + // if(!_supportForGetTextCharacters) + //{ + System.arraycopy(_xmlSteam.getTextCharacters(), _xmlSteam.getTextStart(), _buf, _length, textLength); + _length = _length + textLength; + //} + } + + private void addEntityToBuffer() { + String text = _xmlSteam.getText(); + + int textLength = text.length(); + ensureBufferLength(textLength); + + text.getChars(0, text.length(), _buf, _length); + _length = _length + text.length(); + } + + CharSequence reloadAtt(int index, int style) + throws XMLStreamException { + _location.reset(); + _location.set(_xmlSteam.getLocation()); + String value = _xmlSteam.getAttributeValue(index); + + if (value == null && _xmlSteam._defaultValue != null) { + value = _xmlSteam._defaultValue; + } + + _xmlSteam._defaultValue = null; + + int length = value.length(); + + if (style == XMLWHITESPACE_PRESERVE) { + return value; + } else if (style == XMLWHITESPACE_TRIM) { + int nonWSStart, nonWSEnd; + for (nonWSStart = 0; nonWSStart < length; nonWSStart++) { + if (!XMLChar.isSpace(value.charAt(nonWSStart))) { + break; + } + } + for (nonWSEnd = length; nonWSEnd > nonWSStart; nonWSEnd--) { + if (!XMLChar.isSpace(value.charAt(nonWSEnd - 1))) { + break; + } + } + if (nonWSStart == 0 && nonWSEnd == length) { + return value; + } else { + return value.subSequence(nonWSStart, nonWSEnd); + } + } + + throw new IllegalStateException("unknown style"); + } + + CharSequence reloadAtt(String uri, String local, int style) + throws XMLStreamException { + _location.reset(); + _location.set(_xmlSteam.getLocation()); + String value = _xmlSteam.getAttributeValue(uri, local); + + if (value == null && _xmlSteam._defaultValue != null) { + value = _xmlSteam._defaultValue; + } + + _xmlSteam._defaultValue = null; + + int length = value.length(); + + if (style == XMLWHITESPACE_PRESERVE) { + return value; + } else if (style == XMLWHITESPACE_TRIM) { + for (_nonWSStart = 0; _nonWSStart < length; _nonWSStart++) { + if (!XMLChar.isSpace(value.charAt(_nonWSStart))) { + break; + } + } + for (_nonWSEnd = length; _nonWSEnd > _nonWSStart; _nonWSEnd--) { + if (!XMLChar.isSpace(value.charAt(_nonWSEnd - 1))) { + break; + } + } + if (_nonWSStart == 0 && _nonWSEnd == length) { + return value; + } else { + return value.subSequence(_nonWSStart, _nonWSEnd); + } + } + throw new IllegalStateException("unknown style"); + } + + Location getLocation() { + ExtLocation loc = new ExtLocation(); + loc.set(_location); + return loc; + } + + public int length() { + return _nonWSEnd - _nonWSStart; + } + + public char charAt(int index) { + // for each char, this has to be fast, using assert instead of if throw + assert (index < _nonWSEnd - _nonWSStart && -1 < index) : + "Index " + index + " must be >-1 and <" + (_nonWSEnd - _nonWSStart); + + return _buf[_nonWSStart + index]; + } + + public CharSequence subSequence(int start, int end) { + return new String(_buf, _nonWSStart + start, end - start); + } + + public String toString() { + if (_toStringValue != null) { + return _toStringValue; + } + + _toStringValue = new String(_buf, _nonWSStart, _nonWSEnd - _nonWSStart); + return _toStringValue; + } + + private static class ExtLocation implements Location { + private int _line; + private int _col; + private int _off; + private String _pid; + private String _sid; + private boolean _isSet; + + ExtLocation() { + _isSet = false; + } + + public int getLineNumber() { + if (_isSet) { + return _line; + } else { + throw new IllegalStateException(); + } + } + + public int getColumnNumber() { + if (_isSet) { + return _col; + } else { + throw new IllegalStateException(); + } + } + + public int getCharacterOffset() { + if (_isSet) { + return _off; + } else { + throw new IllegalStateException(); + } + } + + public String getPublicId() { + if (_isSet) { + return _pid; + } else { + throw new IllegalStateException(); + } + } + + public String getSystemId() { + if (_isSet) { + return _sid; + } else { + throw new IllegalStateException(); + } + } + + void set(Location loc) { + if (_isSet) { + return; + } + + _isSet = true; + _line = loc.getLineNumber(); + _col = loc.getColumnNumber(); + _off = loc.getCharacterOffset(); + _pid = loc.getPublicId(); + _sid = loc.getSystemId(); + } + + void reset() { + _isSet = false; + } + } + } + + // XMLStreamReader methods + public Object getProperty(String s) + throws IllegalArgumentException { + return _xmlStream.getProperty(s); + } + + public int next() + throws XMLStreamException { + return _xmlStream.next(); + } + + public void require(int i, String s, String s1) + throws XMLStreamException { + _xmlStream.require(i, s, s1); + } + + public String getElementText() throws XMLStreamException { + return _xmlStream.getElementText(); + } + + public int nextTag() throws XMLStreamException { + return _xmlStream.nextTag(); + } + + public boolean hasNext() throws XMLStreamException { + return _xmlStream.hasNext(); + } + + public void close() throws XMLStreamException { + _xmlStream.close(); + } + + public String getNamespaceURI(String s) { + return _xmlStream.getNamespaceURI(s); + } + + public boolean isStartElement() { + return _xmlStream.isStartElement(); + } + + public boolean isEndElement() { + return _xmlStream.isEndElement(); + } + + public boolean isCharacters() { + return _xmlStream.isCharacters(); + } + + public boolean isWhiteSpace() { + return _xmlStream.isWhiteSpace(); + } + + public String getAttributeValue(String s, String s1) { + return _xmlStream.getAttributeValue(s, s1); + } + + public int getAttributeCount() { + return _xmlStream.getAttributeCount(); + } + + public QName getAttributeName(int i) { + return _xmlStream.getAttributeName(i); + } + + public String getAttributeNamespace(int i) { + return _xmlStream.getAttributeNamespace(i); + } + + public String getAttributeLocalName(int i) { + return _xmlStream.getAttributeLocalName(i); + } + + public String getAttributePrefix(int i) { + return _xmlStream.getAttributePrefix(i); + } + + public String getAttributeType(int i) { + return _xmlStream.getAttributeType(i); + } + + public String getAttributeValue(int i) { + return _xmlStream.getAttributeValue(i); + } + + public boolean isAttributeSpecified(int i) { + return _xmlStream.isAttributeSpecified(i); + } + + public int getNamespaceCount() { + return _xmlStream.getNamespaceCount(); + } + + public String getNamespacePrefix(int i) { + return _xmlStream.getNamespacePrefix(i); + } + + public String getNamespaceURI(int i) { + return _xmlStream.getNamespaceURI(i); + } + + public NamespaceContext getNamespaceContext() { + return _xmlStream.getNamespaceContext(); + } + + public int getEventType() { + return _xmlStream.getEventType(); + } + + public String getText() { + return _xmlStream.getText(); + } + + public char[] getTextCharacters() { + return _xmlStream.getTextCharacters(); + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) + throws XMLStreamException { + return _xmlStream.getTextCharacters(i, chars, i1, i2); + } + + public int getTextStart() { + return _xmlStream.getTextStart(); + } + + public int getTextLength() { + return _xmlStream.getTextLength(); + } + + public String getEncoding() { + return _xmlStream.getEncoding(); + } + + public boolean hasText() { + return _xmlStream.hasText(); + } + + public Location getLocation() { + return _xmlStream.getLocation(); + } + + public QName getName() { + return _xmlStream.getName(); + } + + public String getLocalName() { + return _xmlStream.getLocalName(); + } + + public boolean hasName() { + return _xmlStream.hasName(); + } + + public String getNamespaceURI() { + return _xmlStream.getNamespaceURI(); + } + + public String getPrefix() { + return _xmlStream.getPrefix(); + } + + public String getVersion() { + return _xmlStream.getVersion(); + } + + public boolean isStandalone() { + return _xmlStream.isStandalone(); + } + + public boolean standaloneSet() { + return _xmlStream.standaloneSet(); + } + + public String getCharacterEncodingScheme() { + return _xmlStream.getCharacterEncodingScheme(); + } + + public String getPITarget() { + return _xmlStream.getPITarget(); + } + + public String getPIData() { + return _xmlStream.getPIData(); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java b/src/main/java/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java similarity index 97% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java rename to src/main/java/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java index 7b90cb6..43239a4 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java +++ b/src/main/java/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java @@ -15,34 +15,19 @@ package org.apache.xmlbeans.impl.schema; -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.Filer; +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.common.QNameHelper; import org.apache.xmlbeans.impl.values.XmlIntegerImpl; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; import org.apache.xmlbeans.impl.values.XmlStringImpl; -import org.apache.xmlbeans.impl.regex.RegularExpression; -import org.apache.xmlbeans.impl.regex.SchemaRegularExpression; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; import javax.xml.namespace.QName; - import java.io.File; import java.io.InputStream; -import java.util.Map; -import java.util.HashMap; -import java.util.Collections; import java.math.BigInteger; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public class BuiltinSchemaTypeSystem extends SchemaTypeLoaderBase implements SchemaTypeSystem { @@ -375,7 +360,7 @@ public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) return null; } - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) + public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { return null; } @@ -511,7 +496,7 @@ private static XmlValueRef buildNnInteger(BigInteger bigInt) try { XmlIntegerImpl i = new XmlIntegerImpl(); - i.set(bigInt); + i.setBigIntegerValue(bigInt); i.setImmutable(); return new XmlValueRef(i); } @@ -528,7 +513,7 @@ private static XmlValueRef buildInteger(BigInteger bigInt) try { XmlIntegerImpl i = new XmlIntegerImpl(); - i.set(bigInt); + i.setBigIntegerValue(bigInt); i.setImmutable(); return new XmlValueRef(i); } @@ -546,7 +531,7 @@ private static XmlValueRef buildString(String str) try { XmlStringImpl i = new XmlStringImpl(); - i.set(str); + i.setStringValue(str); i.setImmutable(); return new XmlValueRef(i); } @@ -995,11 +980,12 @@ else if (variety == SchemaType.ATOMIC) switch (btc) { case SchemaType.BTC_LANGUAGE: - pattern = "[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"; // we used to have ([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{1,8})*", but s4s uses the more lenient pattern to the left. + // we used to have ([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{1,8})*", but s4s uses the more lenient pattern to the left. + pattern = "[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"; hasPattern = true; break; case SchemaType.BTC_NMTOKEN: - pattern = "\\c+"; + pattern = "\\c+"; hasPattern = true; break; case SchemaType.BTC_NAME: diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/ClassLoaderResourceLoader.java b/src/main/java/org/apache/xmlbeans/impl/schema/ClassLoaderResourceLoader.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/ClassLoaderResourceLoader.java rename to src/main/java/org/apache/xmlbeans/impl/schema/ClassLoaderResourceLoader.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/FileResourceLoader.java b/src/main/java/org/apache/xmlbeans/impl/schema/FileResourceLoader.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/FileResourceLoader.java rename to src/main/java/org/apache/xmlbeans/impl/schema/FileResourceLoader.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/PathResourceLoader.java b/src/main/java/org/apache/xmlbeans/impl/schema/PathResourceLoader.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/PathResourceLoader.java rename to src/main/java/org/apache/xmlbeans/impl/schema/PathResourceLoader.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAnnotationImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaAnnotationImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAnnotationImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaAnnotationImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaContainer.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaContainer.java new file mode 100644 index 0000000..7a48ead --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaContainer.java @@ -0,0 +1,224 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +/*package*/ class SchemaContainer { + // The namespace that this is the container for + // TODO(radup) In the future, I think the right approach is one container + // per file instead of per namespace, but per namespace is easier for now + private final String _namespace; + + SchemaContainer(String namespace) { + _namespace = namespace; + } + + String getNamespace() { + return _namespace; + } + + // The SchemaTypeSystem on behalf of which this acts + private SchemaTypeSystem _typeSystem; + + // This is the whole idea of the containers + // By synchronizing getter/setters on this field, we allow + // both SchemaTypeSystems and SchemaTypes to be immutable + // at the same time providing the mechanism through which + // we can "move" SchemaTypes from one SchemaTypeSystem to another + // via incremental compilation + synchronized SchemaTypeSystem getTypeSystem() { + return _typeSystem; + } + + synchronized void setTypeSystem(SchemaTypeSystem typeSystem) { + _typeSystem = typeSystem; + } + + // Immutability refers to the content of the container + // Once the container has been initialized, one cannot add/remove + // SchemaComponents from it. Instead, one has to blow it away + // and build a new one. + // Immutability does not mean that one cannot move this container + // between typesystems. + boolean _immutable; + + synchronized void setImmutable() { + _immutable = true; + } + + synchronized void unsetImmutable() { + _immutable = false; + } + + private void check_immutable() { + if (_immutable) { + throw new IllegalStateException("Cannot add components to immutable SchemaContainer"); + } + } + + // Data + // TODO(radup) unmodifiableList() is not really necessary, since this + // is package-level access and code in this package should do the "right thing" + // Global Elements + private final List _globalElements = new ArrayList<>(); + + void addGlobalElement(SchemaGlobalElement.Ref e) { + check_immutable(); + _globalElements.add(e); + } + + List globalElements() { + return _globalElements.stream().map(SchemaGlobalElement.Ref::get).collect(Collectors.toList()); + } + + // Global Attributes + private final List _globalAttributes = new ArrayList<>(); + + void addGlobalAttribute(SchemaGlobalAttribute.Ref a) { + check_immutable(); + _globalAttributes.add(a); + } + + List globalAttributes() { + return _globalAttributes.stream().map(SchemaGlobalAttribute.Ref::get).collect(Collectors.toList()); + } + + // Model Groups + private final List _modelGroups = new ArrayList<>(); + + void addModelGroup(SchemaModelGroup.Ref g) { + check_immutable(); + _modelGroups.add(g); + } + + List modelGroups() { + return _modelGroups.stream().map(SchemaModelGroup.Ref::get).collect(Collectors.toList()); + } + + // Redefined Model Groups + private final List _redefinedModelGroups = new ArrayList<>(); + + void addRedefinedModelGroup(SchemaModelGroup.Ref g) { + check_immutable(); + _redefinedModelGroups.add(g); + } + + List redefinedModelGroups() { + return _redefinedModelGroups.stream().map(SchemaModelGroup.Ref::get).collect(Collectors.toList()); + } + + // Attribute Groups + private final List _attributeGroups = new ArrayList<>(); + + void addAttributeGroup(SchemaAttributeGroup.Ref g) { + check_immutable(); + _attributeGroups.add(g); + } + + List attributeGroups() { + return _attributeGroups.stream().map(SchemaAttributeGroup.Ref::get).collect(Collectors.toList()); + } + + // Redefined Attribute Groups + private final List _redefinedAttributeGroups = new ArrayList<>(); + + void addRedefinedAttributeGroup(SchemaAttributeGroup.Ref g) { + check_immutable(); + _redefinedAttributeGroups.add(g); + } + + List redefinedAttributeGroups() { + return _redefinedAttributeGroups.stream().map(SchemaAttributeGroup.Ref::get).collect(Collectors.toList()); + } + + // Global Types + private final List _globalTypes = new ArrayList<>(); + + void addGlobalType(SchemaType.Ref t) { + check_immutable(); + _globalTypes.add(t); + } + + List globalTypes() { + return _globalTypes.stream().map(SchemaType.Ref::get).collect(Collectors.toList()); + } + + // Redefined Global Types + private final List _redefinedGlobalTypes = new ArrayList<>(); + + void addRedefinedType(SchemaType.Ref t) { + check_immutable(); + _redefinedGlobalTypes.add(t); + } + + List redefinedGlobalTypes() { + return _redefinedGlobalTypes.stream().map(SchemaType.Ref::get).collect(Collectors.toList()); + } + + // Document Types + private final List _documentTypes = new ArrayList<>(); + + void addDocumentType(SchemaType.Ref t) { + check_immutable(); + _documentTypes.add(t); + } + + List documentTypes() { + return _documentTypes.stream().map(SchemaType.Ref::get).collect(Collectors.toList()); + } + + // Attribute Types + private final List _attributeTypes = new ArrayList<>(); + + void addAttributeType(SchemaType.Ref t) { + check_immutable(); + _attributeTypes.add(t); + } + + List attributeTypes() { + return _attributeTypes.stream().map(SchemaType.Ref::get).collect(Collectors.toList()); + } + + // Identity Constraints + private final List _identityConstraints = new ArrayList<>(); + + void addIdentityConstraint(SchemaIdentityConstraint.Ref c) { + check_immutable(); + _identityConstraints.add(c); + } + + List identityConstraints() { + return _identityConstraints.stream().map(SchemaIdentityConstraint.Ref::get).collect(Collectors.toList()); + } + + // Annotations + private final List _annotations = new ArrayList<>(); + + void addAnnotation(SchemaAnnotation a) { + check_immutable(); + _annotations.add(a); + } + + List annotations() { + return Collections.unmodifiableList(_annotations); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java new file mode 100644 index 0000000..2693b1d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java @@ -0,0 +1,108 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import java.util.*; +import java.util.stream.Collectors; + +public class SchemaDependencies { + // This class is NOT synchronized + + /** + * Records the list of files associated to each namespace. + * This is needed so that we can return a list of files that + * need to be compiled once we get a set of altered namespaces + */ + private final Map> _contributions = new HashMap<>(); + + /** + * Records anti-dependencies. Keys are namespaces and values are + * the lists of namespaces that depend on each key + */ + private final Map> _dependencies = new HashMap<>(); + + void registerDependency(String source, String target) { + _dependencies.computeIfAbsent(target, k -> new HashSet<>()).add(source); + } + + + Set computeTransitiveClosure(List modifiedNamespaces) { + List nsList = new ArrayList<>(modifiedNamespaces); + Set result = new HashSet<>(modifiedNamespaces); + for (int i = 0; i < nsList.size(); i++) { + Set deps = _dependencies.get(nsList.get(i)); + if (deps == null) { + continue; + } + for (String ns : deps) { + if (!result.contains(ns)) { + nsList.add(ns); + result.add(ns); + } + } + } + return result; + } + + SchemaDependencies() { + } + + SchemaDependencies(SchemaDependencies base, Set updatedNs) { + for (String target : base._dependencies.keySet()) { + if (updatedNs.contains(target)) { + continue; + } + Set depSet = new HashSet<>(); + _dependencies.put(target, depSet); + Set baseDepSet = base._dependencies.get(target); + for (String source : baseDepSet) { + if (updatedNs.contains(source)) { + continue; + } + depSet.add(source); + } + } + for (String ns : base._contributions.keySet()) { + if (updatedNs.contains(ns)) { + continue; + } + List fileList = new ArrayList<>(); + _contributions.put(ns, fileList); + fileList.addAll(base._contributions.get(ns)); + } + } + + void registerContribution(String ns, String fileURL) { + _contributions.computeIfAbsent(ns, k -> new ArrayList<>()).add(fileURL); + } + + boolean isFileRepresented(String fileURL) { + return _contributions.values().stream().anyMatch(l -> l.contains(fileURL)); + } + + List getFilesTouched(Set updatedNs) { + return updatedNs.stream().map(_contributions::get). + filter(Objects::nonNull).flatMap(List::stream). + collect(Collectors.toList()); + } + + List getNamespacesTouched(Set modifiedFiles) { + return _contributions.entrySet().stream(). + filter(e -> e.getValue().stream().anyMatch(modifiedFiles::contains)). + map(Map.Entry::getKey). + collect(Collectors.toList()); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalAttributeImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaGlobalAttributeImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalAttributeImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaGlobalAttributeImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java new file mode 100644 index 0000000..076a29a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java @@ -0,0 +1,212 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.xpath.XPath; + +import javax.xml.namespace.QName; +import java.util.Collections; +import java.util.Map; + +public class SchemaIdentityConstraintImpl implements SchemaIdentityConstraint { + private final SchemaContainer _container; + private String _selector; + private String[] _fields; + private SchemaIdentityConstraint.Ref _key; + private QName _name; + private int _type; + private XmlObject _parse; + private Object _userData; + private SchemaAnnotation _annotation; + private Map _nsMap = Collections.emptyMap(); + private String _parseTNS; + private boolean _chameleon; + private String _filename; + + // Lazily computed paths + private volatile XPath _selectorPath; + private volatile XPath[] _fieldPaths; + + public SchemaIdentityConstraintImpl(SchemaContainer c) { + _container = c; + } + + public void setFilename(String filename) { + _filename = filename; + } + + public String getSourceName() { + return _filename; + } + + + public String getSelector() { + return _selector; + } + + public Object getSelectorPath() { + XPath p = _selectorPath; + if (p == null) { + try { + buildPaths(); + p = _selectorPath; + } catch (XPath.XPathCompileException e) { + assert false : "Failed to compile xpath. Should be caught by compiler " + e; + return null; + } + } + return p; + } + + public void setAnnotation(SchemaAnnotation ann) { + _annotation = ann; + } + + public SchemaAnnotation getAnnotation() { + return _annotation; + } + + public void setNSMap(Map nsMap) { + _nsMap = nsMap; + } + + public Map getNSMap() { + return Collections.unmodifiableMap(_nsMap); + } + + public void setSelector(String selector) { + assert selector != null; + _selector = selector; + } + + public void setFields(String[] fields) { + assert fields != null && fields.length > 0; + _fields = fields.clone(); + } + + public String[] getFields() { + String[] fields = new String[_fields.length]; + System.arraycopy(_fields, 0, fields, 0, fields.length); + return fields; + } + + public Object getFieldPath(int index) { + XPath[] p = _fieldPaths; + if (p == null) { + try { + buildPaths(); + p = _fieldPaths; + } catch (XPath.XPathCompileException e) { + assert false : "Failed to compile xpath. Should be caught by compiler " + e; + return null; + } + } + return p[index]; + } + + public void buildPaths() throws XPath.XPathCompileException { + // TODO: Need the namespace map - requires store support + _selectorPath = XPath.compileXPath(_selector, _nsMap); + + _fieldPaths = new XPath[_fields.length]; + for (int i = 0; i < _fieldPaths.length; i++) { + _fieldPaths[i] = XPath.compileXPath(_fields[i], _nsMap); + } + } + + public void setReferencedKey(SchemaIdentityConstraint.Ref key) { + _key = key; + } + + public SchemaIdentityConstraint getReferencedKey() { + return _key.get(); + } + + public void setConstraintCategory(int type) { + assert type >= CC_KEY && type <= CC_UNIQUE; + _type = type; + } + + public int getConstraintCategory() { + return _type; + } + + public void setName(QName name) { + assert name != null; + _name = name; + } + + public QName getName() { + return _name; + } + + public int getComponentType() { + return IDENTITY_CONSTRAINT; + } + + public SchemaTypeSystem getTypeSystem() { + return _container.getTypeSystem(); + } + + SchemaContainer getContainer() { + return _container; + } + + public void setParseContext(XmlObject o, String targetNamespace, boolean chameleon) { + _parse = o; + _parseTNS = targetNamespace; + _chameleon = chameleon; + } + + public XmlObject getParseObject() { + return _parse; + } + + public String getTargetNamespace() { + return _parseTNS; + } + + public String getChameleonNamespace() { + return _chameleon ? _parseTNS : null; + } + + + /** + * Only applicable to keyrefs. Other types are implicitly resolved. + */ + public boolean isResolved() { + return getConstraintCategory() != CC_KEYREF || _key != null; + } + + private final SchemaIdentityConstraint.Ref _selfref = new SchemaIdentityConstraint.Ref(this); + + public SchemaIdentityConstraint.Ref getRef() { + return _selfref; + } + + public SchemaComponent.Ref getComponentRef() { + return getRef(); + } + + public Object getUserData() { + return _userData; + } + + public void setUserData(Object data) { + _userData = data; + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalAttributeImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaLocalAttributeImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalAttributeImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaLocalAttributeImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java similarity index 79% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java index 4aa51f5..1f664ec 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaLocalElementImpl.java @@ -16,15 +16,14 @@ package org.apache.xmlbeans.impl.schema; import org.apache.xmlbeans.SchemaAnnotation; +import org.apache.xmlbeans.SchemaIdentityConstraint; import org.apache.xmlbeans.SchemaLocalElement; import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaIdentityConstraint; import org.apache.xmlbeans.soap.SOAPArrayType; import org.apache.xmlbeans.soap.SchemaWSDLArrayType; public class SchemaLocalElementImpl extends SchemaParticleImpl - implements SchemaLocalElement, SchemaWSDLArrayType -{ + implements SchemaLocalElement, SchemaWSDLArrayType { private boolean _blockExt; private boolean _blockRest; private boolean _blockSubst; @@ -34,73 +33,63 @@ public class SchemaLocalElementImpl extends SchemaParticleImpl private SchemaIdentityConstraint.Ref[] _constraints = new SchemaIdentityConstraint.Ref[0]; - public SchemaLocalElementImpl() - { + public SchemaLocalElementImpl() { setParticleType(SchemaParticle.ELEMENT); } - public boolean blockExtension() - { + public boolean blockExtension() { return _blockExt; } - public boolean blockRestriction() - { + public boolean blockRestriction() { return _blockRest; } - public boolean blockSubstitution() - { + public boolean blockSubstitution() { return _blockSubst; } - public boolean isAbstract() - { + public boolean isAbstract() { return _abs; } - public void setAbstract(boolean abs) - { + public void setAbstract(boolean abs) { _abs = abs; } - public void setBlock(boolean extension, boolean restriction, boolean substitution) - { + public void setBlock(boolean extension, boolean restriction, boolean substitution) { mutate(); _blockExt = extension; _blockRest = restriction; _blockSubst = substitution; } - public void setAnnotation(SchemaAnnotation ann) - { + public void setAnnotation(SchemaAnnotation ann) { _annotation = ann; } - public void setWsdlArrayType(SOAPArrayType arrayType) - { + public void setWsdlArrayType(SOAPArrayType arrayType) { _wsdlArrayType = arrayType; } - public SchemaAnnotation getAnnotation() - { + public SchemaAnnotation getAnnotation() { return _annotation; } - public SOAPArrayType getWSDLArrayType() - { + public SOAPArrayType getWSDLArrayType() { return _wsdlArrayType; } public void setIdentityConstraints(SchemaIdentityConstraint.Ref[] constraints) { mutate(); - _constraints = constraints; + _constraints = (constraints == null) ? null : constraints.clone(); } public SchemaIdentityConstraint[] getIdentityConstraints() { SchemaIdentityConstraint[] result = new SchemaIdentityConstraint[_constraints.length]; - for (int i = 0 ; i < result.length ; i++) + for (int i = 0; i < result.length; i++) { result[i] = _constraints[i].get(); + } return result; } diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java new file mode 100644 index 0000000..6752e8b --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java @@ -0,0 +1,290 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.values.NamespaceContext; + +import javax.xml.namespace.QName; +import java.math.BigInteger; + +public class SchemaParticleImpl implements SchemaParticle { + private int _particleType; + private BigInteger _minOccurs; + private BigInteger _maxOccurs; + private SchemaParticle[] _particleChildren; + private boolean _isImmutable; + private QNameSet _startSet; + private QNameSet _excludeNextSet; + private boolean _isSkippable; + private boolean _isDeterministic; + private int _intMinOccurs; + private int _intMaxOccurs; + private QNameSet _wildcardSet; + private int _wildcardProcess; + private String _defaultText; + private boolean _isDefault; + private boolean _isFixed; + private QName _qName; + private boolean _isNillable; + private SchemaType.Ref _typeref; + protected XmlObject _parseObject; + private Object _userData; + private XmlValueRef _defaultValue; + + protected void mutate() { + if (_isImmutable) { + throw new IllegalStateException(); + } + } + + public void setImmutable() { + mutate(); + _isImmutable = true; + } + + public boolean hasTransitionRules() { + return (_startSet != null); + } + + public boolean hasTransitionNotes() { + return (_excludeNextSet != null); + } + + public void setTransitionRules(QNameSet start, + boolean isSkippable) { + _startSet = start; + _isSkippable = isSkippable; + } + + public void setTransitionNotes(QNameSet excludeNext, boolean isDeterministic) { + _excludeNextSet = excludeNext; + _isDeterministic = isDeterministic; + } + + public boolean canStartWithElement(QName name) { + return name != null && _startSet.contains(name); + } + + public QNameSet acceptedStartNames() { + return _startSet; + } + + public QNameSet getExcludeNextSet() { + return _excludeNextSet; + } + + public boolean isSkippable() { + return _isSkippable; + } + + public boolean isDeterministic() { + return _isDeterministic; + } + + public int getParticleType() { + return _particleType; + } + + public void setParticleType(int pType) { + mutate(); + _particleType = pType; + } + + public boolean isSingleton() { + return _maxOccurs != null && + _maxOccurs.compareTo(BigInteger.ONE) == 0 && + _minOccurs.compareTo(BigInteger.ONE) == 0; + } + + public BigInteger getMinOccurs() { + return _minOccurs; + } + + public void setMinOccurs(BigInteger min) { + mutate(); + _minOccurs = min; + _intMinOccurs = pegBigInteger(min); + } + + public int getIntMinOccurs() { + return _intMinOccurs; + } + + public BigInteger getMaxOccurs() { + return _maxOccurs; + } + + public int getIntMaxOccurs() { + return _intMaxOccurs; + } + + public void setMaxOccurs(BigInteger max) { + mutate(); + _maxOccurs = max; + _intMaxOccurs = pegBigInteger(max); + } + + public SchemaParticle[] getParticleChildren() { + if (_particleChildren == null) { + assert _particleType != SchemaParticle.ALL && + _particleType != SchemaParticle.SEQUENCE && + _particleType != SchemaParticle.CHOICE; + return null; + } + SchemaParticle[] result = new SchemaParticle[_particleChildren.length]; + System.arraycopy(_particleChildren, 0, result, 0, _particleChildren.length); + return result; + } + + public void setParticleChildren(SchemaParticle[] children) { + mutate(); + _particleChildren = (children == null) ? null : children.clone(); + } + + public SchemaParticle getParticleChild(int i) { + return _particleChildren[i]; + } + + public int countOfParticleChild() { + return _particleChildren == null ? 0 : _particleChildren.length; + } + + public void setWildcardSet(QNameSet set) { + mutate(); + _wildcardSet = set; + } + + public QNameSet getWildcardSet() { + return _wildcardSet; + } + + public void setWildcardProcess(int process) { + mutate(); + _wildcardProcess = process; + } + + public int getWildcardProcess() { + return _wildcardProcess; + } + + private static final BigInteger _maxint = BigInteger.valueOf(Integer.MAX_VALUE); + + private static int pegBigInteger(BigInteger bi) { + if (bi == null) { + return Integer.MAX_VALUE; + } + if (bi.signum() <= 0) { + return 0; + } + if (bi.compareTo(_maxint) >= 0) { + return Integer.MAX_VALUE; + } + return bi.intValue(); + } + + public QName getName() { + return _qName; + } + + public void setNameAndTypeRef(QName formname, SchemaType.Ref typeref) { + mutate(); + _qName = formname; + _typeref = typeref; + } + + public boolean isTypeResolved() { + return (_typeref != null); + } + + public void resolveTypeRef(SchemaType.Ref typeref) { + if (_typeref != null) { + throw new IllegalStateException(); + } + _typeref = typeref; + } + + public boolean isAttribute() { + return false; + } + + public SchemaType getType() { + if (_typeref == null) { + return null; + } + return _typeref.get(); + } + + public String getDefaultText() { + return _defaultText; + } + + public boolean isDefault() { + return _isDefault; + } + + public boolean isFixed() { + return _isFixed; + } + + public void setDefault(String deftext, boolean isFixed, XmlObject parseObject) { + mutate(); + _defaultText = deftext; + _isDefault = (deftext != null); + _isFixed = isFixed; + _parseObject = parseObject; + } + + public boolean isNillable() { + return _isNillable; + } + + public void setNillable(boolean nillable) { + mutate(); + _isNillable = nillable; + } + + public XmlAnySimpleType getDefaultValue() { + if (_defaultValue != null) { + return _defaultValue.get(); + } + if (_defaultText != null && XmlAnySimpleType.type.isAssignableFrom(getType())) { + if (_parseObject != null && XmlQName.type.isAssignableFrom(getType())) { + try { + NamespaceContext.push(new NamespaceContext(_parseObject)); + return getType().newValue(_defaultText); + } finally { + NamespaceContext.pop(); + } + } + return getType().newValue(_defaultText); + } + return null; + } + + public void setDefaultValue(XmlValueRef defaultRef) { + mutate(); + _defaultValue = defaultRef; + } + + public Object getUserData() { + return _userData; + } + + public void setUserData(Object data) { + _userData = data; + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaPropertyImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaPropertyImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaPropertyImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaPropertyImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaStringEnumEntryImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaStringEnumEntryImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaStringEnumEntryImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaStringEnumEntryImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java new file mode 100644 index 0000000..10318c4 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java @@ -0,0 +1,2437 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.NameUtil; + +import javax.xml.namespace.QName; +import java.io.IOException; +import java.io.Writer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.util.*; + +/** + * Prints the java code for a single schema type + */ +public final class SchemaTypeCodePrinter implements SchemaCodePrinter { + Writer _writer; + int _indent; + + + static final String LINE_SEPARATOR = + SystemProperties.getProperty("line.separator") == null + ? "\n" + : SystemProperties.getProperty("line.separator"); + + static final String MAX_SPACES = " "; + static final int INDENT_INCREMENT = 4; + + public static final String INDEX_CLASSNAME = "TypeSystemHolder"; + + public static void printTypeImpl(Writer writer, SchemaType sType, + XmlOptions opt) + throws IOException { + getPrinter(opt).printTypeImpl(writer, sType); + } + + public static void printType(Writer writer, SchemaType sType, + XmlOptions opt) + throws IOException { + getPrinter(opt).printType(writer, sType); + } + + private static SchemaCodePrinter getPrinter(XmlOptions opt) { + SchemaCodePrinter printer = opt == null ? null : opt.getSchemaCodePrinter(); + return printer == null ? new SchemaTypeCodePrinter() : printer; + } + + public SchemaTypeCodePrinter() { + _indent = 0; + } + + void indent() { + _indent += INDENT_INCREMENT; + } + + void outdent() { + _indent -= INDENT_INCREMENT; + } + + void emit(String s) throws IOException { + int indent = _indent; + + if (indent > MAX_SPACES.length() / 2) { + indent = MAX_SPACES.length() / 4 + indent / 2; + } + + if (indent > MAX_SPACES.length()) { + indent = MAX_SPACES.length(); + } + + _writer.write(MAX_SPACES.substring(0, indent)); + try { + _writer.write(s); + } catch (CharacterCodingException cce) { + _writer.write(makeSafe(s)); + } + _writer.write(LINE_SEPARATOR); + + // System.out.print(MAX_SPACES.substring(0, indent)); + // System.out.println(s); + } + + private static String makeSafe(String s) { + Charset charset = Charset.forName(System.getProperty("file.encoding")); + CharsetEncoder cEncoder = charset.newEncoder(); + StringBuilder result = new StringBuilder(); + int i; + for (i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (!cEncoder.canEncode(c)) { + break; + } + } + for (; i < s.length(); i++) { + char c = s.charAt(i); + if (cEncoder.canEncode(c)) { + result.append(c); + } else { + String hexValue = Integer.toHexString(c); + switch (hexValue.length()) { + case 1: + result.append("\\u000").append(hexValue); + break; + case 2: + result.append("\\u00").append(hexValue); + break; + case 3: + result.append("\\u0").append(hexValue); + break; + case 4: + result.append("\\u").append(hexValue); + break; + default: + throw new IllegalStateException(); + } + } + } + return result.toString(); + } + + public void printType(Writer writer, SchemaType sType) throws IOException { + _writer = writer; + printTopComment(sType); + printPackage(sType, true); + emit(""); + printInnerType(sType, sType.getTypeSystem()); + _writer.flush(); + } + + public void printTypeImpl(Writer writer, SchemaType sType) + throws IOException { + _writer = writer; + printTopComment(sType); + printPackage(sType, false); + printInnerTypeImpl(sType, sType.getTypeSystem(), false); + } + + /** + * Since not all schema types have java types, this skips + * over any that don't and gives you the nearest java base type. + */ + String findJavaType(SchemaType sType) { + while (sType.getFullJavaName() == null) { + sType = sType.getBaseType(); + } + + return sType.getFullJavaName(); + } + + static String prettyQName(QName qname) { + if (qname == null) { + return ""; + } + String result = qname.getLocalPart(); + if (qname.getNamespaceURI() != null) { + result += "(@" + qname.getNamespaceURI() + ")"; + } + return result; + } + + void printInnerTypeJavaDoc(SchemaType sType) throws IOException { + QName name = sType.getName(); + if (name == null) { + if (sType.isDocumentType()) { + name = sType.getDocumentElementName(); + } else if (sType.isAttributeType()) { + name = sType.getAttributeTypeAttributeName(); + } else if (sType.getContainerField() != null) { + name = sType.getContainerField().getName(); + } + } + + emit("/**"); + if (sType.isDocumentType()) { + emit(" * A document containing one " + prettyQName(name) + " element."); + } else if (sType.isAttributeType()) { + emit(" * A document containing one " + prettyQName(name) + " attribute."); + } else if (name != null) { + emit(" * An XML " + prettyQName(name) + "."); + } else { + emit(" * An anonymous inner XML type."); + } + emit(" *"); + switch (sType.getSimpleVariety()) { + case SchemaType.NOT_SIMPLE: + emit(" * This is a complex type."); + break; + case SchemaType.ATOMIC: + emit(" * This is an atomic type that is a restriction of " + getFullJavaName(sType) + "."); + break; + case SchemaType.LIST: + emit(" * This is a list type whose items are " + sType.getListItemType().getFullJavaName() + "."); + break; + case SchemaType.UNION: + emit(" * This is a union type. Instances are of one of the following types:"); + SchemaType[] members = sType.getUnionConstituentTypes(); + for (SchemaType member : members) { + emit(" * " + member.getFullJavaName()); + } + break; + } + emit(" */"); + } + + private String getFullJavaName(SchemaType sType) { + + SchemaTypeImpl sTypeI = (SchemaTypeImpl) sType; + String ret = sTypeI.getFullJavaName(); + + while (sTypeI != null && sTypeI.isRedefinition()) { + ret = sTypeI.getFullJavaName(); + sTypeI = (SchemaTypeImpl) sTypeI.getBaseType(); + } + return ret; + } + + private String getUserTypeStaticHandlerMethod(boolean encode, SchemaTypeImpl stype) { + String unqualifiedName = stype.getName().getLocalPart(); + if (unqualifiedName.length() < 2) { + unqualifiedName = unqualifiedName.toUpperCase(Locale.ROOT); + } else { + unqualifiedName = unqualifiedName.substring(0, 1).toUpperCase(Locale.ROOT) + unqualifiedName.substring(1); + } + + if (encode) { + return stype.getUserTypeHandlerName() + ".encode" + unqualifiedName; + } else { + return stype.getUserTypeHandlerName() + ".decode" + unqualifiedName; + } + } + + + public static String indexClassForSystem(SchemaTypeSystem system) { + String name = system.getName(); + return name + "." + INDEX_CLASSNAME; + } + + void printStaticTypeDeclaration(SchemaType sType, SchemaTypeSystem system) throws IOException { + emit("org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)"); + indent(); + emit("Factory.getTypeLoader().resolveHandle(\"" + ((SchemaTypeSystemImpl) system).handleForType(sType) + "\");"); + outdent(); + } + + void printInnerType(SchemaType sType, SchemaTypeSystem system) throws IOException { + emit(""); + + printInnerTypeJavaDoc(sType); + + startInterface(sType); + + printStaticTypeDeclaration(sType, system); + + if (sType.isSimpleType()) { + if (sType.hasStringEnumValues()) { + printStringEnumeration(sType); + } + } else { + if (sType.getContentType() == SchemaType.SIMPLE_CONTENT && sType.hasStringEnumValues()) { + printStringEnumeration(sType); + } + + SchemaProperty[] props = getDerivedProperties(sType); + + for (SchemaProperty prop : props) { + printPropertyGetters( + prop.getName(), + prop.isAttribute(), + prop.getJavaPropertyName(), + prop.getJavaTypeCode(), + javaTypeForProperty(prop), + xmlTypeForProperty(prop), + prop.hasNillable() != SchemaProperty.NEVER, + prop.extendsJavaOption(), + prop.extendsJavaArray(), + prop.extendsJavaSingleton() + ); + + if (!prop.isReadOnly()) { + printPropertySetters( + prop.getName(), + prop.isAttribute(), + prop.getJavaPropertyName(), + prop.getJavaTypeCode(), + javaTypeForProperty(prop), + xmlTypeForProperty(prop), + prop.hasNillable() != SchemaProperty.NEVER, + prop.extendsJavaOption(), + prop.extendsJavaArray(), + prop.extendsJavaSingleton() + ); + } + } + + } + + printNestedInnerTypes(sType, system); + + printFactory(sType); + + endBlock(); + } + + void printFactory(SchemaType sType) throws IOException { + // Only need full factories for top-level types + boolean fullFactory = true; + if (sType.isAnonymousType() && !sType.isDocumentType() && !sType.isAttributeType()) { + fullFactory = false; + } + + String fullName = sType.getFullJavaName().replace('$', '.'); + + emit(""); + emit("/**"); + emit(" * A factory class with static methods for creating instances"); + emit(" * of this type."); + emit(" */"); + emit(""); + // BUGBUG - Can I use the name loader here? could it be a + // nested type name? It is lower case! + emit("final class Factory"); + emit("{"); + indent(); + + emit("private static synchronized " + sType.getTypeSystem().getName() + ".TypeSystemHolder getTypeLoader() {"); + emit(" return " + sType.getTypeSystem().getName() + ".TypeSystemHolder.typeSystem;"); + emit("}"); + emit(""); + + if (sType.isSimpleType()) { + emit("public static " + fullName + " newValue(java.lang.Object obj) {"); + emit(" return (" + fullName + ") type.newValue( obj ); }"); + emit(""); + } + + // Only need newInstance() for non-abstract types + if (!sType.isAbstract()) { + emit("public static " + fullName + " newInstance() {"); + emit(" return (" + fullName + ") getTypeLoader().newInstance( type, null ); }"); + emit(""); + + emit("public static " + fullName + " newInstance(org.apache.xmlbeans.XmlOptions options) {"); + emit(" return (" + fullName + ") getTypeLoader().newInstance( type, options ); }"); + emit(""); + } + + if (fullFactory) { + emit("/** @param xmlAsString the string value to parse */"); + emit("public static " + fullName + " parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( xmlAsString, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( xmlAsString, type, options ); }"); + emit(""); + + emit("/** @param file the file from which to load an xml document */"); + emit("public static " + fullName + " parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( file, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( file, type, options ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( u, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( u, type, options ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( is, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( is, type, options ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( r, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( r, type, options ); }"); + emit(""); + + emit("public static " + fullName + " parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( sr, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( sr, type, options ); }"); + emit(""); + + emit("public static " + fullName + " parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( node, type, null ); }"); + emit(""); + + emit("public static " + fullName + " parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {"); + emit(" return (" + fullName + ") getTypeLoader().parse( node, type, options ); }"); + emit(""); + } + + emit("private Factory() { } // No instance of this class allowed"); + outdent(); + emit("}"); + } + + void printNestedInnerTypes(SchemaType sType, SchemaTypeSystem system) throws IOException { + boolean redefinition = sType.getName() != null && + sType.getName().equals(sType.getBaseType().getName()); + while (sType != null) { + SchemaType[] anonTypes = sType.getAnonymousTypes(); + for (SchemaType anonType : anonTypes) { + if (anonType.isSkippedAnonymousType()) { + printNestedInnerTypes(anonType, system); + } else { + printInnerType(anonType, system); + } + } + // For redefinition other than by extension for complex types, go ahead and print + // the anonymous types in the base + if (!redefinition || + (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType())) { + break; + } + sType = sType.getBaseType(); + } + } + + void printTopComment(SchemaType sType) throws IOException { + emit("/*"); + if (sType.getName() != null) { + emit(" * XML Type: " + sType.getName().getLocalPart()); + emit(" * Namespace: " + sType.getName().getNamespaceURI()); + } else { + QName thename = null; + + if (sType.isDocumentType()) { + thename = sType.getDocumentElementName(); + emit(" * An XML document type."); + } else if (sType.isAttributeType()) { + thename = sType.getAttributeTypeAttributeName(); + emit(" * An XML attribute type."); + } else { + assert false; + } + + assert (thename != null); + + emit(" * Localname: " + thename.getLocalPart()); + emit(" * Namespace: " + thename.getNamespaceURI()); + } + emit(" * Java type: " + sType.getFullJavaName()); + emit(" *"); + emit(" * Automatically generated - do not modify."); + emit(" */"); + } + + void printPackage(SchemaType sType, boolean intf) throws IOException { + String fqjn; + if (intf) { + fqjn = sType.getFullJavaName(); + } else { + fqjn = sType.getFullJavaImplName(); + } + + int lastdot = fqjn.lastIndexOf('.'); + if (lastdot < 0) { + return; + } + String pkg = fqjn.substring(0, lastdot); + emit("package " + pkg + ";"); + } + + void startInterface(SchemaType sType) throws IOException { + String shortName = sType.getShortJavaName(); + + String baseInterface = findJavaType(sType.getBaseType()); + + /* + StringBuffer specializedInterfaces = new StringBuffer(); + + if (sType.getSimpleVariety() == SchemaType.ATOMIC && + sType.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) + { + int bits = sType.getDecimalSize(); + if (bits == SchemaType.SIZE_BIG_INTEGER) + specializedInterfaces.append(", org.apache.xmlbeans.BigIntegerValue"); + if (bits == SchemaType.SIZE_LONG) + specializedInterfaces.append(", org.apache.xmlbeans.LongValue"); + if (bits <= SchemaType.SIZE_INT) + specializedInterfaces.append(", org.apache.xmlbeans.IntValue"); + } + if (sType.getSimpleVariety() == SchemaType.LIST) + specializedInterfaces.append(", org.apache.xmlbeans.ListValue"); + + if (sType.getSimpleVariety() == SchemaType.UNION) + { + SchemaType ctype = sType.getUnionCommonBaseType(); + String javaTypeHolder = javaTypeHolderForType(ctype); + if (javaTypeHolder != null) + specializedInterfaces.append(", " + javaTypeHolder); + } + */ + + emit("public interface " + shortName + " extends " + baseInterface + getExtensionInterfaces(sType)); + emit("{"); + indent(); + emitSpecializedAccessors(sType); + } + + private static String getExtensionInterfaces(SchemaType sType) { + SchemaTypeImpl sImpl = getImpl(sType); + if (sImpl == null) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + + InterfaceExtension[] exts = sImpl.getInterfaceExtensions(); + if (exts != null) { + for (InterfaceExtension ext : exts) { + sb.append(", ").append(ext.getInterface()); + } + } + + return sb.toString(); + } + + private static SchemaTypeImpl getImpl(SchemaType sType) { + if (sType instanceof SchemaTypeImpl) { + return (SchemaTypeImpl) sType; + } else { + return null; + } + } + + private void emitSpecializedAccessors(SchemaType sType) throws IOException { + if (sType.getSimpleVariety() == SchemaType.ATOMIC && + sType.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) { + int bits = sType.getDecimalSize(); + int parentBits = sType.getBaseType().getDecimalSize(); + if (bits != parentBits || sType.getBaseType().getFullJavaName() == null) { + if (bits == SchemaType.SIZE_BIG_INTEGER) { + emit("java.math.BigInteger getBigIntegerValue();"); + emit("void setBigIntegerValue(java.math.BigInteger bi);"); + } else if (bits == SchemaType.SIZE_LONG) { + emit("long getLongValue();"); + emit("void setLongValue(long l);"); + } else if (bits == SchemaType.SIZE_INT) { + emit("int getIntValue();"); + emit("void setIntValue(int i);"); + } else if (bits == SchemaType.SIZE_SHORT) { + emit("short getShortValue();"); + emit("void setShortValue(short s);"); + } else if (bits == SchemaType.SIZE_BYTE) { + emit("byte getByteValue();"); + emit("void setByteValue(byte b);"); + } + } + } + + if (sType.getSimpleVariety() == SchemaType.UNION) { + emit("java.lang.Object getObjectValue();"); + emit("void setObjectValue(java.lang.Object val);"); + emit("org.apache.xmlbeans.SchemaType instanceType();"); + SchemaType ctype = sType.getUnionCommonBaseType(); + if (ctype != null && ctype.getSimpleVariety() != SchemaType.UNION) { + emitSpecializedAccessors(ctype); + } + } + + if (sType.getSimpleVariety() == SchemaType.LIST) { + emit("java.util.List getListValue();"); + emit("java.util.List xgetListValue();"); + emit("void setListValue(java.util.List list);"); + } + } + + void startBlock() { + // emit("{"); + indent(); + } + + void endBlock() throws IOException { + outdent(); + emit("}"); + } + + void printJavaDoc(String sentence) throws IOException { + emit(""); + emit("/**"); + emit(" * " + sentence); + emit(" */"); + } + + public static String javaStringEscape(String str) { + // forbidden: \n, \r, \", \\. + test: + { + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) { + case '\n': + case '\r': + case '\"': + case '\\': + break test; + } + } + return str; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + switch (ch) { + default: + sb.append(ch); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + } + } + return sb.toString(); + } + + void printStringEnumeration(SchemaType sType) throws IOException { + SchemaType baseEnumType = sType.getBaseEnumType(); + String baseEnumClass = baseEnumType.getFullJavaName(); + boolean hasBase = hasBase(sType); + + if (!hasBase) { + emit(""); + emit("org.apache.xmlbeans.StringEnumAbstractBase getEnumValue();"); + emit("void setEnumValue(org.apache.xmlbeans.StringEnumAbstractBase e);"); + } + + emit(""); + SchemaStringEnumEntry[] entries = sType.getStringEnumEntries(); + HashSet seenValues = new HashSet<>(); + HashSet repeatValues = new HashSet<>(); + for (SchemaStringEnumEntry entry : entries) { + String enumValue = entry.getString(); + if (seenValues.contains(enumValue)) { + repeatValues.add(enumValue); + continue; + } else { + seenValues.add(enumValue); + } + String constName = entry.getEnumName(); + if (hasBase) { + emit("static final " + baseEnumClass + ".Enum " + constName + " = " + baseEnumClass + "." + constName + ";"); + } else { + emit("static final Enum " + constName + " = Enum.forString(\"" + javaStringEscape(enumValue) + "\");"); + } + } + emit(""); + for (SchemaStringEnumEntry entry : entries) { + if (repeatValues.contains(entry.getString())) { + continue; + } + String constName = "INT_" + entry.getEnumName(); + if (hasBase) { + emit("static final int " + constName + " = " + baseEnumClass + "." + constName + ";"); + } else { + emit("static final int " + constName + " = Enum." + constName + ";"); + } + } + if (!hasBase) { + emit(""); + emit("/**"); + emit(" * Enumeration value class for " + baseEnumClass + "."); + emit(" * These enum values can be used as follows:"); + emit(" *

      ");
      +            emit(" * enum.toString(); // returns the string value of the enum");
      +            emit(" * enum.intValue(); // returns an int value, useful for switches");
      +            if (entries.length > 0) {
      +                emit(" * // e.g., case Enum.INT_" + entries[0].getEnumName());
      +            }
      +            emit(" * Enum.forString(s); // returns the enum value for a string");
      +            emit(" * Enum.forInt(i); // returns the enum value for an int");
      +            emit(" * 
      "); + emit(" * Enumeration objects are immutable singleton objects that"); + emit(" * can be compared using == object equality. They have no"); + emit(" * public constructor. See the constants defined within this"); + emit(" * class for all the valid values."); + emit(" */"); + emit("static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase"); + emit("{"); + indent(); + emit("/**"); + emit(" * Returns the enum value for a string, or null if none."); + emit(" */"); + emit("public static Enum forString(java.lang.String s)"); + emit(" { return (Enum)table.forString(s); }"); + emit("/**"); + emit(" * Returns the enum value corresponding to an int, or null if none."); + emit(" */"); + emit("public static Enum forInt(int i)"); + emit(" { return (Enum)table.forInt(i); }"); + emit(""); + emit("private Enum(java.lang.String s, int i)"); + emit(" { super(s, i); }"); + emit(""); + for (SchemaStringEnumEntry entry : entries) { + String constName = "INT_" + entry.getEnumName(); + int intValue = entry.getIntValue(); + emit("static final int " + constName + " = " + intValue + ";"); + } + emit(""); + emit("public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table ="); + emit(" new org.apache.xmlbeans.StringEnumAbstractBase.Table"); + emit("("); + indent(); + emit("new Enum[]"); + emit("{"); + indent(); + for (SchemaStringEnumEntry entry : entries) { + String enumValue = entry.getString(); + String constName = "INT_" + entry.getEnumName(); + emit("new Enum(\"" + javaStringEscape(enumValue) + "\", " + constName + "),"); + } + outdent(); + emit("}"); + outdent(); + emit(");"); + emit("private static final long serialVersionUID = 1L;"); + emit("private java.lang.Object readResolve() { return forInt(intValue()); } "); + outdent(); + emit("}"); + } + } + + private boolean hasBase(SchemaType sType) { + boolean hasBase; + SchemaType baseEnumType = sType.getBaseEnumType(); + if (baseEnumType.isAnonymousType() && baseEnumType.isSkippedAnonymousType()) { + if (sType.getContentBasedOnType() != null) { + hasBase = sType.getContentBasedOnType().getBaseType() != baseEnumType; + } else { + hasBase = sType.getBaseType() != baseEnumType; + } + } else { + hasBase = baseEnumType != sType; + } + return hasBase; + } + + String xmlTypeForProperty(SchemaProperty sProp) { + SchemaType sType = sProp.javaBasedOnType(); + return findJavaType(sType).replace('$', '.'); + } + + static boolean xmlTypeForPropertyIsUnion(SchemaProperty sProp) { + SchemaType sType = sProp.javaBasedOnType(); + return (sType.isSimpleType() && sType.getSimpleVariety() == SchemaType.UNION); + } + + static boolean isJavaPrimitive(int javaType) { + return (javaType >= SchemaProperty.JAVA_FIRST_PRIMITIVE && (javaType <= SchemaProperty.JAVA_LAST_PRIMITIVE)); + } + + /** + * Returns the wrapped type for a java primitive. + */ + static String javaWrappedType(int javaType) { + switch (javaType) { + case SchemaProperty.JAVA_BOOLEAN: + return "java.lang.Boolean"; + case SchemaProperty.JAVA_FLOAT: + return "java.lang.Float"; + case SchemaProperty.JAVA_DOUBLE: + return "java.lang.Double"; + case SchemaProperty.JAVA_BYTE: + return "java.lang.Byte"; + case SchemaProperty.JAVA_SHORT: + return "java.lang.Short"; + case SchemaProperty.JAVA_INT: + return "java.lang.Integer"; + case SchemaProperty.JAVA_LONG: + return "java.lang.Long"; + + // anything else is not a java primitive + default: + assert false; + throw new IllegalStateException(); + } + } + + String javaTypeForProperty(SchemaProperty sProp) { + // The type to use is the XML object.... + if (sProp.getJavaTypeCode() == SchemaProperty.XML_OBJECT) { + SchemaType sType = sProp.javaBasedOnType(); + return findJavaType(sType).replace('$', '.'); + } + + if (sProp.getJavaTypeCode() == SchemaProperty.JAVA_USER) { + return ((SchemaTypeImpl) sProp.getType()).getUserTypeName(); + } + + switch (sProp.getJavaTypeCode()) { + case SchemaProperty.JAVA_BOOLEAN: + return "boolean"; + case SchemaProperty.JAVA_FLOAT: + return "float"; + case SchemaProperty.JAVA_DOUBLE: + return "double"; + case SchemaProperty.JAVA_BYTE: + return "byte"; + case SchemaProperty.JAVA_SHORT: + return "short"; + case SchemaProperty.JAVA_INT: + return "int"; + case SchemaProperty.JAVA_LONG: + return "long"; + + case SchemaProperty.JAVA_BIG_DECIMAL: + return "java.math.BigDecimal"; + case SchemaProperty.JAVA_BIG_INTEGER: + return "java.math.BigInteger"; + case SchemaProperty.JAVA_STRING: + return "java.lang.String"; + case SchemaProperty.JAVA_BYTE_ARRAY: + return "byte[]"; + case SchemaProperty.JAVA_GDATE: + return "org.apache.xmlbeans.GDate"; + case SchemaProperty.JAVA_GDURATION: + return "org.apache.xmlbeans.GDuration"; + case SchemaProperty.JAVA_DATE: + return "java.util.Date"; + case SchemaProperty.JAVA_QNAME: + return "javax.xml.namespace.QName"; + case SchemaProperty.JAVA_LIST: + return "java.util.List"; + case SchemaProperty.JAVA_CALENDAR: + return "java.util.Calendar"; + + case SchemaProperty.JAVA_ENUM: + SchemaType sType = sProp.javaBasedOnType(); + if (sType.getSimpleVariety() == SchemaType.UNION) { + sType = sType.getUnionCommonBaseType(); + } + assert sType.getBaseEnumType() != null; + if (hasBase(sType)) { + return findJavaType(sType.getBaseEnumType()).replace('$', '.') + ".Enum"; + } else { + return findJavaType(sType).replace('$', '.') + ".Enum"; + } + + case SchemaProperty.JAVA_OBJECT: + return "java.lang.Object"; + + default: + assert (false); + throw new IllegalStateException(); + } + } + + void printPropertyGetters(QName qName, boolean isAttr, + String propertyName, int javaType, + String type, String xtype, + boolean nillable, boolean optional, + boolean several, boolean singleton) + throws IOException { + String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); + boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); + + if (singleton) { + printJavaDoc((several ? "Gets first " : "Gets the ") + propdesc); + emit(type + " get" + propertyName + "();"); + + if (!xmltype) { + printJavaDoc((several ? "Gets (as xml) first " : "Gets (as xml) the ") + propdesc); + emit(xtype + " xget" + propertyName + "();"); + } + + if (nillable) { + printJavaDoc((several ? "Tests for nil first " : "Tests for nil ") + propdesc); + emit("boolean isNil" + propertyName + "();"); + } + } + + if (optional) { + printJavaDoc((several ? "True if has at least one " : "True if has ") + propdesc); + emit("boolean isSet" + propertyName + "();"); + } + + if (several) { + String arrayName = propertyName + "Array"; + + String wrappedType = type; + if (isJavaPrimitive(javaType)) { + wrappedType = javaWrappedType(javaType); + } + + printJavaDoc("Gets a List of " + propdesc + "s"); + emit("java.util.List<" + wrappedType + "> get" + propertyName + "List();"); + + printJavaDoc("Gets array of all " + propdesc + "s"); + emit(type + "[] get" + arrayName + "();"); + + printJavaDoc("Gets ith " + propdesc); + emit(type + " get" + arrayName + "(int i);"); + + if (!xmltype) { + printJavaDoc("Gets (as xml) a List of " + propdesc + "s"); + emit("java.util.List<" + xtype + "> xget" + propertyName + "List();"); + + printJavaDoc("Gets (as xml) array of all " + propdesc + "s"); + emit(xtype + "[] xget" + arrayName + "();"); + + printJavaDoc("Gets (as xml) ith " + propdesc); + emit(xtype + " xget" + arrayName + "(int i);"); + } + + if (nillable) { + printJavaDoc("Tests for nil ith " + propdesc); + emit("boolean isNil" + arrayName + "(int i);"); + } + + printJavaDoc("Returns number of " + propdesc); + emit("int sizeOf" + arrayName + "();"); + } + } + + void printPropertySetters(QName qName, boolean isAttr, + String propertyName, int javaType, String type, String xtype, + boolean nillable, boolean optional, + boolean several, boolean singleton) + throws IOException { + String safeVarName = NameUtil.nonJavaKeyword(NameUtil.lowerCamelCase(propertyName)); + if (safeVarName.equals("i")) { + safeVarName = "iValue"; + } + boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); + + String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); + + if (singleton) { + printJavaDoc((several ? "Sets first " : "Sets the ") + propdesc); + emit("void set" + propertyName + "(" + type + " " + safeVarName + ");"); + + if (!xmltype) { + printJavaDoc((several ? "Sets (as xml) first " : "Sets (as xml) the ") + propdesc); + emit("void xset" + propertyName + "(" + xtype + " " + safeVarName + ");"); + } + + if (xmltype && !several) { + printJavaDoc("Appends and returns a new empty " + propdesc); + emit(xtype + " addNew" + propertyName + "();"); + } + + if (nillable) { + printJavaDoc((several ? "Nils the first " : "Nils the ") + propdesc); + emit("void setNil" + propertyName + "();"); + } + } + + if (optional) { + printJavaDoc((several ? "Removes first " : "Unsets the ") + propdesc); + emit("void unset" + propertyName + "();"); + } + + if (several) { + String arrayName = propertyName + "Array"; + + printJavaDoc("Sets array of all " + propdesc); + emit("void set" + arrayName + "(" + type + "[] " + safeVarName + "Array);"); + + printJavaDoc("Sets ith " + propdesc); + emit("void set" + arrayName + "(int i, " + type + " " + safeVarName + ");"); + + if (!xmltype) { + printJavaDoc("Sets (as xml) array of all " + propdesc); + emit("void xset" + arrayName + "(" + xtype + "[] " + safeVarName + "Array);"); + + printJavaDoc("Sets (as xml) ith " + propdesc); + emit("void xset" + arrayName + "(int i, " + xtype + " " + safeVarName + ");"); + } + + if (nillable) { + printJavaDoc("Nils the ith " + propdesc); + emit("void setNil" + arrayName + "(int i);"); + } + + if (!xmltype) { + printJavaDoc("Inserts the value as the ith " + propdesc); + emit("void insert" + propertyName + "(int i, " + type + " " + safeVarName + ");"); + + printJavaDoc("Appends the value as the last " + propdesc); + emit("void add" + propertyName + "(" + type + " " + safeVarName + ");"); + } + + printJavaDoc("Inserts and returns a new empty value (as xml) as the ith " + propdesc); + emit(xtype + " insertNew" + propertyName + "(int i);"); + + printJavaDoc("Appends and returns a new empty value (as xml) as the last " + propdesc); + emit(xtype + " addNew" + propertyName + "();"); + + printJavaDoc("Removes the ith " + propdesc); + emit("void remove" + propertyName + "(int i);"); + } + } + + String getAtomicRestrictionType(SchemaType sType) { + SchemaType pType = sType.getPrimitiveType(); + switch (pType.getBuiltinTypeCode()) { + case SchemaType.BTC_ANY_SIMPLE: + return "org.apache.xmlbeans.impl.values.XmlAnySimpleTypeImpl"; + case SchemaType.BTC_BOOLEAN: + return "org.apache.xmlbeans.impl.values.JavaBooleanHolderEx"; + case SchemaType.BTC_BASE_64_BINARY: + return "org.apache.xmlbeans.impl.values.JavaBase64HolderEx"; + case SchemaType.BTC_HEX_BINARY: + return "org.apache.xmlbeans.impl.values.JavaHexBinaryHolderEx"; + case SchemaType.BTC_ANY_URI: + return "org.apache.xmlbeans.impl.values.JavaUriHolderEx"; + case SchemaType.BTC_QNAME: + return "org.apache.xmlbeans.impl.values.JavaQNameHolderEx"; + case SchemaType.BTC_NOTATION: + return "org.apache.xmlbeans.impl.values.JavaNotationHolderEx"; + case SchemaType.BTC_FLOAT: + return "org.apache.xmlbeans.impl.values.JavaFloatHolderEx"; + case SchemaType.BTC_DOUBLE: + return "org.apache.xmlbeans.impl.values.JavaDoubleHolderEx"; + case SchemaType.BTC_DECIMAL: + switch (sType.getDecimalSize()) { + default: + assert (false); + case SchemaType.SIZE_BIG_DECIMAL: + return "org.apache.xmlbeans.impl.values.JavaDecimalHolderEx"; + case SchemaType.SIZE_BIG_INTEGER: + return "org.apache.xmlbeans.impl.values.JavaIntegerHolderEx"; + case SchemaType.SIZE_LONG: + return "org.apache.xmlbeans.impl.values.JavaLongHolderEx"; + case SchemaType.SIZE_INT: + case SchemaType.SIZE_SHORT: + case SchemaType.SIZE_BYTE: + return "org.apache.xmlbeans.impl.values.JavaIntHolderEx"; + } + case SchemaType.BTC_STRING: + if (sType.hasStringEnumValues()) { + return "org.apache.xmlbeans.impl.values.JavaStringEnumerationHolderEx"; + } else { + return "org.apache.xmlbeans.impl.values.JavaStringHolderEx"; + } + + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + return "org.apache.xmlbeans.impl.values.JavaGDateHolderEx"; + + case SchemaType.BTC_DURATION: + return "org.apache.xmlbeans.impl.values.JavaGDurationHolderEx"; + default: + assert (false) : "unrecognized primitive type"; + return null; + } + } + + static SchemaType findBaseType(SchemaType sType) { + while (sType.getFullJavaName() == null) { + sType = sType.getBaseType(); + } + return sType; + } + + String getBaseClass(SchemaType sType) { + SchemaType baseType = findBaseType(sType.getBaseType()); + + switch (sType.getSimpleVariety()) { + case SchemaType.NOT_SIMPLE: + // non-simple-content: inherit from base type impl + if (!XmlObject.type.equals(baseType)) { + return baseType.getFullJavaImplName(); + } + return "org.apache.xmlbeans.impl.values.XmlComplexContentImpl"; + + case SchemaType.ATOMIC: + // We should only get called for restrictions + assert (!sType.isBuiltinType()); + return getAtomicRestrictionType(sType); + + case SchemaType.LIST: + return "org.apache.xmlbeans.impl.values.XmlListImpl"; + + case SchemaType.UNION: + return "org.apache.xmlbeans.impl.values.XmlUnionImpl"; + + default: + throw new IllegalStateException(); + } + } + + void printConstructor(SchemaType sType, String shortName) throws IOException { + emit(""); + emit("public " + shortName + "(org.apache.xmlbeans.SchemaType sType) {"); + startBlock(); + emit("super(sType" + (sType.getSimpleVariety() == SchemaType.NOT_SIMPLE ? + "" : + ", " + !sType.isSimpleType()) + + ");"); + endBlock(); + + if (sType.getSimpleVariety() != SchemaType.NOT_SIMPLE) { + emit(""); + emit("protected " + shortName + "(org.apache.xmlbeans.SchemaType sType, boolean b) {"); + startBlock(); + emit("super(sType, b);"); + endBlock(); + } + } + + void startClass(SchemaType sType, boolean isInner) throws IOException { + String shortName = sType.getShortJavaImplName(); + String baseClass = getBaseClass(sType); + StringBuilder interfaces = new StringBuilder(); + interfaces.append(sType.getFullJavaName().replace('$', '.')); + + if (sType.getSimpleVariety() == SchemaType.UNION) { + SchemaType[] memberTypes = sType.getUnionMemberTypes(); + for (SchemaType memberType : memberTypes) { + interfaces.append(", ").append(memberType.getFullJavaName().replace('$', '.')); + } + } + + emit("public " + (isInner ? "static " : "") + "class " + shortName + + " extends " + baseClass + " implements " + interfaces.toString() + " {"); + + startBlock(); + + emit("private static final long serialVersionUID = 1L;"); + } + + void makeAttributeDefaultValue(String jtargetType, SchemaProperty prop, String identifier) throws IOException { + String fullName = jtargetType; + if (fullName == null) { + fullName = prop.javaBasedOnType().getFullJavaName().replace('$', '.'); + } + + emit("target = (" + fullName + ")get_default_attribute_value(" + identifier + ");"); + } + + void makeMissingValue(int javaType) throws IOException { + switch (javaType) { + case SchemaProperty.JAVA_BOOLEAN: + emit("return false;"); + break; + + case SchemaProperty.JAVA_FLOAT: + emit("return 0.0f;"); + break; + + case SchemaProperty.JAVA_DOUBLE: + emit("return 0.0;"); + break; + + case SchemaProperty.JAVA_BYTE: + case SchemaProperty.JAVA_SHORT: + case SchemaProperty.JAVA_INT: + emit("return 0;"); + break; + + case SchemaProperty.JAVA_LONG: + emit("return 0L;"); + break; + + default: + case SchemaProperty.XML_OBJECT: + case SchemaProperty.JAVA_BIG_DECIMAL: + case SchemaProperty.JAVA_BIG_INTEGER: + case SchemaProperty.JAVA_STRING: + case SchemaProperty.JAVA_BYTE_ARRAY: + case SchemaProperty.JAVA_GDATE: + case SchemaProperty.JAVA_GDURATION: + case SchemaProperty.JAVA_DATE: + case SchemaProperty.JAVA_QNAME: + case SchemaProperty.JAVA_LIST: + case SchemaProperty.JAVA_CALENDAR: + case SchemaProperty.JAVA_ENUM: + case SchemaProperty.JAVA_OBJECT: + emit("return null;"); + break; + } + } + + void printJGetArrayValue(int javaType, String type, SchemaTypeImpl stype, String setIdentifier) throws IOException { + switch (javaType) { + case SchemaProperty.XML_OBJECT: + emit("return getXmlObjectArray(" + setIdentifier + ", new " + type + "[0]);"); + break; + + case SchemaProperty.JAVA_ENUM: + emit("return getEnumArray(" + setIdentifier + ", " + type + "[]::new);"); + break; + + case SchemaProperty.JAVA_BOOLEAN: + emit("return getBooleanArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_FLOAT: + emit("return getFloatArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_DOUBLE: + emit("return getDoubleArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_BYTE: + emit("return getByteArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_SHORT: + emit("return getShortArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_INT: + emit("return getIntArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_LONG: + emit("return getLongArray(" + setIdentifier + ");"); + break; + + case SchemaProperty.JAVA_BIG_DECIMAL: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getBigDecimalValue, java.math.BigDecimal[]::new);"); + break; + + case SchemaProperty.JAVA_BIG_INTEGER: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getBigIntegerValue, java.math.BigInteger[]::new);"); + break; + + case SchemaProperty.JAVA_STRING: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getStringValue, String[]::new);"); + break; + + case SchemaProperty.JAVA_BYTE_ARRAY: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getByteArrayValue, byte[][]::new);"); + break; + + case SchemaProperty.JAVA_CALENDAR: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getCalendarValue, java.util.Calendar[]::new);"); + break; + + case SchemaProperty.JAVA_DATE: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getDateValue, java.util.Date[]::new);"); + break; + + case SchemaProperty.JAVA_GDATE: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getGDateValue, org.apache.xmlbeans.GDate[]::new);"); + break; + + case SchemaProperty.JAVA_GDURATION: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getGDurationValue, org.apache.xmlbeans.GDuration[]::new);"); + break; + + case SchemaProperty.JAVA_QNAME: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getQNameValue, javax.xml.namespace.QName[]::new);"); + break; + + case SchemaProperty.JAVA_LIST: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getListValue, java.util.List[]::new);"); + break; + + case SchemaProperty.JAVA_OBJECT: + emit("return getObjectArray(" + setIdentifier + ", org.apache.xmlbeans.SimpleValue::getObjectValue, java.util.Object[]::new);"); + break; + + case SchemaProperty.JAVA_USER: + // TOOD: replace lambda with method reference + emit("return getObjectArray(" + setIdentifier + ", e -> " + getUserTypeStaticHandlerMethod(false, stype) + "(e), " + stype.getUserTypeName() + "[]::new);"); + break; + + default: + throw new IllegalStateException(); + } + } + + void printJGetValue(int javaType, String type, SchemaTypeImpl stype) throws IOException { + switch (javaType) { + case SchemaProperty.XML_OBJECT: + emit("return target;"); + break; + + case SchemaProperty.JAVA_BOOLEAN: + emit("return target.getBooleanValue();"); + break; + + case SchemaProperty.JAVA_FLOAT: + emit("return target.getFloatValue();"); + break; + + case SchemaProperty.JAVA_DOUBLE: + emit("return target.getDoubleValue();"); + break; + + case SchemaProperty.JAVA_BYTE: + emit("return target.getByteValue();"); + break; + + case SchemaProperty.JAVA_SHORT: + emit("return target.getShortValue();"); + break; + + case SchemaProperty.JAVA_INT: + emit("return target.getIntValue();"); + break; + + case SchemaProperty.JAVA_LONG: + emit("return target.getLongValue();"); + break; + + case SchemaProperty.JAVA_BIG_DECIMAL: + emit("return target.getBigDecimalValue();"); + break; + + case SchemaProperty.JAVA_BIG_INTEGER: + emit("return target.getBigIntegerValue();"); + break; + + case SchemaProperty.JAVA_STRING: + emit("return target.getStringValue();"); + break; + + case SchemaProperty.JAVA_BYTE_ARRAY: + emit("return target.getByteArrayValue();"); + break; + + case SchemaProperty.JAVA_GDATE: + emit("return target.getGDateValue();"); + break; + + case SchemaProperty.JAVA_GDURATION: + emit("return target.getGDurationValue();"); + break; + + case SchemaProperty.JAVA_CALENDAR: + emit("return target.getCalendarValue();"); + break; + + case SchemaProperty.JAVA_DATE: + emit("return target.getDateValue();"); + break; + + case SchemaProperty.JAVA_QNAME: + emit("return target.getQNameValue();"); + break; + + case SchemaProperty.JAVA_LIST: + emit("return target.getListValue();"); + break; + + case SchemaProperty.JAVA_ENUM: + emit("return (" + type + ")target.getEnumValue();"); + break; + + case SchemaProperty.JAVA_OBJECT: + emit("return target.getObjectValue();"); + break; + + case SchemaProperty.JAVA_USER: + emit("return " + getUserTypeStaticHandlerMethod(false, stype) + + "(target);"); + break; + + default: + throw new IllegalStateException(); + } + } + + void printJSetValue(int javaType, String safeVarName, SchemaTypeImpl stype) throws IOException { + switch (javaType) { + case SchemaProperty.XML_OBJECT: + emit("target.set(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_BOOLEAN: + emit("target.setBooleanValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_FLOAT: + emit("target.setFloatValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_DOUBLE: + emit("target.setDoubleValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_BYTE: + emit("target.setByteValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_SHORT: + emit("target.setShortValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_INT: + emit("target.setIntValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_LONG: + emit("target.setLongValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_BIG_DECIMAL: + emit("target.setBigDecimalValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_BIG_INTEGER: + emit("target.setBigIntegerValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_STRING: + emit("target.setStringValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_BYTE_ARRAY: + emit("target.setByteArrayValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_GDATE: + emit("target.setGDateValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_GDURATION: + emit("target.setGDurationValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_CALENDAR: + emit("target.setCalendarValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_DATE: + emit("target.setDateValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_QNAME: + emit("target.setQNameValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_LIST: + emit("target.setListValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_ENUM: + emit("target.setEnumValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_OBJECT: + emit("target.setObjectValue(" + safeVarName + ");"); + break; + + case SchemaProperty.JAVA_USER: + emit(getUserTypeStaticHandlerMethod(true, stype) + + "(" + safeVarName + ", target);"); + break; + + default: + throw new IllegalStateException(); + } + } + + String getIdentifier(Map qNameMap, QName qName) { + return qNameMap.get(qName)[0]; + } + + String getSetIdentifier(Map qNameMap, QName qName) { + String[] identifiers = qNameMap.get(qName); + return identifiers[1] == null ? identifiers[0] : identifiers[1]; + } + + Map printStaticFields(SchemaProperty[] properties) throws IOException { + final Map results = new HashMap<>(); + + emit(""); + for (int i = 0; i < properties.length; i++) { + final String[] identifiers = new String[2]; + final SchemaProperty prop = properties[i]; + final QName name = prop.getName(); + results.put(name, identifiers); + final String javaName = prop.getJavaPropertyName(); + identifiers[0] = (javaName + "$" + (i * 2)).toUpperCase(Locale.ROOT); + final String uriString = "\"" + name.getNamespaceURI() + "\""; + + emit("private static final javax.xml.namespace.QName " + identifiers[0] + + " = "); + indent(); + emit("new javax.xml.namespace.QName(" + + uriString + ", \"" + name.getLocalPart() + "\");"); + outdent(); + + if (properties[i].acceptedNames() != null) { + final QName[] qnames = properties[i].acceptedNames(); + + if (qnames.length > 1) { + identifiers[1] = (javaName + "$" + (i * 2 + 1)).toUpperCase(Locale.ROOT); + + emit("private static final org.apache.xmlbeans.QNameSet " + identifiers[1] + + " = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { "); + indent(); + for (QName qname : qnames) { + emit("new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() + + "\", \"" + qname.getLocalPart() + "\"),"); + } + + outdent(); + + emit("});"); + } + } + } + emit(""); + return results; + } + + void emitImplementationPreamble() throws IOException { + emit("synchronized (monitor())"); + emit("{"); + indent(); + emit("check_orphaned();"); + } + + void emitImplementationPostamble() throws IOException { + outdent(); + emit("}"); + } + + void emitAddTarget(String identifier, boolean isAttr, String xtype) + throws IOException { + if (isAttr) { + emit("target = (" + xtype + ")get_store().add_attribute_user(" + identifier + ");"); + } else { + emit("target = (" + xtype + ")get_store().add_element_user(" + identifier + ");"); + } + } + + void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException { + emitPre(sType, opType, identifier, isAttr, "-1"); + } + + void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException { + SchemaTypeImpl sImpl = getImpl(sType); + if (sImpl == null) { + return; + } + + PrePostExtension ext = sImpl.getPrePostExtension(); + if (ext != null) { + if (ext.hasPreCall()) { + emit("if ( " + ext.getStaticHandler() + ".preSet(" + prePostOpString(opType) + ", this, " + identifier + ", " + isAttr + ", " + index + ")) {"); + startBlock(); + } + } + } + + void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException { + emitPost(sType, opType, identifier, isAttr, "-1"); + } + + void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException { + SchemaTypeImpl sImpl = getImpl(sType); + if (sImpl == null) { + return; + } + + PrePostExtension ext = sImpl.getPrePostExtension(); + if (ext != null) { + if (ext.hasPreCall()) { + endBlock(); + } + + if (ext.hasPostCall()) { + emit(ext.getStaticHandler() + ".postSet(" + prePostOpString(opType) + ", this, " + identifier + ", " + isAttr + ", " + index + ");"); + } + } + } + + String prePostOpString(int opType) { + switch (opType) { + default: + assert false; + + case PrePostExtension.OPERATION_SET: + return "org.apache.xmlbeans.PrePostExtension.OPERATION_SET"; + + case PrePostExtension.OPERATION_INSERT: + return "org.apache.xmlbeans.PrePostExtension.OPERATION_INSERT"; + + case PrePostExtension.OPERATION_REMOVE: + return "org.apache.xmlbeans.PrePostExtension.OPERATION_REMOVE"; + } + } + + private static final int NOTHING = 1; + private static final int ADD_NEW_VALUE = 3; + private static final int THROW_EXCEPTION = 4; + + void emitGetTarget(String setIdentifier, + String identifier, + boolean isAttr, + String index, + int nullBehaviour, + String xtype) + throws IOException { + assert setIdentifier != null && identifier != null; + + emit(xtype + " target = null;"); + + if (isAttr) { + emit("target = (" + xtype + ")get_store().find_attribute_user(" + identifier + ");"); + } else { + emit("target = (" + xtype + ")get_store().find_element_user(" + setIdentifier + ", " + index + ");"); + } + + if (nullBehaviour == NOTHING) { + return; + } + + emit("if (target == null) {"); + + startBlock(); + + switch (nullBehaviour) { + case ADD_NEW_VALUE: + // target already emited, no need for emitDeclareTarget(false, xtype); + emitAddTarget(identifier, isAttr, xtype); + break; + + case THROW_EXCEPTION: + emit("throw new IndexOutOfBoundsException();"); + break; + + case NOTHING: + break; + + default: + assert false : "Bad behaviour type: " + nullBehaviour; + } + + endBlock(); + } + + void printListGetter15Impl(String parentJavaName, + String propdesc, String propertyName, + String wrappedType, + boolean xmltype, boolean xget) + throws IOException { + String arrayName = propertyName + "Array"; + String listName = propertyName + "List"; + String parentThis = parentJavaName + ".this."; + + String xgetMethod = (xget ? "x" : "") + "get"; + String xsetMethod = (xget ? "x" : "") + "set"; + + printJavaDoc("Gets " + (xget ? "(as xml) " : "") + "a List of " + propdesc + "s"); + + emit("public java.util.List<" + wrappedType + "> " + xgetMethod + listName + "() {"); + startBlock(); + + emit("final class " + listName + " extends java.util.AbstractList<" + wrappedType + "> {"); + startBlock(); + + // Object get(i) + emit("@Override"); + emit("public " + wrappedType + " get(int i)"); + emit(" { return " + parentThis + xgetMethod + arrayName + "(i); }"); + emit(""); + + // Object set(i, o) + emit("@Override"); + emit("public " + wrappedType + " set(int i, " + wrappedType + " o) {"); + startBlock(); + emit(wrappedType + " old = " + parentThis + xgetMethod + arrayName + "(i);"); + emit(parentThis + xsetMethod + arrayName + "(i, o);"); + emit("return old;"); + endBlock(); + emit(""); + + // void add(i, o) + emit("@Override"); + emit("public void add(int i, " + wrappedType + " o)"); + if (xmltype || xget) { + emit(" { " + parentThis + "insertNew" + propertyName + "(i).set(o); }"); + } else { + emit(" { " + parentThis + "insert" + propertyName + "(i, o); }"); + } + emit(""); + + // Object remove(i) + emit("@Override"); + emit("public " + wrappedType + " remove(int i) {"); + startBlock(); + emit(wrappedType + " old = " + parentThis + xgetMethod + arrayName + "(i);"); + emit(parentThis + "remove" + propertyName + "(i);"); + emit("return old;"); + endBlock(); + emit(""); + + // int size() + emit("@Override"); + emit("public int size()"); + emit(" { return " + parentThis + "sizeOf" + arrayName + "(); }"); + emit(""); + + endBlock(); + + emit(""); + + emitImplementationPreamble(); + + emit("return new " + listName + "();"); + + emitImplementationPostamble(); + endBlock(); + } + + void printGetterImpls(String parentJavaName, + SchemaProperty prop, QName qName, boolean isAttr, String propertyName, + int javaType, String type, String xtype, boolean nillable, + boolean optional, boolean several, boolean singleton, + boolean isunion, + String identifier, String setIdentifier) + throws IOException { + String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); + boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); + String jtargetType = (isunion || !xmltype) ? "org.apache.xmlbeans.SimpleValue" : xtype; + + if (singleton) { + // Value getProp() + printJavaDoc((several ? "Gets first " : "Gets the ") + propdesc); + emit("public " + type + " get" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + + emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, jtargetType); + + if (isAttr && (prop.hasDefault() == SchemaProperty.CONSISTENTLY || + prop.hasFixed() == SchemaProperty.CONSISTENTLY)) { + emit("if (target == null) {"); + startBlock(); + makeAttributeDefaultValue(jtargetType, prop, identifier); + endBlock(); + } + emit("if (target == null) {"); + startBlock(); + makeMissingValue(javaType); + endBlock(); + + + printJGetValue(javaType, type, (SchemaTypeImpl) prop.getType()); + + + emitImplementationPostamble(); + + endBlock(); + + if (!xmltype) { + // Value xgetProp() + printJavaDoc((several ? "Gets (as xml) first " : "Gets (as xml) the ") + propdesc); + emit("public " + xtype + " xget" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, xtype); + + if (isAttr && (prop.hasDefault() == SchemaProperty.CONSISTENTLY || + prop.hasFixed() == SchemaProperty.CONSISTENTLY)) { + emit("if (target == null) {"); + startBlock(); + makeAttributeDefaultValue(xtype, prop, identifier); + endBlock(); + } + + emit("return target;"); + emitImplementationPostamble(); + endBlock(); + } + + if (nillable) { + // boolean isNilProp() + printJavaDoc((several ? "Tests for nil first " : "Tests for nil ") + propdesc); + emit("public boolean isNil" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, xtype); + + emit("if (target == null) return false;"); + emit("return target.isNil();"); + emitImplementationPostamble(); + endBlock(); + } + } + + if (optional) { + // boolean isSetProp() + printJavaDoc((several ? "True if has at least one " : "True if has ") + propdesc); + emit("public boolean isSet" + propertyName + "() {"); + + startBlock(); + emitImplementationPreamble(); + + if (isAttr) { + emit("return get_store().find_attribute_user(" + identifier + ") != null;"); + } else { + emit("return get_store().count_elements(" + setIdentifier + ") != 0;"); + } + + emitImplementationPostamble(); + endBlock(); + } + + if (several) { + String arrayName = propertyName + "Array"; + + // use boxed type if the java type is a primitive and jdk1.5 + // jdk1.5 will box/unbox for us + String wrappedType = type; + if (isJavaPrimitive(javaType)) { + wrappedType = javaWrappedType(javaType); + } + + printListGetter15Impl(parentJavaName, propdesc, propertyName, wrappedType, xmltype, false); + + // Value[] getProp() + printJavaDoc("Gets array of all " + propdesc + "s"); + emit("public " + type + "[] get" + arrayName + "() {"); + startBlock(); + + printJGetArrayValue(javaType, type, (SchemaTypeImpl) prop.getType(), setIdentifier); + + endBlock(); + + // Value getProp(int i) + printJavaDoc("Gets ith " + propdesc); + emit("public " + type + " get" + arrayName + "(int i) {"); + startBlock(); + emitImplementationPreamble(); + + emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, jtargetType); + printJGetValue(javaType, type, (SchemaTypeImpl) prop.getType()); + + emitImplementationPostamble(); + endBlock(); + + if (!xmltype) { + printListGetter15Impl(parentJavaName, propdesc, propertyName, xtype, false, true); + + // Value[] xgetProp() + printJavaDoc("Gets (as xml) array of all " + propdesc + "s"); + emit("public " + xtype + "[] xget" + arrayName + "() {"); + startBlock(); + emit("return xgetArray(" + setIdentifier + ", " + xtype + "[]::new);"); + endBlock(); + + // Value xgetProp(int i) + printJavaDoc("Gets (as xml) ith " + propdesc); + emit("public " + xtype + " xget" + arrayName + "(int i) {"); + startBlock(); + emitImplementationPreamble(); + emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); + emit("return target;"); + emitImplementationPostamble(); + endBlock(); + + } + + if (nillable) { + // boolean isNil(int i); + printJavaDoc("Tests for nil ith " + propdesc); + emit("public boolean isNil" + arrayName + "(int i) {"); + startBlock(); + emitImplementationPreamble(); + emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); + emit("return target.isNil();"); + emitImplementationPostamble(); + endBlock(); + } + + // int countProp(); + printJavaDoc("Returns number of " + propdesc); + emit("public int sizeOf" + arrayName + "() {"); + startBlock(); + emitImplementationPreamble(); + emit("return get_store().count_elements(" + setIdentifier + ");"); + emitImplementationPostamble(); + endBlock(); + } + } + + void printSetterImpls(QName qName, SchemaProperty prop, boolean isAttr, + String propertyName, int javaType, String type, String xtype, + boolean nillable, boolean optional, boolean several, boolean singleton, + boolean isunion, String identifier, String setIdentifier, SchemaType sType) + throws IOException { + String safeVarName = NameUtil.nonJavaKeyword(NameUtil.lowerCamelCase(propertyName)); + safeVarName = NameUtil.nonExtraKeyword(safeVarName); + + boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); + boolean isobj = (javaType == SchemaProperty.JAVA_OBJECT); + boolean isSubstGroup = !Objects.equals(identifier, setIdentifier); + String jtargetType = (isunion || !xmltype) ? "org.apache.xmlbeans.SimpleValue" : xtype; + + String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); + + if (singleton) { + // void setProp(Value v); + printJavaDoc((several ? "Sets first " : "Sets the ") + propdesc); + emit("public void set" + propertyName + "(" + type + " " + safeVarName + ") {"); + startBlock(); + if (xmltype && !isSubstGroup && !isAttr) { + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, false, several ? "0" : "-1"); + emit("generatedSetterHelperImpl(" + safeVarName + ", " + setIdentifier + ", 0, " + + "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, false, several ? "0" : "-1"); + } else { + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); + emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, jtargetType); + printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType()); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); + emitImplementationPostamble(); + } + endBlock(); + + if (!xmltype) { + // void xsetProp(Value v) + printJavaDoc((several ? "Sets (as xml) first " : "Sets (as xml) the ") + propdesc); + emit("public void xset" + propertyName + "(" + xtype + " " + safeVarName + ") {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); + emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, xtype); + emit("target.set(" + safeVarName + ");"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); + emitImplementationPostamble(); + endBlock(); + + } + + if (xmltype && !several) { + // Value addNewProp() + printJavaDoc("Appends and returns a new empty " + propdesc); + emit("public " + xtype + " addNew" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + emit(xtype + " target = null;"); + emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); + emitAddTarget(identifier, isAttr, xtype); + emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); + emit("return target;"); + emitImplementationPostamble(); + endBlock(); + } + + if (nillable) { + printJavaDoc((several ? "Nils the first " : "Nils the ") + propdesc); + emit("public void setNil" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); + emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, xtype); + emit("target.setNil();"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); + emitImplementationPostamble(); + endBlock(); + } + } + + if (optional) { + printJavaDoc((several ? "Removes first " : "Unsets the ") + propdesc); + emit("public void unset" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, several ? "0" : "-1"); + if (isAttr) { + emit("get_store().remove_attribute(" + identifier + ");"); + } else { + emit("get_store().remove_element(" + setIdentifier + ", 0);"); + } + emitPost(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, several ? "0" : "-1"); + emitImplementationPostamble(); + endBlock(); + } + + if (several) { + String arrayName = propertyName + "Array"; + + if (xmltype) { + printJavaDoc("Sets array of all " + propdesc + " WARNING: This method is not atomicaly synchronized."); + emit("public void set" + arrayName + "(" + type + "[] " + safeVarName + "Array) {"); + startBlock(); + // do not use synchronize (monitor()) { and GlobalLock inside } !!! deadlock + //emitImplementationPreamble(); + emit("check_orphaned();"); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); + + if (isobj) { + if (!isSubstGroup) { + emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");"); + } else { + emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");"); + } + } else { + if (!isSubstGroup) { + emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");"); + } else { + emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");"); + } + } + + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); + //emitImplementationPostamble(); to avoid deadlock + endBlock(); + } else { + printJavaDoc("Sets array of all " + propdesc); + emit("public void set" + arrayName + "(" + type + "[] " + safeVarName + "Array) {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); + + if (isobj) { + if (!isSubstGroup) { + emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");"); + } else { + emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");"); + } + } else if (prop.getJavaTypeCode() == SchemaProperty.JAVA_USER) { + if (!isSubstGroup) { + emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ");"); + emit("for ( int i = 0 ; i < dests.length ; i++ ) {"); + emit(" " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl) prop.getType()) + + "(" + safeVarName + "Array[i], dests[i]);"); + emit("}"); + } else { + emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ", " + setIdentifier + ");"); + emit("for ( int i = 0 ; i < dests.length ; i++ ) {"); + emit(" " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl) prop.getType()) + + "(" + safeVarName + "Array[i], dests[i]);"); + emit("}"); + } + } else { + if (!isSubstGroup) { + emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");"); + } else { + emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");"); + } + } + + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); + emitImplementationPostamble(); + endBlock(); + } + + printJavaDoc("Sets ith " + propdesc); + emit("public void set" + arrayName + "(int i, " + type + " " + safeVarName + ") {"); + startBlock(); + if (xmltype && !isSubstGroup) { + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emit("generatedSetterHelperImpl(" + safeVarName + ", " + setIdentifier + ", i, " + + "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + } else { + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, jtargetType); + printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType()); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emitImplementationPostamble(); + } + endBlock(); + + if (!xmltype) { + printJavaDoc("Sets (as xml) array of all " + propdesc); + emit("public void xset" + arrayName + "(" + xtype + "[]" + safeVarName + "Array) {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); + emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); + emitImplementationPostamble(); + endBlock(); + + printJavaDoc("Sets (as xml) ith " + propdesc); + emit("public void xset" + arrayName + "(int i, " + xtype + " " + safeVarName + ") {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); + emit("target.set(" + safeVarName + ");"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emitImplementationPostamble(); + endBlock(); + } + + if (nillable) { + printJavaDoc("Nils the ith " + propdesc); + emit("public void setNil" + arrayName + "(int i) {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); + emit("target.setNil();"); + emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); + emitImplementationPostamble(); + endBlock(); + } + + if (!xmltype) { + printJavaDoc("Inserts the value as the ith " + propdesc); + emit("public void insert" + propertyName + "(int i, " + type + " " + safeVarName + ") {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); + emit(jtargetType + " target = "); + indent(); + if (!isSubstGroup) { + emit("(" + jtargetType + ")get_store().insert_element_user(" + identifier + ", i);"); + } else // This is a subst group case + { + emit("(" + jtargetType + ")get_store().insert_element_user(" + setIdentifier + ", " + + identifier + ", i);"); + } + outdent(); + printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType()); + emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); + emitImplementationPostamble(); + endBlock(); + + printJavaDoc("Appends the value as the last " + propdesc); + emit("public void add" + propertyName + "(" + type + " " + safeVarName + ") {"); + startBlock(); + emitImplementationPreamble(); + emit(jtargetType + " target = null;"); + emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); + emitAddTarget(identifier, isAttr, jtargetType); + printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType()); + emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); + emitImplementationPostamble(); + endBlock(); + } + + printJavaDoc("Inserts and returns a new empty value (as xml) as the ith " + propdesc); + emit("public " + xtype + " insertNew" + propertyName + "(int i) {"); + startBlock(); + emitImplementationPreamble(); + emit(xtype + " target = null;"); + emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); + if (!isSubstGroup) { + emit("target = (" + xtype + ")get_store().insert_element_user(" + identifier + ", i);"); + } else // This is a subst group case + { + emit("target = (" + xtype + ")get_store().insert_element_user(" + + setIdentifier + ", " + identifier + ", i);"); + } + emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); + emit("return target;"); + emitImplementationPostamble(); + endBlock(); + + printJavaDoc("Appends and returns a new empty value (as xml) as the last " + propdesc); + emit("public " + xtype + " addNew" + propertyName + "() {"); + startBlock(); + emitImplementationPreamble(); + emit(xtype + " target = null;"); + emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); + emitAddTarget(identifier, isAttr, xtype); + emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); + emit("return target;"); + emitImplementationPostamble(); + endBlock(); + + printJavaDoc("Removes the ith " + propdesc); + emit("public void remove" + propertyName + "(int i) {"); + startBlock(); + emitImplementationPreamble(); + emitPre(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, "i"); + emit("get_store().remove_element(" + setIdentifier + ", i);"); + emitPost(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, "i"); + emitImplementationPostamble(); + endBlock(); + } + } + + void printInnerTypeImpl( + SchemaType sType, SchemaTypeSystem system, boolean isInner) throws IOException { + String shortName = sType.getShortJavaImplName(); + + printInnerTypeJavaDoc(sType); + + startClass(sType, isInner); + + printConstructor(sType, shortName); + + printExtensionImplMethods(sType); + + if (!sType.isSimpleType()) { + SchemaProperty[] properties; + + if (sType.getContentType() == SchemaType.SIMPLE_CONTENT) { + // simple content types impls derive directly from "holder" impls + // in order to handle the case (for ints or string enums e.g.) where + // there is a simple type restriction. So property getters need to + // be implemented "from scratch" for each derived complex type + // Moreover, attribute or element properties can be removed via restriction, + // but we still need to implement them because this class is supposed to + // also implement all the interfaces + SchemaType baseType = sType.getBaseType(); + List extraProperties = null; + while (!baseType.isSimpleType() && !baseType.isBuiltinType()) { + SchemaProperty[] baseProperties = baseType.getDerivedProperties(); + for (SchemaProperty baseProperty : baseProperties) { + if (!(baseProperty.isAttribute() && + sType.getAttributeProperty(baseProperty.getName()) != null)) { + if (extraProperties == null) { + extraProperties = new ArrayList<>(); + } + extraProperties.add(baseProperty); + } + } + baseType = baseType.getBaseType(); + } + + properties = sType.getProperties(); + if (extraProperties != null) { + Collections.addAll(extraProperties, properties); + properties = extraProperties.toArray(new SchemaProperty[0]); + } + } else { + // complex content type implementations derive from base type impls + // so derived property impls can be reused + + properties = getDerivedProperties(sType); + } + + Map qNameMap = printStaticFields(properties); + + for (SchemaProperty prop : properties) { + QName name = prop.getName(); + String xmlType = xmlTypeForProperty(prop); + + printGetterImpls( + shortName, + prop, + name, + prop.isAttribute(), + prop.getJavaPropertyName(), + prop.getJavaTypeCode(), + javaTypeForProperty(prop), + xmlType, + prop.hasNillable() != SchemaProperty.NEVER, + prop.extendsJavaOption(), + prop.extendsJavaArray(), + prop.extendsJavaSingleton(), + xmlTypeForPropertyIsUnion(prop), + getIdentifier(qNameMap, name), + getSetIdentifier(qNameMap, name) + ); + + if (!prop.isReadOnly()) { + printSetterImpls( + name, + prop, + prop.isAttribute(), + prop.getJavaPropertyName(), + prop.getJavaTypeCode(), + javaTypeForProperty(prop), + xmlType, + prop.hasNillable() != SchemaProperty.NEVER, + prop.extendsJavaOption(), + prop.extendsJavaArray(), + prop.extendsJavaSingleton(), + xmlTypeForPropertyIsUnion(prop), + getIdentifier(qNameMap, name), + getSetIdentifier(qNameMap, name), + sType + ); + } + } + } + + printNestedTypeImpls(sType, system); + + endBlock(); + } + + private SchemaProperty[] getDerivedProperties(SchemaType sType) { + // We have to see if this is redefined, because if it is we have + // to include all properties associated to its supertypes + QName name = sType.getName(); + if (name != null && name.equals(sType.getBaseType().getName())) { + SchemaType sType2 = sType.getBaseType(); + // Walk all the redefined types and record any properties + // not present in sType, because the redefined types do not + // have a generated class to represent them + SchemaProperty[] props = sType.getDerivedProperties(); + Map propsByName = new LinkedHashMap<>(); + for (SchemaProperty prop : props) { + propsByName.put(prop.getName(), prop); + } + while (sType2 != null && name.equals(sType2.getName())) { + props = sType2.getDerivedProperties(); + for (SchemaProperty prop : props) { + if (!propsByName.containsKey(prop.getName())) { + propsByName.put(prop.getName(), prop); + } + } + sType2 = sType2.getBaseType(); + } + return propsByName.values().toArray(new SchemaProperty[0]); + } else { + return sType.getDerivedProperties(); + } + } + + private void printExtensionImplMethods(SchemaType sType) throws IOException { + SchemaTypeImpl sImpl = getImpl(sType); + if (sImpl == null) { + return; + } + + InterfaceExtension[] exts = sImpl.getInterfaceExtensions(); + if (exts != null) { + for (InterfaceExtension ext : exts) { + InterfaceExtension.MethodSignature[] methods = ext.getMethods(); + if (methods != null) { + for (InterfaceExtension.MethodSignature method : methods) { + printJavaDoc("Implementation method for interface " + ext.getStaticHandler()); + printInterfaceMethodDecl(method); + startBlock(); + printInterfaceMethodImpl(ext.getStaticHandler(), method); + endBlock(); + } + } + } + } + } + + void printInterfaceMethodDecl(InterfaceExtension.MethodSignature method) throws IOException { + StringBuilder decl = new StringBuilder(60); + + decl.append("public ").append(method.getReturnType()); + decl.append(" ").append(method.getName()).append("("); + + String[] paramTypes = method.getParameterTypes(); + for (int i = 0; i < paramTypes.length; i++) { + if (i != 0) { + decl.append(", "); + } + decl.append(paramTypes[i]).append(" p").append(i); + } + + decl.append(")"); + + String[] exceptions = method.getExceptionTypes(); + for (int i = 0; i < exceptions.length; i++) { + decl.append(i == 0 ? " throws " : ", ").append(exceptions[i]); + } + + decl.append(" {"); + + emit(decl.toString()); + } + + void printInterfaceMethodImpl(String handler, InterfaceExtension.MethodSignature method) throws IOException { + StringBuilder impl = new StringBuilder(60); + + if (!method.getReturnType().equals("void")) { + impl.append("return "); + } + + impl.append(handler).append(".").append(method.getName()).append("(this"); + + String[] params = method.getParameterTypes(); + for (int i = 0; i < params.length; i++) { + impl.append(", p").append(i); + } + + impl.append(");"); + + emit(impl.toString()); + } + + void printNestedTypeImpls(SchemaType sType, SchemaTypeSystem system) throws IOException { + boolean redefinition = sType.getName() != null && + sType.getName().equals(sType.getBaseType().getName()); + while (sType != null) { + SchemaType[] anonTypes = sType.getAnonymousTypes(); + for (SchemaType anonType : anonTypes) { + if (anonType.isSkippedAnonymousType()) { + printNestedTypeImpls(anonType, system); + } else { + printInnerTypeImpl(anonType, system, true); + } + } + // For redefinition by extension, go ahead and print the anonymous + // types in the base + if (!redefinition || + (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType())) { + break; + } + sType = sType.getBaseType(); + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java new file mode 100644 index 0000000..5299026 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java @@ -0,0 +1,2390 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.XBeanDebug; +import org.apache.xmlbeans.impl.values.*; + +import javax.xml.namespace.QName; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.math.BigInteger; +import java.util.*; + +public final class SchemaTypeImpl implements SchemaType, TypeStoreUserFactory { + // global types have names + private QName _name; + + // annotation on the type + private SchemaAnnotation _annotation; + + // compilation support + private int _resolvePhase; + private static final int UNRESOLVED = 0; + private static final int RESOLVING_SGS = 1; // For document types only + private static final int RESOLVED_SGS = 2; // For document types only + private static final int RESOLVING = 3; + private static final int RESOLVED = 4; + private static final int JAVAIZING = 5; + private static final int JAVAIZED = 6; + + // anonymous type support + private SchemaType.Ref _outerSchemaTypeRef; + private volatile SchemaComponent.Ref _containerFieldRef; + private volatile SchemaField _containerField; + private volatile int _containerFieldCode; + private volatile int _containerFieldIndex; + private volatile QName[] _groupReferenceContext; + private SchemaType.Ref[] _anonymousTyperefs; + private boolean _isDocumentType; + private boolean _isAttributeType; + // private boolean _skippedAnonymousType; + + // compiletime java type support + private boolean _isCompiled; + private String _shortJavaName; + private String _fullJavaName; + private String _shortJavaImplName; + private String _fullJavaImplName; + private InterfaceExtension[] _interfaces; + private PrePostExtension _prepost; + + // runtime java type support: volatile because they're cached + private volatile Class _javaClass; + private volatile Class _javaEnumClass; + private volatile Class _javaImplClass; + private volatile Constructor _javaImplConstructor; + private volatile Constructor _javaImplConstructor2; + private volatile boolean _implNotAvailable; + + // user data objects not persisted + private volatile Object _userData; + + private final Object[] _ctrArgs = new Object[]{this}; + + // reflective support + private SchemaContainer _container; + private String _filename; + + // complex content support + private SchemaParticle _contentModel; + private volatile SchemaLocalElement[] _localElts; // lazily computed + private volatile Map _eltToIndexMap; // lazily computed + private volatile Map _attrToIndexMap; // lazily computed + private Map _propertyModelByElementName; + private Map _propertyModelByAttributeName; + private boolean _hasAllContent; + private boolean _orderSensitive; + private QNameSet _typedWildcardElements; + private QNameSet _typedWildcardAttributes; + private boolean _hasWildcardElements; + private boolean _hasWildcardAttributes; + // set of valid QNames that can be substituted for a property + private Set _validSubstitutions = Collections.emptySet(); + + // simple content support + private int _complexTypeVariety; + private SchemaAttributeModel _attributeModel; + + // simple type support + private int _builtinTypeCode; + + private int _simpleTypeVariety; + private boolean _isSimpleType; + + private SchemaType.Ref _baseTyperef; // via restriction or extension + private int _baseDepth; // how many inheritance steps to AnyType + private int _derivationType; + + // user type support + private String _userTypeName; + private String _userTypeHandler; + + // for complex types with simple content + private SchemaType.Ref _contentBasedOnTyperef; + + // facets + private XmlValueRef[] _facetArray; + private boolean[] _fixedFacetArray; + + // fundamental facets + private int _ordered; + private boolean _isFinite; + private boolean _isBounded; + private boolean _isNumeric; + + private boolean _abs; + private boolean _finalExt; + private boolean _finalRest; + private boolean _finalList; + private boolean _finalUnion; + private boolean _blockExt; + private boolean _blockRest; + + // whitespace facet + private int _whiteSpaceRule; + + // regex patterns + private boolean _hasPatterns; // also takes into account base classes + private org.apache.xmlbeans.impl.regex.RegularExpression[] _patterns; + + // enumerated values + private XmlValueRef[] _enumerationValues; + private SchemaType.Ref _baseEnumTyperef; + private boolean _stringEnumEnsured; + private volatile Map _lookupStringEnum; + private volatile List _listOfStringEnum; + private volatile Map _lookupStringEnumEntry; + private SchemaStringEnumEntry[] _stringEnumEntries; + + // for lists only + private SchemaType.Ref _listItemTyperef; + + // for unions only + private boolean _isUnionOfLists; + private SchemaType.Ref[] _unionMemberTyperefs; + private int _anonymousUnionMemberOrdinal; + private volatile SchemaType[] _unionConstituentTypes; + private volatile SchemaType[] _unionSubTypes; + private volatile SchemaType _unionCommonBaseType; + + // for atomic types only + private SchemaType.Ref _primitiveTypeRef; + + // for decimal restrictions only + private int _decimalSize; + + // lazy loading support + private volatile boolean _unloaded; + + // for document types only - only valid during compilation + private QName _sg; + private final List _sgMembers = new ArrayList<>(); + + public boolean isUnloaded() { + return _unloaded; + } + + public void finishLoading() { + _unloaded = false; + } + + + SchemaTypeImpl(SchemaContainer container) { + _container = container; + } + + SchemaTypeImpl(SchemaContainer container, boolean unloaded) { + _container = container; + _unloaded = unloaded; + if (unloaded) { + finishQuick(); + } + } + + public boolean isSGResolved() { + return _resolvePhase >= RESOLVED_SGS; + } + + public boolean isSGResolving() { + return _resolvePhase >= RESOLVING_SGS; + } + + public boolean isResolved() { + return _resolvePhase >= RESOLVED; + } + + public boolean isResolving() { + return _resolvePhase == RESOLVING; + } + + public boolean isUnjavaized() { + return _resolvePhase < JAVAIZED; + } + + public boolean isJavaized() { + return _resolvePhase == JAVAIZED; + } + + public void startResolvingSGs() { + if (_resolvePhase != UNRESOLVED) { + throw new IllegalStateException(); + } + _resolvePhase = RESOLVING_SGS; + } + + public void finishResolvingSGs() { + if (_resolvePhase != RESOLVING_SGS) { + throw new IllegalStateException(); + } + _resolvePhase = RESOLVED_SGS; + } + + public void startResolving() { + if ((_isDocumentType && _resolvePhase != RESOLVED_SGS) || + (!_isDocumentType && _resolvePhase != UNRESOLVED)) { + throw new IllegalStateException(); + } + _resolvePhase = RESOLVING; + } + + public void finishResolving() { + if (_resolvePhase != RESOLVING) { + throw new IllegalStateException(); + } + _resolvePhase = RESOLVED; + } + + public void startJavaizing() { + if (_resolvePhase != RESOLVED) { + throw new IllegalStateException(); + } + _resolvePhase = JAVAIZING; + } + + public void finishJavaizing() { + if (_resolvePhase != JAVAIZING) { + throw new IllegalStateException(); + } + _resolvePhase = JAVAIZED; + } + + private void finishQuick() { + _resolvePhase = JAVAIZED; + } + + private void assertUnresolved() { + if (_resolvePhase != UNRESOLVED && !_unloaded) { + throw new IllegalStateException(); + } + } + + private void assertSGResolving() { + if (_resolvePhase != RESOLVING_SGS && !_unloaded) { + throw new IllegalStateException(); + } + } + + private void assertSGResolved() { + if (_resolvePhase != RESOLVED_SGS && !_unloaded) { + throw new IllegalStateException(); + } + } + + private void assertResolving() { + if (_resolvePhase != RESOLVING && !_unloaded) { + throw new IllegalStateException(); + } + } + + private void assertResolved() { + if (_resolvePhase != RESOLVED && !_unloaded) { + throw new IllegalStateException(); + } + } + + private void assertJavaizing() { + if (_resolvePhase != JAVAIZING && !_unloaded) { + throw new IllegalStateException(); + } + } + + public QName getName() { + return _name; + } + + public void setName(QName name) { + assertUnresolved(); + _name = name; + } + + public String getSourceName() { + if (_filename != null) { + return _filename; + } + if (getOuterType() != null) { + return getOuterType().getSourceName(); + } + + SchemaField field = getContainerField(); + if (field != null) { + if (field instanceof SchemaGlobalElement) { + return ((SchemaGlobalElement) field).getSourceName(); + } + if (field instanceof SchemaGlobalAttribute) { + return ((SchemaGlobalAttribute) field).getSourceName(); + } + } + return null; + } + + public void setFilename(String filename) { + assertUnresolved(); + _filename = filename; + } + + public int getComponentType() { + return SchemaComponent.TYPE; + } + + public boolean isAnonymousType() { + return _name == null; + } + + public boolean isDocumentType() { + return _isDocumentType; + } + + public boolean isAttributeType() { + return _isAttributeType; + } + + public QName getDocumentElementName() { + if (_isDocumentType) { + SchemaParticle sp = getContentModel(); + if (sp != null) { + return sp.getName(); + } + } + + return null; + } + + public QName getAttributeTypeAttributeName() { + if (_isAttributeType) { + SchemaAttributeModel sam = getAttributeModel(); + if (sam != null) { + SchemaLocalAttribute[] slaArray = sam.getAttributes(); + if (slaArray != null && slaArray.length > 0) { + SchemaLocalAttribute sla = slaArray[0]; + return sla.getName(); + } + } + } + + return null; + } + + public void setAnnotation(SchemaAnnotation ann) { + assertUnresolved(); + _annotation = ann; + } + + public SchemaAnnotation getAnnotation() { + return _annotation; + } + + public void setDocumentType(boolean isDocument) { + assertUnresolved(); + _isDocumentType = isDocument; + } + + public void setAttributeType(boolean isAttribute) { + assertUnresolved(); + _isAttributeType = isAttribute; + } + + public int getContentType() { + return _complexTypeVariety; + } + + public void setComplexTypeVariety(int complexTypeVariety) { + assertResolving(); + _complexTypeVariety = complexTypeVariety; + } + + public SchemaTypeElementSequencer getElementSequencer() { + if (_complexTypeVariety == NOT_COMPLEX_TYPE) { + return new SequencerImpl(null); + } + + return new SequencerImpl(new SchemaTypeVisitorImpl(_contentModel)); + } + + /** + * Set the abstract and final flags for a complex type + */ + void setAbstractFinal( + boolean abs, boolean finalExt, boolean finalRest, boolean finalList, boolean finalUnion) { + assertResolving(); + _abs = abs; + _finalExt = finalExt; + _finalRest = finalRest; + _finalList = finalList; + _finalUnion = finalUnion; + } + + /** + * Set the final flags for a simple type + */ + void setSimpleFinal(boolean finalRest, boolean finalList, boolean finalUnion) { + assertResolving(); + _finalRest = finalRest; + _finalList = finalList; + _finalUnion = finalUnion; + } + + void setBlock(boolean blockExt, boolean blockRest) { + assertResolving(); + _blockExt = blockExt; + _blockRest = blockRest; + } + + public boolean blockRestriction() { + return _blockRest; + } + + public boolean blockExtension() { + return _blockExt; + } + + public boolean isAbstract() { + return _abs; + } + + public boolean finalExtension() { + return _finalExt; + } + + public boolean finalRestriction() { + return _finalRest; + } + + public boolean finalList() { + return _finalList; + } + + public boolean finalUnion() { + return _finalUnion; + } + + public synchronized SchemaField getContainerField() { + if (_containerFieldCode != -1) { + SchemaType outer = getOuterType(); + if (_containerFieldCode == 0) { + _containerField = _containerFieldRef == null ? null : (SchemaField) _containerFieldRef.getComponent(); + } else if (_containerFieldCode == 1) { + assert (outer != null); + _containerField = outer.getAttributeModel().getAttributes()[_containerFieldIndex]; + } else { + assert (outer != null); + _containerField = ((SchemaTypeImpl) outer).getLocalElementByIndex(_containerFieldIndex); + } + _containerFieldCode = -1; + } + return _containerField; + } + + public void setContainerField(SchemaField field) { + assertUnresolved(); + _containerField = field; + _containerFieldCode = -1; + } + + public void setContainerFieldRef(SchemaComponent.Ref ref) { + assertUnresolved(); + _containerFieldRef = ref; + _containerFieldCode = 0; + } + + public void setContainerFieldIndex(short code, int index) { + assertUnresolved(); + _containerFieldCode = code; + _containerFieldIndex = index; + } + + /* package */ void setGroupReferenceContext(QName[] groupNames) { + assertUnresolved(); + _groupReferenceContext = groupNames; + } + + /* package */ QName[] getGroupReferenceContext() { + return _groupReferenceContext; + } + + public SchemaType getOuterType() { + return _outerSchemaTypeRef == null ? null : _outerSchemaTypeRef.get(); + } + + public void setOuterSchemaTypeRef(SchemaType.Ref typeref) { + assertUnresolved(); + _outerSchemaTypeRef = typeref; + } + + public boolean isCompiled() { + return _isCompiled; + } + + public void setCompiled(boolean f) { + assertJavaizing(); + _isCompiled = f; + } + + public boolean isSkippedAnonymousType() { + SchemaType outerType = getOuterType(); + return (outerType != null && (outerType.getBaseType() == this || + outerType.getContentBasedOnType() == this)); + } + + public String getShortJavaName() { + return _shortJavaName; + } + + public void setShortJavaName(String name) { + assertResolved(); + _shortJavaName = name; + SchemaType outer = _outerSchemaTypeRef.get(); + while (outer.getFullJavaName() == null) { + outer = outer.getOuterType(); + } + + _fullJavaName = outer.getFullJavaName() + "$" + _shortJavaName; + } + + public String getFullJavaName() { + return _fullJavaName; + } + + public void setFullJavaName(String name) { + assertResolved(); + _fullJavaName = name; + int index = Math.max(_fullJavaName.lastIndexOf('$'), + _fullJavaName.lastIndexOf('.')) + 1; + _shortJavaName = _fullJavaName.substring(index); + } + + public void setShortJavaImplName(String name) { + assertResolved(); + _shortJavaImplName = name; + SchemaType outer = _outerSchemaTypeRef.get(); + while (outer.getFullJavaImplName() == null) { + outer = outer.getOuterType(); + } + + _fullJavaImplName = outer.getFullJavaImplName() + "$" + _shortJavaImplName; + } + + public void setFullJavaImplName(String name) { + assertResolved(); + _fullJavaImplName = name; + int index = Math.max(_fullJavaImplName.lastIndexOf('$'), + _fullJavaImplName.lastIndexOf('.')) + 1; + _shortJavaImplName = _fullJavaImplName.substring(index); + } + + public String getFullJavaImplName() { + return _fullJavaImplName; + } + + public String getShortJavaImplName() { + return _shortJavaImplName; + } + + public String getUserTypeName() { + return _userTypeName; + } + + public void setUserTypeName(String userTypeName) { + _userTypeName = userTypeName; + } + + public String getUserTypeHandlerName() { + return _userTypeHandler; + } + + public void setUserTypeHandlerName(String typeHandler) { + _userTypeHandler = typeHandler; + } + + public void setInterfaceExtensions(InterfaceExtension[] interfaces) { + assertResolved(); + _interfaces = (interfaces == null) ? null : interfaces.clone(); + } + + public InterfaceExtension[] getInterfaceExtensions() { + return _interfaces; + } + + public void setPrePostExtension(PrePostExtension prepost) { + assertResolved(); + _prepost = prepost; + } + + public PrePostExtension getPrePostExtension() { + return _prepost; + } + + public Object getUserData() { + return _userData; + } + + public void setUserData(Object data) { + _userData = data; + } + + /* Only used for asserts */ + SchemaContainer getContainer() { + return _container; + } + + void setContainer(SchemaContainer container) { + _container = container; + } + + public SchemaTypeSystem getTypeSystem() { + return _container.getTypeSystem(); + } + + public SchemaParticle getContentModel() { + return _contentModel; + } + + private static void buildEltList(List eltList, SchemaParticle contentModel) { + if (contentModel == null) { + return; + } + + switch (contentModel.getParticleType()) { + case SchemaParticle.ELEMENT: + eltList.add((SchemaLocalElement) contentModel); + break; + case SchemaParticle.ALL: + case SchemaParticle.CHOICE: + case SchemaParticle.SEQUENCE: + for (int i = 0; i < contentModel.countOfParticleChild(); i++) { + buildEltList(eltList, contentModel.getParticleChild(i)); + } + break; + default: + break; + } + } + + private void buildLocalElts() { + List eltList = new ArrayList<>(); + buildEltList(eltList, _contentModel); + _localElts = eltList.toArray(new SchemaLocalElement[0]); + } + + public SchemaLocalElement getLocalElementByIndex(int i) { + SchemaLocalElement[] elts = _localElts; + if (elts == null) { + buildLocalElts(); + elts = _localElts; + } + return elts[i]; + } + + public int getIndexForLocalElement(SchemaLocalElement elt) { + Map localEltMap = _eltToIndexMap; + if (localEltMap == null) { + if (_localElts == null) { + buildLocalElts(); + } + localEltMap = new HashMap<>(); + for (int i = 0; i < _localElts.length; i++) { + localEltMap.put(_localElts[i], i); + } + _eltToIndexMap = localEltMap; + } + return localEltMap.get(elt); + } + + public int getIndexForLocalAttribute(SchemaLocalAttribute attr) { + Map localAttrMap = _attrToIndexMap; + if (localAttrMap == null) { + localAttrMap = new HashMap<>(); + SchemaLocalAttribute[] attrs = this._attributeModel.getAttributes(); + for (int i = 0; i < attrs.length; i++) { + localAttrMap.put(attrs[i], i); + } + _attrToIndexMap = localAttrMap; + } + return localAttrMap.get(attr); + } + + public SchemaAttributeModel getAttributeModel() { + return _attributeModel; + } + + public SchemaProperty[] getProperties() { + if (_propertyModelByElementName == null) { + return getAttributeProperties(); + } + + if (_propertyModelByAttributeName == null) { + return getElementProperties(); + } + + List list = new ArrayList<>(); + list.addAll(_propertyModelByElementName.values()); + list.addAll(_propertyModelByAttributeName.values()); + return list.toArray(new SchemaProperty[0]); + } + + private static final SchemaProperty[] NO_PROPERTIES = new SchemaProperty[0]; + + public SchemaProperty[] getDerivedProperties() { + SchemaType baseType = getBaseType(); + if (baseType == null) { + return getProperties(); + } + + List results = new ArrayList<>(); + + if (_propertyModelByElementName != null) { + results.addAll(_propertyModelByElementName.values()); + } + + if (_propertyModelByAttributeName != null) { + results.addAll(_propertyModelByAttributeName.values()); + } + + for (Iterator it = results.iterator(); it.hasNext(); ) { + SchemaProperty prop = it.next(); + SchemaProperty baseProp = prop.isAttribute() ? + baseType.getAttributeProperty(prop.getName()) : + baseType.getElementProperty(prop.getName()); + + + // Remove the derived property from the results if it is + // A) present in the base type and + // B) all the details are the same (cardinality, nillability, default) + + if (baseProp != null) { + if (eq(prop.getMinOccurs(), baseProp.getMinOccurs()) && + eq(prop.getMaxOccurs(), baseProp.getMaxOccurs()) && + prop.hasNillable() == baseProp.hasNillable() && + eq(prop.getDefaultText(), baseProp.getDefaultText())) { + it.remove(); + } + + } + + } + + return results.toArray(new SchemaProperty[0]); + } + + private static boolean eq(BigInteger a, BigInteger b) { + if (a == null && b == null) { + return true; + } + if (a == null || b == null) { + return false; + } + return a.equals(b); + } + + private static boolean eq(String a, String b) { + if (a == null && b == null) { + return true; + } + if (a == null || b == null) { + return false; + } + return a.equals(b); + } + + public SchemaProperty[] getElementProperties() { + if (_propertyModelByElementName == null) { + return NO_PROPERTIES; + } + + return _propertyModelByElementName.values().toArray(new SchemaProperty[0]); + } + + public SchemaProperty[] getAttributeProperties() { + if (_propertyModelByAttributeName == null) { + return NO_PROPERTIES; + } + + return _propertyModelByAttributeName.values().toArray(new SchemaProperty[0]); + } + + public SchemaProperty getElementProperty(QName eltName) { + return _propertyModelByElementName == null ? null : _propertyModelByElementName.get(eltName); + } + + public SchemaProperty getAttributeProperty(QName attrName) { + return _propertyModelByAttributeName == null ? null : _propertyModelByAttributeName.get(attrName); + } + + public boolean hasAllContent() { + return _hasAllContent; + } + + public boolean isOrderSensitive() { + return _orderSensitive; + } + + public void setOrderSensitive(boolean sensitive) { + assertJavaizing(); + _orderSensitive = sensitive; + } + + public void setContentModel( + SchemaParticle contentModel, + SchemaAttributeModel attrModel, + Map propertyModelByElementName, + Map propertyModelByAttributeName, + boolean isAll) { + assertResolving(); + _contentModel = contentModel; + _attributeModel = attrModel; + _propertyModelByElementName = propertyModelByElementName; + _propertyModelByAttributeName = propertyModelByAttributeName; + _hasAllContent = isAll; + + + // Add entries for each element property for substitution group members + if (_propertyModelByElementName != null) { + _validSubstitutions = new LinkedHashSet<>(); + Collection eltProps = _propertyModelByElementName.values(); + for (SchemaProperty prop : eltProps) { + QName[] names = prop.acceptedNames(); + for (QName name : names) { + if (!_propertyModelByElementName.containsKey(name)) { + _validSubstitutions.add(name); + } + } + } + } + } + + private boolean containsElements() { + return getContentType() == ELEMENT_CONTENT || + getContentType() == MIXED_CONTENT; + } + + public boolean hasAttributeWildcards() { + return _hasWildcardAttributes; + } + + public boolean hasElementWildcards() { + return _hasWildcardElements; + } + + public boolean isValidSubstitution(QName name) { + return _validSubstitutions.contains(name); + } + + public SchemaType getElementType(QName eltName, QName xsiType, SchemaTypeLoader wildcardTypeLoader) { + if (isSimpleType() || !containsElements() || isNoType()) { + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + + SchemaType type; + SchemaProperty prop = _propertyModelByElementName.get(eltName); + if (prop != null) { + type = prop.getType(); + } else { + if (wildcardTypeLoader == null) { + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + + if (_typedWildcardElements.contains(eltName) || + _validSubstitutions.contains(eltName)) { + SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); + if (elt == null) { + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + // According to http://www.w3.org/TR/xmlschema-1/#key-lva, + // the line above should return ST_ANY_TYPE. + type = elt.getType(); + } else { + // Substitution groups + // Actually, better not enable this yet + /*SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); + SchemaGlobalElement sghead = elt == null ? null : elt.substitutionGroup(); + while (sghead != null) + { + prop = (SchemaProperty)_propertyModelByElementName.get(sghead.getName()); + if (prop != null) + { + type = elt.getType(); + break; + } + sghead = sghead.substitutionGroup(); + } + */ + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + } + + if (xsiType != null && wildcardTypeLoader != null) { + SchemaType itype = wildcardTypeLoader.findType(xsiType); + + // NOTE: a previous version of XMLBeans used ST_NO_TYPE if the + // xsiType was not derived from 'type', but this results in a + // ClassCastException. Instead we ignore xsi:type if it's not + // found or a derived type. + if (itype != null && type.isAssignableFrom(itype)) { + return itype; + } + } + + return type; + } + + public SchemaType getAttributeType(QName attrName, SchemaTypeLoader wildcardTypeLoader) { + if (isSimpleType() || isNoType()) { + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + + if (isURType()) { + return BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + SchemaProperty prop = _propertyModelByAttributeName.get(attrName); + if (prop != null) { + return prop.getType(); + } + + if (!_typedWildcardAttributes.contains(attrName) || wildcardTypeLoader == null) { + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + // For symmetry with the element case (as well as with URType), perhaps + // the above line should be returning ST_ANY_SIMPLE + + SchemaGlobalAttribute attr = wildcardTypeLoader.findAttribute(attrName); + if (attr == null) { + return BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + return attr.getType(); + } + + /* These two methods, createElementType and getElementType have to stay + * synchronized, because they create an XmlObject and return the type + * for that object, respectively. But since they do slightly different + * things, they can't be refactored to share code, so exercise caution + */ + public XmlObject createElementType(QName eltName, QName xsiType, SchemaTypeLoader wildcardTypeLoader) { + SchemaType type; + SchemaProperty prop = null; + if (isSimpleType() || !containsElements() || isNoType()) { + type = BuiltinSchemaTypeSystem.ST_NO_TYPE; + } else { + prop = _propertyModelByElementName.get(eltName); + if (prop != null) { + type = prop.getType(); + } else if (_typedWildcardElements.contains(eltName) || + _validSubstitutions.contains(eltName)) { + SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); + if (elt != null) { + type = elt.getType(); + SchemaType docType = wildcardTypeLoader.findDocumentType(eltName); + if (docType != null) { + prop = docType.getElementProperty(eltName); + } + } else { + type = BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + } else { + // Check if the requested element isn't by any chance part of a + // substitution group headed by one of the declared elements + // Better not enable this yet + /* + SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); + SchemaGlobalElement sghead = elt == null ? null : elt.substitutionGroup(); + while (sghead != null) + { + if (_propertyModelByElementName.containsKey(sghead.getName())) + { + type = elt.getType(); + SchemaType docType = wildcardTypeLoader.findDocumentType(elt.getName()); + if (docType != null) + prop = docType.getElementProperty(elt.getName()); + break; + } + sghead = sghead.substitutionGroup(); + } + */ + type = BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + + if (xsiType != null) { + SchemaType itype = wildcardTypeLoader.findType(xsiType); + + // NOTE: a previous version of XMLBeans used ST_NO_TYPE if the + // xsiType was not derived from 'type', but this results in a + // ClassCastException. Instead we ignore xsi:type if it's not + // found or a derived type. + if (itype != null && type.isAssignableFrom(itype)) { + type = itype; + } + } + } + + if (type != null) { + return ((SchemaTypeImpl) type).createUnattachedNode(prop); + } + return null; + } + + public XmlObject createAttributeType(QName attrName, SchemaTypeLoader wildcardTypeLoader) { + SchemaTypeImpl type; + SchemaProperty prop = null; + if (isSimpleType() || isNoType()) { + type = BuiltinSchemaTypeSystem.ST_NO_TYPE; + } else if (isURType()) { + type = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } else { + prop = _propertyModelByAttributeName.get(attrName); + if (prop != null) { + type = (SchemaTypeImpl) prop.getType(); + } else if (!_typedWildcardAttributes.contains(attrName)) { + type = BuiltinSchemaTypeSystem.ST_NO_TYPE; + } else { + SchemaGlobalAttribute attr = wildcardTypeLoader.findAttribute(attrName); + if (attr != null) { + type = (SchemaTypeImpl) attr.getType(); + } else { + type = BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + } + } + + if (type != null) { + return type.createUnattachedNode(prop); + } + + return null; + } + + public void setWildcardSummary(QNameSet elementSet, boolean haswcElt, QNameSet attributeSet, boolean haswcAtt) { + assertResolving(); + _typedWildcardElements = elementSet; + _hasWildcardElements = haswcElt; + _typedWildcardAttributes = attributeSet; + _hasWildcardAttributes = haswcAtt; + } + + public SchemaType[] getAnonymousTypes() { + SchemaType[] result = new SchemaType[_anonymousTyperefs.length]; + for (int i = 0; i < result.length; i++) { + result[i] = _anonymousTyperefs[i].get(); + } + return result; + } + + public void setAnonymousTypeRefs(SchemaType.Ref[] anonymousTyperefs) { + _anonymousTyperefs = anonymousTyperefs == null ? null : anonymousTyperefs.clone(); + } + + + private static SchemaType[] staCopy(SchemaType[] a) { + if (a == null) { + return null; + } + + SchemaType[] result = new SchemaType[a.length]; + System.arraycopy(a, 0, result, 0, a.length); + return result; + } + + private static boolean[] boaCopy(boolean[] a) { + if (a == null) { + return null; + } + + boolean[] result = new boolean[a.length]; + System.arraycopy(a, 0, result, 0, a.length); + return result; + } + + + public void setSimpleTypeVariety(int variety) { + assertResolving(); + _simpleTypeVariety = variety; + } + + public int getSimpleVariety() { + return _simpleTypeVariety; + } + + public boolean isURType() { + return _builtinTypeCode == BTC_ANY_TYPE || _builtinTypeCode == BTC_ANY_SIMPLE; + } + + public boolean isNoType() { + return this == BuiltinSchemaTypeSystem.ST_NO_TYPE; + } + + public boolean isSimpleType() { + return _isSimpleType; + } + + public void setSimpleType(boolean f) { + assertUnresolved(); + _isSimpleType = f; + } + + public boolean isUnionOfLists() { + return _isUnionOfLists; + } + + public void setUnionOfLists(boolean f) { + assertResolving(); + _isUnionOfLists = f; + } + + public SchemaType getPrimitiveType() { + return _primitiveTypeRef == null ? null : _primitiveTypeRef.get(); + } + + public void setPrimitiveTypeRef(SchemaType.Ref typeref) { + assertResolving(); + _primitiveTypeRef = typeref; + } + + public int getDecimalSize() { + return _decimalSize; + } + + public void setDecimalSize(int bits) { + assertResolving(); + _decimalSize = bits; + } + + public SchemaType getBaseType() { + return _baseTyperef == null ? null : _baseTyperef.get(); + } + + public void setBaseTypeRef(SchemaType.Ref typeref) { + assertResolving(); + _baseTyperef = typeref; + } + + public int getBaseDepth() { + return _baseDepth; + } + + public void setBaseDepth(int depth) { + assertResolving(); + _baseDepth = depth; + } + + public SchemaType getContentBasedOnType() { + return _contentBasedOnTyperef == null ? null : _contentBasedOnTyperef.get(); + } + + public void setContentBasedOnTypeRef(SchemaType.Ref typeref) { + assertResolving(); + _contentBasedOnTyperef = typeref; + } + + public int getDerivationType() { + return _derivationType; + } + + public void setDerivationType(int type) { + assertResolving(); + _derivationType = type; + } + + public SchemaType getListItemType() { + return _listItemTyperef == null ? null : _listItemTyperef.get(); + } + + public void setListItemTypeRef(SchemaType.Ref typeref) { + assertResolving(); + _listItemTyperef = typeref; + } + + public SchemaType[] getUnionMemberTypes() { + SchemaType[] result = new SchemaType[_unionMemberTyperefs == null ? 0 : _unionMemberTyperefs.length]; + for (int i = 0; i < result.length; i++) { + result[i] = _unionMemberTyperefs[i].get(); + } + return result; + } + + public void setUnionMemberTypeRefs(SchemaType.Ref[] typerefs) { + assertResolving(); + _unionMemberTyperefs = typerefs == null ? null : typerefs.clone(); + } + + public int getAnonymousUnionMemberOrdinal() { + return _anonymousUnionMemberOrdinal; + } + + public void setAnonymousUnionMemberOrdinal(int i) { + assertUnresolved(); + _anonymousUnionMemberOrdinal = i; + } + + public synchronized SchemaType[] getUnionConstituentTypes() { + if (_unionCommonBaseType == null) { + computeFlatUnionModel(); + } + return staCopy(_unionConstituentTypes); + } + + private void setUnionConstituentTypes(SchemaType[] types) { + _unionConstituentTypes = types; + } + + public synchronized SchemaType[] getUnionSubTypes() { + if (_unionCommonBaseType == null) { + computeFlatUnionModel(); + } + return staCopy(_unionSubTypes); + } + + private void setUnionSubTypes(SchemaType[] types) { + _unionSubTypes = types; + } + + public synchronized SchemaType getUnionCommonBaseType() { + if (_unionCommonBaseType == null) { + computeFlatUnionModel(); + } + return _unionCommonBaseType; + } + + private void setUnionCommonBaseType(SchemaType type) { + _unionCommonBaseType = type; + } + + private void computeFlatUnionModel() { + if (getSimpleVariety() != SchemaType.UNION) { + throw new IllegalStateException("Operation is only supported on union types"); + } + Set constituentMemberTypes = new LinkedHashSet<>(); + Set allSubTypes = new LinkedHashSet<>(); + SchemaType commonBaseType = null; + + allSubTypes.add(this); + + for (Ref unionMemberTyperef : _unionMemberTyperefs) { + SchemaTypeImpl mImpl = (SchemaTypeImpl) unionMemberTyperef.get(); + + switch (mImpl.getSimpleVariety()) { + case SchemaType.LIST: + constituentMemberTypes.add(mImpl); + allSubTypes.add(mImpl); + commonBaseType = mImpl.getCommonBaseType(commonBaseType); + break; + case SchemaType.UNION: + constituentMemberTypes.addAll(Arrays.asList(mImpl.getUnionConstituentTypes())); + allSubTypes.addAll(Arrays.asList(mImpl.getUnionSubTypes())); + SchemaType otherCommonBaseType = mImpl.getUnionCommonBaseType(); + if (otherCommonBaseType != null) { + commonBaseType = otherCommonBaseType.getCommonBaseType(commonBaseType); + } + break; + case SchemaType.ATOMIC: + constituentMemberTypes.add(mImpl); + allSubTypes.add(mImpl); + commonBaseType = mImpl.getCommonBaseType(commonBaseType); + break; + default: + assert (false); + } + } + + setUnionConstituentTypes(constituentMemberTypes.toArray(StscState.EMPTY_ST_ARRAY)); + setUnionSubTypes(allSubTypes.toArray(StscState.EMPTY_ST_ARRAY)); + setUnionCommonBaseType(commonBaseType); + } + + public QName getSubstitutionGroup() { + return _sg; + } + + public void setSubstitutionGroup(QName sg) { + assertSGResolving(); + _sg = sg; + } + + public void addSubstitutionGroupMember(QName member) { + assertSGResolved(); + _sgMembers.add(member); + } + + public QName[] getSubstitutionGroupMembers() { + return _sgMembers.toArray(new QName[0]); + } + + public int getWhiteSpaceRule() { + return _whiteSpaceRule; + } + + public void setWhiteSpaceRule(int ws) { + assertResolving(); + _whiteSpaceRule = ws; + } + + public XmlAnySimpleType getFacet(int facetCode) { + if (_facetArray == null) { + return null; + } + XmlValueRef ref = _facetArray[facetCode]; + if (ref == null) { + return null; + } + return ref.get(); + } + + public boolean isFacetFixed(int facetCode) { + return _fixedFacetArray[facetCode]; + } + + public XmlAnySimpleType[] getBasicFacets() { + XmlAnySimpleType[] result = new XmlAnySimpleType[SchemaType.LAST_FACET + 1]; + for (int i = 0; i <= SchemaType.LAST_FACET; i++) { + result[i] = getFacet(i); + } + return result; + } + + public boolean[] getFixedFacets() { + return boaCopy(_fixedFacetArray); + } + + public void setBasicFacets(XmlValueRef[] values, boolean[] fixed) { + assertResolving(); + _facetArray = values == null ? null : values.clone(); + _fixedFacetArray = fixed == null ? null : fixed.clone(); + } + + public int ordered() { + return _ordered; + } + + public void setOrdered(int ordering) { + assertResolving(); + _ordered = ordering; + } + + public boolean isBounded() { + return _isBounded; + } + + public void setBounded(boolean f) { + assertResolving(); + _isBounded = f; + } + + public boolean isFinite() { + return _isFinite; + } + + public void setFinite(boolean f) { + assertResolving(); + _isFinite = f; + } + + public boolean isNumeric() { + return _isNumeric; + } + + public void setNumeric(boolean f) { + assertResolving(); + _isNumeric = f; + } + + + public boolean hasPatternFacet() { + return _hasPatterns; + } + + public void setPatternFacet(boolean hasPatterns) { + assertResolving(); + _hasPatterns = hasPatterns; + } + + public boolean matchPatternFacet(String s) { + if (!_hasPatterns) { + return true; + } + + if (_patterns != null && _patterns.length > 0) { + int i; + for (i = 0; i < _patterns.length; i++) { + if (_patterns[i].matches(s)) { + break; + } + } + if (i >= _patterns.length) { + return false; + } + } + + return getBaseType().matchPatternFacet(s); + } + + public String[] getPatterns() { + if (_patterns == null) { + return new String[0]; + } + String[] patterns = new String[_patterns.length]; + for (int i = 0; i < _patterns.length; i++) { + patterns[i] = _patterns[i].getPattern(); + } + return patterns; + } + + public org.apache.xmlbeans.impl.regex.RegularExpression[] getPatternExpressions() { + if (_patterns == null) { + return new org.apache.xmlbeans.impl.regex.RegularExpression[0]; + } + org.apache.xmlbeans.impl.regex.RegularExpression[] result = new org.apache.xmlbeans.impl.regex.RegularExpression[_patterns.length]; + System.arraycopy(_patterns, 0, result, 0, _patterns.length); + return result; + } + + public void setPatterns(org.apache.xmlbeans.impl.regex.RegularExpression[] list) { + assertResolving(); + _patterns = list == null ? null : list.clone(); + } + + public XmlAnySimpleType[] getEnumerationValues() { + if (_enumerationValues == null) { + return null; + } + XmlAnySimpleType[] result = new XmlAnySimpleType[_enumerationValues.length]; + for (int i = 0; i < result.length; i++) { + XmlValueRef ref = _enumerationValues[i]; + result[i] = (ref == null ? null : ref.get()); + + } + return result; + } + + public void setEnumerationValues(XmlValueRef[] a) { + assertResolving(); + _enumerationValues = a == null ? null : a.clone(); + } + + public StringEnumAbstractBase enumForString(String s) { + ensureStringEnumInfo(); + if (_lookupStringEnum == null) { + return null; + } + return _lookupStringEnum.get(s); + } + + public StringEnumAbstractBase enumForInt(int i) { + ensureStringEnumInfo(); + if (_listOfStringEnum == null || i < 0 || i >= _listOfStringEnum.size()) { + return null; + } + return _listOfStringEnum.get(i); + } + + public SchemaStringEnumEntry enumEntryForString(String s) { + ensureStringEnumInfo(); + if (_lookupStringEnumEntry == null) { + return null; + } + return _lookupStringEnumEntry.get(s); + } + + public SchemaType getBaseEnumType() { + return _baseEnumTyperef == null ? null : _baseEnumTyperef.get(); + } + + public void setBaseEnumTypeRef(SchemaType.Ref baseEnumTyperef) { + _baseEnumTyperef = baseEnumTyperef; + } + + public SchemaStringEnumEntry[] getStringEnumEntries() { + if (_stringEnumEntries == null) { + return null; + } + SchemaStringEnumEntry[] result = new SchemaStringEnumEntry[_stringEnumEntries.length]; + System.arraycopy(_stringEnumEntries, 0, result, 0, result.length); + return result; + } + + public void setStringEnumEntries(SchemaStringEnumEntry[] sEnums) { + assertJavaizing(); + _stringEnumEntries = sEnums == null ? null : sEnums.clone(); + } + + private void ensureStringEnumInfo() { + if (_stringEnumEnsured) { + return; + } + + SchemaStringEnumEntry[] sEnums = _stringEnumEntries; + if (sEnums == null) { + _stringEnumEnsured = true; + return; + } + + Map lookupStringEnum = new HashMap<>(sEnums.length); + List listOfStringEnum = new ArrayList<>(sEnums.length + 1); + Map lookupStringEnumEntry = new HashMap<>(sEnums.length); + + for (SchemaStringEnumEntry sEnum : sEnums) { + lookupStringEnumEntry.put(sEnum.getString(), sEnum); + } + + Class jc = _baseEnumTyperef.get().getEnumJavaClass(); + if (jc != null) { + try { + StringEnumAbstractBase.Table table = (StringEnumAbstractBase.Table) jc.getField("table").get(null); + for (SchemaStringEnumEntry sEnum : sEnums) { + int j = sEnum.getIntValue(); + StringEnumAbstractBase enumVal = table.forInt(j); + lookupStringEnum.put(sEnum.getString(), enumVal); + while (listOfStringEnum.size() <= j) { + listOfStringEnum.add(null); + } + listOfStringEnum.set(j, enumVal); + } + } catch (Exception e) { + System.err.println("Something wrong: could not locate enum table for " + jc); + jc = null; + lookupStringEnum.clear(); + listOfStringEnum.clear(); + } + } + + if (jc == null) { + for (SchemaStringEnumEntry sEnum : sEnums) { + int j = sEnum.getIntValue(); + String s = sEnum.getString(); + StringEnumAbstractBase enumVal = new StringEnumValue(s, j); + lookupStringEnum.put(s, enumVal); + while (listOfStringEnum.size() <= j) { + listOfStringEnum.add(null); + } + listOfStringEnum.set(j, enumVal); + } + } + + synchronized (this) { + if (!_stringEnumEnsured) { + _lookupStringEnum = lookupStringEnum; + _listOfStringEnum = listOfStringEnum; + _lookupStringEnumEntry = lookupStringEnumEntry; + } + } + // HACKHACK: two syncrhonized blocks force a memory barrier: + // BUGBUG: this behavior is likely to change in future VMs + synchronized (this) { + _stringEnumEnsured = true; + } + } + + public boolean hasStringEnumValues() { + return _stringEnumEntries != null; + } + + public void copyEnumerationValues(SchemaTypeImpl baseImpl) { + assertResolving(); + _enumerationValues = baseImpl._enumerationValues; + _baseEnumTyperef = baseImpl._baseEnumTyperef; + } + + public int getBuiltinTypeCode() { + return _builtinTypeCode; + } // special: set up pre-init + + public void setBuiltinTypeCode(int builtinTypeCode) { + assertResolving(); + _builtinTypeCode = builtinTypeCode; + } + + synchronized void assignJavaElementSetterModel() { + // To compute the element setter model, we need to compute the + // delimiting elements for each element. + + SchemaProperty[] eltProps = getElementProperties(); + SchemaParticle contentModel = getContentModel(); + Map state = new HashMap<>(); + QNameSet allContents = computeAllContainedElements(contentModel, state); + + for (SchemaProperty eltProp : eltProps) { + SchemaPropertyImpl sImpl = (SchemaPropertyImpl) eltProp; + QNameSet nde = computeNondelimitingElements(sImpl.getName(), contentModel, state); + QNameSetBuilder builder = new QNameSetBuilder(allContents); + builder.removeAll(nde); + sImpl.setJavaSetterDelimiter(builder.toQNameSet()); + } + } + + /** + * Used to compute setter model. + *

      + * Returns the QNameSet of all elements that can possibly come before an + * element whose name is given by the target in a valid instance of the + * contentModel. When appending an element, it comes before the first + * one that is not in this set. + */ + private static QNameSet computeNondelimitingElements(QName target, SchemaParticle contentModel, Map state) { + QNameSet allContents = computeAllContainedElements(contentModel, state); + if (!allContents.contains(target)) { + return QNameSet.EMPTY; + } + + // If iterated, then all contents are delimiting. + if (contentModel.getMaxOccurs() == null || + contentModel.getMaxOccurs().compareTo(BigInteger.ONE) > 0) { + return allContents; + } + + QNameSetBuilder builder; + + switch (contentModel.getParticleType()) { + case SchemaParticle.ALL: + case SchemaParticle.ELEMENT: + default: + return allContents; + + case SchemaParticle.WILDCARD: + return QNameSet.singleton(target); + + case SchemaParticle.CHOICE: + builder = new QNameSetBuilder(); + for (int i = 0; i < contentModel.countOfParticleChild(); i++) { + QNameSet childContents = computeAllContainedElements(contentModel.getParticleChild(i), state); + if (childContents.contains(target)) { + builder.addAll(computeNondelimitingElements(target, contentModel.getParticleChild(i), state)); + } + } + return builder.toQNameSet(); + + case SchemaParticle.SEQUENCE: + builder = new QNameSetBuilder(); + boolean seenTarget = false; + for (int i = contentModel.countOfParticleChild(); i > 0; ) { + i--; + QNameSet childContents = computeAllContainedElements(contentModel.getParticleChild(i), state); + if (seenTarget) { + builder.addAll(childContents); + } else if (childContents.contains(target)) { + builder.addAll(computeNondelimitingElements(target, contentModel.getParticleChild(i), state)); + seenTarget = true; + } + } + return builder.toQNameSet(); + } + } + + /** + * Used to compute the setter model. + *

      + * Returns the set of all QNames of elements that could possibly be + * contained in the given contentModel. The state variable is used + * to record the results, so that if they are needed again later, + * they do not need to be recomputed. + */ + private static QNameSet computeAllContainedElements(SchemaParticle contentModel, Map state) { + // Remember previously computed results to avoid complexity explosion + QNameSet result = state.get(contentModel); + if (result != null) { + return result; + } + + QNameSetBuilder builder; + + switch (contentModel.getParticleType()) { + case SchemaParticle.ALL: + case SchemaParticle.CHOICE: + case SchemaParticle.SEQUENCE: + default: + builder = new QNameSetBuilder(); + for (int i = 0; i < contentModel.countOfParticleChild(); i++) { + builder.addAll(computeAllContainedElements(contentModel.getParticleChild(i), state)); + } + result = builder.toQNameSet(); + break; + + case SchemaParticle.WILDCARD: + result = contentModel.getWildcardSet(); + break; + + case SchemaParticle.ELEMENT: + // Fix for XMLBEANS-228 + result = contentModel.acceptedStartNames(); + break; + } + state.put(contentModel, result); + return result; + } + + @SuppressWarnings("unchecked") + public Class getJavaClass() { + // This field is declared volatile and Class is immutable so this is allowed. + if (_javaClass == null && getFullJavaName() != null) { + try { + _javaClass = (Class) Class.forName(getFullJavaName(), false, getTypeSystem().getClassLoader()); + } catch (ClassNotFoundException e) { + // This is a legitimate use, when users get a SchemaTypeSystem without compiling classes + _javaClass = null; + } + } + + return _javaClass; + } + + @SuppressWarnings("unchecked") + public Class getJavaImplClass() { + if (_implNotAvailable) { + return null; + } + + if (_javaImplClass == null) { + try { + if (getFullJavaImplName() != null) { + _javaImplClass = (Class) Class.forName(getFullJavaImplName(), false, getTypeSystem().getClassLoader()); + } else { + _implNotAvailable = true; + } + } catch (ClassNotFoundException e) { + _implNotAvailable = true; + } + } + + return _javaImplClass; + } + + public Constructor getJavaImplConstructor() { + if (_javaImplConstructor == null && !_implNotAvailable) { + final Class impl = getJavaImplClass(); + if (impl == null) { + return null; + } + try { + _javaImplConstructor = impl.getConstructor(SchemaType.class); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + } + + return _javaImplConstructor; + + } + + public Constructor getJavaImplConstructor2() { + if (_javaImplConstructor2 == null && !_implNotAvailable) { + final Class impl = getJavaImplClass(); + if (impl == null) { + return null; + } + try { + _javaImplConstructor2 = impl.getDeclaredConstructor(SchemaType.class, boolean.class); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + } + + return _javaImplConstructor2; + + } + + @SuppressWarnings("unchecked") + @Override + public Class getEnumJavaClass() { + // This field is declared volatile and Class is immutable so this is allowed. + if (_javaEnumClass == null) { + if (getBaseEnumType() != null) { + try { + _javaEnumClass = (Class) Class.forName(getBaseEnumType().getFullJavaName() + "$Enum", false, getTypeSystem().getClassLoader()); + } catch (ClassNotFoundException e) { + _javaEnumClass = null; + } + } + } + + return _javaEnumClass; + } + + public void setJavaClass(Class javaClass) { + assertResolved(); + _javaClass = javaClass; + setFullJavaName(javaClass.getName()); + } + + public boolean isPrimitiveType() { + return (getBuiltinTypeCode() >= BTC_FIRST_PRIMITIVE && + getBuiltinTypeCode() <= BTC_LAST_PRIMITIVE); + } + + public boolean isBuiltinType() { + return getBuiltinTypeCode() != 0; + } + + public XmlObject createUnwrappedNode() { + // Todo: attach a new xml store! + return createUnattachedNode(null); + } + + /** + * TypeStoreUserFactory implementation + */ + public TypeStoreUser createTypeStoreUser() { + return (TypeStoreUser) createUnattachedNode(null); + } + + + public XmlAnySimpleType newValidatingValue(Object obj) { + return newValue(obj, true); + } + + /** + * Creates an immutable simple value. + */ + public XmlAnySimpleType newValue(Object obj) { + return newValue(obj, false); + } + + public XmlAnySimpleType newValue(Object obj, boolean validateOnSet) { + if (!isSimpleType() && getContentType() != SchemaType.SIMPLE_CONTENT) { + throw new XmlValueOutOfRangeException(); // values must be simple + } + + XmlObjectBase result = (XmlObjectBase) createUnattachedNode(null); + if (validateOnSet) { + result.setValidateOnSet(); + } + + // In the case of tree copy, need to call a specla setter to avoid + // set(XmlObject) + if (obj instanceof XmlObject) { + result.set_newValue((XmlObject) obj); + } else { + result.setObjectValue(obj); + } + + result.check_dated(); + result.setImmutable(); + + return (XmlAnySimpleType) result; + } + + /** + * Creates an instance of this type. + */ + private XmlObject createUnattachedNode(SchemaProperty prop) { + XmlObject result = null; + + if (!isBuiltinType() && !isNoType()) { + // System.out.println("Attempting to load impl class: " + getFullJavaImplName()); + Constructor ctr = getJavaImplConstructor(); + if (ctr != null) { + try { + return ctr.newInstance(_ctrArgs); + } catch (Exception e) { + System.out.println("Exception trying to instantiate impl class."); + e.printStackTrace(); + } + } + } else { + result = createBuiltinInstance(); + } + + // if no result, we must be a restriction of some compiled type + for (SchemaType sType = this; result == null; sType = sType.getBaseType()) { + result = ((SchemaTypeImpl) sType).createUnattachedSubclass(this); + } + + ((XmlObjectBase) result).init_flags(prop); + return result; + } + + private XmlObject createUnattachedSubclass(SchemaType sType) { + if (!isBuiltinType() && !isNoType()) { + Constructor ctr = getJavaImplConstructor2(); + try { + return (ctr == null) ? null : ctr.newInstance(sType, !sType.isSimpleType()); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + XBeanDebug.logException(e); + return null; + } + } else { + return createBuiltinSubclass(sType); + } + } + + private XmlObject createBuiltinInstance() { + switch (getBuiltinTypeCode()) { + case BTC_NOT_BUILTIN: + return new XmlAnyTypeImpl(BuiltinSchemaTypeSystem.ST_NO_TYPE); + case BTC_ANY_TYPE: + return new XmlAnyTypeImpl(); + case BTC_ANY_SIMPLE: + return new XmlAnySimpleTypeImpl(); + case BTC_BOOLEAN: + return new XmlBooleanImpl(); + case BTC_BASE_64_BINARY: + return new XmlBase64BinaryImpl(); + case BTC_HEX_BINARY: + return new XmlHexBinaryImpl(); + case BTC_ANY_URI: + return new XmlAnyUriImpl(); + case BTC_QNAME: + return new XmlQNameImpl(); + case BTC_NOTATION: + return new XmlNotationImpl(); + case BTC_FLOAT: + return new XmlFloatImpl(); + case BTC_DOUBLE: + return new XmlDoubleImpl(); + case BTC_DECIMAL: + return new XmlDecimalImpl(); + case BTC_STRING: + return new XmlStringImpl(); + case BTC_DURATION: + return new XmlDurationImpl(); + case BTC_DATE_TIME: + return new XmlDateTimeImpl(); + case BTC_TIME: + return new XmlTimeImpl(); + case BTC_DATE: + return new XmlDateImpl(); + case BTC_G_YEAR_MONTH: + return new XmlGYearMonthImpl(); + case BTC_G_YEAR: + return new XmlGYearImpl(); + case BTC_G_MONTH_DAY: + return new XmlGMonthDayImpl(); + case BTC_G_DAY: + return new XmlGDayImpl(); + case BTC_G_MONTH: + return new XmlGMonthImpl(); + case BTC_INTEGER: + return new XmlIntegerImpl(); + case BTC_LONG: + return new XmlLongImpl(); + case BTC_INT: + return new XmlIntImpl(); + case BTC_SHORT: + return new XmlShortImpl(); + case BTC_BYTE: + return new XmlByteImpl(); + case BTC_NON_POSITIVE_INTEGER: + return new XmlNonPositiveIntegerImpl(); + case BTC_NEGATIVE_INTEGER: + return new XmlNegativeIntegerImpl(); + case BTC_NON_NEGATIVE_INTEGER: + return new XmlNonNegativeIntegerImpl(); + case BTC_POSITIVE_INTEGER: + return new XmlPositiveIntegerImpl(); + case BTC_UNSIGNED_LONG: + return new XmlUnsignedLongImpl(); + case BTC_UNSIGNED_INT: + return new XmlUnsignedIntImpl(); + case BTC_UNSIGNED_SHORT: + return new XmlUnsignedShortImpl(); + case BTC_UNSIGNED_BYTE: + return new XmlUnsignedByteImpl(); + case BTC_NORMALIZED_STRING: + return new XmlNormalizedStringImpl(); + case BTC_TOKEN: + return new XmlTokenImpl(); + case BTC_NAME: + return new XmlNameImpl(); + case BTC_NCNAME: + return new XmlNCNameImpl(); + case BTC_LANGUAGE: + return new XmlLanguageImpl(); + case BTC_ID: + return new XmlIdImpl(); + case BTC_IDREF: + return new XmlIdRefImpl(); + case BTC_IDREFS: + return new XmlIdRefsImpl(); + case BTC_ENTITY: + return new XmlEntityImpl(); + case BTC_ENTITIES: + return new XmlEntitiesImpl(); + case BTC_NMTOKEN: + return new XmlNmTokenImpl(); + case BTC_NMTOKENS: + return new XmlNmTokensImpl(); + default: + throw new IllegalStateException("Unrecognized builtin type: " + getBuiltinTypeCode()); + } + } + + private XmlObject createBuiltinSubclass(SchemaType sType) { + boolean complex = !sType.isSimpleType(); + switch (getBuiltinTypeCode()) { + case BTC_NOT_BUILTIN: + return new XmlAnyTypeImpl(BuiltinSchemaTypeSystem.ST_NO_TYPE); + case BTC_ANY_TYPE: + case BTC_ANY_SIMPLE: + switch (sType.getSimpleVariety()) { + case NOT_SIMPLE: + return new XmlComplexContentImpl(sType); + case ATOMIC: + return new XmlAnySimpleTypeRestriction(sType, complex); + case LIST: + return new XmlListImpl(sType, complex); + case UNION: + return new XmlUnionImpl(sType, complex); + default: + throw new IllegalStateException(); + } + case BTC_BOOLEAN: + return new XmlBooleanRestriction(sType, complex); + case BTC_BASE_64_BINARY: + return new XmlBase64BinaryRestriction(sType, complex); + case BTC_HEX_BINARY: + return new XmlHexBinaryRestriction(sType, complex); + case BTC_ANY_URI: + return new XmlAnyUriRestriction(sType, complex); + case BTC_QNAME: + return new XmlQNameRestriction(sType, complex); + case BTC_NOTATION: + return new XmlNotationRestriction(sType, complex); + case BTC_FLOAT: + return new XmlFloatRestriction(sType, complex); + case BTC_DOUBLE: + return new XmlDoubleRestriction(sType, complex); + case BTC_DECIMAL: + return new XmlDecimalRestriction(sType, complex); + case BTC_STRING: + if (sType.hasStringEnumValues()) { + return new XmlStringEnumeration(sType, complex); + } else { + return new XmlStringRestriction(sType, complex); + } + case BTC_DURATION: + return new XmlDurationImpl(sType, complex); + case BTC_DATE_TIME: + return new XmlDateTimeImpl(sType, complex); + case BTC_TIME: + return new XmlTimeImpl(sType, complex); + case BTC_DATE: + return new XmlDateImpl(sType, complex); + case BTC_G_YEAR_MONTH: + return new XmlGYearMonthImpl(sType, complex); + case BTC_G_YEAR: + return new XmlGYearImpl(sType, complex); + case BTC_G_MONTH_DAY: + return new XmlGMonthDayImpl(sType, complex); + case BTC_G_DAY: + return new XmlGDayImpl(sType, complex); + case BTC_G_MONTH: + return new XmlGMonthImpl(sType, complex); + case BTC_INTEGER: + return new XmlIntegerRestriction(sType, complex); + case BTC_LONG: + return new XmlLongRestriction(sType, complex); + case BTC_INT: + return new XmlIntRestriction(sType, complex); + case BTC_SHORT: + return new XmlShortImpl(sType, complex); + case BTC_BYTE: + return new XmlByteImpl(sType, complex); + case BTC_NON_POSITIVE_INTEGER: + return new XmlNonPositiveIntegerImpl(sType, complex); + case BTC_NEGATIVE_INTEGER: + return new XmlNegativeIntegerImpl(sType, complex); + case BTC_NON_NEGATIVE_INTEGER: + return new XmlNonNegativeIntegerImpl(sType, complex); + case BTC_POSITIVE_INTEGER: + return new XmlPositiveIntegerImpl(sType, complex); + case BTC_UNSIGNED_LONG: + return new XmlUnsignedLongImpl(sType, complex); + case BTC_UNSIGNED_INT: + return new XmlUnsignedIntImpl(sType, complex); + case BTC_UNSIGNED_SHORT: + return new XmlUnsignedShortImpl(sType, complex); + case BTC_UNSIGNED_BYTE: + return new XmlUnsignedByteImpl(sType, complex); + case BTC_NORMALIZED_STRING: + return new XmlNormalizedStringImpl(sType, complex); + case BTC_TOKEN: + return new XmlTokenImpl(sType, complex); + case BTC_NAME: + return new XmlNameImpl(sType, complex); + case BTC_NCNAME: + return new XmlNCNameImpl(sType, complex); + case BTC_LANGUAGE: + return new XmlLanguageImpl(sType, complex); + case BTC_ID: + return new XmlIdImpl(sType, complex); + case BTC_IDREF: + return new XmlIdRefImpl(sType, complex); + case BTC_IDREFS: + return new XmlIdRefsImpl(sType, complex); + case BTC_ENTITY: + return new XmlEntityImpl(sType, complex); + case BTC_ENTITIES: + return new XmlEntitiesImpl(sType, complex); + case BTC_NMTOKEN: + return new XmlNmTokenImpl(sType, complex); + case BTC_NMTOKENS: + return new XmlNmTokensImpl(sType, complex); + default: + throw new IllegalStateException("Unrecognized builtin type: " + getBuiltinTypeCode()); + } + } + + public SchemaType getCommonBaseType(SchemaType type) { + // null type is treated as the no-type + if (this == BuiltinSchemaTypeSystem.ST_ANY_TYPE || type == null || type.isNoType()) { + return this; + } + + // any type is the universal base type; noType is the universal derived type + if (type == BuiltinSchemaTypeSystem.ST_ANY_TYPE || isNoType()) { + return type; + } + + // the regular case: + SchemaTypeImpl sImpl1 = (SchemaTypeImpl) type; + while (sImpl1.getBaseDepth() > getBaseDepth()) { + sImpl1 = (SchemaTypeImpl) sImpl1.getBaseType(); + } + SchemaTypeImpl sImpl2 = this; + while (sImpl2.getBaseDepth() > sImpl1.getBaseDepth()) { + sImpl2 = (SchemaTypeImpl) sImpl2.getBaseType(); + } + while (!sImpl1.equals(sImpl2)) { + sImpl1 = (SchemaTypeImpl) sImpl1.getBaseType(); + sImpl2 = (SchemaTypeImpl) sImpl2.getBaseType(); + assert (sImpl1 != null && sImpl2 != null); // must meet at anyType + } + return sImpl1; + } + + public boolean isAssignableFrom(SchemaType type) { + if (type == null || type.isNoType()) { + return true; + } + + if (isNoType()) { + return false; + } + + if (getSimpleVariety() == UNION) { + SchemaType[] members = getUnionMemberTypes(); + for (SchemaType member : members) { + if (member.isAssignableFrom(type)) { + return true; + } + } + } + + int depth = ((SchemaTypeImpl) type).getBaseDepth() - getBaseDepth(); + if (depth < 0) { + return false; + } + while (depth > 0) { + type = type.getBaseType(); + depth -= 1; + } + return (type != null && type.equals(this)); + } + + + public String toString() { + if (getName() != null) { + return "T=" + QNameHelper.pretty(getName()); + } + + if (isDocumentType()) { + return "D=" + QNameHelper.pretty(getDocumentElementName()); + } + + if (isAttributeType()) { + return "R=" + QNameHelper.pretty(getAttributeTypeAttributeName()); + } + + String prefix; + + if (getContainerField() != null) { + prefix = (getContainerField().getName().getNamespaceURI().length() > 0 ? + (getContainerField().isAttribute() ? "Q=" : "E=") : + (getContainerField().isAttribute() ? "A=" : "U=")) + + getContainerField().getName().getLocalPart(); + if (getOuterType() == null) { + return prefix + "@" + getContainerField().getName().getNamespaceURI(); + } + } else if (isNoType()) { + return "N="; + } else if (getOuterType() == null) { + return "noouter"; + } else if (getOuterType().getBaseType() == this) { + prefix = "B="; + } else if (getOuterType().getContentBasedOnType() == this) { + prefix = "S="; + } else if (getOuterType().getSimpleVariety() == SchemaType.LIST) { + prefix = "I="; + } else if (getOuterType().getSimpleVariety() == SchemaType.UNION) { + prefix = "M=" + getAnonymousUnionMemberOrdinal(); + } else { + prefix = "strange="; + } + + return prefix + "|" + getOuterType().toString(); + } + + private XmlObject _parseObject; + private String _parseTNS; + private String _elemFormDefault; + private String _attFormDefault; + private boolean _chameleon; + private boolean _redefinition; + + public void setParseContext(XmlObject parseObject, String targetNamespace, boolean chameleon, String elemFormDefault, String attFormDefault, boolean redefinition) { + _parseObject = parseObject; + _parseTNS = targetNamespace; + _chameleon = chameleon; + _elemFormDefault = elemFormDefault; + _attFormDefault = attFormDefault; + _redefinition = redefinition; + } + + public XmlObject getParseObject() { + return _parseObject; + } + + public String getTargetNamespace() { + return _parseTNS; + } + + public boolean isChameleon() { + return _chameleon; + } + + public String getElemFormDefault() { + return _elemFormDefault; + } + + public String getAttFormDefault() { + return _attFormDefault; + } + + public String getChameleonNamespace() { + return _chameleon ? _parseTNS : null; + } + + public boolean isRedefinition() { + return _redefinition; + } + + private final SchemaType.Ref _selfref = new SchemaType.Ref(this); + + public SchemaType.Ref getRef() { + return _selfref; + } + + public SchemaComponent.Ref getComponentRef() { + return getRef(); + } + + /** + * Gives access to the internals of element validation + */ + private static class SequencerImpl implements SchemaTypeElementSequencer { + private final SchemaTypeVisitorImpl _visitor; + + private SequencerImpl(SchemaTypeVisitorImpl visitor) { + _visitor = visitor; + } + + public boolean next(QName elementName) { + if (_visitor == null) { + return false; + } + + return _visitor.visit(elementName); + } + + public boolean peek(QName elementName) { + if (_visitor == null) { + return false; + } + + return _visitor.testValid(elementName); + } + } + + /** + * Returns a QNameSet of elements that may exist in wildcard + * buchets and are not explicitly defined in this schema type. + * Note: In this example: + * + * + * + * + * + * + * the returned QNameSet will not contain the qname of 'someElement'. + * + * @return the constructed QNameSet + */ + public QNameSet qnameSetForWildcardElements() { + SchemaParticle model = this.getContentModel(); + QNameSetBuilder wildcardSet = new QNameSetBuilder(); + computeWildcardSet(model, wildcardSet); + + QNameSetBuilder qnsb = new QNameSetBuilder(wildcardSet); + SchemaProperty[] props = this.getElementProperties(); + + for (SchemaProperty prop : props) { + qnsb.remove(prop.getName()); + } + + return qnsb.toQNameSet(); + } + + private static void computeWildcardSet(SchemaParticle model, QNameSetBuilder result) { + if (model.getParticleType() == SchemaParticle.WILDCARD) { + QNameSet cws = model.getWildcardSet(); + result.addAll(cws); + return; + } + for (int i = 0; i < model.countOfParticleChild(); i++) { + SchemaParticle child = model.getParticleChild(i); + computeWildcardSet(child, result); + } + } + + /** + * Returns a QNameSet of attributes that may exist in wildcard + * buchets and are not explicitly defined in this schema type. + * Note: In this example: + * + * ... + * + * + * + * the returned QNameSet will not contain the qname of 'someAttribute'. + * + * @return the constructed QNameSet + */ + public QNameSet qnameSetForWildcardAttributes() { + SchemaAttributeModel model = this.getAttributeModel(); + QNameSet wildcardSet = model.getWildcardSet(); + + if (wildcardSet == null) { + return QNameSet.EMPTY; + } + + QNameSetBuilder qnsb = new QNameSetBuilder(wildcardSet); + + SchemaProperty[] props = this.getAttributeProperties(); + + for (SchemaProperty prop : props) { + qnsb.remove(prop.getName()); + } + + return qnsb.toQNameSet(); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java new file mode 100644 index 0000000..bd9afdc --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java @@ -0,0 +1,475 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.store.Locale; +import org.apache.xmlbeans.impl.xpath.XPathFactory; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Node; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; + +public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader { + private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")"; + + private static String doCompilePath(String pathExpr, XmlOptions options) { + return XPathFactory.compilePath(pathExpr, options); + } + + private static String doCompileQuery(String queryExpr, XmlOptions options) { + return XPathFactory.compileQuery(queryExpr, options); + } + + public SchemaType findType(QName name) { + SchemaType.Ref ref = findTypeRef(name); + if (ref == null) { + return null; + } + SchemaType result = ref.get(); + assert (result != null); + return result; + } + + public SchemaType findDocumentType(QName name) { + SchemaType.Ref ref = findDocumentTypeRef(name); + if (ref == null) { + return null; + } + SchemaType result = ref.get(); + assert (result != null); + return result; + } + + public SchemaType findAttributeType(QName name) { + SchemaType.Ref ref = findAttributeTypeRef(name); + if (ref == null) { + return null; + } + SchemaType result = ref.get(); + assert (result != null); + return result; + } + + public SchemaModelGroup findModelGroup(QName name) { + SchemaModelGroup.Ref ref = findModelGroupRef(name); + if (ref == null) { + return null; + } + SchemaModelGroup result = ref.get(); + assert (result != null); + return result; + } + + public SchemaAttributeGroup findAttributeGroup(QName name) { + SchemaAttributeGroup.Ref ref = findAttributeGroupRef(name); + if (ref == null) { + return null; + } + SchemaAttributeGroup result = ref.get(); + assert (result != null); + return result; + } + + public SchemaGlobalElement findElement(QName name) { + SchemaGlobalElement.Ref ref = findElementRef(name); + if (ref == null) { + return null; + } + SchemaGlobalElement result = ref.get(); + assert (result != null); + return result; + } + + public SchemaGlobalAttribute findAttribute(QName name) { + SchemaGlobalAttribute.Ref ref = findAttributeRef(name); + if (ref == null) { + return null; + } + SchemaGlobalAttribute result = ref.get(); + assert (result != null); + return result; + } + + // + // + // + + public XmlObject newInstance(SchemaType type, XmlOptions options) { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + if (hook != null) { + return hook.newInstance(this, type, options); + } + + return Locale.newInstance(this, type, options); + } + + public XmlObject parse(String xmlText, SchemaType type, XmlOptions options) throws XmlException { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + if (hook != null) { + return hook.parse(this, xmlText, type, options); + } + + return Locale.parseToXmlObject(this, xmlText, type, options); + } + + public XmlObject parse(XMLStreamReader xsr, SchemaType type, XmlOptions options) throws XmlException { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + if (hook != null) { + return hook.parse(this, xsr, type, options); + } + + return Locale.parseToXmlObject(this, xsr, type, options); + } + + public XmlObject parse(File file, SchemaType type, XmlOptions options) throws XmlException, IOException { + String fileName = file.toURI().normalize().toString(); + if (options == null) { + options = new XmlOptions(); + options.setDocumentSourceName(fileName); + } else if (options.getDocumentSourceName() == null) { + options = new XmlOptions(options); + options.setDocumentSourceName(fileName); + } + + try (InputStream fis = new FileInputStream(file)) { + return parse(fis, type, options); + } + } + + public XmlObject parse(URL url, SchemaType type, XmlOptions options) throws XmlException, IOException { + if (options == null) { + options = new XmlOptions(); + options.setDocumentSourceName(url.toString()); + } else if (options.getDocumentSourceName() == null) { + options = new XmlOptions(options); + options.setDocumentSourceName(url.toString()); + } + + + boolean redirected = false; + int count = 0; + URLConnection conn; + + do { + conn = url.openConnection(); + conn.addRequestProperty("User-Agent", USER_AGENT); + conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); + if (conn instanceof HttpURLConnection) { + HttpURLConnection httpcon = (HttpURLConnection) conn; + int code = httpcon.getResponseCode(); + redirected = (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP); + if (redirected && count > 5) { + redirected = false; + } + + if (redirected) { + String newLocation = httpcon.getHeaderField("Location"); + if (newLocation == null) { + redirected = false; + } else { + url = new URL(newLocation); + count++; + } + } + } + } while (redirected); + + try (InputStream stream = conn.getInputStream()) { + return parse(stream, type, options); + } + } + + public XmlObject parse(InputStream jiois, SchemaType type, XmlOptions options) throws XmlException, IOException { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + DigestInputStream digestStream = null; + + setupDigest: + if (options != null && options.isLoadMessageDigest()) { + MessageDigest sha; + + try { + sha = MessageDigest.getInstance("SHA"); + } catch (NoSuchAlgorithmException e) { + break setupDigest; + } + + digestStream = new DigestInputStream(jiois, sha); + jiois = digestStream; + } + + if (hook != null) { + return hook.parse(this, jiois, type, options); + } + + XmlObject result = Locale.parseToXmlObject(this, jiois, type, options); + + if (digestStream != null) { + result.documentProperties().setMessageDigest(digestStream.getMessageDigest().digest()); + } + + return result; + } + + public XmlObject parse(Reader jior, SchemaType type, XmlOptions options) throws XmlException, IOException { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + if (hook != null) { + return hook.parse(this, jior, type, options); + } + + return Locale.parseToXmlObject(this, jior, type, options); + } + + public XmlObject parse(Node node, SchemaType type, XmlOptions options) throws XmlException { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + if (hook != null) { + return hook.parse(this, node, type, options); + } + + return Locale.parseToXmlObject(this, node, type, options); + } + + public XmlSaxHandler newXmlSaxHandler(SchemaType type, XmlOptions options) { + XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + + if (hook != null) { + return hook.newXmlSaxHandler(this, type, options); + } + + return Locale.newSaxHandler(this, type, options); + } + + public DOMImplementation newDomImplementation(XmlOptions options) { + return Locale.newDomImplementation(this, options); + } + + // + // + // + + public String compilePath(String pathExpr) { + return compilePath(pathExpr, null); + } + + public String compilePath(String pathExpr, XmlOptions options) { + return doCompilePath(pathExpr, options); + } + + public String compileQuery(String queryExpr) { + return compileQuery(queryExpr, null); + } + + public String compileQuery(String queryExpr, XmlOptions options) { + return doCompileQuery(queryExpr, options); + } + + /** + * Utility function to load a type from a signature. + *

      + * A signature is the string you get from type.toString(). + */ + public SchemaType typeForSignature(String signature) { + int end = signature.indexOf('@'); + String uri; + + if (end < 0) { + uri = ""; + end = signature.length(); + } else { + uri = signature.substring(end + 1); + } + + List parts = new ArrayList<>(); + + for (int index = 0; index < end; ) { + int nextc = signature.indexOf(':', index); + int nextd = signature.indexOf('|', index); + int next = (nextc < 0 ? nextd : nextd < 0 ? nextc : Math.min(nextc, nextd)); + if (next < 0 || next > end) { + next = end; + } + String part = signature.substring(index, next); + parts.add(part); + index = next + 1; + } + + SchemaType curType = null; + + for (int i = parts.size() - 1; i >= 0; i -= 1) { + String part = parts.get(i); + if (part.length() < 1) { + throw new IllegalArgumentException(); + } + int offset = (part.length() >= 2 && part.charAt(1) == '=') ? 2 : 1; + cases: + switch (part.charAt(0)) { + case 'T': + if (curType != null) { + throw new IllegalArgumentException(); + } + curType = findType(QNameHelper.forLNS(part.substring(offset), uri)); + if (curType == null) { + return null; + } + break; + + case 'D': + if (curType != null) { + throw new IllegalArgumentException(); + } + curType = findDocumentType(QNameHelper.forLNS(part.substring(offset), uri)); + if (curType == null) { + return null; + } + break; + + case 'C': // deprecated + case 'R': // current + if (curType != null) { + throw new IllegalArgumentException(); + } + curType = findAttributeType(QNameHelper.forLNS(part.substring(offset), uri)); + if (curType == null) { + return null; + } + break; + + case 'E': + case 'U': // distinguish qualified/unqualified TBD + if (curType != null) { + if (curType.getContentType() < SchemaType.ELEMENT_CONTENT) { + return null; + } + SchemaType[] subTypes = curType.getAnonymousTypes(); + String localName = part.substring(offset); + for (SchemaType subType : subTypes) { + SchemaField field = subType.getContainerField(); + if (field != null && !field.isAttribute() && field.getName().getLocalPart().equals(localName)) { + curType = subType; + break cases; + } + } + return null; + } else { + SchemaGlobalElement elt = findElement(QNameHelper.forLNS(part.substring(offset), uri)); + if (elt == null) { + return null; + } + curType = elt.getType(); + } + break; + + case 'A': + case 'Q': // distinguish qualified/unqualified TBD + if (curType != null) { + if (curType.isSimpleType()) { + return null; + } + SchemaType[] subTypes = curType.getAnonymousTypes(); + String localName = part.substring(offset); + for (SchemaType subType : subTypes) { + SchemaField field = subType.getContainerField(); + if (field != null && field.isAttribute() && field.getName().getLocalPart().equals(localName)) { + curType = subType; + break cases; + } + } + return null; + } else { + SchemaGlobalAttribute attr = findAttribute(QNameHelper.forLNS(part.substring(offset), uri)); + if (attr == null) { + return null; + } + curType = attr.getType(); + } + break; + + case 'B': + if (curType == null) { + throw new IllegalArgumentException(); + } else { + if (curType.getSimpleVariety() != SchemaType.ATOMIC) { + return null; + } + SchemaType[] subTypes = curType.getAnonymousTypes(); + if (subTypes.length != 1) { + return null; + } + curType = subTypes[0]; + } + break; + + case 'I': + if (curType == null) { + throw new IllegalArgumentException(); + } else { + if (curType.getSimpleVariety() != SchemaType.LIST) { + return null; + } + SchemaType[] subTypes = curType.getAnonymousTypes(); + if (subTypes.length != 1) { + return null; + } + curType = subTypes[0]; + } + break; + + case 'M': + if (curType == null) { + throw new IllegalArgumentException(); + } else { + int index; + try { + index = Integer.parseInt(part.substring(offset)); + } catch (Exception e) { + throw new IllegalArgumentException(); + } + + if (curType.getSimpleVariety() != SchemaType.UNION) { + return null; + } + SchemaType[] subTypes = curType.getAnonymousTypes(); + if (subTypes.length <= index) { + return null; + } + curType = subTypes[index]; + } + break; + + default: + throw new IllegalArgumentException(); + } + } + return curType; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java new file mode 100644 index 0000000..c427ddd --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java @@ -0,0 +1,603 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.SystemCache; +import org.apache.xmlbeans.impl.common.XBeanDebug; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; + +import javax.xml.namespace.QName; +import java.io.InputStream; +import java.lang.ref.SoftReference; +import java.util.*; + +import static org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.METADATA_PACKAGE_GEN; + +public class SchemaTypeLoaderImpl extends SchemaTypeLoaderBase { + private final ResourceLoader _resourceLoader; + private final ClassLoader _classLoader; + private final SchemaTypeLoader[] _searchPath; + + private Map _classpathTypeSystems; + private Map _classLoaderTypeSystems; + private Map _elementCache; + private Map _attributeCache; + private Map _modelGroupCache; + private Map _attributeGroupCache; + private Map _idConstraintCache; + private Map _typeCache; + private Map _documentCache; + private Map _attributeTypeCache; + private Map _classnameCache; + private final String _metadataPath; + + public static String METADATA_PACKAGE_LOAD = METADATA_PACKAGE_GEN; + private static final Object CACHED_NOT_FOUND = new Object(); + + private static final String[] basePackage = {"org.apache.xmlbeans.metadata", "schemaorg_apache_xmlbeans"}; + private static final String[] baseSchemas = {"sXMLCONFIG", "sXMLLANG", "sXMLSCHEMA", "sXMLTOOLS"}; + + + private static class SchemaTypeLoaderCache extends SystemCache { + // The following maintains a cache of SchemaTypeLoaders per ClassLoader per Thread. + // I use soft references to allow the garbage collector to reclain the type loaders + // and/pr class loaders at will. + + private final ThreadLocal>> _cachedTypeSystems = ThreadLocal.withInitial(ArrayList::new); + + @Override + public void clearThreadLocals() { + _cachedTypeSystems.remove(); + + super.clearThreadLocals(); + } + + public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) { + List> a = _cachedTypeSystems.get(); + + int candidate = -1; + SchemaTypeLoaderImpl result = null; + + for (int i = 0; i < a.size(); i++) { + SchemaTypeLoaderImpl tl = a.get(i).get(); + + if (tl == null) { + a.remove(i--); + } else if (tl._classLoader == cl) { + candidate = i; + result = tl; + break; + } + } + + // Make sure the most recently accessed entry is at the beginning of the array + + if (candidate > 0) { + SoftReference t = a.get(0); + a.set(0, a.get(candidate)); + a.set(candidate, t); + } + + return result; + } + + public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) { + assert (stl instanceof SchemaTypeLoaderImpl) && + ((SchemaTypeLoaderImpl) stl)._classLoader == cl; + + List> a = _cachedTypeSystems.get(); + // Make sure this entry is at the top of the stack + if (a.size() > 0) { + SoftReference t = a.get(0); + a.set(0, new SoftReference<>((SchemaTypeLoaderImpl) stl)); + a.add(t); + } else { + a.add(new SoftReference<>((SchemaTypeLoaderImpl) stl)); + } + } + } + + public static SchemaTypeLoaderImpl getContextTypeLoader() { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + SchemaTypeLoaderImpl result = (SchemaTypeLoaderImpl) + SystemCache.get().getFromTypeLoaderCache(cl); + + if (result == null) { + result = + new SchemaTypeLoaderImpl( + new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get()}, null, cl, null); + SystemCache.get().addToTypeLoaderCache(result, cl); + } + + return result; + } + + public static SchemaTypeLoader build(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader) { + return build(searchPath, resourceLoader, classLoader, null); + } + + /** + * Initialize a SchemaTypeLoader via the given loaders and paths + * + * @param searchPath the searchPath to use + * @param resourceLoader the resourceLoader to use + * @param classLoader the classLoader to use + * @param metadataPath the custom metadata path + * @return the schemaTypeLoader + * @since XmlBeans 3.1.0 + */ + public static SchemaTypeLoader build(final SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) { + // assemble a flattened search path with no duplicates + SubLoaderList list = new SubLoaderList(); + + list.add(searchPath); + + ClassLoader cl = (classLoader == null) ? SchemaDocument.class.getClassLoader() : classLoader; + + for (String prefix : basePackage) { + for (String holder : baseSchemas) { + String clName = prefix + ".system." + holder + ".TypeSystemHolder"; + if (cl.getResource(clName.replace(".", "/") + ".class") == null) { + // if the first class isn't found in the package, continue with the next package + break; + } + try { + @SuppressWarnings("unchecked") + Class cls = (Class) Class.forName(clName, true, cl); + list.add((SchemaTypeLoader) cls.getDeclaredField("typeSystem").get(null)); + } catch (Exception e) { + throw new XmlRuntimeException(e); + } + } + } + + return new SchemaTypeLoaderImpl(list.toArray(), resourceLoader, classLoader, metadataPath); + } + + /** + * Just used to avoid duplicate path entries + */ + private static class SubLoaderList { + private final List theList = new ArrayList<>(); + private final Map seen = new IdentityHashMap<>(); + + void add(SchemaTypeLoader[] searchPath) { + if (searchPath == null) { + return; + } + for (SchemaTypeLoader stl : searchPath) { + if (stl instanceof SchemaTypeLoaderImpl) { + SchemaTypeLoaderImpl sub = (SchemaTypeLoaderImpl) stl; + if (sub._classLoader != null || sub._resourceLoader != null) { + add(sub); + } else { + add(sub._searchPath); + } + } else { + add(stl); + } + } + } + + void add(SchemaTypeLoader loader) { + if (loader != null && !seen.containsKey(loader)) { + theList.add(loader); + seen.put(loader, null); + } + } + + SchemaTypeLoader[] toArray() { + return theList.toArray(EMPTY_SCHEMATYPELOADER_ARRAY); + } + } + + /** + * Constructs a SchemaTypeLoaderImpl that searches for objects + * in the following order: + *

      + * (1) First on the searchPath of other SchemaTypeSystems supplied, + * in order that they are listed. + * (2) Next on the classpath of .jar files or directories supplied, + * in the order that they are listed. When types are returned in + * this way, they are instantiated from a private typesystem. + * In other words, if a type is loaded from another SchemaTypeLoaderImpl + * that was initialized on the same file, the instance of the type will + * be different. + * (3) Finally on the classloader supplied. + */ + private SchemaTypeLoaderImpl(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) { + _searchPath = (searchPath == null) ? EMPTY_SCHEMATYPELOADER_ARRAY : searchPath; + _resourceLoader = resourceLoader; + _classLoader = classLoader; + + if (metadataPath != null) { + this._metadataPath = metadataPath; + } else { + final String path26 = "schema" + METADATA_PACKAGE_LOAD.replace("/", "_"); + this._metadataPath = (isPath30(_classLoader)) ? METADATA_PACKAGE_LOAD : path26; + } + + initCaches(); + } + + private static boolean isPath30(ClassLoader loader) { + final String path30 = METADATA_PACKAGE_LOAD + "/system"; + final ClassLoader cl = (loader != null) ? loader : SchemaDocument.class.getClassLoader(); + return cl.getResource(path30) != null; + } + + /** + * Initializes the caches. + */ + private void initCaches() { + _classpathTypeSystems = Collections.synchronizedMap(new HashMap<>()); + _classLoaderTypeSystems = Collections.synchronizedMap(new HashMap<>()); + _elementCache = Collections.synchronizedMap(new HashMap<>()); + _attributeCache = Collections.synchronizedMap(new HashMap<>()); + _modelGroupCache = Collections.synchronizedMap(new HashMap<>()); + _attributeGroupCache = Collections.synchronizedMap(new HashMap<>()); + _idConstraintCache = Collections.synchronizedMap(new HashMap<>()); + _typeCache = Collections.synchronizedMap(new HashMap<>()); + _documentCache = Collections.synchronizedMap(new HashMap<>()); + _attributeTypeCache = Collections.synchronizedMap(new HashMap<>()); + _classnameCache = Collections.synchronizedMap(new HashMap<>()); + } + + SchemaTypeSystemImpl typeSystemForComponent(String searchdir, QName name) { + String searchfor = searchdir + QNameHelper.hexsafedir(name) + ".xsb"; + String tsname = null; + + if (_resourceLoader != null) { + tsname = crackEntry(_resourceLoader, searchfor); + } + + if (_classLoader != null) { + tsname = crackEntry(_classLoader, searchfor); + } + + if (tsname != null) { + return (SchemaTypeSystemImpl) typeSystemForName(tsname); + } + + return null; + } + + public SchemaTypeSystem typeSystemForName(String name) { + if (_resourceLoader != null) { + SchemaTypeSystem result = getTypeSystemOnClasspath(name); + if (result != null) { + return result; + } + } + + if (_classLoader != null) { + SchemaTypeSystem result = getTypeSystemOnClassloader(name); + if (result != null) { + return result; + } + } + return null; + } + + SchemaTypeSystemImpl typeSystemForClassname(String searchdir, String name) { + String searchfor = searchdir + name.replace('.', '/') + ".xsb"; + + if (_resourceLoader != null) { + String tsname = crackEntry(_resourceLoader, searchfor); + if (tsname != null) { + return getTypeSystemOnClasspath(tsname); + } + } + + if (_classLoader != null) { + String tsname = crackEntry(_classLoader, searchfor); + if (tsname != null) { + return getTypeSystemOnClassloader(tsname); + } + } + + return null; + } + + SchemaTypeSystemImpl getTypeSystemOnClasspath(String name) { + return _classpathTypeSystems.computeIfAbsent(name, n -> new SchemaTypeSystemImpl(_resourceLoader, n, this)); + } + + SchemaTypeSystemImpl getTypeSystemOnClassloader(String name) { + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finding type system " + name + " on classloader", 0); + SchemaTypeSystemImpl result = _classLoaderTypeSystems.get(name); + if (result == null) { + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Type system " + name + " not cached - consulting field", 0); + result = SchemaTypeSystemImpl.forName(name, _classLoader); + _classLoaderTypeSystems.put(name, result); + } + return result; + } + + static String crackEntry(ResourceLoader loader, String searchfor) { + InputStream is = loader.getResourceAsStream(searchfor); + return is == null ? null : crackPointer(is); + } + + static String crackEntry(ClassLoader loader, String searchfor) { + InputStream stream = loader.getResourceAsStream(searchfor); + return stream == null ? null : crackPointer(stream); + } + + static String crackPointer(InputStream stream) { + return SchemaTypeSystemImpl.crackPointer(stream); + } + + public boolean isNamespaceDefined(String namespace) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (schemaTypeLoader.isNamespaceDefined(namespace)) { + return true; + } + } + + SchemaTypeSystem sts = typeSystemForComponent(_metadataPath + "/namespace/", new QName(namespace, "xmlns")); + return (sts != null); + } + + public SchemaType.Ref findTypeRef(QName name) { + // The maps are synchronized, we use two accesses to the cache (one read and one write), but the code in-between + // is not synchronized. The assumption is that the underlying datastructures (the search path and the classloader) + // do not change, so two threads running the code in parallel will come up with the same result. + Object cached = _typeCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaType.Ref result = (SchemaType.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findTypeRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/type/", name); + if (ts != null) { + result = ts.findTypeRef(name); + assert (result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it"; + } + } + _typeCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaType typeForClassname(String classname) { + classname = classname.replace('$', '.'); + + Object cached = _classnameCache.get(classname); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaType result = (SchemaType) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.typeForClassname(classname))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForClassname(_metadataPath + "/javaname/", classname); + if (ts != null) { + result = ts.typeForClassname(classname); + assert (result != null) : "Type system registered type " + classname + " but does not return it"; + } + } + _classnameCache.put(classname, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaType.Ref findDocumentTypeRef(QName name) { + Object cached = _documentCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaType.Ref result = (SchemaType.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findDocumentTypeRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/element/", name); + if (ts != null) { + result = ts.findDocumentTypeRef(name); + assert (result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type"; + } + } + _documentCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaType.Ref findAttributeTypeRef(QName name) { + Object cached = _attributeTypeCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaType.Ref result = (SchemaType.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findAttributeTypeRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attribute/", name); + if (ts != null) { + result = ts.findAttributeTypeRef(name); + assert (result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type"; + } + } + _attributeTypeCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaGlobalElement.Ref findElementRef(QName name) { + Object cached = _elementCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaGlobalElement.Ref result = (SchemaGlobalElement.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findElementRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/element/", name); + if (ts != null) { + result = ts.findElementRef(name); + assert (result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it"; + } + } + _elementCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaGlobalAttribute.Ref findAttributeRef(QName name) { + Object cached = _attributeCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaGlobalAttribute.Ref result = (SchemaGlobalAttribute.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findAttributeRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attribute/", name); + if (ts != null) { + result = ts.findAttributeRef(name); + assert (result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it"; + } + } + _attributeCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaModelGroup.Ref findModelGroupRef(QName name) { + Object cached = _modelGroupCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaModelGroup.Ref result = (SchemaModelGroup.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findModelGroupRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/modelgroup/", name); + if (ts != null) { + result = ts.findModelGroupRef(name); + assert (result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it"; + } + } + _modelGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) { + Object cached = _attributeGroupCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaAttributeGroup.Ref result = (SchemaAttributeGroup.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findAttributeGroupRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attributegroup/", name); + if (ts != null) { + result = ts.findAttributeGroupRef(name); + assert (result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it"; + } + } + _attributeGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { + Object cached = _idConstraintCache.get(name); + if (cached == CACHED_NOT_FOUND) { + return null; + } + SchemaIdentityConstraint.Ref result = (SchemaIdentityConstraint.Ref) cached; + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findIdentityConstraintRef(name))) { + break; + } + } + if (result == null) { + SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/identityconstraint/", name); + if (ts != null) { + result = ts.findIdentityConstraintRef(name); + assert (result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it"; + } + } + _idConstraintCache.put(name, result == null ? CACHED_NOT_FOUND : result); + } + return result; + } + + public InputStream getSourceAsStream(String sourceName) { + InputStream result = null; + + if (!sourceName.startsWith("/")) { + sourceName = "/" + sourceName; + } + + if (_resourceLoader != null) { + result = _resourceLoader.getResourceAsStream(_metadataPath + "/src" + sourceName); + } + + if (result == null && _classLoader != null) { + return _classLoader.getResourceAsStream(_metadataPath + "/src" + sourceName); + } + + return result; + } + + private static final SchemaTypeLoader[] EMPTY_SCHEMATYPELOADER_ARRAY = new SchemaTypeLoader[0]; + + static { + if (SystemCache.get() != null) { + SystemCache.set(new SchemaTypeLoaderCache()); + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java new file mode 100644 index 0000000..3a512be --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java @@ -0,0 +1,404 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.XmlErrorWatcher; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.net.URI; +import java.util.*; + +public class SchemaTypeSystemCompiler { + public static class Parameters { + private SchemaTypeSystem existingSystem; + private String name; + private Schema[] schemas; + private BindingConfig config; + private SchemaTypeLoader linkTo; + private XmlOptions options; + private Collection errorListener; + private boolean javaize; + private URI baseURI; + private Map sourcesToCopyMap; + private File schemasDir; + + public SchemaTypeSystem getExistingTypeSystem() { + return existingSystem; + } + + public void setExistingTypeSystem(SchemaTypeSystem system) { + this.existingSystem = system; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public SchemaDocument.Schema[] getSchemas() { + return schemas; + } + + public void setSchemas(SchemaDocument.Schema[] schemas) { + this.schemas = (schemas == null) ? null : schemas.clone(); + } + + public BindingConfig getConfig() { + return config; + } + + public void setConfig(BindingConfig config) { + this.config = config; + } + + public SchemaTypeLoader getLinkTo() { + return linkTo; + } + + public void setLinkTo(SchemaTypeLoader linkTo) { + this.linkTo = linkTo; + } + + public XmlOptions getOptions() { + return options; + } + + public void setOptions(XmlOptions options) { + this.options = options; + } + + public Collection getErrorListener() { + return errorListener; + } + + public void setErrorListener(Collection errorListener) { + this.errorListener = errorListener; + } + + public boolean isJavaize() { + return javaize; + } + + public void setJavaize(boolean javaize) { + this.javaize = javaize; + } + + public URI getBaseURI() { + return baseURI; + } + + public void setBaseURI(URI baseURI) { + this.baseURI = baseURI; + } + + public Map getSourcesToCopyMap() { + return sourcesToCopyMap; + } + + public void setSourcesToCopyMap(Map sourcesToCopyMap) { + this.sourcesToCopyMap = sourcesToCopyMap; + } + + public File getSchemasDir() { + return schemasDir; + } + + public void setSchemasDir(File schemasDir) { + this.schemasDir = schemasDir; + } + + } + + /** + * Compiles a SchemaTypeSystem. Use XmlBeans.compileXmlBeans() if you can. + */ + public static SchemaTypeSystem compile(Parameters params) { + return compileImpl(params.getExistingTypeSystem(), params.getName(), + params.getSchemas(), params.getConfig(), params.getLinkTo(), + params.getOptions(), params.getErrorListener(), params.isJavaize(), + params.getBaseURI(), params.getSourcesToCopyMap(), params.getSchemasDir()); + } + + /** + * Please do not invoke this method directly as the signature could change unexpectedly. + * Use one of + * {@link XmlBeans#loadXsd(XmlObject[])}, + * {@link XmlBeans#compileXsd(XmlObject[], SchemaTypeLoader, XmlOptions)}, + * or + * {@link XmlBeans#compileXmlBeans(String, SchemaTypeSystem, XmlObject[], BindingConfig, SchemaTypeLoader, Filer, XmlOptions)} + */ + public static SchemaTypeSystemImpl compile(String name, SchemaTypeSystem existingSTS, + XmlObject[] input, BindingConfig config, SchemaTypeLoader linkTo, Filer filer, XmlOptions options) + throws XmlException { + options = XmlOptions.maskNull(options); + ArrayList schemas = new ArrayList<>(); + + if (input != null) { + for (int i = 0; i < input.length; i++) { + if (input[i] instanceof Schema) { + schemas.add((Schema) input[i]); + } else if (input[i] instanceof SchemaDocument && ((SchemaDocument) input[i]).getSchema() != null) { + schemas.add(((SchemaDocument) input[i]).getSchema()); + } else { + throw new XmlException("Thread " + Thread.currentThread().getName() + ": The " + i + "th supplied input is not a schema document: its type is " + input[i].schemaType()); + } + } + } + + Collection userErrors = options.getErrorListener(); + XmlErrorWatcher errorWatcher = new XmlErrorWatcher(userErrors); + + SchemaTypeSystemImpl stsi = compileImpl(existingSTS, name, + schemas.toArray(new Schema[0]), + config, linkTo, options, errorWatcher, filer != null, options.getBaseURI(), + null, null); + + // if there is an error and compile didn't recover (stsi==null), throw exception + if (errorWatcher.hasError() && stsi == null) { + throw new XmlException(errorWatcher.firstError()); + } + + if (stsi != null && !stsi.isIncomplete() && filer != null) { + stsi.save(filer); + generateTypes(stsi, filer, options); + } + + return stsi; + } + + // + // Compiles a SchemaTypeSystem + // + /* package */ + static SchemaTypeSystemImpl compileImpl(SchemaTypeSystem system, String name, + Schema[] schemas, BindingConfig config, SchemaTypeLoader linkTo, + XmlOptions options, Collection outsideErrors, boolean javaize, + URI baseURI, Map sourcesToCopyMap, File schemasDir) { + if (linkTo == null) { + throw new IllegalArgumentException("Must supply linkTo"); + } + + XmlErrorWatcher errorWatcher = new XmlErrorWatcher(outsideErrors); + boolean incremental = system != null; + + // construct the state + StscState state = StscState.start(); + boolean validate = (options == null || !options.isCompileNoValidation()); + try { + state.setErrorListener(errorWatcher); + state.setBindingConfig(config); + state.setOptions(options); + state.setGivenTypeSystemName(name); + state.setSchemasDir(schemasDir); + if (baseURI != null) { + state.setBaseUri(baseURI); + } + + // construct the classpath (you always get the builtin types) + linkTo = SchemaTypeLoaderImpl.build(new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get(), linkTo}, null, null); + state.setImportingTypeLoader(linkTo); + + List validSchemas = new ArrayList<>(schemas.length); + + // load all the xsd files into it + if (validate) { + XmlOptions validateOptions = new XmlOptions().setErrorListener(errorWatcher); + if (options != null && options.isValidateTreatLaxAsSkip()) { + validateOptions.setValidateTreatLaxAsSkip(); + } + for (Schema schema : schemas) { + if (schema.validate(validateOptions)) { + validSchemas.add(schema); + } + } + } else { + validSchemas.addAll(Arrays.asList(schemas)); + } + + Schema[] startWith = validSchemas.toArray(new Schema[0]); + + if (incremental) { + Set namespaces = new HashSet<>(); + startWith = getSchemasToRecompile((SchemaTypeSystemImpl) system, startWith, namespaces); + state.initFromTypeSystem((SchemaTypeSystemImpl) system, namespaces); + } else { + state.setDependencies(new SchemaDependencies()); + } + + // deal with imports and includes + StscImporter.SchemaToProcess[] schemasAndChameleons = StscImporter.resolveImportsAndIncludes(startWith, incremental); + + // call the translator so that it may also perform magic + StscTranslator.addAllDefinitions(schemasAndChameleons); + + // call the resolver to do its magic + StscResolver.resolveAll(); + + // call the checker to check both restrictions and defaults + StscChecker.checkAll(); + + // call the javaizer to do its magic + StscJavaizer.javaizeAllTypes(javaize); + + // construct the loader out of the state + StscState.get().sts().loadFromStscState(state); + + // fill in the source-copy map + if (sourcesToCopyMap != null) { + sourcesToCopyMap.putAll(state.sourceCopyMap()); + } + + if (errorWatcher.hasError()) { + // EXPERIMENTAL: recovery from compilation errors and partial type system + if (state.allowPartial() && state.getRecovered() == errorWatcher.size()) { + // if partial type system allowed and all errors were recovered + StscState.get().sts().setIncomplete(true); + } else { + // if any non-recoverable errors, return null + return null; + } + } + + if (system != null) { + ((SchemaTypeSystemImpl) system).setIncomplete(true); + } + + return StscState.get().sts(); + } finally { + StscState.end(); + } + } + + /** + * Get the list of Schemas to be recompiled, based on the list of Schemas that + * were modified. + * We make use of the depencency information that we stored in the typesystem + * and of the entity resolvers that have been set up + */ + private static Schema[] getSchemasToRecompile(SchemaTypeSystemImpl system, + Schema[] modified, Set namespaces) { + Set modifiedFiles = new HashSet<>(); + Map haveFile = new HashMap<>(); + List result = new ArrayList<>(); + for (Schema schema : modified) { + String fileURL = schema.documentProperties().getSourceName(); + if (fileURL == null) { + throw new IllegalArgumentException("One of the Schema files passed in" + + " doesn't have the source set, which prevents it to be incrementally" + + " compiled"); + } + modifiedFiles.add(fileURL); + haveFile.put(fileURL, schema); + result.add(schema); + } + SchemaDependencies dep = system.getDependencies(); + List nss = dep.getNamespacesTouched(modifiedFiles); + namespaces.addAll(dep.computeTransitiveClosure(nss)); + List needRecompilation = dep.getFilesTouched(namespaces); + StscState.get().setDependencies(new SchemaDependencies(dep, namespaces)); + for (String url : needRecompilation) { + Schema have = haveFile.get(url); + if (have == null) { + // We have to load the file from the entity resolver + try { + XmlObject xdoc = StscImporter.DownloadTable. + downloadDocument(StscState.get().getS4SLoader(), null, url); + XmlOptions voptions = new XmlOptions(); + voptions.setErrorListener(StscState.get().getErrorListener()); + if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) { + StscState.get().error("Referenced document is not a valid schema, URL = " + url, XmlErrorCodes.CANNOT_FIND_RESOURCE, null); + continue; + } + + SchemaDocument sDoc = (SchemaDocument) xdoc; + + result.add(sDoc.getSchema()); + } catch (java.net.MalformedURLException mfe) { + StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"MalformedURLException", url, mfe.getMessage()}, null); + } catch (IOException ioe) { + StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"IOException", url, ioe.getMessage()}, null); + } catch (XmlException xmle) { + StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"XmlException", url, xmle.getMessage()}, null); + } + } + } + return result.toArray(new Schema[0]); + } + + + /** + * Generate java source files for a SchemaTypeSystem. + * Please do not invoke this method directly as the signature could change unexpectedly. + * Use {@link org.apache.xmlbeans.XmlBeans#compileXmlBeans} + * + * @param system the SchemaTypeSystem to generated java source for + * @param filer to create the java source files + * @param options See {@link XmlOptions#setSchemaCodePrinter(org.apache.xmlbeans.SchemaCodePrinter)} + * @return true if saving the generated source succeeded. + */ + public static boolean generateTypes(SchemaTypeSystem system, Filer filer, XmlOptions options) { + // partial type systems not allowed to be saved + if (system instanceof SchemaTypeSystemImpl && ((SchemaTypeSystemImpl) system).isIncomplete()) { + return false; + } + + boolean success = true; + + List types = new ArrayList<>(); + types.addAll(Arrays.asList(system.globalTypes())); + types.addAll(Arrays.asList(system.documentTypes())); + types.addAll(Arrays.asList(system.attributeTypes())); + + for (SchemaType type : types) { + if (type.isBuiltinType()) { + continue; + } + if (type.getFullJavaName() == null) { + continue; + } + + String fjn = type.getFullJavaName(); + + try (Writer writer = filer.createSourceFile(fjn)) { + // Generate interface class + SchemaTypeCodePrinter.printType(writer, type, options); + } catch (IOException e) { + System.err.println("IO Error " + e); + success = false; + } + + fjn = type.getFullJavaImplName(); + + try (Writer writer = filer.createSourceFile(fjn)) { + // Generate Implementation class + SchemaTypeCodePrinter.printTypeImpl(writer, type, options); + } catch (IOException e) { + System.err.println("IO Error " + e); + success = false; + } + } + + return success; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java new file mode 100644 index 0000000..1cd1d3e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java @@ -0,0 +1,3346 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.DefaultClassLoaderResourceLoader; +import org.apache.xmlbeans.impl.common.NameUtil; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.XBeanDebug; +import org.apache.xmlbeans.impl.repackage.Repackager; +import org.apache.xmlbeans.impl.util.FilerImpl; +import org.apache.xmlbeans.impl.util.HexBin; +import org.apache.xmlbeans.impl.values.XmlObjectBase; +import org.apache.xmlbeans.impl.xb.xsdschema.AttributeGroupDocument; +import org.apache.xmlbeans.impl.xb.xsdschema.GroupDocument; +import org.apache.xmlbeans.soap.SOAPArrayType; +import org.apache.xmlbeans.soap.SchemaWSDLArrayType; + +import javax.xml.namespace.QName; +import java.io.*; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +public class SchemaTypeSystemImpl extends SchemaTypeLoaderBase implements SchemaTypeSystem { + public static final int DATA_BABE = 0xDA7ABABE; + public static final int MAJOR_VERSION = 2; // must match == to be compatible + public static final int MINOR_VERSION = 24; // must be <= to be compatible + public static final int RELEASE_NUMBER = 0; // should be compatible even if < or > + + public static final int FILETYPE_SCHEMAINDEX = 1; + public static final int FILETYPE_SCHEMATYPE = 2; + public static final int FILETYPE_SCHEMAELEMENT = 3; + public static final int FILETYPE_SCHEMAATTRIBUTE = 4; + public static final int FILETYPE_SCHEMAPOINTER = 5; + public static final int FILETYPE_SCHEMAMODELGROUP = 6; + public static final int FILETYPE_SCHEMAATTRIBUTEGROUP = 7; + public static final int FILETYPE_SCHEMAIDENTITYCONSTRAINT = 8; + + public static final int FLAG_PART_SKIPPABLE = 1; + public static final int FLAG_PART_FIXED = 4; + public static final int FLAG_PART_NILLABLE = 8; + public static final int FLAG_PART_BLOCKEXT = 16; + public static final int FLAG_PART_BLOCKREST = 32; + public static final int FLAG_PART_BLOCKSUBST = 64; + public static final int FLAG_PART_ABSTRACT = 128; + public static final int FLAG_PART_FINALEXT = 256; + public static final int FLAG_PART_FINALREST = 512; + + public static final int FLAG_PROP_ISATTR = 1; + public static final int FLAG_PROP_JAVASINGLETON = 2; + public static final int FLAG_PROP_JAVAOPTIONAL = 4; + public static final int FLAG_PROP_JAVAARRAY = 8; + + public static final int FIELD_NONE = 0; + public static final int FIELD_GLOBAL = 1; + public static final int FIELD_LOCALATTR = 2; + public static final int FIELD_LOCALELT = 3; + + // type flags + static final int FLAG_SIMPLE_TYPE = 0x1; + static final int FLAG_DOCUMENT_TYPE = 0x2; + static final int FLAG_ORDERED = 0x4; + static final int FLAG_BOUNDED = 0x8; + static final int FLAG_FINITE = 0x10; + static final int FLAG_NUMERIC = 0x20; + static final int FLAG_STRINGENUM = 0x40; + static final int FLAG_UNION_OF_LISTS = 0x80; + static final int FLAG_HAS_PATTERN = 0x100; + static final int FLAG_ORDER_SENSITIVE = 0x200; + static final int FLAG_TOTAL_ORDER = 0x400; + static final int FLAG_COMPILED = 0x800; + static final int FLAG_BLOCK_EXT = 0x1000; + static final int FLAG_BLOCK_REST = 0x2000; + static final int FLAG_FINAL_EXT = 0x4000; + static final int FLAG_FINAL_REST = 0x8000; + static final int FLAG_FINAL_UNION = 0x10000; + static final int FLAG_FINAL_LIST = 0x20000; + static final int FLAG_ABSTRACT = 0x40000; + static final int FLAG_ATTRIBUTE_TYPE = 0x80000; + + /** + * regex to identify the type system holder package namespace + */ + private static final Pattern packPat = Pattern.compile("^(.+)(\\.[^.]+){2}$"); + + /** + * This is to support the feature of a separate/private XMLBeans + * distribution that will not colide with the public org apache + * xmlbeans one. + * METADATA_PACKAGE_GEN will be "" for the original and something like + * com.mycompany.private.xmlbeans for a private distribution of XMLBeans. + *

      + * There are two properties: + * METADATA_PACKAGE_GEN - used for generating metadata + * and METADATA_PACKAGE_LOAD - used for loading the metadata. + * Most of the time they have the same value, with one exception, during the + * repackage process scomp needs to load from old package and generate into + * a new package. + */ + public static String METADATA_PACKAGE_GEN = "org/apache/xmlbeans/metadata"; +// public static String METADATA_PACKAGE_GEN; +// static +// { +// // fix for maven classloader +// Package stsPackage = SchemaTypeSystem.class.getPackage(); +// String stsPackageName = (stsPackage==null) ? +// SchemaTypeSystem.class.getName().substring(0, SchemaTypeSystem.class.getName().lastIndexOf(".")) : +// stsPackage.getName(); +// +// METADATA_PACKAGE_GEN = stsPackageName.replace('.', '/') + "/metadata"; +// } + + private static String nameToPathString(String nameForSystem) { + nameForSystem = nameForSystem.replace('.', '/'); + + if (!nameForSystem.endsWith("/") && nameForSystem.length() > 0) { + nameForSystem = nameForSystem + "/"; + } + + return nameForSystem; + } + + protected SchemaTypeSystemImpl() { + String fullname = getClass().getName(); + _name = fullname.substring(0, fullname.lastIndexOf('.')); + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Loading type system " + _name, 1); + _basePackage = nameToPathString(_name); + _classloader = getClass().getClassLoader(); + _linker = this; + _resourceLoader = new ClassLoaderResourceLoader(_classloader); + try { + initFromHeader(); + } catch (Error | RuntimeException e) { + XBeanDebug.logException(e); + throw e; + } + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finished loading type system " + _name, -1); + } + + public SchemaTypeSystemImpl(Class indexclass) { + String fullname = indexclass.getName(); + _name = fullname.substring(0, fullname.lastIndexOf('.')); + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Loading type system " + _name, 1); + _basePackage = nameToPathString(_name); + _classloader = indexclass.getClassLoader(); + _linker = SchemaTypeLoaderImpl.build(null, null, _classloader, getMetadataPath()); + _resourceLoader = new ClassLoaderResourceLoader(_classloader); + try { + initFromHeader(); + } catch (RuntimeException | Error e) { + XBeanDebug.logException(e); + throw e; + } + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finished loading type system " + _name, -1); + } + + public static boolean fileContainsTypeSystem(File file, String name) { + String indexname = nameToPathString(name) + "index.xsb"; + + if (file.isDirectory()) { + return (new File(file, indexname)).isFile(); + } else { + try (ZipFile zipfile = new ZipFile(file)) { + ZipEntry entry = zipfile.getEntry(indexname); + return (entry != null && !entry.isDirectory()); + } catch (IOException e) { + XBeanDebug.log("Problem loading SchemaTypeSystem, zipfilename " + file); + XBeanDebug.logException(e); + throw new SchemaTypeLoaderException(e.getMessage(), name, "index", SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + } + + public static SchemaTypeSystemImpl forName(String name, ClassLoader loader) { + try { + Class c = Class.forName(name + "." + SchemaTypeCodePrinter.INDEX_CLASSNAME, true, loader); + return (SchemaTypeSystemImpl) c.getField("typeSystem").get(null); + } catch (Throwable e) { + return null; + } + } + + public SchemaTypeSystemImpl(ResourceLoader resourceLoader, String name, SchemaTypeLoader linker) { + _name = name; + _basePackage = nameToPathString(_name); + _linker = linker; + _resourceLoader = resourceLoader; + try { + initFromHeader(); + } catch (RuntimeException | Error e) { + XBeanDebug.logException(e); + throw e; + } + } + + private void initFromHeader() { + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Reading unresolved handles for type system " + _name, 0); + XsbReader reader = null; + try { + // Read the index file, which starts with a header. + reader = new XsbReader("index", FILETYPE_SCHEMAINDEX); + + // has a handle pool (count, handle/type, handle/type...) + _localHandles = new HandlePool(); + reader.readHandlePool(_localHandles); + + // then a qname map of global elements (count, qname/handle, qname/handle...) + _globalElements = reader.readQNameRefMap(); + + // qname map of global attributes + _globalAttributes = reader.readQNameRefMap(); + + // qname map of model groups + _modelGroups = reader.readQNameRefMap(); + + // qname map of attribute groups + _attributeGroups = reader.readQNameRefMap(); + + _identityConstraints = reader.readQNameRefMap(); + + // qname map of global types + _globalTypes = reader.readQNameRefMap(); + + // qname map of document types, by the qname of the contained element + _documentTypes = reader.readQNameRefMap(); + + // qname mape of attribute types, by the qname of the contained attribute + _attributeTypes = reader.readQNameRefMap(); + + // string map of all types, by fully qualified classname + _typeRefsByClassname = reader.readClassnameRefMap(); + + _namespaces = reader.readNamespaces(); + + // support for redefine, at the end of the file + List typeNames = new ArrayList<>(); + List modelGroupNames = new ArrayList<>(); + List attributeGroupNames = new ArrayList<>(); + if (reader.atLeast(2, 15, 0)) { + _redefinedGlobalTypes = reader.readQNameRefMapAsList(typeNames); + _redefinedModelGroups = reader.readQNameRefMapAsList(modelGroupNames); + _redefinedAttributeGroups = reader.readQNameRefMapAsList(attributeGroupNames); + } + if (reader.atLeast(2, 19, 0)) { + _annotations = reader.readAnnotations(); + } + + buildContainers(typeNames, modelGroupNames, attributeGroupNames); + } finally { + if (reader != null) { + reader.readEnd(); + } + } + } + + void saveIndex() { + String handle = "index"; + XsbReader saver = new XsbReader(handle); + saver.writeIndexData(); + saver.writeRealHeader(handle, FILETYPE_SCHEMAINDEX); + saver.writeIndexData(); + saver.writeEnd(); + } + + void savePointers() { + savePointersForComponents(globalElements(), getMetadataPath() + "/element/"); + savePointersForComponents(globalAttributes(), getMetadataPath() + "/attribute/"); + savePointersForComponents(modelGroups(), getMetadataPath() + "/modelgroup/"); + savePointersForComponents(attributeGroups(), getMetadataPath() + "/attributegroup/"); + savePointersForComponents(globalTypes(), getMetadataPath() + "/type/"); + savePointersForComponents(identityConstraints(), getMetadataPath() + "/identityconstraint/"); + savePointersForNamespaces(_namespaces, getMetadataPath() + "/namespace/"); + savePointersForClassnames(_typeRefsByClassname.keySet(), getMetadataPath() + "/javaname/"); + savePointersForComponents(redefinedModelGroups(), getMetadataPath() + "/redefinedmodelgroup/"); + savePointersForComponents(redefinedAttributeGroups(), getMetadataPath() + "/redefinedattributegroup/"); + savePointersForComponents(redefinedGlobalTypes(), getMetadataPath() + "/redefinedtype/"); + } + + void savePointersForComponents(SchemaComponent[] components, String dir) { + for (SchemaComponent component : components) { + savePointerFile(dir + QNameHelper.hexsafedir(component.getName()), _name); + } + } + + void savePointersForClassnames(Set classnames, String dir) { + for (String classname : classnames) { + savePointerFile(dir + classname.replace('.', '/'), _name); + } + } + + void savePointersForNamespaces(Set namespaces, String dir) { + for (String ns : namespaces) { + savePointerFile(dir + QNameHelper.hexsafedir(new QName(ns, "xmlns")), _name); + } + } + + void savePointerFile(String filename, String name) { + XsbReader saver = new XsbReader(filename); + saver.writeString(name); + saver.writeRealHeader(filename, FILETYPE_SCHEMAPOINTER); + saver.writeString(name); + saver.writeEnd(); + } + + /** + * The strategy here is to copy the compiled TypeSystemHolder.template class + * to a new TypeSystemHolder.class needed by the schema type system. When + * saving a loader, we read the TypeSystemHolder.template class file and + * swap out the utf8 string constants with new ones to create a new + * TypeSystemHolder class file. This saves us the need to rely on javac + * to compile a generated .java file into the class file. + *

      + * See the JVM spec on how to interpret the bytes of a class file. + */ + void saveLoader() { + String indexClassName = SchemaTypeCodePrinter.indexClassForSystem(this); + String[] replace = makeClassStrings(indexClassName); + assert replace.length == HOLDER_TEMPLATE_NAMES.length; + + Repackager repackager = null; + if (_filer instanceof FilerImpl) { + repackager = ((FilerImpl) _filer).getRepackager(); + } + + final String outName = indexClassName.replace('.', '/') + ".class"; + try (DataInputStream in = new DataInputStream(getHolder()); + DataOutputStream out = new DataOutputStream(_filer.createBinaryFile(outName))) { + + // java magic + out.writeInt(in.readInt()); + + // java minor and major version + out.writeShort(in.readUnsignedShort()); + out.writeShort(in.readUnsignedShort()); + + int poolsize = in.readUnsignedShort(); + out.writeShort(poolsize); + + // the constant pool is indexed from 1 to poolsize-1 + for (int i = 1; i < poolsize; i++) { + int tag = in.readUnsignedByte(); + out.writeByte(tag); + + switch (tag) { + case CONSTANT_UTF8: + String value = in.readUTF(); + out.writeUTF(repackageConstant(value, replace, repackager)); + break; + + case CONSTANT_CLASS: + case CONSTANT_STRING: + out.writeShort(in.readUnsignedShort()); + break; + + case CONSTANT_NAMEANDTYPE: + case CONSTANT_METHOD: + case CONSTANT_FIELD: + case CONSTANT_INTERFACEMETHOD: + out.writeShort(in.readUnsignedShort()); + out.writeShort(in.readUnsignedShort()); + break; + + case CONSTANT_INTEGER: + case CONSTANT_FLOAT: + out.writeInt(in.readInt()); + break; + + case CONSTANT_LONG: + case CONSTANT_DOUBLE: + out.writeInt(in.readInt()); + out.writeInt(in.readInt()); + break; + + default: + throw new RuntimeException("Unexpected constant type: " + tag); + } + } + + // we're done with the class' constant pool, + // we can just copy the rest of the bytes + copy(in, out); + } catch (IOException e) { + // ok + } + } + + private InputStream getHolder() { + InputStream is = SchemaTypeSystemImpl.class.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE); + if (is != null) { + return is; + } + DefaultClassLoaderResourceLoader clLoader = new DefaultClassLoaderResourceLoader(); + is = clLoader.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE); + if (is != null) { + return is; + } + throw new SchemaTypeLoaderException("couldn't find resource: " + HOLDER_TEMPLATE_CLASSFILE, + _name, null, SchemaTypeLoaderException.IO_EXCEPTION); + } + + private static long copy(InputStream inp, OutputStream out) throws IOException { + final byte[] buff = new byte[4096]; + long totalCount = 0; + int readBytes; + do { + int todoBytes = buff.length; + readBytes = inp.read(buff, 0, todoBytes); + if (readBytes > 0) { + out.write(buff, 0, readBytes); + totalCount += readBytes; + } + } while (readBytes >= 0); + + return totalCount; + } + + private static final String HOLDER_TEMPLATE_CLASS = "org.apache.xmlbeans.impl.schema.TypeSystemHolder"; + private static final String HOLDER_TEMPLATE_CLASSFILE = "TypeSystemHolder.template"; + private static final String[] HOLDER_TEMPLATE_NAMES = makeClassStrings(HOLDER_TEMPLATE_CLASS); + + // constant pool entry types + private static final int CONSTANT_UTF8 = 1; + // private static final int CONSTANT_UNICODE = 2; + private static final int CONSTANT_INTEGER = 3; + private static final int CONSTANT_FLOAT = 4; + private static final int CONSTANT_LONG = 5; + private static final int CONSTANT_DOUBLE = 6; + private static final int CONSTANT_CLASS = 7; + private static final int CONSTANT_STRING = 8; + private static final int CONSTANT_FIELD = 9; + private static final int CONSTANT_METHOD = 10; + private static final int CONSTANT_INTERFACEMETHOD = 11; + private static final int CONSTANT_NAMEANDTYPE = 12; + + // MAX_UNSIGNED_SHORT + private static final int MAX_UNSIGNED_SHORT = Short.MAX_VALUE * 2 + 1; + + private static String repackageConstant(String value, String[] replace, Repackager repackager) { + for (int i = 0; i < HOLDER_TEMPLATE_NAMES.length; i++) { + if (HOLDER_TEMPLATE_NAMES[i].equals(value)) { + return replace[i]; + } + } + + if (repackager != null) { + return repackager.repackage(new StringBuffer(value)).toString(); + } + + return value; + } + + /** + * Construct an array of Strings found in a class file for a classname. + * For the class name 'a.b.C' it will generate an array of: + * 'a.b.C', 'a/b/C', 'La/b/C;', and 'class$a$b$C'. + */ + private static String[] makeClassStrings(String classname) { + String[] result = new String[4]; + + result[0] = classname; + result[1] = classname.replace('.', '/'); + result[2] = "L" + result[1] + ";"; + result[3] = "class$" + classname.replace('.', '$'); + + return result; + } + + private Map buildTypeRefsByClassname(Map typesByClassname) { + Map result = new LinkedHashMap<>(); + for (String className : typesByClassname.keySet()) { + result.put(className, typesByClassname.get(className).getRef()); + } + return result; + } + + private static Map buildComponentRefMap(SchemaComponent[] components) { + return buildComponentRefMap(Arrays.asList(components)); + } + + private static Map buildComponentRefMap(List components) { + return components.stream().collect(Collectors.toMap(SchemaComponent::getName, SchemaComponent::getComponentRef, + (u, v) -> v, LinkedHashMap::new)); + } + + private static List buildComponentRefList(SchemaComponent[] components) { + return buildComponentRefList(Arrays.asList(components)); + } + + private static List buildComponentRefList(List components) { + return components.stream().map(SchemaComponent::getComponentRef).collect(Collectors.toList()); + } + + private static Map buildDocumentMap(SchemaType[] types) { + return buildDocumentMap(Arrays.asList(types)); + } + + private static Map buildDocumentMap(List types) { + Map result = new LinkedHashMap<>(); + for (SchemaComponent comp : types) { + SchemaType type = (SchemaType) comp; + result.put(type.getDocumentElementName(), type.getRef()); + } + return result; + } + + private static Map buildAttributeTypeMap(SchemaType[] types) { + Map result = new LinkedHashMap<>(); + for (SchemaType type : types) { + result.put(type.getAttributeTypeAttributeName(), type.getRef()); + } + return result; + } + + private static Map buildAttributeTypeMap(List types) { + Map result = new LinkedHashMap<>(); + for (SchemaComponent comp : types) { + SchemaType type = (SchemaType) comp; + result.put(type.getAttributeTypeAttributeName(), type.getRef()); + } + return result; + } + + // Container operation + private SchemaContainer getContainer(String namespace) { + return _containers.get(namespace); + } + + private void addContainer(String namespace) { + SchemaContainer c = new SchemaContainer(namespace); + c.setTypeSystem(this); + _containers.put(namespace, c); + } + + private SchemaContainer getContainerNonNull(String namespace) { + SchemaContainer result = getContainer(namespace); + if (result == null) { + addContainer(namespace); + result = getContainer(namespace); + } + return result; + } + + @SuppressWarnings("unchecked") + private void buildContainersHelper(Map elements, BiConsumer adder) { + elements.forEach((k, v) -> adder.accept(getContainerNonNull(k.getNamespaceURI()), (T) v)); + } + + @SuppressWarnings("unchecked") + private void buildContainersHelper(List refs, List names, BiConsumer adder) { + Iterator it = refs.iterator(); + Iterator itname = names.iterator(); + while (it.hasNext()) { + String ns = itname.next().getNamespaceURI(); + SchemaContainer sc = getContainerNonNull(ns); + adder.accept(sc, (T) it.next()); + } + } + + // Only called during init + private void buildContainers(List redefTypeNames, List redefModelGroupNames, List redefAttributeGroupNames) { + // This method walks the reference maps and copies said references + // into the appropriate container + buildContainersHelper(_globalElements, SchemaContainer::addGlobalElement); + buildContainersHelper(_globalAttributes, SchemaContainer::addGlobalAttribute); + buildContainersHelper(_modelGroups, SchemaContainer::addModelGroup); + buildContainersHelper(_attributeGroups, SchemaContainer::addAttributeGroup); + buildContainersHelper(_identityConstraints, SchemaContainer::addIdentityConstraint); + buildContainersHelper(_globalTypes, SchemaContainer::addGlobalType); + buildContainersHelper(_attributeTypes, SchemaContainer::addAttributeType); + + // Some earlier .xsb versions don't have records for redefinitions + if (_redefinedGlobalTypes != null && _redefinedModelGroups != null && + _redefinedAttributeGroups != null) { + assert _redefinedGlobalTypes.size() == redefTypeNames.size(); + buildContainersHelper(_redefinedGlobalTypes, redefTypeNames, SchemaContainer::addRedefinedType); + buildContainersHelper(_redefinedModelGroups, redefModelGroupNames, SchemaContainer::addRedefinedModelGroup); + buildContainersHelper(_redefinedAttributeGroups, redefAttributeGroupNames, SchemaContainer::addRedefinedAttributeGroup); + } + // Some earlier .xsb versions don't have records for annotations + if (_annotations != null && !_annotations.isEmpty()) { + // BUGBUG(radup) + _annotations.forEach(getContainerNonNull("")::addAnnotation); + } + _containers.values().forEach(SchemaContainer::setImmutable); + } + + /** + * This is the crux of the container work and role. + * It makes a sweep over all containers and fixes each container's + * typesystem to point to this typesystem. + * Because SchemaComponents have a link to their containers, this has as + * effect all components now indirectly pointing to this typesystem + * even though they (as well as the typesystem itself) are immutable. + */ + private void fixupContainers() { + for (SchemaContainer container : _containers.values()) { + container.setTypeSystem(this); + container.setImmutable(); + } + } + + private void assertContainersHelper(Map comp, Function> fun, Function, ? extends Map> fun2) { + final Map temp = _containers.values().stream() + .map(fun).map(fun2 == null ? SchemaTypeSystemImpl::buildComponentRefMap : fun2) + .map(Map::entrySet).flatMap(Set::stream) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + assert comp.equals(temp); + } + + private void assertContainersHelper(List comp, Function> fun) { + final Set temp = _containers.values().stream() + .map(fun).map(SchemaTypeSystemImpl::buildComponentRefList) + .flatMap(List::stream).collect(Collectors.toSet()); + assert new HashSet<>(comp).equals(temp); + } + + private void assertContainersSynchronized() { + boolean assertEnabled = false; + // This code basically checks whether asserts are enabled so we don't do + // all the work if they arent + assert assertEnabled = true; + if (!assertEnabled) { + return; + } + + assertContainersHelper(_globalElements, SchemaContainer::globalElements, null); + assertContainersHelper(_globalAttributes, SchemaContainer::globalAttributes, null); + assertContainersHelper(_modelGroups, SchemaContainer::modelGroups, null); + assertContainersHelper(_modelGroups, SchemaContainer::modelGroups, null); + assertContainersHelper(_redefinedModelGroups, SchemaContainer::redefinedModelGroups); + assertContainersHelper(_attributeGroups, SchemaContainer::attributeGroups, null); + assertContainersHelper(_redefinedAttributeGroups, SchemaContainer::redefinedAttributeGroups); + assertContainersHelper(_globalTypes, SchemaContainer::globalTypes, null); + assertContainersHelper(_redefinedGlobalTypes, SchemaContainer::redefinedGlobalTypes); + assertContainersHelper(_documentTypes, SchemaContainer::documentTypes, SchemaTypeSystemImpl::buildDocumentMap); + assertContainersHelper(_attributeTypes, SchemaContainer::attributeTypes, SchemaTypeSystemImpl::buildAttributeTypeMap); + assertContainersHelper(_identityConstraints, SchemaContainer::identityConstraints, null); + + // annotations + Set temp3 = _containers.values().stream() + .map(SchemaContainer::annotations).flatMap(List::stream).collect(Collectors.toSet()); + assert new HashSet<>(_annotations).equals(temp3); + // namespaces + Set temp4 = _containers.values().stream() + .map(SchemaContainer::getNamespace).collect(Collectors.toSet()); + assert _namespaces.equals(temp4); + } + + private static Random _random; + private static final byte[] _mask = new byte[128 / 8]; + + /** + * Fun, fun. Produce 128 bits of uniqueness randomly. + * We used to use SecureRandom, but now we don't because SecureRandom + * hits the filesystem and hangs us on a filesystem lock. It also eats + * a thread and other expensive resources.. :-). + *

      + * We don't really care that non-secure Random() can only do 48 bits of + * randomness, since we're certainly not going to be called more than 2^48 + * times within our process lifetime. + *

      + * Our real concern is that by seeding Random() with the current + * time, two users will end up with the same bits if they start a + * schema compilation within the same millisecond. That makes the + * probability of collision in the real world slightly too high. + * We're going to have millions of users, remember? With a million + * users, and one-compilation-per-day each, we'd see a collision every + * few months. + *

      + * So we'll just xor the results of random with our few extra + * bits of information computed below to help reduce the probability + * of collision by a few decimal places. To collide, you will have had + * to have the same amount of free memory, the same user name, timezone, + * and country, the same current directory, the same java classpath, + * the same operating system and jvm version, and the same choices of + * identity hashcodes for a few objects. And be started within the same + * millisecond. Or you can collide if you have a cosmic 128-bit mathematical + * coincidence. No worries. + */ + private static synchronized void nextBytes(byte[] result) { + if (_random == null) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream daos = new DataOutputStream(baos); + + // at least 10 bits of unqieueness, right? Maybe even 50 or 60. + daos.writeInt(System.identityHashCode(SchemaTypeSystemImpl.class)); + String[] props = new String[]{"user.name", "user.dir", "user.timezone", "user.country", "java.class.path", "java.home", "java.vendor", "java.version", "os.version"}; + for (String s : props) { + String prop = SystemProperties.getProperty(s); + if (prop != null) { + daos.writeUTF(prop); + daos.writeInt(System.identityHashCode(prop)); + } + } + daos.writeLong(Runtime.getRuntime().freeMemory()); + daos.close(); + byte[] bytes = baos.toByteArray(); + for (int i = 0; i < bytes.length; i++) { + int j = i % _mask.length; + _mask[j] *= 21; + _mask[j] += i; + } + } catch (IOException e) { + XBeanDebug.logException(e); + } + + _random = new Random(System.currentTimeMillis()); + } + _random.nextBytes(result); + for (int i = 0; i < result.length; i++) { + int j = i & _mask.length; + result[i] ^= _mask[j]; + } + } + + public SchemaTypeSystemImpl(String nameForSystem) { + // if we have no name, select a random one + if (nameForSystem == null) { + // get 128 random bits (that'll be 32 hex digits) + byte[] bytes = new byte[128 / 8]; + nextBytes(bytes); + nameForSystem = "s" + new String(HexBin.encode(bytes), StandardCharsets.ISO_8859_1); + } + + _name = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN.replace('/', '.') + ".system." + nameForSystem; + _basePackage = nameToPathString(_name); + _classloader = null; + } + + public void loadFromStscState(StscState state) { + assert (_classloader == null); + _localHandles = new HandlePool(); + _globalElements = buildComponentRefMap(state.globalElements()); + _globalAttributes = buildComponentRefMap(state.globalAttributes()); + _modelGroups = buildComponentRefMap(state.modelGroups()); + _redefinedModelGroups = buildComponentRefList(state.redefinedModelGroups()); + _attributeGroups = buildComponentRefMap(state.attributeGroups()); + _redefinedAttributeGroups = buildComponentRefList(state.redefinedAttributeGroups()); + _globalTypes = buildComponentRefMap(state.globalTypes()); + _redefinedGlobalTypes = buildComponentRefList(state.redefinedGlobalTypes()); + _documentTypes = buildDocumentMap(state.documentTypes()); + _attributeTypes = buildAttributeTypeMap(state.attributeTypes()); + _typeRefsByClassname = buildTypeRefsByClassname(state.typesByClassname()); + _identityConstraints = buildComponentRefMap(state.idConstraints()); + _annotations = state.annotations(); + _namespaces = new HashSet<>(Arrays.asList(state.getNamespaces())); + _containers = state.getContainerMap(); + fixupContainers(); + // Checks that data in the containers matches the lookup maps + assertContainersSynchronized(); + setDependencies(state.getDependencies()); + } + + final SchemaTypeSystemImpl getTypeSystem() { + return this; + } + + void setDependencies(SchemaDependencies deps) { + _deps = deps; + } + + SchemaDependencies getDependencies() { + return _deps; + } + + // EXPERIMENTAL + public boolean isIncomplete() { + return _incomplete; + } + + // EXPERIMENTAL + void setIncomplete(boolean incomplete) { + _incomplete = incomplete; + } + + static class StringPool { + private final List intsToStrings = new ArrayList<>(); + private final Map stringsToInts = new HashMap<>(); + private final String _handle; + private final String _name; + + /** + * Constructs an empty StringPool to be filled with strings. + */ + StringPool(String handle, String name) { + _handle = handle; + _name = name; + intsToStrings.add(null); + } + + int codeForString(String str) { + if (str == null) { + return 0; + } + Integer result = stringsToInts.get(str); + if (result == null) { + result = intsToStrings.size(); + intsToStrings.add(str); + stringsToInts.put(str, result); + } + return result; + } + + String stringForCode(int code) { + if (code == 0) { + return null; + } + return intsToStrings.get(code); + } + + void writeTo(DataOutputStream output) { + if (intsToStrings.size() >= MAX_UNSIGNED_SHORT) { + throw new SchemaTypeLoaderException("Too many strings (" + intsToStrings.size() + ")", _name, _handle, SchemaTypeLoaderException.INT_TOO_LARGE); + } + + try { + output.writeShort(intsToStrings.size()); + boolean isNext = false; + for (String str : intsToStrings) { + if (isNext) { + output.writeUTF(str); + } + isNext = true; + } + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + void readFrom(DataInputStream input) { + if (intsToStrings.size() != 1 || stringsToInts.size() != 0) { + throw new IllegalStateException(); + } + + try { + int size = input.readUnsignedShort(); + for (int i = 1; i < size; i++) { + String str = input.readUTF().intern(); + int code = codeForString(str); + if (code != i) { + throw new IllegalStateException(); + } + } + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage() == null ? e.getMessage() : "IO Exception", _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + } + + class HandlePool { + private final Map _handlesToRefs = new LinkedHashMap<>(); + // populated on write + private final Map _componentsToHandles = new LinkedHashMap<>(); + private boolean _started; + + /** + * Constructs an empty HandlePool to be populated. + */ + HandlePool() { + } + + private String addUniqueHandle(SchemaComponent obj, String base) { + // we lowercase handles because of case-insensitive Windows filenames!!! + base = base.toLowerCase(Locale.ROOT); + String handle = base; + for (int index = 2; _handlesToRefs.containsKey(handle); index++) { + handle = base + index; + } + _handlesToRefs.put(handle, obj.getComponentRef()); + _componentsToHandles.put(obj, handle); + return handle; + } + + String handleForComponent(SchemaComponent comp) { + if (comp == null) { + return null; + } + if (comp.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + if (comp instanceof SchemaType) { + return handleForType((SchemaType) comp); + } + if (comp instanceof SchemaGlobalElement) { + return handleForElement((SchemaGlobalElement) comp); + } + if (comp instanceof SchemaGlobalAttribute) { + return handleForAttribute((SchemaGlobalAttribute) comp); + } + if (comp instanceof SchemaModelGroup) { + return handleForModelGroup((SchemaModelGroup) comp); + } + if (comp instanceof SchemaAttributeGroup) { + return handleForAttributeGroup((SchemaAttributeGroup) comp); + } + if (comp instanceof SchemaIdentityConstraint) { + return handleForIdentityConstraint((SchemaIdentityConstraint) comp); + } + throw new IllegalStateException("Component type cannot have a handle"); + } + + String handleForElement(SchemaGlobalElement element) { + if (element == null) { + return null; + } + if (element.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + String handle = _componentsToHandles.get(element); + if (handle == null) { + handle = addUniqueHandle(element, NameUtil.upperCamelCase(element.getName().getLocalPart()) + "Element"); + } + return handle; + } + + String handleForAttribute(SchemaGlobalAttribute attribute) { + if (attribute == null) { + return null; + } + if (attribute.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + String handle = _componentsToHandles.get(attribute); + if (handle == null) { + handle = addUniqueHandle(attribute, NameUtil.upperCamelCase(attribute.getName().getLocalPart()) + "Attribute"); + } + return handle; + } + + String handleForModelGroup(SchemaModelGroup group) { + if (group == null) { + return null; + } + if (group.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + String handle = _componentsToHandles.get(group); + if (handle == null) { + handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "ModelGroup"); + } + return handle; + } + + String handleForAttributeGroup(SchemaAttributeGroup group) { + if (group == null) { + return null; + } + if (group.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + String handle = _componentsToHandles.get(group); + if (handle == null) { + handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "AttributeGroup"); + } + return handle; + } + + String handleForIdentityConstraint(SchemaIdentityConstraint idc) { + if (idc == null) { + return null; + } + if (idc.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + String handle = _componentsToHandles.get(idc); + if (handle == null) { + handle = addUniqueHandle(idc, NameUtil.upperCamelCase(idc.getName().getLocalPart()) + "IdentityConstraint"); + } + return handle; + } + + String handleForType(SchemaType type) { + if (type == null) { + return null; + } + if (type.getTypeSystem() != getTypeSystem()) { + throw new IllegalArgumentException("Cannot supply handles for types from another type system"); + } + String handle = _componentsToHandles.get(type); + if (handle == null) { + QName name = type.getName(); + String suffix = ""; + if (name == null) { + if (type.isDocumentType()) { + name = type.getDocumentElementName(); + suffix = "Doc"; + } else if (type.isAttributeType()) { + name = type.getAttributeTypeAttributeName(); + suffix = "AttrType"; + } else if (type.getContainerField() != null) { + name = type.getContainerField().getName(); + suffix = type.getContainerField().isAttribute() ? "Attr" : "Elem"; + } + } + + String baseName; + String uniq = Integer.toHexString(type.toString().hashCode() | 0x80000000).substring(4).toUpperCase(Locale.ROOT); + if (name == null) { + baseName = "Anon" + uniq + "Type"; + } else { + baseName = NameUtil.upperCamelCase(name.getLocalPart()) + uniq + suffix + "Type"; + } + + handle = addUniqueHandle(type, baseName); + } + + return handle; + } + + SchemaComponent.Ref refForHandle(String handle) { + if (handle == null) { + return null; + } + + return _handlesToRefs.get(handle); + } + + void startWriteMode() { + _started = true; + _componentsToHandles.clear(); + for (String handle : _handlesToRefs.keySet()) { + SchemaComponent comp = _handlesToRefs.get(handle).getComponent(); + _componentsToHandles.put(comp, handle); + } + } + + } + + private final String _name; + private final String _basePackage; + + // EXPERIMENTAL: recovery from compilation errors and partial type systems + private boolean _incomplete = false; + + // classloader is available for sts's that were compiled and loaded, not dynamic ones + private ClassLoader _classloader; + + // the loader for loading .xsb resources + private ResourceLoader _resourceLoader; + + // the following is used to link references during load + SchemaTypeLoader _linker; + + private HandlePool _localHandles; + private Filer _filer; + + // top-level annotations + private List _annotations; + + // container + private Map _containers = new HashMap<>(); + // dependencies + private SchemaDependencies _deps; + + private List _redefinedModelGroups; + private List _redefinedAttributeGroups; + private List _redefinedGlobalTypes; + + // actual type system data, map QNames -> SchemaComponent.Ref + private Map _globalElements; + private Map _globalAttributes; + private Map _modelGroups; + private Map _attributeGroups; + private Map _globalTypes; + private Map _documentTypes; + private Map _attributeTypes; + private Map _identityConstraints = Collections.emptyMap(); + private Map _typeRefsByClassname = new HashMap<>(); + private Set _namespaces; + + static private final SchemaType[] EMPTY_ST_ARRAY = new SchemaType[0]; + static private final SchemaGlobalElement[] EMPTY_GE_ARRAY = new SchemaGlobalElement[0]; + static private final SchemaGlobalAttribute[] EMPTY_GA_ARRAY = new SchemaGlobalAttribute[0]; + static private final SchemaModelGroup[] EMPTY_MG_ARRAY = new SchemaModelGroup[0]; + static private final SchemaAttributeGroup[] EMPTY_AG_ARRAY = new SchemaAttributeGroup[0]; + static private final SchemaIdentityConstraint[] EMPTY_IC_ARRAY = new SchemaIdentityConstraint[0]; + static private final SchemaAnnotation[] EMPTY_ANN_ARRAY = new SchemaAnnotation[0]; + + public void saveToDirectory(File classDir) { + save(new FilerImpl(classDir, null, null, false, false)); + } + + public void save(Filer filer) { + if (_incomplete) { + throw new IllegalStateException("Incomplete SchemaTypeSystems cannot be saved."); + } + + if (filer == null) { + throw new IllegalArgumentException("filer must not be null"); + } + _filer = filer; + + _localHandles.startWriteMode(); + saveTypesRecursively(globalTypes()); + saveTypesRecursively(documentTypes()); + saveTypesRecursively(attributeTypes()); + saveGlobalElements(globalElements()); + saveGlobalAttributes(globalAttributes()); + saveModelGroups(modelGroups()); + saveAttributeGroups(attributeGroups()); + saveIdentityConstraints(identityConstraints()); + + saveTypesRecursively(redefinedGlobalTypes()); + saveModelGroups(redefinedModelGroups()); + saveAttributeGroups(redefinedAttributeGroups()); + + saveIndex(); + savePointers(); + + saveLoader(); + } + + void saveTypesRecursively(SchemaType[] types) { + for (SchemaType type : types) { + if (type.getTypeSystem() != getTypeSystem()) { + continue; + } + saveType(type); + saveTypesRecursively(type.getAnonymousTypes()); + } + } + + public void saveGlobalElements(SchemaGlobalElement[] elts) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + for (SchemaGlobalElement elt : elts) { + saveGlobalElement(elt); + } + } + + public void saveGlobalAttributes(SchemaGlobalAttribute[] attrs) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + for (SchemaGlobalAttribute attr : attrs) { + saveGlobalAttribute(attr); + } + } + + public void saveModelGroups(SchemaModelGroup[] groups) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + for (SchemaModelGroup group : groups) { + saveModelGroup(group); + } + } + + public void saveAttributeGroups(SchemaAttributeGroup[] groups) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + for (SchemaAttributeGroup group : groups) { + saveAttributeGroup(group); + } + } + + public void saveIdentityConstraints(SchemaIdentityConstraint[] idcs) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + for (SchemaIdentityConstraint idc : idcs) { + saveIdentityConstraint(idc); + } + } + + public void saveGlobalElement(SchemaGlobalElement elt) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + String handle = _localHandles.handleForElement(elt); + XsbReader saver = new XsbReader(handle); + saver.writeParticleData((SchemaParticle) elt); + saver.writeString(elt.getSourceName()); + saver.writeRealHeader(handle, FILETYPE_SCHEMAELEMENT); + saver.writeParticleData((SchemaParticle) elt); + saver.writeString(elt.getSourceName()); + saver.writeEnd(); + } + + public void saveGlobalAttribute(SchemaGlobalAttribute attr) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + String handle = _localHandles.handleForAttribute(attr); + XsbReader saver = new XsbReader(handle); + saver.writeAttributeData(attr); + saver.writeString(attr.getSourceName()); + saver.writeRealHeader(handle, FILETYPE_SCHEMAATTRIBUTE); + saver.writeAttributeData(attr); + saver.writeString(attr.getSourceName()); + saver.writeEnd(); + } + + public void saveModelGroup(SchemaModelGroup grp) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + String handle = _localHandles.handleForModelGroup(grp); + XsbReader saver = new XsbReader(handle); + saver.writeModelGroupData(grp); + saver.writeRealHeader(handle, FILETYPE_SCHEMAMODELGROUP); + saver.writeModelGroupData(grp); + saver.writeEnd(); + } + + public void saveAttributeGroup(SchemaAttributeGroup grp) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + String handle = _localHandles.handleForAttributeGroup(grp); + XsbReader saver = new XsbReader(handle); + saver.writeAttributeGroupData(grp); + saver.writeRealHeader(handle, FILETYPE_SCHEMAATTRIBUTEGROUP); + saver.writeAttributeGroupData(grp); + saver.writeEnd(); + } + + public void saveIdentityConstraint(SchemaIdentityConstraint idc) { + if (_incomplete) { + throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); + } + String handle = _localHandles.handleForIdentityConstraint(idc); + XsbReader saver = new XsbReader(handle); + saver.writeIdConstraintData(idc); + saver.writeRealHeader(handle, FILETYPE_SCHEMAIDENTITYCONSTRAINT); + saver.writeIdConstraintData(idc); + saver.writeEnd(); + } + + void saveType(SchemaType type) { + String handle = _localHandles.handleForType(type); + XsbReader saver = new XsbReader(handle); + saver.writeTypeData(type); + saver.writeRealHeader(handle, FILETYPE_SCHEMATYPE); + saver.writeTypeData(type); + saver.writeEnd(); + } + + public static String crackPointer(InputStream stream) { + try (DataInputStream input = new DataInputStream(stream)) { + + int magic = input.readInt(); + if (magic != DATA_BABE) { + return null; + } + + int majorver = input.readShort(); + int minorver = input.readShort(); + + if (majorver != MAJOR_VERSION) { + return null; + } + + if (minorver > MINOR_VERSION) { + return null; + } + + if (minorver >= 18) { + input.readShort(); // release number present in atLeast(2, 18, 0) + } + + int actualfiletype = input.readShort(); + if (actualfiletype != FILETYPE_SCHEMAPOINTER) { + return null; + } + + StringPool stringPool = new StringPool("pointer", "unk"); + stringPool.readFrom(input); + + return stringPool.stringForCode(input.readShort()); + } catch (IOException e) { + return null; + } + } + + private class XsbReader { + DataInputStream _input; + DataOutputStream _output; + StringPool _stringPool; + String _handle; + private int _majorver; + private int _minorver; + private int _releaseno; + int _actualfiletype; + + public XsbReader(String handle, int filetype) { + String resourcename = _basePackage + handle + ".xsb"; + InputStream rawinput = getLoaderStream(resourcename); + if (rawinput == null) { + throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Could not locate compiled schema resource " + resourcename, _name, handle, SchemaTypeLoaderException.NO_RESOURCE); + } + + _input = new DataInputStream(rawinput); + _handle = handle; + + int magic = readInt(); + if (magic != DATA_BABE) { + throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Wrong magic cookie", _name, handle, SchemaTypeLoaderException.WRONG_MAGIC_COOKIE); + } + + _majorver = readShort(); + _minorver = readShort(); + + if (_majorver != MAJOR_VERSION) { + throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Wrong major version - expecting " + MAJOR_VERSION + ", got " + _majorver, _name, handle, SchemaTypeLoaderException.WRONG_MAJOR_VERSION); + } + + if (_minorver > MINOR_VERSION) { + throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Incompatible minor version - expecting up to " + MINOR_VERSION + ", got " + _minorver, _name, handle, SchemaTypeLoaderException.WRONG_MINOR_VERSION); + } + + // Clip to 14 because we're not backward compatible with earlier + // minor versions. Remove this when upgrading to a new major + // version + + if (_minorver < 14) { + throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Incompatible minor version - expecting at least 14, got " + _minorver, _name, handle, SchemaTypeLoaderException.WRONG_MINOR_VERSION); + } + + if (atLeast(2, 18, 0)) { + _releaseno = readShort(); + } + + int actualfiletype = readShort(); + if (actualfiletype != filetype && filetype != 0xFFFF) { + throw new SchemaTypeLoaderException("XML-BEANS compiled schema: File has the wrong type - expecting type " + filetype + ", got type " + actualfiletype, _name, handle, SchemaTypeLoaderException.WRONG_FILE_TYPE); + } + + _stringPool = new StringPool(_handle, _name); + _stringPool.readFrom(_input); + + _actualfiletype = actualfiletype; + } + + protected boolean atLeast(int majorver, int minorver, int releaseno) { + if (_majorver > majorver) { + return true; + } + if (_majorver < majorver) { + return false; + } + if (_minorver > minorver) { + return true; + } + if (_minorver < minorver) { + return false; + } + return (_releaseno >= releaseno); + } + + protected boolean atMost(int majorver, int minorver, int releaseno) { + if (_majorver > majorver) { + return false; + } + if (_majorver < majorver) { + return true; + } + if (_minorver > minorver) { + return false; + } + if (_minorver < minorver) { + return true; + } + return (_releaseno <= releaseno); + } + + int getActualFiletype() { + return _actualfiletype; + } + + XsbReader(String handle) { + _handle = handle; + _stringPool = new StringPool(_handle, _name); + } + + void writeRealHeader(String handle, int filetype) { + // hackeroo: if handle contains a "/" it's not relative. + String resourcename; + + if (handle.indexOf('/') >= 0) { + resourcename = handle + ".xsb"; + } else { + resourcename = _basePackage + handle + ".xsb"; + } + + OutputStream rawoutput = getSaverStream(resourcename); + if (rawoutput == null) { + throw new SchemaTypeLoaderException("Could not write compiled schema resource " + resourcename, _name, handle, SchemaTypeLoaderException.NOT_WRITEABLE); + } + + _output = new DataOutputStream(rawoutput); + _handle = handle; + + writeInt(DATA_BABE); + writeShort(MAJOR_VERSION); + writeShort(MINOR_VERSION); + writeShort(RELEASE_NUMBER); + writeShort(filetype); + + _stringPool.writeTo(_output); + } + + void readEnd() { + try { + if (_input != null) { + _input.close(); + } + } catch (IOException e) { + // oh, well. + } + _input = null; + _stringPool = null; + _handle = null; + } + + void writeEnd() { + try { + if (_output != null) { + _output.flush(); + _output.close(); + } + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + _output = null; + _stringPool = null; + _handle = null; + } + + int fileTypeFromComponentType(int componentType) { + switch (componentType) { + case SchemaComponent.TYPE: + return SchemaTypeSystemImpl.FILETYPE_SCHEMATYPE; + case SchemaComponent.ELEMENT: + return SchemaTypeSystemImpl.FILETYPE_SCHEMAELEMENT; + case SchemaComponent.ATTRIBUTE: + return SchemaTypeSystemImpl.FILETYPE_SCHEMAATTRIBUTE; + case SchemaComponent.MODEL_GROUP: + return SchemaTypeSystemImpl.FILETYPE_SCHEMAMODELGROUP; + case SchemaComponent.ATTRIBUTE_GROUP: + return SchemaTypeSystemImpl.FILETYPE_SCHEMAATTRIBUTEGROUP; + case SchemaComponent.IDENTITY_CONSTRAINT: + return SchemaTypeSystemImpl.FILETYPE_SCHEMAIDENTITYCONSTRAINT; + default: + throw new IllegalStateException("Unexpected component type"); + } + } + + void writeIndexData() { + // has a handle pool (count, handle/type, handle/type...) + writeHandlePool(_localHandles); + + // then a qname map of global elements (count, qname/handle, qname/handle...) + writeQNameMap(globalElements()); + + // qname map of global attributes + writeQNameMap(globalAttributes()); + + // qname map of model groups + writeQNameMap(modelGroups()); + + // qname map of attribute groups + writeQNameMap(attributeGroups()); + + // qname map of identity constraints + writeQNameMap(identityConstraints()); + + // qname map of global types + writeQNameMap(globalTypes()); + + // qname map of document types, by the qname of the contained element + writeDocumentTypeMap(documentTypes()); + + // qname map of attribute types, by the qname of the contained attribute + writeAttributeTypeMap(attributeTypes()); + + // all the types by classname + writeClassnameMap(_typeRefsByClassname); + + // all the namespaces + writeNamespaces(_namespaces); + + // VERSION 2.15 and newer below + writeQNameMap(redefinedGlobalTypes()); + writeQNameMap(redefinedModelGroups()); + writeQNameMap(redefinedAttributeGroups()); + writeAnnotations(annotations()); + } + + void writeHandlePool(HandlePool pool) { + writeShort(pool._componentsToHandles.size()); + pool._componentsToHandles.forEach((comp, handle) -> { + writeString(handle); + writeShort(fileTypeFromComponentType(comp.getComponentType())); + }); + } + + void readHandlePool(HandlePool pool) { + if (pool._handlesToRefs.size() != 0 || pool._started) { + throw new IllegalStateException("Nonempty handle set before read"); + } + + int size = readShort(); + for (int i = 0; i < size; i++) { + String handle = readString(); + int code = readShort(); + SchemaComponent.Ref result; + switch (code) { + case FILETYPE_SCHEMATYPE: + result = new SchemaType.Ref(getTypeSystem(), handle); + break; + case FILETYPE_SCHEMAELEMENT: + result = new SchemaGlobalElement.Ref(getTypeSystem(), handle); + break; + case FILETYPE_SCHEMAATTRIBUTE: + result = new SchemaGlobalAttribute.Ref(getTypeSystem(), handle); + break; + case FILETYPE_SCHEMAMODELGROUP: + result = new SchemaModelGroup.Ref(getTypeSystem(), handle); + break; + case FILETYPE_SCHEMAATTRIBUTEGROUP: + result = new SchemaAttributeGroup.Ref(getTypeSystem(), handle); + break; + case FILETYPE_SCHEMAIDENTITYCONSTRAINT: + result = new SchemaIdentityConstraint.Ref(getTypeSystem(), handle); + break; + default: + throw new SchemaTypeLoaderException("Schema index has an unrecognized entry of type " + code, _name, handle, SchemaTypeLoaderException.UNRECOGNIZED_INDEX_ENTRY); + } + pool._handlesToRefs.put(handle, result); + } + } + + int readShort() { + try { + return _input.readUnsignedShort(); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + void writeShort(int s) { + if (s >= MAX_UNSIGNED_SHORT || s < -1) { + throw new SchemaTypeLoaderException("Value " + s + " out of range: must fit in a 16-bit unsigned short.", _name, _handle, SchemaTypeLoaderException.INT_TOO_LARGE); + } + if (_output != null) { + try { + _output.writeShort(s); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + } + + int readInt() { + try { + return _input.readInt(); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + void writeInt(int i) { + if (_output != null) { + try { + _output.writeInt(i); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + } + + String readString() { + return _stringPool.stringForCode(readShort()); + } + + void writeString(String str) { + int code = _stringPool.codeForString(str); + writeShort(code); + } + + QName readQName() { + String namespace = readString(); + String localname = readString(); + if (localname == null) { + return null; + } + return new QName(namespace, localname); + } + + void writeQName(QName qname) { + if (qname == null) { + writeString(null); + writeString(null); + return; + } + writeString(qname.getNamespaceURI()); + writeString(qname.getLocalPart()); + } + + SOAPArrayType readSOAPArrayType() { + QName qName = readQName(); + String dimensions = readString(); + if (qName == null) { + return null; + } + return new SOAPArrayType(qName, dimensions); + } + + void writeSOAPArrayType(SOAPArrayType arrayType) { + if (arrayType == null) { + writeQName(null); + writeString(null); + } else { + writeQName(arrayType.getQName()); + writeString(arrayType.soap11DimensionString()); + } + } + + void writeAnnotation(SchemaAnnotation a) { + // Write attributes + if (a == null) { + writeInt(-1); + return; + } + SchemaAnnotation.Attribute[] attributes = a.getAttributes(); + writeInt(attributes.length); + for (SchemaAnnotation.Attribute attribute : attributes) { + QName name = attribute.getName(); + String value = attribute.getValue(); + String valueURI = attribute.getValueUri(); + writeQName(name); + writeString(value); + writeString(valueURI); + } + + // Write documentation items + XmlObject[] documentationItems = a.getUserInformation(); + writeInt(documentationItems.length); + XmlOptions opt = new XmlOptions().setSaveOuter().setSaveAggressiveNamespaces(); + for (XmlObject doc : documentationItems) { + writeString(doc.xmlText(opt)); + } + + // Write application info items + XmlObject[] appInfoItems = a.getApplicationInformation(); + writeInt(appInfoItems.length); + for (XmlObject doc : appInfoItems) { + writeString(doc.xmlText(opt)); + } + } + + SchemaAnnotation readAnnotation(SchemaContainer c) { + if (!atLeast(2, 19, 0)) { + return null; // no annotations for this version of the file + } + // Read attributes + int n = readInt(); + if (n == -1) { + return null; + } + SchemaAnnotation.Attribute[] attributes = + new SchemaAnnotation.Attribute[n]; + for (int i = 0; i < n; i++) { + QName name = readQName(); + String value = readString(); + String valueUri = null; + if (atLeast(2, 24, 0)) { + valueUri = readString(); + } + attributes[i] = new SchemaAnnotationImpl.AttributeImpl(name, value, valueUri); + } + + // Read documentation items + n = readInt(); + String[] docStrings = new String[n]; + for (int i = 0; i < n; i++) { + docStrings[i] = readString(); + } + + // Read application info items + n = readInt(); + String[] appInfoStrings = new String[n]; + for (int i = 0; i < n; i++) { + appInfoStrings[i] = readString(); + } + + return new SchemaAnnotationImpl(c, appInfoStrings, + docStrings, attributes); + } + + void writeAnnotations(SchemaAnnotation[] anns) { + writeInt(anns.length); + for (SchemaAnnotation ann : anns) { + writeAnnotation(ann); + } + } + + List readAnnotations() { + int n = readInt(); + List result = new ArrayList<>(n); + // BUGBUG(radup) + SchemaContainer container = getContainerNonNull(""); + for (int i = 0; i < n; i++) { + result.add(readAnnotation(container)); + } + return result; + } + + SchemaComponent.Ref readHandle() { + String handle = readString(); + if (handle == null) { + return null; + } + + if (handle.charAt(0) != '_') { + return _localHandles.refForHandle(handle); + } + + switch (handle.charAt(2)) { + case 'I': // _BI_ - built-in schema type system + SchemaType st = (SchemaType) BuiltinSchemaTypeSystem.get().resolveHandle(handle); + if (st != null) { + return st.getRef(); + } + st = (SchemaType) XQuerySchemaTypeSystem.get().resolveHandle(handle); + return st.getRef(); + case 'T': // _XT_ - external type + return _linker.findTypeRef(QNameHelper.forPretty(handle, 4)); + case 'E': // _XE_ - external element + return _linker.findElementRef(QNameHelper.forPretty(handle, 4)); + case 'A': // _XA_ - external attribute + return _linker.findAttributeRef(QNameHelper.forPretty(handle, 4)); + case 'M': // _XM_ - external model group + return _linker.findModelGroupRef(QNameHelper.forPretty(handle, 4)); + case 'N': // _XN_ - external attribute group + return _linker.findAttributeGroupRef(QNameHelper.forPretty(handle, 4)); + case 'D': // _XD_ - external identity constraint + return _linker.findIdentityConstraintRef(QNameHelper.forPretty(handle, 4)); + case 'R': // _XR_ - external ref to attribute's type + // deprecated: replaced by _XY_ + SchemaGlobalAttribute attr = _linker.findAttribute(QNameHelper.forPretty(handle, 4)); + if (attr == null) { + throw new SchemaTypeLoaderException("Cannot resolve attribute for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); + } + return attr.getType().getRef(); + case 'S': // _XS_ - external ref to element's type + // deprecated: replaced by _XY_ + SchemaGlobalElement elem = _linker.findElement(QNameHelper.forPretty(handle, 4)); + if (elem == null) { + throw new SchemaTypeLoaderException("Cannot resolve element for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); + } + return elem.getType().getRef(); + case 'O': // _XO_ - external ref to document type + return _linker.findDocumentTypeRef(QNameHelper.forPretty(handle, 4)); + case 'Y': // _XY_ - external ref to any possible type + SchemaType type = _linker.typeForSignature(handle.substring(4)); + if (type == null) { + throw new SchemaTypeLoaderException("Cannot resolve type for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); + } + return type.getRef(); + default: + throw new SchemaTypeLoaderException("Cannot resolve handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); + } + } + + void writeHandle(SchemaComponent comp) { + if (comp == null || comp.getTypeSystem() == getTypeSystem()) { + writeString(_localHandles.handleForComponent(comp)); + return; + } + + switch (comp.getComponentType()) { + case SchemaComponent.ATTRIBUTE: + writeString("_XA_" + QNameHelper.pretty(comp.getName())); + return; + case SchemaComponent.MODEL_GROUP: + writeString("_XM_" + QNameHelper.pretty(comp.getName())); + return; + case SchemaComponent.ATTRIBUTE_GROUP: + writeString("_XN_" + QNameHelper.pretty(comp.getName())); + return; + case SchemaComponent.ELEMENT: + writeString("_XE_" + QNameHelper.pretty(comp.getName())); + return; + case SchemaComponent.IDENTITY_CONSTRAINT: + writeString("_XD_" + QNameHelper.pretty(comp.getName())); + return; + case SchemaComponent.TYPE: + SchemaType type = (SchemaType) comp; + if (type.isBuiltinType()) { + writeString("_BI_" + type.getName().getLocalPart()); + return; + } + + // fix for CR120759 - added output of types _XR_ & _XS_ + // when an attribute (_XR_) or element (_XS_) declaration + // uses ref to refer to an attribute or element in another + // schema and the type of that attribute or element + // is an anonymous (local) type + // kkrouse 02/1/2005: _XR_ and _XS_ refs are replaced by _XY_ + if (type.getName() != null) { + writeString("_XT_" + QNameHelper.pretty(type.getName())); + } else if (type.isDocumentType()) { + // Substitution groups will create document types that + // extend from other document types, possibly in + // different jars + writeString("_XO_" + QNameHelper.pretty(type.getDocumentElementName())); + } else { + // fix for XMLBEANS-105: + // save out the external type reference using the type's signature. + writeString("_XY_" + type.toString()); + } + + return; + + default: + assert (false); + throw new SchemaTypeLoaderException("Cannot write handle for component " + comp, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); + } + } + + SchemaType.Ref readTypeRef() { + return (SchemaType.Ref) readHandle(); + } + + void writeType(SchemaType type) { + writeHandle(type); + } + + Map readQNameRefMap() { + Map result = new HashMap<>(); + int size = readShort(); + for (int i = 0; i < size; i++) { + QName name = readQName(); + SchemaComponent.Ref obj = readHandle(); + result.put(name, obj); + } + return result; + } + + List readQNameRefMapAsList(List names) { + int size = readShort(); + List result = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + QName name = readQName(); + SchemaComponent.Ref obj = readHandle(); + result.add(obj); + names.add(name); + } + return result; + } + + void writeQNameMap(SchemaComponent[] components) { + writeShort(components.length); + for (SchemaComponent component : components) { + writeQName(component.getName()); + writeHandle(component); + } + } + + void writeDocumentTypeMap(SchemaType[] doctypes) { + writeShort(doctypes.length); + for (SchemaType doctype : doctypes) { + writeQName(doctype.getDocumentElementName()); + writeHandle(doctype); + } + } + + void writeAttributeTypeMap(SchemaType[] attrtypes) { + writeShort(attrtypes.length); + for (SchemaType attrtype : attrtypes) { + writeQName(attrtype.getAttributeTypeAttributeName()); + writeHandle(attrtype); + } + } + + SchemaType.Ref[] readTypeRefArray() { + int size = readShort(); + SchemaType.Ref[] result = new SchemaType.Ref[size]; + for (int i = 0; i < size; i++) { + result[i] = readTypeRef(); + } + return result; + } + + void writeTypeArray(SchemaType[] array) { + writeShort(array.length); + for (SchemaType schemaType : array) { + writeHandle(schemaType); + } + } + + Map readClassnameRefMap() { + Map result = new HashMap<>(); + int size = readShort(); + for (int i = 0; i < size; i++) { + String name = readString(); + SchemaComponent.Ref obj = readHandle(); + result.put(name, obj); + } + return result; + } + + void writeClassnameMap(Map typesByClass) { + writeShort(typesByClass.size()); + typesByClass.forEach((className, ref) -> { + writeString(className); + writeHandle(((SchemaType.Ref) ref).get()); + }); + } + + Set readNamespaces() { + Set result = new HashSet<>(); + int size = readShort(); + for (int i = 0; i < size; i++) { + String ns = readString(); + result.add(ns); + } + return result; + } + + void writeNamespaces(Set namespaces) { + writeShort(namespaces.size()); + namespaces.forEach(this::writeString); + } + + OutputStream getSaverStream(String name) { + try { + return _filer.createBinaryFile(name); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + InputStream getLoaderStream(String resourcename) { + return _resourceLoader.getResourceAsStream(resourcename); + } + + void checkContainerNotNull(SchemaContainer container, QName name) { + if (container == null) { + throw new LinkageError("Loading of resource " + name + '.' + _handle + + "failed, information from " + name + ".index.xsb is " + + " out of sync (or conflicting index files found)"); + } + } + + /** + * Finishes loading an element after the header has already been loaded. + */ + public SchemaGlobalElement finishLoadingElement() { + String handle = null; + try { + int particleType = readShort(); + if (particleType != SchemaParticle.ELEMENT) { + throw new SchemaTypeLoaderException("Wrong particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE); + } + int particleFlags = readShort(); + BigInteger minOccurs = readBigInteger(); + BigInteger maxOccurs = readBigInteger(); + QNameSet transitionRules = readQNameSet(); + QName name = readQName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + SchemaGlobalElementImpl impl = new SchemaGlobalElementImpl(container); + impl.setParticleType(particleType); + impl.setMinOccurs(minOccurs); + impl.setMaxOccurs(maxOccurs); + impl.setTransitionRules(transitionRules, + (particleFlags & FLAG_PART_SKIPPABLE) != 0); + impl.setNameAndTypeRef(name, readTypeRef()); + impl.setDefault(readString(), (particleFlags & FLAG_PART_FIXED) != 0, null); + if (atLeast(2, 16, 0)) { + impl.setDefaultValue(readXmlValueObject()); + } + impl.setNillable((particleFlags & FLAG_PART_NILLABLE) != 0); + impl.setBlock((particleFlags & FLAG_PART_BLOCKEXT) != 0, + (particleFlags & FLAG_PART_BLOCKREST) != 0, + (particleFlags & FLAG_PART_BLOCKSUBST) != 0); + impl.setWsdlArrayType(readSOAPArrayType()); + impl.setAbstract((particleFlags & FLAG_PART_ABSTRACT) != 0); + impl.setAnnotation(readAnnotation(container)); + impl.setFinal( + (particleFlags & FLAG_PART_FINALEXT) != 0, + (particleFlags & FLAG_PART_FINALREST) != 0); + + if (atLeast(2, 17, 0)) { + impl.setSubstitutionGroup((SchemaGlobalElement.Ref) readHandle()); + } + + int substGroupCount = readShort(); + for (int i = 0; i < substGroupCount; i++) { + impl.addSubstitutionGroupMember(readQName()); + } + SchemaIdentityConstraint.Ref[] idcs = new SchemaIdentityConstraint.Ref[readShort()]; + + for (int i = 0; i < idcs.length; i++) { + idcs[i] = (SchemaIdentityConstraint.Ref) readHandle(); + } + + impl.setIdentityConstraints(idcs); + impl.setFilename(readString()); + return impl; + } catch (SchemaTypeLoaderException e) { + throw e; + } catch (Exception e) { + throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); + } finally { + readEnd(); + } + } + + public SchemaGlobalAttribute finishLoadingAttribute() { + try { + QName name = readQName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + SchemaGlobalAttributeImpl impl = new SchemaGlobalAttributeImpl(container); + loadAttribute(impl, name, container); + impl.setFilename(readString()); + + return impl; + } catch (SchemaTypeLoaderException e) { + throw e; + } catch (Exception e) { + throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); + } finally { + readEnd(); + } + } + + SchemaModelGroup finishLoadingModelGroup() { + QName name = readQName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + SchemaModelGroupImpl impl = new SchemaModelGroupImpl(container); + + try { + impl.init(name, readString(), readShort() == 1, + atLeast(2, 22, 0) ? readString() : null, + atLeast(2, 22, 0) ? readString() : null, + atLeast(2, 15, 0) && readShort() == 1, + GroupDocument.Factory.parse(readString()).getGroup(), readAnnotation(container), null); + if (atLeast(2, 21, 0)) { + impl.setFilename(readString()); + } + return impl; + } catch (SchemaTypeLoaderException e) { + throw e; + } catch (Exception e) { + throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); + } finally { + readEnd(); + } + } + + SchemaIdentityConstraint finishLoadingIdentityConstraint() { + try { + QName name = readQName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + SchemaIdentityConstraintImpl impl = new SchemaIdentityConstraintImpl(container); + impl.setName(name); + impl.setConstraintCategory(readShort()); + impl.setSelector(readString()); + impl.setAnnotation(readAnnotation(container)); + + String[] fields = new String[readShort()]; + for (int i = 0; i < fields.length; i++) { + fields[i] = readString(); + } + impl.setFields(fields); + + if (impl.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) { + impl.setReferencedKey((SchemaIdentityConstraint.Ref) readHandle()); + } + + int mapCount = readShort(); + Map nsMappings = new HashMap<>(); + for (int i = 0; i < mapCount; i++) { + String prefix = readString(); + String uri = readString(); + nsMappings.put(prefix, uri); + } + impl.setNSMap(nsMappings); + + if (atLeast(2, 21, 0)) { + impl.setFilename(readString()); + } + + return impl; + } catch (SchemaTypeLoaderException e) { + throw e; + } catch (Exception e) { + throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); + } finally { + readEnd(); + } + } + + SchemaAttributeGroup finishLoadingAttributeGroup() { + QName name = readQName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + SchemaAttributeGroupImpl impl = new SchemaAttributeGroupImpl(container); + + try { + impl.init(name, readString(), readShort() == 1, + atLeast(2, 22, 0) ? readString() : null, + atLeast(2, 15, 0) && readShort() == 1, + AttributeGroupDocument.Factory.parse(readString()).getAttributeGroup(), + readAnnotation(container), null); + if (atLeast(2, 21, 0)) { + impl.setFilename(readString()); + } + return impl; + } catch (SchemaTypeLoaderException e) { + throw e; + } catch (Exception e) { + throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); + } finally { + readEnd(); + } + } + + public SchemaType finishLoadingType() { + try { + SchemaContainer cNonNull = getContainerNonNull(""); //HACKHACK + SchemaTypeImpl impl = new SchemaTypeImpl(cNonNull, true); + impl.setName(readQName()); + impl.setOuterSchemaTypeRef(readTypeRef()); + impl.setBaseDepth(readShort()); + impl.setBaseTypeRef(readTypeRef()); + impl.setDerivationType(readShort()); + impl.setAnnotation(readAnnotation(null)); + + switch (readShort()) { + case FIELD_GLOBAL: + impl.setContainerFieldRef(readHandle()); + break; + case FIELD_LOCALATTR: + impl.setContainerFieldIndex((short) 1, readShort()); + break; + case FIELD_LOCALELT: + impl.setContainerFieldIndex((short) 2, readShort()); + break; + } + // TODO (radup) find the right solution here + String jn = readString(); + impl.setFullJavaName(jn == null ? "" : jn); + jn = readString(); + impl.setFullJavaImplName(jn == null ? "" : jn); + + impl.setAnonymousTypeRefs(readTypeRefArray()); + + impl.setAnonymousUnionMemberOrdinal(readShort()); + + int flags; + flags = readInt(); + + + boolean isComplexType = ((flags & FLAG_SIMPLE_TYPE) == 0); + impl.setCompiled((flags & FLAG_COMPILED) != 0); + impl.setDocumentType((flags & FLAG_DOCUMENT_TYPE) != 0); + impl.setAttributeType((flags & FLAG_ATTRIBUTE_TYPE) != 0); + impl.setSimpleType(!isComplexType); + + int complexVariety = SchemaType.NOT_COMPLEX_TYPE; + if (isComplexType) { + impl.setAbstractFinal((flags & FLAG_ABSTRACT) != 0, + (flags & FLAG_FINAL_EXT) != 0, + (flags & FLAG_FINAL_REST) != 0, + (flags & FLAG_FINAL_LIST) != 0, + (flags & FLAG_FINAL_UNION) != 0); + impl.setBlock((flags & FLAG_BLOCK_EXT) != 0, + (flags & FLAG_BLOCK_REST) != 0); + + impl.setOrderSensitive((flags & FLAG_ORDER_SENSITIVE) != 0); + complexVariety = readShort(); + impl.setComplexTypeVariety(complexVariety); + + if (atLeast(2, 23, 0)) { + impl.setContentBasedOnTypeRef(readTypeRef()); + } + + // Attribute Model Table + SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); + + int attrCount = readShort(); + for (int i = 0; i < attrCount; i++) { + attrModel.addAttribute(readAttributeData()); + } + + attrModel.setWildcardSet(readQNameSet()); + attrModel.setWildcardProcess(readShort()); + + // Attribute Property Table + Map attrProperties = new LinkedHashMap<>(); + int attrPropCount = readShort(); + for (int i = 0; i < attrPropCount; i++) { + SchemaProperty prop = readPropertyData(); + if (!prop.isAttribute()) { + throw new SchemaTypeLoaderException("Attribute property " + i + " is not an attribute", _name, _handle, SchemaTypeLoaderException.WRONG_PROPERTY_TYPE); + } + attrProperties.put(prop.getName(), prop); + } + + SchemaParticle contentModel = null; + Map elemProperties = null; + int isAll = 0; + + if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT) { + // Content Model Tree + isAll = readShort(); + SchemaParticle[] parts = readParticleArray(); + if (parts.length == 1) { + contentModel = parts[0]; + } else if (parts.length == 0) { + contentModel = null; + } else { + throw new SchemaTypeLoaderException("Content model not well-formed", _name, _handle, SchemaTypeLoaderException.MALFORMED_CONTENT_MODEL); + } + + // Element Property Table + + elemProperties = new LinkedHashMap<>(); + int elemPropCount = readShort(); + for (int i = 0; i < elemPropCount; i++) { + SchemaProperty prop = readPropertyData(); + if (prop.isAttribute()) { + throw new SchemaTypeLoaderException("Element property " + i + " is not an element", _name, _handle, SchemaTypeLoaderException.WRONG_PROPERTY_TYPE); + } + elemProperties.put(prop.getName(), prop); + } + } + + impl.setContentModel(contentModel, attrModel, elemProperties, attrProperties, isAll == 1); + StscComplexTypeResolver.WildcardResult wcElt = StscComplexTypeResolver.summarizeEltWildcards(contentModel); + StscComplexTypeResolver.WildcardResult wcAttr = StscComplexTypeResolver.summarizeAttrWildcards(attrModel); + impl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); + } + + if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT) { + int simpleVariety = readShort(); + impl.setSimpleTypeVariety(simpleVariety); + + boolean isStringEnum = ((flags & FLAG_STRINGENUM) != 0); + + impl.setOrdered((flags & FLAG_ORDERED) != 0 ? SchemaType.UNORDERED : ((flags & FLAG_TOTAL_ORDER) != 0 ? SchemaType.TOTAL_ORDER : SchemaType.PARTIAL_ORDER)); + impl.setBounded((flags & FLAG_BOUNDED) != 0); + impl.setFinite((flags & FLAG_FINITE) != 0); + impl.setNumeric((flags & FLAG_NUMERIC) != 0); + impl.setUnionOfLists((flags & FLAG_UNION_OF_LISTS) != 0); + impl.setSimpleFinal((flags & FLAG_FINAL_REST) != 0, + (flags & FLAG_FINAL_LIST) != 0, + (flags & FLAG_FINAL_UNION) != 0); + + XmlValueRef[] facets = new XmlValueRef[SchemaType.LAST_FACET + 1]; + boolean[] fixedFacets = new boolean[SchemaType.LAST_FACET + 1]; + int facetCount = readShort(); + for (int i = 0; i < facetCount; i++) { + int facetCode = readShort(); + facets[facetCode] = readXmlValueObject(); + fixedFacets[facetCode] = (readShort() == 1); + } + impl.setBasicFacets(facets, fixedFacets); + + impl.setWhiteSpaceRule(readShort()); + + impl.setPatternFacet((flags & FLAG_HAS_PATTERN) != 0); + + int patternCount = readShort(); + org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = new org.apache.xmlbeans.impl.regex.RegularExpression[patternCount]; + for (int i = 0; i < patternCount; i++) { + patterns[i] = new org.apache.xmlbeans.impl.regex.RegularExpression(readString(), "X"); + } + impl.setPatterns(patterns); + + int enumCount = readShort(); + XmlValueRef[] enumValues = new XmlValueRef[enumCount]; + for (int i = 0; i < enumCount; i++) { + enumValues[i] = readXmlValueObject(); + } + impl.setEnumerationValues(enumCount == 0 ? null : enumValues); + + impl.setBaseEnumTypeRef(readTypeRef()); + if (isStringEnum) { + int seCount = readShort(); + SchemaStringEnumEntry[] entries = new SchemaStringEnumEntry[seCount]; + for (int i = 0; i < seCount; i++) { + entries[i] = new SchemaStringEnumEntryImpl(readString(), readShort(), readString()); + } + impl.setStringEnumEntries(entries); + } + + switch (simpleVariety) { + case SchemaType.ATOMIC: + impl.setPrimitiveTypeRef(readTypeRef()); + impl.setDecimalSize(readInt()); + break; + + case SchemaType.LIST: + impl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + impl.setListItemTypeRef(readTypeRef()); + break; + + case SchemaType.UNION: + impl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + impl.setUnionMemberTypeRefs(readTypeRefArray()); + break; + + default: + throw new SchemaTypeLoaderException("Simple type does not have a recognized variety", _name, _handle, SchemaTypeLoaderException.WRONG_SIMPLE_VARIETY); + } + } + + impl.setFilename(readString()); + // Set the container for global, attribute or document types + if (impl.getName() != null) { + SchemaContainer container = getContainer(impl.getName().getNamespaceURI()); + checkContainerNotNull(container, impl.getName()); + impl.setContainer(container); + } else if (impl.isDocumentType()) { + QName name = impl.getDocumentElementName(); + if (name != null) { + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + impl.setContainer(container); + } + } else if (impl.isAttributeType()) { + QName name = impl.getAttributeTypeAttributeName(); + if (name != null) { + SchemaContainer container = getContainer(name.getNamespaceURI()); + checkContainerNotNull(container, name); + impl.setContainer(container); + } + } + + return impl; + } catch (SchemaTypeLoaderException e) { + throw e; + } catch (Exception e) { + throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); + } finally { + readEnd(); + } + } + + void writeTypeData(SchemaType type) { + writeQName(type.getName()); + writeType(type.getOuterType()); + writeShort(((SchemaTypeImpl) type).getBaseDepth()); + writeType(type.getBaseType()); + writeShort(type.getDerivationType()); + writeAnnotation(type.getAnnotation()); + if (type.getContainerField() == null) { + writeShort(FIELD_NONE); + } else if (type.getOuterType().isAttributeType() || type.getOuterType().isDocumentType()) { + writeShort(FIELD_GLOBAL); + writeHandle((SchemaComponent) type.getContainerField()); + } else if (type.getContainerField().isAttribute()) { + writeShort(FIELD_LOCALATTR); + writeShort(((SchemaTypeImpl) type.getOuterType()).getIndexForLocalAttribute((SchemaLocalAttribute) type.getContainerField())); + } else { + writeShort(FIELD_LOCALELT); + writeShort(((SchemaTypeImpl) type.getOuterType()).getIndexForLocalElement((SchemaLocalElement) type.getContainerField())); + } + writeString(type.getFullJavaName()); + writeString(type.getFullJavaImplName()); + writeTypeArray(type.getAnonymousTypes()); + writeShort(type.getAnonymousUnionMemberOrdinal()); + + int flags = 0; + if (type.isSimpleType()) { + flags |= FLAG_SIMPLE_TYPE; + } + if (type.isDocumentType()) { + flags |= FLAG_DOCUMENT_TYPE; + } + if (type.isAttributeType()) { + flags |= FLAG_ATTRIBUTE_TYPE; + } + if (type.ordered() != SchemaType.UNORDERED) { + flags |= FLAG_ORDERED; + } + if (type.ordered() == SchemaType.TOTAL_ORDER) { + flags |= FLAG_TOTAL_ORDER; + } + if (type.isBounded()) { + flags |= FLAG_BOUNDED; + } + if (type.isFinite()) { + flags |= FLAG_FINITE; + } + if (type.isNumeric()) { + flags |= FLAG_NUMERIC; + } + if (type.hasStringEnumValues()) { + flags |= FLAG_STRINGENUM; + } + if (((SchemaTypeImpl) type).isUnionOfLists()) { + flags |= FLAG_UNION_OF_LISTS; + } + if (type.hasPatternFacet()) { + flags |= FLAG_HAS_PATTERN; + } + if (type.isOrderSensitive()) { + flags |= FLAG_ORDER_SENSITIVE; + } + + if (type.blockExtension()) { + flags |= FLAG_BLOCK_EXT; + } + if (type.blockRestriction()) { + flags |= FLAG_BLOCK_REST; + } + if (type.finalExtension()) { + flags |= FLAG_FINAL_EXT; + } + if (type.finalRestriction()) { + flags |= FLAG_FINAL_EXT; + } + if (type.finalList()) { + flags |= FLAG_FINAL_LIST; + } + if (type.finalUnion()) { + flags |= FLAG_FINAL_UNION; + } + if (type.isAbstract()) { + flags |= FLAG_ABSTRACT; + } + + writeInt(flags); + + if (!type.isSimpleType()) { + writeShort(type.getContentType()); + + writeType(type.getContentBasedOnType()); + + // Attribute Model Table + SchemaAttributeModel attrModel = type.getAttributeModel(); + SchemaLocalAttribute[] attrs = attrModel.getAttributes(); + + writeShort(attrs.length); + for (SchemaLocalAttribute attr : attrs) { + writeAttributeData(attr); + } + + writeQNameSet(attrModel.getWildcardSet()); + writeShort(attrModel.getWildcardProcess()); + + // Attribute Property Table + SchemaProperty[] attrProperties = type.getAttributeProperties(); + writeShort(attrProperties.length); + for (SchemaProperty attrProperty : attrProperties) { + writePropertyData(attrProperty); + } + + if (type.getContentType() == SchemaType.ELEMENT_CONTENT || + type.getContentType() == SchemaType.MIXED_CONTENT) { + // Content Model Tree + writeShort(type.hasAllContent() ? 1 : 0); + SchemaParticle[] parts; + if (type.getContentModel() != null) { + parts = new SchemaParticle[]{type.getContentModel()}; + } else { + parts = new SchemaParticle[0]; + } + + writeParticleArray(parts); + + // Element Property Table + SchemaProperty[] eltProperties = type.getElementProperties(); + writeShort(eltProperties.length); + for (SchemaProperty eltProperty : eltProperties) { + writePropertyData(eltProperty); + } + } + } + + if (type.isSimpleType() || type.getContentType() == SchemaType.SIMPLE_CONTENT) { + writeShort(type.getSimpleVariety()); + + int facetCount = 0; + for (int i = 0; i <= SchemaType.LAST_FACET; i++) { + if (type.getFacet(i) != null) { + facetCount++; + } + } + writeShort(facetCount); + for (int i = 0; i <= SchemaType.LAST_FACET; i++) { + XmlAnySimpleType facet = type.getFacet(i); + if (facet != null) { + writeShort(i); + writeXmlValueObject(facet); + writeShort(type.isFacetFixed(i) ? 1 : 0); + } + } + + writeShort(type.getWhiteSpaceRule()); + + org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = ((SchemaTypeImpl) type).getPatternExpressions(); + writeShort(patterns.length); + for (org.apache.xmlbeans.impl.regex.RegularExpression pattern : patterns) { + writeString(pattern.getPattern()); + } + + XmlAnySimpleType[] enumValues = type.getEnumerationValues(); + if (enumValues == null) { + writeShort(0); + } else { + writeShort(enumValues.length); + for (XmlAnySimpleType enumValue : enumValues) { + writeXmlValueObject(enumValue); + } + } + + // new for version 2.3 + writeType(type.getBaseEnumType()); + if (type.hasStringEnumValues()) { + SchemaStringEnumEntry[] entries = type.getStringEnumEntries(); + writeShort(entries.length); + for (SchemaStringEnumEntry entry : entries) { + writeString(entry.getString()); + writeShort(entry.getIntValue()); + writeString(entry.getEnumName()); + } + } + + switch (type.getSimpleVariety()) { + case SchemaType.ATOMIC: + writeType(type.getPrimitiveType()); + writeInt(type.getDecimalSize()); + break; + + case SchemaType.LIST: + writeType(type.getListItemType()); + break; + + case SchemaType.UNION: + writeTypeArray(type.getUnionMemberTypes()); + break; + } + } + + writeString(type.getSourceName()); + } + + /* + void readExtensionsList() { + int count = readShort(); + assert count == 0; + + for (int i = 0; i < count; i++) { + readString(); + readString(); + readString(); + } + } + */ + + SchemaLocalAttribute readAttributeData() { + SchemaLocalAttributeImpl result = new SchemaLocalAttributeImpl(); + loadAttribute(result, readQName(), null); + return result; + } + + + void loadAttribute(SchemaLocalAttributeImpl result, QName name, SchemaContainer container) { + // name, type, use, deftext, defval, fixed, soaparraytype, annotation + result.init(name, readTypeRef(), readShort(), readString(), null, atLeast(2, 16, 0) ? readXmlValueObject() : null, readShort() == 1, readSOAPArrayType(), readAnnotation(container), null); + } + + void writeAttributeData(SchemaLocalAttribute attr) { + writeQName(attr.getName()); + writeType(attr.getType()); + writeShort(attr.getUse()); + writeString(attr.getDefaultText()); + writeXmlValueObject(attr.getDefaultValue()); + writeShort(attr.isFixed() ? 1 : 0); + writeSOAPArrayType(((SchemaWSDLArrayType) attr).getWSDLArrayType()); + writeAnnotation(attr.getAnnotation()); + } + + void writeIdConstraintData(SchemaIdentityConstraint idc) { + writeQName(idc.getName()); + writeShort(idc.getConstraintCategory()); + writeString(idc.getSelector()); + writeAnnotation(idc.getAnnotation()); + + String[] fields = idc.getFields(); + writeShort(fields.length); + for (String field : fields) { + writeString(field); + } + + + if (idc.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) { + writeHandle(idc.getReferencedKey()); + } + + Map mappings = idc.getNSMap(); + writeShort(mappings.size()); + mappings.forEach((prefix, uri) -> { + writeString(prefix); + writeString(uri); + }); + writeString(idc.getSourceName()); + } + + SchemaParticle[] readParticleArray() { + SchemaParticle[] result = new SchemaParticle[readShort()]; + for (int i = 0; i < result.length; i++) { + result[i] = readParticleData(); + } + return result; + } + + void writeParticleArray(SchemaParticle[] spa) { + writeShort(spa.length); + for (SchemaParticle schemaParticle : spa) { + writeParticleData(schemaParticle); + } + } + + SchemaParticle readParticleData() { + int particleType = readShort(); + SchemaParticleImpl result; + if (particleType != SchemaParticle.ELEMENT) { + result = new SchemaParticleImpl(); + } else { + result = new SchemaLocalElementImpl(); + } + loadParticle(result, particleType); + return result; + } + + void loadParticle(SchemaParticleImpl result, int particleType) { + int particleFlags = readShort(); + + result.setParticleType(particleType); + result.setMinOccurs(readBigInteger()); + result.setMaxOccurs(readBigInteger()); + + result.setTransitionRules(readQNameSet(), + (particleFlags & FLAG_PART_SKIPPABLE) != 0); + + switch (particleType) { + case SchemaParticle.WILDCARD: + result.setWildcardSet(readQNameSet()); + result.setWildcardProcess(readShort()); + break; + + case SchemaParticle.ELEMENT: + SchemaLocalElementImpl lresult = (SchemaLocalElementImpl) result; + lresult.setNameAndTypeRef(readQName(), readTypeRef()); + lresult.setDefault(readString(), (particleFlags & FLAG_PART_FIXED) != 0, null); + if (atLeast(2, 16, 0)) { + lresult.setDefaultValue(readXmlValueObject()); + } + lresult.setNillable((particleFlags & FLAG_PART_NILLABLE) != 0); + lresult.setBlock((particleFlags & FLAG_PART_BLOCKEXT) != 0, + (particleFlags & FLAG_PART_BLOCKREST) != 0, + (particleFlags & FLAG_PART_BLOCKSUBST) != 0); + lresult.setWsdlArrayType(readSOAPArrayType()); + lresult.setAbstract((particleFlags & FLAG_PART_ABSTRACT) != 0); + lresult.setAnnotation(readAnnotation(null)); + + SchemaIdentityConstraint.Ref[] idcs = new SchemaIdentityConstraint.Ref[readShort()]; + + for (int i = 0; i < idcs.length; i++) { + idcs[i] = (SchemaIdentityConstraint.Ref) readHandle(); + } + + lresult.setIdentityConstraints(idcs); + + break; + + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + case SchemaParticle.CHOICE: + result.setParticleChildren(readParticleArray()); + break; + + default: + throw new SchemaTypeLoaderException("Unrecognized particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE); + } + } + + void writeParticleData(SchemaParticle part) { + writeShort(part.getParticleType()); + short flags = 0; + if (part.isSkippable()) { + flags |= FLAG_PART_SKIPPABLE; + } + if (part.getParticleType() == SchemaParticle.ELEMENT) { + SchemaLocalElement lpart = (SchemaLocalElement) part; + if (lpart.isFixed()) { + flags |= FLAG_PART_FIXED; + } + if (lpart.isNillable()) { + flags |= FLAG_PART_NILLABLE; + } + if (lpart.blockExtension()) { + flags |= FLAG_PART_BLOCKEXT; + } + if (lpart.blockRestriction()) { + flags |= FLAG_PART_BLOCKREST; + } + if (lpart.blockSubstitution()) { + flags |= FLAG_PART_BLOCKSUBST; + } + if (lpart.isAbstract()) { + flags |= FLAG_PART_ABSTRACT; + } + + if (lpart instanceof SchemaGlobalElement) { + SchemaGlobalElement gpart = (SchemaGlobalElement) lpart; + if (gpart.finalExtension()) { + flags |= FLAG_PART_FINALEXT; + } + if (gpart.finalRestriction()) { + flags |= FLAG_PART_FINALREST; + } + } + } + writeShort(flags); + writeBigInteger(part.getMinOccurs()); + writeBigInteger(part.getMaxOccurs()); + writeQNameSet(part.acceptedStartNames()); + + switch (part.getParticleType()) { + case SchemaParticle.WILDCARD: + writeQNameSet(part.getWildcardSet()); + writeShort(part.getWildcardProcess()); + break; + + case SchemaParticle.ELEMENT: + SchemaLocalElement lpart = (SchemaLocalElement) part; + writeQName(lpart.getName()); + writeType(lpart.getType()); + writeString(lpart.getDefaultText()); + writeXmlValueObject(lpart.getDefaultValue()); + writeSOAPArrayType(((SchemaWSDLArrayType) lpart).getWSDLArrayType()); + writeAnnotation(lpart.getAnnotation()); + if (lpart instanceof SchemaGlobalElement) { + SchemaGlobalElement gpart = (SchemaGlobalElement) lpart; + + writeHandle(gpart.substitutionGroup()); + + QName[] substGroupMembers = gpart.substitutionGroupMembers(); + writeShort(substGroupMembers.length); + for (QName substGroupMember : substGroupMembers) { + writeQName(substGroupMember); + } + } + + SchemaIdentityConstraint[] idcs = lpart.getIdentityConstraints(); + + writeShort(idcs.length); + for (SchemaIdentityConstraint idc : idcs) { + writeHandle(idc); + } + + break; + + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + case SchemaParticle.CHOICE: + writeParticleArray(part.getParticleChildren()); + break; + + default: + throw new SchemaTypeLoaderException("Unrecognized particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE); + } + } + + SchemaProperty readPropertyData() { + SchemaPropertyImpl prop = new SchemaPropertyImpl(); + prop.setName(readQName()); + prop.setTypeRef(readTypeRef()); + int propflags = readShort(); + prop.setAttribute((propflags & FLAG_PROP_ISATTR) != 0); + prop.setContainerTypeRef(readTypeRef()); + prop.setMinOccurs(readBigInteger()); + prop.setMaxOccurs(readBigInteger()); + prop.setNillable(readShort()); + prop.setDefault(readShort()); + prop.setFixed(readShort()); + prop.setDefaultText(readString()); + + prop.setJavaPropertyName(readString()); + prop.setJavaTypeCode(readShort()); + prop.setExtendsJava(readTypeRef(), + (propflags & FLAG_PROP_JAVASINGLETON) != 0, + (propflags & FLAG_PROP_JAVAOPTIONAL) != 0, + (propflags & FLAG_PROP_JAVAARRAY) != 0); + if (atMost(2, 19, 0)) { + prop.setJavaSetterDelimiter(readQNameSet()); + } + if (atLeast(2, 16, 0)) { + prop.setDefaultValue(readXmlValueObject()); + } + + if (!prop.isAttribute() && atLeast(2, 17, 0)) { + int size = readShort(); + Set qnames = new LinkedHashSet<>(size); + for (int i = 0; i < size; i++) { + qnames.add(readQName()); + } + prop.setAcceptedNames(qnames); + } + prop.setImmutable(); + return prop; + } + + void writePropertyData(SchemaProperty prop) { + writeQName(prop.getName()); + writeType(prop.getType()); + writeShort((prop.isAttribute() ? FLAG_PROP_ISATTR : 0) | + (prop.extendsJavaSingleton() ? FLAG_PROP_JAVASINGLETON : 0) | + (prop.extendsJavaOption() ? FLAG_PROP_JAVAOPTIONAL : 0) | + (prop.extendsJavaArray() ? FLAG_PROP_JAVAARRAY : 0)); + writeType(prop.getContainerType()); + writeBigInteger(prop.getMinOccurs()); + writeBigInteger(prop.getMaxOccurs()); + writeShort(prop.hasNillable()); + writeShort(prop.hasDefault()); + writeShort(prop.hasFixed()); + writeString(prop.getDefaultText()); + + writeString(prop.getJavaPropertyName()); + writeShort(prop.getJavaTypeCode()); + writeType(prop.javaBasedOnType()); + writeXmlValueObject(prop.getDefaultValue()); + + if (!prop.isAttribute()) { + QName[] names = prop.acceptedNames(); + writeShort(names.length); + for (QName name : names) { + writeQName(name); + } + } + } + + void writeModelGroupData(SchemaModelGroup grp) { + SchemaModelGroupImpl impl = (SchemaModelGroupImpl) grp; + writeQName(impl.getName()); + writeString(impl.getTargetNamespace()); + writeShort(impl.getChameleonNamespace() != null ? 1 : 0); + writeString(impl.getElemFormDefault()); // new for version 2.22 + writeString(impl.getAttFormDefault()); // new for version 2.22 + writeShort(impl.isRedefinition() ? 1 : 0); // new for version 2.15 + writeString(impl.getParseObject().xmlText(new XmlOptions().setSaveOuter())); + writeAnnotation(impl.getAnnotation()); + writeString(impl.getSourceName()); + } + + void writeAttributeGroupData(SchemaAttributeGroup grp) { + SchemaAttributeGroupImpl impl = (SchemaAttributeGroupImpl) grp; + writeQName(impl.getName()); + writeString(impl.getTargetNamespace()); + writeShort(impl.getChameleonNamespace() != null ? 1 : 0); + writeString(impl.getFormDefault()); // new for version 2.22 + writeShort(impl.isRedefinition() ? 1 : 0); // new for version 2.15 + writeString(impl.getParseObject().xmlText(new XmlOptions().setSaveOuter())); + writeAnnotation(impl.getAnnotation()); + writeString(impl.getSourceName()); + } + + XmlValueRef readXmlValueObject() { + SchemaType.Ref typeref = readTypeRef(); + if (typeref == null) { + return null; + } + int btc = readShort(); + switch (btc) { + default: + assert (false); + case 0: + return new XmlValueRef(typeref, null); + case 0xFFFF: { + int size = readShort(); + List values = new ArrayList<>(); + // BUGBUG: this was: writeShort(values.size()); + writeShort(size); + for (int i = 0; i < size; i++) { + values.add(readXmlValueObject()); + } + return new XmlValueRef(typeref, values); + } + + + case SchemaType.BTC_ANY_SIMPLE: + case SchemaType.BTC_ANY_URI: + case SchemaType.BTC_STRING: + case SchemaType.BTC_DURATION: + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + case SchemaType.BTC_DECIMAL: + case SchemaType.BTC_BOOLEAN: + return new XmlValueRef(typeref, readString()); + + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: + return new XmlValueRef(typeref, readByteArray()); + + case SchemaType.BTC_QNAME: + case SchemaType.BTC_NOTATION: + return new XmlValueRef(typeref, readQName()); + + case SchemaType.BTC_FLOAT: + case SchemaType.BTC_DOUBLE: + return new XmlValueRef(typeref, readDouble()); + } + } + + void writeXmlValueObject(XmlAnySimpleType value) { + SchemaType type = value == null ? null : value.schemaType(); + writeType(type); + if (type == null) { + return; + } + + SchemaType iType = ((SimpleValue) value).instanceType(); + if (iType == null) { + writeShort(0); + } else if (iType.getSimpleVariety() == SchemaType.LIST) { + writeShort(-1); + List values = ((XmlObjectBase) value).xgetListValue(); + writeShort(values.size()); + values.forEach(this::writeXmlValueObject); + } else { + int btc = iType.getPrimitiveType().getBuiltinTypeCode(); + writeShort(btc); + switch (btc) { + case SchemaType.BTC_ANY_SIMPLE: + case SchemaType.BTC_ANY_URI: + case SchemaType.BTC_STRING: + case SchemaType.BTC_DURATION: + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + case SchemaType.BTC_DECIMAL: + case SchemaType.BTC_BOOLEAN: + writeString(value.getStringValue()); + break; + + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: + writeByteArray(((SimpleValue) value).getByteArrayValue()); + break; + + case SchemaType.BTC_QNAME: + case SchemaType.BTC_NOTATION: + writeQName(((SimpleValue) value).getQNameValue()); + break; + + case SchemaType.BTC_FLOAT: + writeDouble(((SimpleValue) value).getFloatValue()); + break; + + case SchemaType.BTC_DOUBLE: + writeDouble(((SimpleValue) value).getDoubleValue()); + break; + } + } + } + + double readDouble() { + try { + return _input.readDouble(); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + void writeDouble(double d) { + if (_output != null) { + try { + _output.writeDouble(d); + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + } + + QNameSet readQNameSet() { + int flag = readShort(); + + Set uriSet = new HashSet<>(); + int uriCount = readShort(); + for (int i = 0; i < uriCount; i++) { + uriSet.add(readString()); + } + + Set qnameSet1 = new HashSet<>(); + int qncount1 = readShort(); + for (int i = 0; i < qncount1; i++) { + qnameSet1.add(readQName()); + } + + Set qnameSet2 = new HashSet<>(); + int qncount2 = readShort(); + for (int i = 0; i < qncount2; i++) { + qnameSet2.add(readQName()); + } + + if (flag == 1) { + return QNameSet.forSets(uriSet, null, qnameSet1, qnameSet2); + } else { + return QNameSet.forSets(null, uriSet, qnameSet2, qnameSet1); + } + } + + void writeQNameSet(QNameSet set) { + boolean invert = (set.excludedURIs() != null); + writeShort(invert ? 1 : 0); + + Set uriSet = invert ? set.excludedURIs() : set.includedURIs(); + assert (uriSet != null); + writeShort(uriSet.size()); + uriSet.forEach(this::writeString); + + Set qnameSet1 = invert ? set.excludedQNamesInIncludedURIs() : set.includedQNamesInExcludedURIs(); + writeShort(qnameSet1.size()); + qnameSet1.forEach(this::writeQName); + + Set qnameSet2 = invert ? set.includedQNamesInExcludedURIs() : set.excludedQNamesInIncludedURIs(); + writeShort(qnameSet2.size()); + qnameSet2.forEach(this::writeQName); + } + + byte[] readByteArray() { + try { + int len = _input.readShort(); + byte[] result = new byte[len]; + _input.readFully(result); + return result; + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + void writeByteArray(byte[] ba) { + try { + writeShort(ba.length); + if (_output != null) { + _output.write(ba); + } + } catch (IOException e) { + throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); + } + } + + BigInteger readBigInteger() { + byte[] result = readByteArray(); + if (result.length == 0) { + return null; + } + if (result.length == 1 && result[0] == 0) { + return BigInteger.ZERO; + } + if (result.length == 1 && result[0] == 1) { + return BigInteger.ONE; + } + return new BigInteger(result); + } + + void writeBigInteger(BigInteger bi) { + if (bi == null) { + writeShort(0); + } else if (bi.signum() == 0) { + writeByteArray(SINGLE_ZERO_BYTE); + } else { + writeByteArray(bi.toByteArray()); + } + } + + } + + static final byte[] SINGLE_ZERO_BYTE = {0}; + + public SchemaType typeForHandle(String handle) { + synchronized (_resolvedHandles) { + return (SchemaType) _resolvedHandles.get(handle); + } + } + + public SchemaType typeForClassname(String classname) { + SchemaType.Ref ref = (SchemaType.Ref) _typeRefsByClassname.get(classname); + return (ref != null) ? ref.get() : null; + } + + public SchemaComponent resolveHandle(String handle) { + SchemaComponent result; + + synchronized (_resolvedHandles) { + result = _resolvedHandles.get(handle); + } + if (result == null) { + XsbReader reader = new XsbReader(handle, 0xFFFF); + int filetype = reader.getActualFiletype(); + switch (filetype) { + case FILETYPE_SCHEMATYPE: + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving type for handle " + handle, 0); + result = reader.finishLoadingType(); + break; + case FILETYPE_SCHEMAELEMENT: + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving element for handle " + handle, 0); + result = reader.finishLoadingElement(); + break; + case FILETYPE_SCHEMAATTRIBUTE: + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving attribute for handle " + handle, 0); + result = reader.finishLoadingAttribute(); + break; + case FILETYPE_SCHEMAMODELGROUP: + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving model group for handle " + handle, 0); + result = reader.finishLoadingModelGroup(); + break; + case FILETYPE_SCHEMAATTRIBUTEGROUP: + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving attribute group for handle " + handle, 0); + result = reader.finishLoadingAttributeGroup(); + break; + case FILETYPE_SCHEMAIDENTITYCONSTRAINT: + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving id constraint for handle " + handle, 0); + result = reader.finishLoadingIdentityConstraint(); + break; + default: + throw new IllegalStateException("Illegal handle type"); + } + + synchronized (_resolvedHandles) { + if (!_resolvedHandles.containsKey(handle)) { + _resolvedHandles.put(handle, result); + } else { + result = _resolvedHandles.get(handle); + } + } + } + return result; + } + + private final Map _resolvedHandles = new HashMap<>(); + private boolean _allNonGroupHandlesResolved = false; + + public void resolve() { + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolve called type system " + _name, 0); + if (_allNonGroupHandlesResolved) { + return; + } + + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving all handles for type system " + _name, 1); + + List refs = new ArrayList<>(); + refs.addAll(_globalElements.values()); + refs.addAll(_globalAttributes.values()); + refs.addAll(_globalTypes.values()); + refs.addAll(_documentTypes.values()); + refs.addAll(_attributeTypes.values()); + refs.addAll(_identityConstraints.values()); + + for (SchemaComponent.Ref ref : refs) { + // Forces ref to be resolved + ref.getComponent(); + } + + XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finished resolving type system " + _name, -1); + _allNonGroupHandlesResolved = true; + } + + + public boolean isNamespaceDefined(String namespace) { + return _namespaces.contains(namespace); + } + + public SchemaType.Ref findTypeRef(QName name) { + return (SchemaType.Ref) _globalTypes.get(name); + } + + public SchemaType.Ref findDocumentTypeRef(QName name) { + return (SchemaType.Ref) _documentTypes.get(name); + } + + public SchemaType.Ref findAttributeTypeRef(QName name) { + return (SchemaType.Ref) _attributeTypes.get(name); + } + + public SchemaGlobalElement.Ref findElementRef(QName name) { + return (SchemaGlobalElement.Ref) _globalElements.get(name); + } + + public SchemaGlobalAttribute.Ref findAttributeRef(QName name) { + return (SchemaGlobalAttribute.Ref) _globalAttributes.get(name); + } + + public SchemaModelGroup.Ref findModelGroupRef(QName name) { + return (SchemaModelGroup.Ref) _modelGroups.get(name); + } + + public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) { + return (SchemaAttributeGroup.Ref) _attributeGroups.get(name); + } + + public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { + return (SchemaIdentityConstraint.Ref) _identityConstraints.get(name); + } + + private static U[] refHelper(Map map, Function fun, IntFunction target, U[] emptyTarget) { + return refHelper(map == null ? null : map.values(), fun, target, emptyTarget); + } + + private static U[] refHelper(Collection list, Function fun, IntFunction target, U[] emptyTarget) { + //noinspection unchecked + return (list == null || list.isEmpty()) ? emptyTarget : list.stream().map(e -> (T) e).map(fun).toArray(target); + } + + public SchemaType[] globalTypes() { + return refHelper(_globalTypes, SchemaType.Ref::get, SchemaType[]::new, EMPTY_ST_ARRAY); + } + + public SchemaType[] redefinedGlobalTypes() { + return refHelper(_redefinedGlobalTypes, SchemaType.Ref::get, SchemaType[]::new, EMPTY_ST_ARRAY); + } + + public InputStream getSourceAsStream(String sourceName) { + if (!sourceName.startsWith("/")) { + sourceName = "/" + sourceName; + } + + return _resourceLoader.getResourceAsStream(getMetadataPath() + "/src" + sourceName); + } + + SchemaContainer[] containers() { + return _containers.values().toArray(new SchemaContainer[0]); + } + + public SchemaType[] documentTypes() { + return refHelper(_documentTypes, SchemaType.Ref::get, SchemaType[]::new, EMPTY_ST_ARRAY); + } + + public SchemaType[] attributeTypes() { + return refHelper(_attributeTypes, SchemaType.Ref::get, SchemaType[]::new, EMPTY_ST_ARRAY); + } + + public SchemaGlobalElement[] globalElements() { + return refHelper(_globalElements, SchemaGlobalElement.Ref::get, SchemaGlobalElement[]::new, EMPTY_GE_ARRAY); + } + + public SchemaGlobalAttribute[] globalAttributes() { + return refHelper(_globalAttributes, SchemaGlobalAttribute.Ref::get, SchemaGlobalAttribute[]::new, EMPTY_GA_ARRAY); + } + + public SchemaModelGroup[] modelGroups() { + return refHelper(_modelGroups, SchemaModelGroup.Ref::get, SchemaModelGroup[]::new, EMPTY_MG_ARRAY); + } + + public SchemaModelGroup[] redefinedModelGroups() { + return refHelper(_redefinedModelGroups, SchemaModelGroup.Ref::get, SchemaModelGroup[]::new, EMPTY_MG_ARRAY); + } + + public SchemaAttributeGroup[] attributeGroups() { + return refHelper(_attributeGroups, SchemaAttributeGroup.Ref::get, SchemaAttributeGroup[]::new, EMPTY_AG_ARRAY); + } + + public SchemaAttributeGroup[] redefinedAttributeGroups() { + return refHelper(_redefinedAttributeGroups, SchemaAttributeGroup.Ref::get, SchemaAttributeGroup[]::new, EMPTY_AG_ARRAY); + } + + public SchemaAnnotation[] annotations() { + return (_annotations == null || _annotations.isEmpty()) ? EMPTY_ANN_ARRAY : _annotations.toArray(EMPTY_ANN_ARRAY); + } + + public SchemaIdentityConstraint[] identityConstraints() { + return refHelper(_identityConstraints, SchemaIdentityConstraint.Ref::get, SchemaIdentityConstraint[]::new, EMPTY_IC_ARRAY); + } + + public ClassLoader getClassLoader() { + return _classloader; + } + + /** + * Used INTERNALLY ONLY by the code output AFTER the type system has + * been saved and a handle has been established for each type. + */ + public String handleForType(SchemaType type) { + return _localHandles.handleForType(type); + } + + public String getName() { + return _name; + } + + public SchemaTypeSystem typeSystemForName(String name) { + return (name != null && name.equals(_name)) ? this : null; + } + + + /** + * Provide method to be overriden by user typesystems using a different metadata path + * + * @return the metadata directory + * @since XmlBeans 3.1.0 + */ + public String getMetadataPath() { + Matcher m = packPat.matcher(_name); + m.find(); + return m.group(1).replace('.', '/'); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java rename to src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java b/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java new file mode 100644 index 0000000..361ae2c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java @@ -0,0 +1,292 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; + +import javax.xml.namespace.QName; +import java.io.File; +import java.io.InputStream; +import java.math.BigInteger; +import java.util.*; + +public class SoapEncSchemaTypeSystem extends SchemaTypeLoaderBase + implements SchemaTypeSystem { + public static final String SOAPENC = "http://schemas.xmlsoap.org/soap/encoding/"; + public static final String SOAP_ARRAY = "Array"; + public static final String ARRAY_TYPE = "arrayType"; + private static final String ATTR_ID = "id"; + private static final String ATTR_HREF = "href"; + private static final String ATTR_OFFSET = "offset"; + + private static final SchemaType[] EMPTY_SCHEMATYPE_ARRAY = new SchemaType[0]; + private static final SchemaGlobalElement[] EMPTY_SCHEMAELEMENT_ARRAY = new SchemaGlobalElement[0]; + private static final SchemaModelGroup[] EMPTY_SCHEMAMODELGROUP_ARRAY = new SchemaModelGroup[0]; + private static final SchemaAttributeGroup[] EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY = new SchemaAttributeGroup[0]; + private static final SchemaAnnotation[] EMPTY_SCHEMAANNOTATION_ARRAY = new SchemaAnnotation[0]; + + // The global builtin type system + public static SchemaTypeSystem get() { + return _global; + } + + private static final SoapEncSchemaTypeSystem _global = new SoapEncSchemaTypeSystem(); + + private final SchemaTypeImpl soapArray; + private final SchemaGlobalAttributeImpl arrayType; + private final Map _handlesToObjects = new HashMap<>(); + private final String soapArrayHandle; + + private SoapEncSchemaTypeSystem() { + // soapenc:Array + SchemaContainer _container = new SchemaContainer(SOAPENC); + _container.setTypeSystem(this); + soapArray = new SchemaTypeImpl(_container, true); + _container.addGlobalType(soapArray.getRef()); + soapArray.setName(new QName(SOAPENC, SOAP_ARRAY)); + soapArrayHandle = SOAP_ARRAY.toLowerCase(Locale.ROOT) + "type"; + soapArray.setComplexTypeVariety(SchemaType.ELEMENT_CONTENT); + soapArray.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef()); + soapArray.setBaseDepth(1); + soapArray.setDerivationType(SchemaType.DT_EXTENSION); + soapArray.setSimpleTypeVariety(SchemaType.NOT_SIMPLE); + SchemaParticleImpl contentModel = new SchemaParticleImpl(); + contentModel.setParticleType(SchemaParticle.SEQUENCE); + contentModel.setMinOccurs(BigInteger.ZERO); + contentModel.setMaxOccurs(BigInteger.ONE); + contentModel.setTransitionRules(QNameSet.ALL, true); + SchemaParticleImpl[] children = new SchemaParticleImpl[1]; + contentModel.setParticleChildren(children); + SchemaParticleImpl contentModel2 = new SchemaParticleImpl(); + contentModel2.setParticleType(SchemaParticle.WILDCARD); + contentModel2.setWildcardSet(QNameSet.ALL); + contentModel2.setWildcardProcess(SchemaParticle.LAX); + contentModel2.setMinOccurs(BigInteger.ZERO); + contentModel2.setMaxOccurs(null); + contentModel2.setTransitionRules(QNameSet.ALL, true); + children[0] = contentModel2; + + SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); + attrModel.setWildcardProcess(SchemaAttributeModel.LAX); + HashSet excludedURI = new HashSet<>(); + excludedURI.add(SOAPENC); + attrModel.setWildcardSet(QNameSet.forSets(excludedURI, null, Collections.emptySet(), Collections.emptySet())); + SchemaLocalAttributeImpl attr = new SchemaLocalAttributeImpl(); + attr.init(new QName("", ATTR_ID), BuiltinSchemaTypeSystem.ST_ID.getRef(), + SchemaLocalAttribute.OPTIONAL, null, null, null, false, null, null, null); + attrModel.addAttribute(attr); + attr = new SchemaLocalAttributeImpl(); + attr.init(new QName("", ATTR_HREF), BuiltinSchemaTypeSystem.ST_ANY_URI.getRef(), + SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); + attrModel.addAttribute(attr); + attr = new SchemaLocalAttributeImpl(); + attr.init(new QName(SOAPENC, ARRAY_TYPE), BuiltinSchemaTypeSystem.ST_STRING.getRef(), + SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); + attrModel.addAttribute(attr); + attr = new SchemaLocalAttributeImpl(); + attr.init(new QName(SOAPENC, ATTR_OFFSET), BuiltinSchemaTypeSystem.ST_STRING.getRef(), + SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); + attrModel.addAttribute(attr); + soapArray.setContentModel(contentModel, attrModel, Collections.emptyMap(), Collections.emptyMap(), false); + + // soapenc:arrayType + arrayType = new SchemaGlobalAttributeImpl(_container); + _container.addGlobalAttribute(arrayType.getRef()); + arrayType.init(new QName(SOAPENC, ARRAY_TYPE), BuiltinSchemaTypeSystem.ST_STRING.getRef(), + SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); + _handlesToObjects.put(soapArrayHandle, soapArray); + _handlesToObjects.put(ARRAY_TYPE.toLowerCase(Locale.ROOT) + "attribute", arrayType); + _container.setImmutable(); + } + + /** + * Returns the name of this loader. + */ + public String getName() { + return "schema.typesystem.soapenc.builtin"; + } + + public SchemaType findType(QName qName) { + if (SOAPENC.equals(qName.getNamespaceURI()) && + SOAP_ARRAY.equals(qName.getLocalPart())) { + return soapArray; + } else { + return null; + } + } + + public SchemaType findDocumentType(QName qName) { + return null; + } + + public SchemaType findAttributeType(QName qName) { + return null; + } + + public SchemaGlobalElement findElement(QName qName) { + return null; + } + + public SchemaGlobalAttribute findAttribute(QName qName) { + if (SOAPENC.equals(qName.getNamespaceURI()) && + ARRAY_TYPE.equals(qName.getLocalPart())) { + return arrayType; + } else { + return null; + } + } + + public SchemaModelGroup findModelGroup(QName qName) { + return null; + } + + public SchemaAttributeGroup findAttributeGroup(QName qName) { + return null; + } + + public boolean isNamespaceDefined(String string) { + return SOAPENC.equals(string); + } + + public SchemaType.Ref findTypeRef(QName qName) { + SchemaType type = findType(qName); + return (type == null ? null : type.getRef()); + } + + public SchemaType.Ref findDocumentTypeRef(QName qName) { + return null; + } + + public SchemaType.Ref findAttributeTypeRef(QName qName) { + return null; + } + + public SchemaGlobalElement.Ref findElementRef(QName qName) { + return null; + } + + public SchemaGlobalAttribute.Ref findAttributeRef(QName qName) { + SchemaGlobalAttribute attr = findAttribute(qName); + return (attr == null ? null : attr.getRef()); + } + + public SchemaModelGroup.Ref findModelGroupRef(QName qName) { + return null; + } + + public SchemaAttributeGroup.Ref findAttributeGroupRef(QName qName) { + return null; + } + + public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName qName) { + return null; + } + + public SchemaType typeForClassname(String string) { + return null; + } + + public InputStream getSourceAsStream(String string) { + return null; // no source + } + + /** + * Returns the classloader used by this loader for resolving types. + */ + public ClassLoader getClassLoader() { + return SoapEncSchemaTypeSystem.class.getClassLoader(); + } + + /** + * Describe resolve method here. + */ + public void resolve() { + // don't need to do anything; already resolved + } + + /** + * @return an array consisting of a single type + */ + public SchemaType[] globalTypes() { + return new SchemaType[]{soapArray}; + } + + public SchemaType[] documentTypes() { + return EMPTY_SCHEMATYPE_ARRAY; + } + + public SchemaType[] attributeTypes() { + return EMPTY_SCHEMATYPE_ARRAY; + } + + public SchemaGlobalElement[] globalElements() { + return EMPTY_SCHEMAELEMENT_ARRAY; + } + + public SchemaGlobalAttribute[] globalAttributes() { + return new SchemaGlobalAttribute[]{arrayType}; + } + + public SchemaModelGroup[] modelGroups() { + return EMPTY_SCHEMAMODELGROUP_ARRAY; + } + + public SchemaAttributeGroup[] attributeGroups() { + return EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY; + } + + public SchemaAnnotation[] annotations() { + return EMPTY_SCHEMAANNOTATION_ARRAY; + } + + /** + * Returns the handle for the given type within this loader. + */ + public String handleForType(SchemaType type) { + if (soapArray.equals(type)) { + return soapArrayHandle; + } else { + return null; + } + } + + /** + * + */ + public SchemaComponent resolveHandle(String string) { + return _handlesToObjects.get(string); + } + + /** + * + */ + public SchemaType typeForHandle(String string) { + return (SchemaType) _handlesToObjects.get(string); + } + + /** + * Describe saveToDirectory method here. + * + * @param file a File value + */ + public void saveToDirectory(File file) { + throw new UnsupportedOperationException("The builtin soap encoding schema type system cannot be saved."); + } + + public void save(Filer filer) { + throw new UnsupportedOperationException("The builtin soap encoding schema type system cannot be saved."); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java new file mode 100644 index 0000000..338f21f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java @@ -0,0 +1,1621 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.XBeanDebug; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.*; + +public class StscChecker { + public static void checkAll() { + // walk the tree of types + StscState state = StscState.get(); + + List allSeenTypes = new ArrayList<>(); + allSeenTypes.addAll(Arrays.asList(state.documentTypes())); + allSeenTypes.addAll(Arrays.asList(state.attributeTypes())); + allSeenTypes.addAll(Arrays.asList(state.redefinedGlobalTypes())); + allSeenTypes.addAll(Arrays.asList(state.globalTypes())); + + for (int i = 0; i < allSeenTypes.size(); i++) { + SchemaType gType = allSeenTypes.get(i); + // option to turn off particle restriction checking + // Don't check doc types for restriction. + if (!state.noPvr() && !gType.isDocumentType()) { + checkRestriction((SchemaTypeImpl) gType); + } + checkFields((SchemaTypeImpl) gType); + allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); + } + + checkSubstitutionGroups(state.globalElements()); + } + + /** + * The following code checks rule #5 of http://www.w3.org/TR/xmlschema-1/#coss-ct + * as well as attribute + element default/fixed validity.

      + * Checks that xs:NOTATION is not used directly + */ + public static void checkFields(SchemaTypeImpl sType) { + if (sType.isSimpleType()) { + return; + } + + XmlObject location = sType.getParseObject(); + + SchemaAttributeModel sAttrModel = sType.getAttributeModel(); + if (sAttrModel != null) { + SchemaLocalAttribute[] sAttrs = sAttrModel.getAttributes(); + QName idAttr = null; + for (SchemaLocalAttribute sAttr : sAttrs) { + XmlObject attrLocation = ((SchemaLocalAttributeImpl) sAttr)._parseObject; + if (XmlID.type.isAssignableFrom(sAttr.getType())) { + if (idAttr == null) { + idAttr = sAttr.getName(); + } else { + StscState.get().error(XmlErrorCodes.ATTR_GROUP_PROPERTIES$TWO_IDS, + new Object[]{QNameHelper.pretty(idAttr), sAttr.getName()}, + attrLocation != null ? attrLocation : location); + } + if (sAttr.getDefaultText() != null) { + StscState.get().error(XmlErrorCodes.ATTR_PROPERTIES$ID_FIXED_OR_DEFAULT, + null, attrLocation != null ? attrLocation : location); + } + } else if (XmlNOTATION.type.isAssignableFrom(sAttr.getType())) { + if (sAttr.getType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION) { + StscState.get().recover(XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN, + new Object[]{QNameHelper.pretty(sAttr.getName())}, + attrLocation != null ? attrLocation : location); + } else { + if (sAttr.getType().getSimpleVariety() == SchemaType.UNION) { + SchemaType[] members = sAttr.getType().getUnionConstituentTypes(); + for (SchemaType member : members) { + if (member.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) { + StscState.get().recover(XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN, + new Object[]{QNameHelper.pretty(sAttr.getName())}, + attrLocation != null ? attrLocation : location); + } + } + } + // Check that the Schema in which this is present doesn't have a targetNS + boolean hasNS; + if (sType.isAttributeType()) { + hasNS = sAttr.getName().getNamespaceURI().length() > 0; + } else { + SchemaType t = sType; + while (t.getOuterType() != null) { + t = t.getOuterType(); + } + if (t.isDocumentType()) { + hasNS = t.getDocumentElementName().getNamespaceURI().length() > 0; + } else { + hasNS = t.getName().getNamespaceURI().length() > 0; + } + } + if (hasNS) { + StscState.get().warning(XmlErrorCodes.ATTR_COMPATIBILITY_TARGETNS, + new Object[]{QNameHelper.pretty(sAttr.getName())}, + attrLocation != null ? attrLocation : location); + } + } + } else { + String valueConstraint = sAttr.getDefaultText(); + if (valueConstraint != null) { + try { + XmlAnySimpleType val = sAttr.getDefaultValue(); + if (!val.validate()) { + throw new Exception(); + } + + SchemaPropertyImpl sProp = (SchemaPropertyImpl) sType.getAttributeProperty(sAttr.getName()); + if (sProp != null && sProp.getDefaultText() != null) { + sProp.setDefaultValue(new XmlValueRef(val)); + } + } catch (Exception e) { + // move to 'fixed' or 'default' attribute on the attribute definition + String constraintName = (sAttr.isFixed() ? "fixed" : "default"); + XmlObject constraintLocation = location; + if (attrLocation != null) { + constraintLocation = attrLocation.selectAttribute("", constraintName); + if (constraintLocation == null) { + constraintLocation = attrLocation; + } + } + + StscState.get().error(XmlErrorCodes.ATTR_PROPERTIES$CONSTRAINT_VALID, + new Object[]{QNameHelper.pretty(sAttr.getName()), + constraintName, + valueConstraint, + QNameHelper.pretty(sAttr.getType().getName())}, + constraintLocation); + } + } + } + } + } + + checkElementDefaults(sType.getContentModel(), location, sType); + } + + /** + * Checks the default values of elements.

      + * Also checks that the type of elements is not one of ID, IDREF, IDREFS, ENTITY, ENTITIES or + * NOTATION as per XMLSchema part 2. + */ + private static void checkElementDefaults(SchemaParticle model, XmlObject location, SchemaType parentType) { + if (model == null) { + return; + } + switch (model.getParticleType()) { + case SchemaParticle.SEQUENCE: + case SchemaParticle.CHOICE: + case SchemaParticle.ALL: + SchemaParticle[] children = model.getParticleChildren(); + for (SchemaParticle child : children) { + checkElementDefaults(child, location, parentType); + } + break; + case SchemaParticle.ELEMENT: + String valueConstraint = model.getDefaultText(); + if (valueConstraint != null) { + if (model.getType().isSimpleType() || model.getType().getContentType() == SchemaType.SIMPLE_CONTENT) { + try { + XmlAnySimpleType val = model.getDefaultValue(); + XmlOptions opt = new XmlOptions(); + opt.setValidateTextOnly(); + if (!val.validate(opt)) { + throw new Exception(); + } + + SchemaPropertyImpl sProp = (SchemaPropertyImpl) parentType.getElementProperty(model.getName()); + if (sProp != null && sProp.getDefaultText() != null) { + sProp.setDefaultValue(new XmlValueRef(val)); + } + } catch (Exception e) { + // move to 'fixed' or 'default' attribute on the element definition + String constraintName = (model.isFixed() ? "fixed" : "default"); + XmlObject constraintLocation = location.selectAttribute("", constraintName); + + StscState.get().error(XmlErrorCodes.ELEM_PROPERTIES$CONSTRAINT_VALID, + new Object[]{QNameHelper.pretty(model.getName()), + constraintName, + valueConstraint, + QNameHelper.pretty(model.getType().getName())}, + (constraintLocation == null ? location : constraintLocation)); + } + } else if (model.getType().getContentType() == SchemaType.MIXED_CONTENT) { + if (!model.getType().getContentModel().isSkippable()) { + String constraintName = (model.isFixed() ? "fixed" : "default"); + XmlObject constraintLocation = location.selectAttribute("", constraintName); + + StscState.get().error(XmlErrorCodes.ELEM_DEFAULT_VALID$MIXED_AND_EMPTIABLE, + new Object[]{QNameHelper.pretty(model.getName()), + constraintName, + valueConstraint}, + (constraintLocation == null ? location : constraintLocation)); + } else { + // Element Default Valid (Immediate): cos-valid-default.2.2.2 + // no need to validate the value; type is a xs:string + SchemaPropertyImpl sProp = (SchemaPropertyImpl) parentType.getElementProperty(model.getName()); + if (sProp != null && sProp.getDefaultText() != null) { + sProp.setDefaultValue(new XmlValueRef(XmlString.type.newValue(valueConstraint))); + } + } + } else if (model.getType().getContentType() == SchemaType.ELEMENT_CONTENT) { + XmlObject constraintLocation = location.selectAttribute("", "default"); + StscState.get().error(XmlErrorCodes.ELEM_DEFAULT_VALID$SIMPLE_TYPE_OR_MIXED, + new Object[]{QNameHelper.pretty(model.getName()), + valueConstraint, + "element"}, + (constraintLocation == null ? location : constraintLocation)); + } else if (model.getType().getContentType() == SchemaType.EMPTY_CONTENT) { + XmlObject constraintLocation = location.selectAttribute("", "default"); + StscState.get().error(XmlErrorCodes.ELEM_DEFAULT_VALID$SIMPLE_TYPE_OR_MIXED, + new Object[]{QNameHelper.pretty(model.getName()), + valueConstraint, + "empty"}, + (constraintLocation == null ? location : constraintLocation)); + } + } + // Checks if the type is one of the "attribute-specific" types + String warningType = null; + if (BuiltinSchemaTypeSystem.ST_ID.isAssignableFrom(model.getType())) { + warningType = BuiltinSchemaTypeSystem.ST_ID.getName().getLocalPart(); + } else if (BuiltinSchemaTypeSystem.ST_IDREF.isAssignableFrom(model.getType())) { + warningType = BuiltinSchemaTypeSystem.ST_IDREF.getName().getLocalPart(); + } else if (BuiltinSchemaTypeSystem.ST_IDREFS.isAssignableFrom(model.getType())) { + warningType = BuiltinSchemaTypeSystem.ST_IDREFS.getName().getLocalPart(); + } else if (BuiltinSchemaTypeSystem.ST_ENTITY.isAssignableFrom(model.getType())) { + warningType = BuiltinSchemaTypeSystem.ST_ENTITY.getName().getLocalPart(); + } else if (BuiltinSchemaTypeSystem.ST_ENTITIES.isAssignableFrom(model.getType())) { + warningType = BuiltinSchemaTypeSystem.ST_ENTITIES.getName().getLocalPart(); + } else if (BuiltinSchemaTypeSystem.ST_NOTATION.isAssignableFrom(model.getType())) { + if (model.getType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION) { + StscState.get().recover(XmlErrorCodes.ELEM_NOTATION_TYPE_FORBIDDEN, + new Object[]{QNameHelper.pretty(model.getName())}, + ((SchemaLocalElementImpl) model)._parseObject == null ? location : + ((SchemaLocalElementImpl) model)._parseObject.selectAttribute("", "type")); + } else { + if (model.getType().getSimpleVariety() == SchemaType.UNION) { + SchemaType[] members = model.getType().getUnionConstituentTypes(); + for (SchemaType member : members) { + if (member.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) { + StscState.get().recover(XmlErrorCodes.ELEM_NOTATION_TYPE_FORBIDDEN, + new Object[]{QNameHelper.pretty(model.getName())}, + ((SchemaLocalElementImpl) model)._parseObject == null ? location : + ((SchemaLocalElementImpl) model)._parseObject.selectAttribute("", "type")); + } + } + } + warningType = BuiltinSchemaTypeSystem.ST_NOTATION.getName().getLocalPart(); + } + + // Check that the Schema in which this is present doesn't have a targetNS + boolean hasNS; + SchemaType t = parentType; + while (t.getOuterType() != null) { + t = t.getOuterType(); + } + if (t.isDocumentType()) { + hasNS = t.getDocumentElementName().getNamespaceURI().length() > 0; + } else { + hasNS = t.getName().getNamespaceURI().length() > 0; + } + if (hasNS) { + StscState.get().warning(XmlErrorCodes.ELEM_COMPATIBILITY_TARGETNS, + new Object[]{QNameHelper.pretty(model.getName())}, + ((SchemaLocalElementImpl) model)._parseObject == null ? location : + ((SchemaLocalElementImpl) model)._parseObject); + } + } + + if (warningType != null) { + StscState.get().warning(XmlErrorCodes.ELEM_COMPATIBILITY_TYPE, new Object[] + {QNameHelper.pretty(model.getName()), warningType}, + ((SchemaLocalElementImpl) model)._parseObject == null ? location : + ((SchemaLocalElementImpl) model)._parseObject.selectAttribute("", "type")); + } + + break; + + default: + // nothing to do. + break; + } + } + + /** + * The following code only checks rule #5 of http://www.w3.org/TR/xmlschema-1/#derivation-ok-restriction + * (Everything else can and should be done in StscResolver, because we can give more detailed line # info there + */ + public static boolean checkRestriction(SchemaTypeImpl sType) { + if (sType.getDerivationType() == SchemaType.DT_RESTRICTION && !sType.isSimpleType()) { + StscState state = StscState.get(); + + // we don't remember very precise line number information, but it's better than nothin. + XmlObject location = sType.getParseObject(); + + SchemaType baseType = sType.getBaseType(); + assert (baseType != null); + if (baseType.isSimpleType()) { + state.error(XmlErrorCodes.SCHEMA_COMPLEX_TYPE$COMPLEX_CONTENT, + new Object[]{QNameHelper.pretty(baseType.getName())}, + location); + return false; + } + + // 5 The appropriate case among the following must be true: + switch (sType.getContentType()) { + case SchemaType.SIMPLE_CONTENT: + // 5.1 If the {content type} of the complex type definition is a simple type definition, then one of the following must be true: + switch (baseType.getContentType()) { + case SchemaType.SIMPLE_CONTENT: + // 5.1.1 The {content type} of the {base type definition} must be a simple type definition of which the {content type} is a �valid restriction� as defined in Derivation Valid (Restriction, Simple) (�3.14.6). + SchemaType cType = sType.getContentBasedOnType(); + if (cType != baseType) { + // We have to check that the contentType is legally derived + // from the base simple type in the hierarchy + SchemaType bType = baseType; + while (bType != null && !bType.isSimpleType()) { + bType = bType.getContentBasedOnType(); + } + if (bType != null && !bType.isAssignableFrom(cType)) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$SC_NOT_DERIVED, + null, location); + return false; + } + } + break; + + case SchemaType.MIXED_CONTENT: + // 5.1.2 The {base type definition} must be mixed and have a particle which is �emptiable� as defined in Particle Emptiable (�3.9.6). + if (baseType.getContentModel() != null && !baseType.getContentModel().isSkippable()) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$SC_AND_MIXED_EMPTIABLE, + null, location); + return false; + } + break; + + default: + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$SC_AND_SIMPLE_TYPE_OR_MIXED, + null, location); + return false; + } + break; + + case SchemaType.EMPTY_CONTENT: + // 5.2 If the {content type} of the complex type itself is empty , then one of the following must be true: + switch (baseType.getContentType()) { + case SchemaType.EMPTY_CONTENT: + // 5.2.1 The {content type} of the {base type definition} must also be empty. + break; + case SchemaType.MIXED_CONTENT: + case SchemaType.ELEMENT_CONTENT: + // 5.2.2 The {content type} of the {base type definition} must be elementOnly or mixed and have a particle which is �emptiable� as defined in Particle Emptiable (�3.9.6). + if (baseType.getContentModel() != null && !baseType.getContentModel().isSkippable()) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$EMPTY_AND_ELEMENT_OR_MIXED_EMPTIABLE, + null, location); + return false; + } + break; + default: + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$EMPTY_AND_NOT_SIMPLE, + null, location); + return false; + } + break; + + case SchemaType.MIXED_CONTENT: + // 5.3 If the {content type} of the {base type definition} is mixed... + if (baseType.getContentType() != SchemaType.MIXED_CONTENT) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_MIXED, + null, location); + return false; + } + + // FALLTHROUGH + case SchemaType.ELEMENT_CONTENT: + // 5.3 ... or the {content type} of the complex type definition itself is element-only,... + if (baseType.getContentType() == SchemaType.EMPTY_CONTENT) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_EMPTY, + null, location); + return false; + } + if (baseType.getContentType() == SchemaType.SIMPLE_CONTENT) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_SIMPLE, + null, location); + return false; + } + + // 5.3 ... then the particle of the complex type definition itself must be a �valid restriction� of the particle of the {content type} of the {base type definition} + SchemaParticle baseModel = baseType.getContentModel(); + SchemaParticle derivedModel = sType.getContentModel(); + + if (derivedModel == null && sType.getDerivationType() == SchemaType.DT_RESTRICTION) { + // it is ok to have an empty contentModel if it's a restriction + // see Particle Valid (Restriction) (3.9.6) all three bulets 2.2.1 + return true; + } else if (baseModel == null || derivedModel == null) { + XBeanDebug.logStackTrace("Null models that weren't caught by EMPTY_CONTENT: " + baseType + " (" + baseModel + "), " + sType + " (" + derivedModel + ")"); + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_VALID, null, location); + return false; + } + + // 5.3 ... as defined in Particle Valid (Restriction) (�3.9.6). + List errors = new ArrayList<>(); + boolean isValid = isParticleValidRestriction(baseModel, derivedModel, errors, location); + if (!isValid) { + // we only add the last error, because isParticleValidRestriction may add errors + // to the collection that it later changes its mind about, or it may (inadvertently) + // forget to describe an error into the collection.... + if (errors.size() == 0) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_VALID, null, location); + } else { + state.getErrorListener().add(errors.get(errors.size() - 1)); + } + //state.getErrorListener().addAll(errors); + return false; // KHK: should return false, right? + } + } + } + return true; + } + + /** + * This function takes in two schema particle types, a baseModel, and a derived model and returns true if the + * derivedModel can be egitimately be used for restriction. Errors are put into the errors collections. + * + * @param baseModel - The base schema particle + * @param derivedModel - The derived (restricted) schema particle + * @param errors - Invalid restriction errors are put into this collection + * @param context . the context + * @return boolean, true if valid restruction, false if invalid restriction + * @ + */ + public static boolean isParticleValidRestriction(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + boolean restrictionValid = false; + // 1 They are the same particle. + if (baseModel.equals(derivedModel)) { + restrictionValid = true; + } else { + // Implement table defined in schema spec on restrictions at: + // http://www.w3.org/TR/xmlschema-1/#cos-particle-restrict + switch (baseModel.getParticleType()) { + case SchemaParticle.ELEMENT: + switch (derivedModel.getParticleType()) { + case SchemaParticle.ELEMENT: + restrictionValid = nameAndTypeOK((SchemaLocalElement) baseModel, (SchemaLocalElement) derivedModel, errors, context); + break; + case SchemaParticle.WILDCARD: + case SchemaParticle.ALL: + case SchemaParticle.CHOICE: + case SchemaParticle.SEQUENCE: + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, context)); + restrictionValid = false; + break; + default: + assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); + } + break; + case SchemaParticle.WILDCARD: + switch (derivedModel.getParticleType()) { + case SchemaParticle.ELEMENT: + restrictionValid = nsCompat(baseModel, (SchemaLocalElement) derivedModel, errors, context); + break; + case SchemaParticle.WILDCARD: + restrictionValid = nsSubset(baseModel, derivedModel, errors, context); + break; + case SchemaParticle.ALL: + case SchemaParticle.CHOICE: + case SchemaParticle.SEQUENCE: + restrictionValid = nsRecurseCheckCardinality(baseModel, derivedModel, errors, context); + break; + default: + assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); + } + break; + case SchemaParticle.ALL: + switch (derivedModel.getParticleType()) { + case SchemaParticle.ELEMENT: + restrictionValid = recurseAsIfGroup(baseModel, derivedModel, errors, context); + break; + case SchemaParticle.WILDCARD: + case SchemaParticle.CHOICE: + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, context)); + restrictionValid = false; + break; + case SchemaParticle.ALL: + restrictionValid = recurse(baseModel, derivedModel, errors, context); + break; + case SchemaParticle.SEQUENCE: + restrictionValid = recurseUnordered(baseModel, derivedModel, errors, context); + break; + default: + assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); + } + break; + case SchemaParticle.CHOICE: + switch (derivedModel.getParticleType()) { + case SchemaParticle.ELEMENT: + restrictionValid = recurseAsIfGroup(baseModel, derivedModel, errors, context); + break; + case SchemaParticle.WILDCARD: + case SchemaParticle.ALL: + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, context)); + restrictionValid = false; + break; + case SchemaParticle.CHOICE: + restrictionValid = recurseLax(baseModel, derivedModel, errors, context); + break; + case SchemaParticle.SEQUENCE: + restrictionValid = mapAndSum(baseModel, derivedModel, errors, context); + break; + default: + assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); + } + break; + case SchemaParticle.SEQUENCE: + switch (derivedModel.getParticleType()) { + case SchemaParticle.ELEMENT: + restrictionValid = recurseAsIfGroup(baseModel, derivedModel, errors, context); + break; + case SchemaParticle.WILDCARD: + case SchemaParticle.ALL: + case SchemaParticle.CHOICE: + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, context)); + restrictionValid = false; + break; + case SchemaParticle.SEQUENCE: + restrictionValid = recurse(baseModel, derivedModel, errors, context); + break; + default: + assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); + } + break; + default: + assert false : XBeanDebug.logStackTrace("Unknown schema type for Base Type"); + + } + } + + return restrictionValid; + } + + private static boolean mapAndSum(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // mapAndSum is call if base: CHOICE, derived: SEQUENCE + assert baseModel.getParticleType() == SchemaParticle.CHOICE; + assert derivedModel.getParticleType() == SchemaParticle.SEQUENCE; + // Schema Component Constraint: Particle Derivation OK (Sequence:Choice -- MapAndSum) + // For a sequence group particle to be a �valid restriction� of a choice group particle all of the following + // must be true: + // 1 There is a complete functional mapping from the particles in the {particles} of R to the particles in the + // {particles} of B such that each particle in the {particles} of R is a �valid restriction� of the particle in + // the {particles} of B it maps to as defined by Particle Valid (Restriction) (�3.9.6). + // interpretation: each particle child in derived should have a match in base. + // 2 The pair consisting of the product of the {min occurs} of R and the length of its {particles} and unbounded + // if {max occurs} is unbounded otherwise the product of the {max occurs} of R and the length of its {particles} + // is a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). + // NOTE: This clause is in principle more restrictive than absolutely necessary, but in practice will cover + // all the likely cases, and is much easier to specify than the fully general version. + // NOTE: This case allows the "unfolding" of iterated disjunctions into sequences. It may be particularly useful + // when the disjunction is an implicit one arising from the use of substitution groups. + + // Map step - for each member of the derived model's particle children search base model's particle children + // for match + SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren(); + SchemaParticle[] baseParticleArray = baseModel.getParticleChildren(); + for (SchemaParticle derivedParticle : derivedParticleArray) { + boolean foundMatch = false; + for (SchemaParticle baseParticle : baseParticleArray) { + // recurse to check if there is a match + if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) { + // if there is a match then no need to check base particles anymore + foundMatch = true; + break; + } + } + if (!foundMatch) { + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$MAP, + new Object[]{printParticle(derivedParticle)}, + context)); + // KHK: if we don't return false now, this error may get swallowed by an error produced below + return false; + } + } + + // Sum step + BigInteger derivedRangeMin = derivedModel.getMinOccurs().multiply(BigInteger.valueOf(derivedModel.getParticleChildren().length)); + BigInteger derivedRangeMax; + if (derivedModel.getMaxOccurs() == null) { + derivedRangeMax = null; + } else { + derivedRangeMax = derivedModel.getMaxOccurs().multiply(BigInteger.valueOf(derivedModel.getParticleChildren().length)); + } + + // Now check derivedRange (derivedRangeMin and derivedRangeMax) against base model occurrence range + // Schema Component Constraint: Occurrence Range OK + // For a particle's occurrence range to be a valid restriction of another's occurrence range all of the following must be true: + // 1 Its {min occurs} is greater than or equal to the other's {min occurs}. + // 2 one of the following must be true: + // 2.1 The other's {max occurs} is unbounded. + // 2.2 Both {max occurs} are numbers, and the particle's is less than or equal to the other's. + + boolean mapAndSumValid = true; + if (derivedRangeMin.compareTo(baseModel.getMinOccurs()) < 0) { + mapAndSumValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MIN_OCCURS_GTE_MIN_OCCURS, + new Object[]{derivedRangeMin.toString(), baseModel.getMinOccurs().toString()}, + context)); + } else if (baseModel.getMaxOccurs() != null && (derivedRangeMax == null || derivedRangeMax.compareTo(baseModel.getMaxOccurs()) > 0)) { + mapAndSumValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MAX_OCCURS_LTE_MAX_OCCURS, + new Object[]{derivedRangeMax == null ? "unbounded" : derivedRangeMax.toString(), baseModel.getMaxOccurs().toString()}, + context)); + } + + return mapAndSumValid; + } + + private static boolean recurseAsIfGroup(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // recurseAsIfGroup is called if: + // base: ALL, derived: ELEMENT + // base: CHOICE, derived: ELEMENT + // base: SEQUENCE, derived: ELEMENT + assert (baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.ELEMENT) + || (baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.ELEMENT) + || (baseModel.getParticleType() == SchemaParticle.SEQUENCE && derivedModel.getParticleType() == SchemaParticle.ELEMENT); + // Schema Component Constraint: Particle Derivation OK (Elt:All/Choice/Sequence -- RecurseAsIfGroup) + + // For an element declaration particle to be a �valid restriction� of a group particle + // (all, choice or sequence) a group particle of the variety corresponding to B's, with {min occurs} and + // {max occurs} of 1 and with {particles} consisting of a single particle the same as the element declaration + // must be a �valid restriction� of the group as defined by Particle Derivation OK + // (All:All,Sequence:Sequence -- Recurse) (�3.9.6), Particle Derivation OK (Choice:Choice -- RecurseLax) + // (�3.9.6) or Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) (�3.9.6), depending on whether + // the group is all, choice or sequence + + // interpretation: make a fake group of the right type, with min occurs and max occurs of 1 + SchemaParticleImpl asIfPart = new SchemaParticleImpl(); + asIfPart.setParticleType(baseModel.getParticleType()); + asIfPart.setMinOccurs(BigInteger.ONE); + asIfPart.setMaxOccurs(BigInteger.ONE); + asIfPart.setParticleChildren(new SchemaParticle[]{derivedModel}); + + // the recurse + return isParticleValidRestriction(baseModel, asIfPart, errors, context); + } + + private static boolean recurseLax(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // recurseLax is called if base: CHOICE, derived: CHOICE + assert baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.CHOICE; + boolean recurseLaxValid = true; + //Schema Component Constraint: Particle Derivation OK (Choice:Choice -- RecurseLax) + // For a choice group particle to be a �valid restriction� of another choice group particle all of the + // following must be true: + // 1 R's occurrence range is a valid restriction of B's occurrence range as defined by Occurrence + // Range OK (�3.9.6); + // 2 There is a complete �order-preserving� functional mapping from the particles in the {particles} of R + // to the particles in the {particles} of B such that each particle in the {particles} of R is a + // �valid restriction� of the particle in the {particles} of B it maps to as defined by + // Particle Valid (Restriction) (�3.9.6). + // NOTE: Although the �validation� semantics of a choice group does not depend on the order of its particles, + // derived choice groups are required to match the order of their base in order to simplify + // checking that the derivation is OK. + // interpretation: check derived choices for match in order, must get an in order match on a base particle, + // don't need to check if base particles are skippable. a lot like recurse + + if (!occurrenceRangeOK(baseModel, derivedModel, errors, context)) { + return false; + } + // cycle thru both derived particle children and base particle children looking for matches + // if the derived particle does not match the base particle then base particle can be skipped + + SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren(); + SchemaParticle[] baseParticleArray = baseModel.getParticleChildren(); + int i = 0, j = 0; + while (i < derivedParticleArray.length && j < baseParticleArray.length) { + SchemaParticle derivedParticle = derivedParticleArray[i]; + SchemaParticle baseParticle = baseParticleArray[j]; + // try to match the two particles by recursing + if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) { + // cool found a match, increment both indexes + i++; + j++; + } else { + // did not match, increment the base particle array index only + // Ok, let's skip this base particle, increment base particle array index only + j++; + } + } + + // ok, got to the end of one of the arrays + // if at end of base particle array and not at the end of derived particle array then remaining derived + // particles must not match + if (i < derivedParticleArray.length) { + recurseLaxValid = false; + //String message = "Found derived particles that are not matched in the base content model."; + //errors.add(XmlError.forObject(formatDerivedMappingError(message, baseModel, derivedModel), context)); + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_LAX$MAP, + new Object[]{printParticles(baseParticleArray, i)}, + context)); + } + + + return recurseLaxValid; + } + + private static boolean recurseUnordered(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // recurseUnorder is called when base: ALL and derived: SEQ + assert baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.SEQUENCE; + boolean recurseUnorderedValid = true; + // Schema Component Constraint: Particle Derivation OK (Sequence:All -- RecurseUnordered) + // For a sequence group particle to be a �valid restriction� of an all group particle all of the + // following must be true: + // 1 R's occurrence range is a valid restriction of B's occurrence range as defined by + // Occurrence Range OK (�3.9.6). + // 2 There is a complete functional mapping from the particles in the {particles} of R to the particles + // in the {particles} of B such that all of the following must be true: + // 2.1 No particle in the {particles} of B is mapped to by more than one of the particles in + // the {particles} of R; + // 2.2 Each particle in the {particles} of R is a �valid restriction� of the particle in the {particles} of B + // it maps to as defined by Particle Valid (Restriction) (�3.9.6); + // 2.3 All particles in the {particles} of B which are not mapped to by any particle in the {particles} + // of R are �emptiable� as defined by Particle Emptiable (�3.9.6). + // NOTE: Although this clause allows reordering, because of the limits on the contents of all groups the + // checking process can still be deterministic. + // 1, 2.2, and 2.3 are the same as recurse, so do 2.1 and then call recurse + + if (!occurrenceRangeOK(baseModel, derivedModel, errors, context)) { + return false; + } + + // read baseParticle array QNames into hashmap + SchemaParticle[] baseParticles = baseModel.getParticleChildren(); + HashMap baseParticleMap = new HashMap<>(10); + final Object MAPPED = new Object(); + // Initialize the hashmap + for (SchemaParticle particle : baseParticles) { + baseParticleMap.put(particle.getName(), particle); + } + + // go thru the sequence (derived model's children) and check off from base particle map + SchemaParticle[] derivedParticles = derivedModel.getParticleChildren(); + for (SchemaParticle derivedParticle : derivedParticles) { + Object baseParticle = baseParticleMap.get(derivedParticle.getName()); + if (baseParticle == null) { + recurseUnorderedValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP, + new Object[]{printParticle(derivedParticle)}, context)); + break; + } else { + // got a match + if (baseParticle == MAPPED) { + // whoa, this base particle has already been matched (see 2.1 above) + recurseUnorderedValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_UNIQUE, + new Object[]{printParticle(derivedParticle)}, context)); + break; + } else { + SchemaParticle matchedBaseParticle = (SchemaParticle) baseParticle; + if (derivedParticle.getMaxOccurs() == null || + derivedParticle.getMaxOccurs().compareTo(BigInteger.ONE) > 0) { + // no derived particles can have a max occurs greater than 1 + recurseUnorderedValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_MAX_OCCURS_1, + new Object[]{printParticle(derivedParticle), printMaxOccurs(derivedParticle.getMinOccurs())}, + context)); + break; + } + if (!isParticleValidRestriction(matchedBaseParticle, derivedParticle, errors, context)) { + // already have an error + recurseUnorderedValid = false; + break; + } + // everything is cool, got a match, update to MAPPED + baseParticleMap.put(derivedParticle.getName(), MAPPED); + } + } + } + + // if everything is cool so far then check to see if any base particles are not matched + if (recurseUnorderedValid) { + // get all the hashmap keys and loop thru looking for NOT_MAPPED + Set baseParticleCollection = baseParticleMap.keySet(); + for (QName baseParticleQName : baseParticleCollection) { + if (baseParticleMap.get(baseParticleQName) != MAPPED && !((SchemaParticle) baseParticleMap.get(baseParticleQName)).isSkippable()) { + // this base particle was not mapped and is not "particle emptiable" (skippable) + recurseUnorderedValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$UNMAPPED_ARE_EMPTIABLE, + new Object[]{printParticle((SchemaParticle) baseParticleMap.get(baseParticleQName))}, + context)); + } + } + } + + return recurseUnorderedValid; + } + + private static boolean recurse(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // recurse is called when base: ALL derived: ALL or base: SEQUENCE derived: SEQUENCE + boolean recurseValid = true; + // For an all or sequence group particle to be a �valid restriction� of another group particle with the same + // {compositor} all of the following must be true: + // 1 R's occurrence range is a valid restriction of B's occurrence range as defined by + // Occurrence Range OK (�3.9.6). + // 2 There is a complete �order-preserving� functional mapping from the particles in the {particles} of R to + // the particles in the {particles} of B such that all of the following must be true: + // 2.1 Each particle in the {particles} of R is a �valid restriction� of the particle in the {particles} + // of B it maps to as defined by Particle Valid (Restriction) (�3.9.6). + // 2.2 All particles in the {particles} of B which are not mapped to by any particle in the {particles} + // of R are �emptiable� as defined by Particle Emptiable (�3.9.6). + // NOTE: Although the �validation� semantics of an all group does not depend on the order of its particles, + // derived all groups are required to match the order of their base in order to simplify checking that + // the derivation is OK. + // [Definition:] A complete functional mapping is order-preserving if each particle r in the domain R maps + // to a particle b in the range B which follows (not necessarily immediately) the particle in the range B + // mapped to by the predecessor of r, if any, where "predecessor" and "follows" are defined with respect to + // the order of the lists which constitute R and B. + + if (!occurrenceRangeOK(baseModel, derivedModel, errors, context)) { + // error message is formatted in occurrencRangeOK ... + return false; + } + // cycle thru both derived particle children and base particle children looking for matches + // if the derived particle does not match the base particle then base particle can be skipped if it is + // skippable (same as "particle emptiable") otherwise is an invalid restriction. + // after the derived particles have been cycled if there are any base particles left over then they + // must be skippable or invalid restriction + + SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren(); + SchemaParticle[] baseParticleArray = baseModel.getParticleChildren(); + int i = 0, j = 0; + while (i < derivedParticleArray.length && j < baseParticleArray.length) { + SchemaParticle derivedParticle = derivedParticleArray[i]; + SchemaParticle baseParticle = baseParticleArray[j]; + // try to match the two particles by recursing + if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) { + // cool found a match, increment both indexes + i++; + j++; + } else { + // did not match, increment the base particle array index only + // that's ok if the base particle is skippable + if (baseParticle.isSkippable()) { + // Ok, let's skip this base particle, increment base particle array index only + j++; + } else { + // whoa, particles are not valid restrictions and base is not skippable - ERROR + recurseValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE$MAP_VALID, + new Object[]{printParticle(derivedParticle), printParticle(derivedModel), + printParticle(baseParticle), printParticle(baseModel)}, + context)); + break; + } + } + } + + // ok, got to the end of one of the arrays + // if at end of base particle array and not at the end of derived particle array then remaining derived + // particles must not match + if (i < derivedParticleArray.length) { + recurseValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE$MAP, + new Object[]{printParticle(derivedModel), printParticle(baseModel), printParticles(derivedParticleArray, i)}, + context)); + } else { + // if at end of derived particle array and not at end of base particle array then chck remaining + // base particles to assure they are skippable + if (j < baseParticleArray.length) { + ArrayList particles = new ArrayList<>(baseParticleArray.length); + for (int k = j; k < baseParticleArray.length; k++) { + if (!baseParticleArray[k].isSkippable()) { + particles.add(baseParticleArray[k]); + } + } + if (particles.size() > 0) { + recurseValid = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE$UNMAPPED_ARE_EMPTIABLE, + new Object[]{printParticle(baseModel), printParticle(derivedModel), printParticles(particles)}, context)); + } + } + } + + return recurseValid; + } + + private static boolean nsRecurseCheckCardinality(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // nsRecurseCheckCardinality is called when: + // base: ANY, derived: ALL + // base: ANY, derived: CHOICE + // base: ANY, derived: SEQUENCE + assert baseModel.getParticleType() == SchemaParticle.WILDCARD; + assert (derivedModel.getParticleType() == SchemaParticle.ALL) + || (derivedModel.getParticleType() == SchemaParticle.CHOICE) + || (derivedModel.getParticleType() == SchemaParticle.SEQUENCE); + boolean nsRecurseCheckCardinality = true; + // For a group particle to be a �valid restriction� of a wildcard particle all of the following must be true: + // 1 Every member of the {particles} of the group is a �valid restriction� of the wildcard as defined by Particle Valid (Restriction) (�3.9.6). + // Note: not positive what this means. Interpreting to mean that every particle of the group must adhere to wildcard derivation rules + // in a recursive manner + // Loop thru the children particles of the group and invoke the appropriate function to check for wildcard restriction validity + + // BAU - an errata should be submitted on this clause of the spec, because the + // spec makes no sense, as the xstc particlesR013.xsd test exemplifies. + // what we _should_ so is an "as if" on the wildcard, allowing it minOccurs="0" maxOccurs="unbounded" + // before recursing + SchemaParticleImpl asIfPart = new SchemaParticleImpl(); + asIfPart.setParticleType(baseModel.getParticleType()); + asIfPart.setWildcardProcess(baseModel.getWildcardProcess()); + asIfPart.setWildcardSet(baseModel.getWildcardSet()); + asIfPart.setMinOccurs(BigInteger.ZERO); + asIfPart.setMaxOccurs(null); + asIfPart.setTransitionRules(baseModel.getWildcardSet(), true); + asIfPart.setTransitionNotes(baseModel.getWildcardSet(), true); + + SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); + for (SchemaParticle particle : particleChildren) { + switch (particle.getParticleType()) { + case SchemaParticle.ELEMENT: + // Check for valid Wildcard/Element derivation + nsRecurseCheckCardinality = nsCompat(asIfPart, (SchemaLocalElement) particle, errors, context); + break; + case SchemaParticle.WILDCARD: + // Check for valid Wildcard/Wildcard derivation + nsRecurseCheckCardinality = nsSubset(asIfPart, particle, errors, context); + break; + case SchemaParticle.ALL: + case SchemaParticle.CHOICE: + case SchemaParticle.SEQUENCE: + // Check for valid Wildcard/Group derivation + nsRecurseCheckCardinality = nsRecurseCheckCardinality(asIfPart, particle, errors, context); + break; + default: + break; + } + // If any particle is invalid then break the loop + if (!nsRecurseCheckCardinality) { + break; + } + } + + // 2 The effective total range of the group, as defined by Effective Total Range (all and sequence) (�3.8.6) + // (if the group is all or sequence) or Effective Total Range (choice) (�3.8.6) (if it is choice) is a valid + // restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). + + if (nsRecurseCheckCardinality) { + nsRecurseCheckCardinality = checkGroupOccurrenceOK(baseModel, derivedModel, errors, context); + } + + return nsRecurseCheckCardinality; + } + + private static boolean checkGroupOccurrenceOK(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + boolean groupOccurrenceOK = true; + BigInteger minRange = BigInteger.ZERO; + BigInteger maxRange = BigInteger.ZERO; + switch (derivedModel.getParticleType()) { + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + minRange = getEffectiveMinRangeAllSeq(derivedModel); + maxRange = getEffectiveMaxRangeAllSeq(derivedModel); + break; + case SchemaParticle.CHOICE: + minRange = getEffectiveMinRangeChoice(derivedModel); + maxRange = getEffectiveMaxRangeChoice(derivedModel); + break; + default: + break; + } + + // Check min occurs for validity + // derived min occurs is valid if its {min occurs} is greater than or equal to the other's {min occurs}. + if (minRange.compareTo(baseModel.getMinOccurs()) < 0) { + groupOccurrenceOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MIN_GTE_MIN, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, + context)); + } + // Check max occurs for validity + // one of the following must be true: + // The base model's {max occurs} is unbounded. + // or both {max occurs} are numbers, and the particle's is less than or equal to the other's + if (baseModel.getMaxOccurs() != null) { + if (maxRange == null) { + groupOccurrenceOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, + context)); + } else { + if (maxRange.compareTo(baseModel.getMaxOccurs()) > 0) { + groupOccurrenceOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, + context)); + } + } + } + return groupOccurrenceOK; + } + + private static BigInteger getEffectiveMaxRangeChoice(SchemaParticle derivedModel) { + BigInteger maxRange = BigInteger.ZERO; + // Schema Component Constraint: Effective Total Range (choice) + // The effective total range of a particle whose {term} is a group whose {compositor} is choice + // is a pair of minimum and maximum, as follows: + // MAXIMUM + // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or + // the maximum part of the effective total range of any of the group particles in the group's {particles} is + // unbounded (note: seems to be the same as Max Range All or Sequence), + // or 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded, + // otherwise 3) the product of the particle's {max occurs} and the maximum of the {max occurs} of every + // wildcard or element declaration particle in the group's {particles} and the *maximum* (note: this is the difference + // between MaxRange Choice ans MaxRange All or Sequence) part of the + // effective total range of each of the group particles in the group's {particles} + // (or 0 if there are no {particles}). + + boolean nonZeroParticleChildFound = false; + BigInteger maxOccursInWildCardOrElement = BigInteger.ZERO; + BigInteger maxOccursInGroup = BigInteger.ZERO; + SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); + for (SchemaParticle particle : particleChildren) { + switch (particle.getParticleType()) { + case SchemaParticle.WILDCARD: + case SchemaParticle.ELEMENT: + // if unbounded then maxoccurs will be null + if (particle.getMaxOccurs() == null) { + maxRange = null; + } else { + if (particle.getIntMaxOccurs() > 0) { + // show tht at least one non-zero particle is found for later test + nonZeroParticleChildFound = true; + if (particle.getMaxOccurs().compareTo(maxOccursInWildCardOrElement) > 0) { + maxOccursInWildCardOrElement = particle.getMaxOccurs(); + } + } + } + break; + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + maxRange = getEffectiveMaxRangeAllSeq(particle); + if (maxRange != null) { + // keep highest maxoccurs found + if (maxRange.compareTo(maxOccursInGroup) > 0) { + maxOccursInGroup = maxRange; + } + } + break; + case SchemaParticle.CHOICE: + maxRange = getEffectiveMaxRangeChoice(particle); + if (maxRange != null) { + // keep highest maxoccurs found + if (maxRange.compareTo(maxOccursInGroup) > 0) { + maxOccursInGroup = maxRange; + } + } + break; + default: + break; + } + // if an unbounded has been found then we are done + if (maxRange == null) { + break; + } + } + + // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or + // the maximum part of the effective total range of any of the group particles in the group's {particles} is + // unbounded + if (maxRange != null) { + // 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded + if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == null) { + maxRange = null; + } else { + // 3) the product of the particle's {max occurs} and the maximum of the {max occurs} of every + // wildcard or element declaration particle in the group's {particles} and the *maximum* + // part of the effective total range of each of the group particles in the group's {particles} + maxRange = derivedModel.getMaxOccurs().multiply(maxOccursInWildCardOrElement.add(maxOccursInGroup)); + } + } + + return maxRange; + } + + private static BigInteger getEffectiveMaxRangeAllSeq(SchemaParticle derivedModel) { + BigInteger maxRange = BigInteger.ZERO; + // Schema Component Constraint: Effective Total Range (all and sequence) + // The effective total range of a particle whose {term} is a group whose {compositor} is all or sequence is a + // pair of minimum and maximum, as follows: + // MAXIMUM + // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or + // the maximum part of the effective total range of any of the group particles in the group's {particles} is + // unbounded, or 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded, otherwise + // 3) the product of the particle's {max occurs} and the *sum* of the {max occurs} of every wildcard or element + // declaration particle in the group's {particles} and the maximum part of the effective total range of each of + // the group particles in the group's {particles} (or 0 if there are no {particles}). + + boolean nonZeroParticleChildFound = false; + BigInteger maxOccursTotal = BigInteger.ZERO; + BigInteger maxOccursInGroup = BigInteger.ZERO; + SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); + for (SchemaParticle particle : particleChildren) { + switch (particle.getParticleType()) { + case SchemaParticle.WILDCARD: + case SchemaParticle.ELEMENT: + // if unbounded then maxoccurs will be null + if (particle.getMaxOccurs() == null) { + maxRange = null; + } else { + if (particle.getIntMaxOccurs() > 0) { + // show tht at least one non-zero particle is found for later test + nonZeroParticleChildFound = true; + maxOccursTotal = maxOccursTotal.add(particle.getMaxOccurs()); + } + } + break; + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + maxRange = getEffectiveMaxRangeAllSeq(particle); + if (maxRange != null) { + // keep highest maxoccurs found + if (maxRange.compareTo(maxOccursInGroup) > 0) { + maxOccursInGroup = maxRange; + } + } + break; + case SchemaParticle.CHOICE: + maxRange = getEffectiveMaxRangeChoice(particle); + if (maxRange != null) { + // keep highest maxoccurs found + if (maxRange.compareTo(maxOccursInGroup) > 0) { + maxOccursInGroup = maxRange; + } + } + break; + default: + break; + } + // if an unbounded has been found then we are done + if (maxRange == null) { + break; + } + } + + // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or + // the maximum part of the effective total range of any of the group particles in the group's {particles} is + // unbounded + if (maxRange != null) { + // 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded + if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == null) { + maxRange = null; + } else { + // 3) the product of the particle's {max occurs} and the sum of the {max occurs} of every wildcard or element + // declaration particle in the group's {particles} and the maximum part of the effective total range of each of + // the group particles in the group's {particles} + maxRange = derivedModel.getMaxOccurs().multiply(maxOccursTotal.add(maxOccursInGroup)); + } + } + + return maxRange; + + } + + private static BigInteger getEffectiveMinRangeChoice(SchemaParticle derivedModel) { + // Schema Component Constraint: Effective Total Range (choice) + // The effective total range of a particle whose {term} is a group whose {compositor} is choice is a pair of + // minimum and maximum, as follows: + // MINIMUM + // The product of the particle's {min occurs} + // and the *minimum* of the {min occurs} of every wildcard or element + // declaration particle in the group's {particles} and the minimum part of the effective total range of each of + // the group particles in the group's {particles} (or 0 if there are no {particles}). + SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); + if (particleChildren.length == 0) { + return BigInteger.ZERO; + } + BigInteger minRange = null; + // get the minimum of every wildcard or element + // total up the effective total range for each group + for (SchemaParticle particle : particleChildren) { + switch (particle.getParticleType()) { + case SchemaParticle.WILDCARD: + case SchemaParticle.ELEMENT: + if (minRange == null || minRange.compareTo(particle.getMinOccurs()) > 0) { + minRange = particle.getMinOccurs(); + } + break; + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + BigInteger mrs = getEffectiveMinRangeAllSeq(particle); + if (minRange == null || minRange.compareTo(mrs) > 0) { + minRange = mrs; + } + break; + case SchemaParticle.CHOICE: + BigInteger mrc = getEffectiveMinRangeChoice(particle); + if (minRange == null || minRange.compareTo(mrc) > 0) { + minRange = mrc; + } + break; + default: + break; + } + } + if (minRange == null) { + minRange = BigInteger.ZERO; + } + + // calculate the total + minRange = derivedModel.getMinOccurs().multiply(minRange); + return minRange; + } + + private static BigInteger getEffectiveMinRangeAllSeq(SchemaParticle derivedModel) { + BigInteger minRange; + // Schema Component Constraint: Effective Total Range (all and sequence) + // The effective total range of a particle whose {term} is a group whose {compositor} is all or sequence is a + // pair of minimum and maximum, as follows: + // MINIMUM + // The product of the particle's {min occurs} + // and the *sum* of the {min occurs} of every wildcard or element + // declaration particle in the group's {particles} + // and the minimum part of the effective total range of each + // of the group particles in the group's {particles} (or 0 if there are no {particles}). + SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); + BigInteger particleTotalMinOccurs = BigInteger.ZERO; + for (SchemaParticle particle : particleChildren) { + switch (particle.getParticleType()) { + case SchemaParticle.WILDCARD: + case SchemaParticle.ELEMENT: + particleTotalMinOccurs = particleTotalMinOccurs.add(particle.getMinOccurs()); + break; + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + particleTotalMinOccurs = particleTotalMinOccurs.add(getEffectiveMinRangeAllSeq(particle)); + break; + case SchemaParticle.CHOICE: + particleTotalMinOccurs = particleTotalMinOccurs.add(getEffectiveMinRangeChoice(particle)); + break; + default: + break; + } + } + + minRange = derivedModel.getMinOccurs().multiply(particleTotalMinOccurs); + + return minRange; + } + + private static boolean nsSubset(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { + // nsSubset is called when base: ANY, derived: ANY + assert baseModel.getParticleType() == SchemaParticle.WILDCARD; + assert derivedModel.getParticleType() == SchemaParticle.WILDCARD; + boolean nsSubset; + // For a wildcard particle to be a �valid restriction� of another wildcard particle all of the following must be true: + // 1 R's occurrence range must be a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). + if (occurrenceRangeOK(baseModel, derivedModel, errors, context)) { + // 2 R's {namespace constraint} must be an intensional subset of B's {namespace constraint} as defined + // by Wildcard Subset (�3.10.6). + if (baseModel.getWildcardSet().inverse().isDisjoint(derivedModel.getWildcardSet())) { + nsSubset = true; + } else { + nsSubset = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_NS_SUBST$WILDCARD_SUBSET, + new Object[]{printParticle(derivedModel), printParticle(baseModel)}, context)); + } + } else { + nsSubset = false; + // error already produced by occurrenceRangeOK + //errors.add(XmlError.forObject(formatNSIsNotSubsetError(baseModel, derivedModel), context)); + } + + + return nsSubset; + } + + private static boolean nsCompat(SchemaParticle baseModel, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { + // nsCompat is called when base: ANY, derived: ELEMENT + assert baseModel.getParticleType() == SchemaParticle.WILDCARD; + boolean nsCompat; + // For an element declaration particle to be a �valid restriction� of a wildcard particle all of the following must be true: + // 1 The element declaration's {target namespace} is �valid� with respect to the wildcard's {namespace constraint} + // as defined by Wildcard allows Namespace Name (�3.10.4). + if (baseModel.getWildcardSet().contains(derivedElement.getName())) { + // 2 R's occurrence range is a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). + nsCompat = occurrenceRangeOK(baseModel, (SchemaParticle) derivedElement, errors, context); + } else { + nsCompat = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_NS_COMPAT$WILDCARD_VALID, + new Object[]{printParticle((SchemaParticle) derivedElement), printParticle(baseModel)}, + context)); + } + + + return nsCompat; + } + + private static boolean nameAndTypeOK(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { + // nameAndTypeOK called when base: ELEMENT and derived: ELEMENT + + // Schema Component Constraint: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) + // 1 The declarations' {name}s and {target namespace}s are the same. + if (!((SchemaParticle) baseElement).canStartWithElement(derivedElement.getName())) { + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$NAME, + new Object[]{printParticle((SchemaParticle) derivedElement), printParticle((SchemaParticle) baseElement)}, context)); + return false; + } + + // 2 Either B's {nillable} is true or R's {nillable} is false. + if (!baseElement.isNillable() && derivedElement.isNillable()) { + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$NILLABLE, + new Object[]{printParticle((SchemaParticle) derivedElement), printParticle((SchemaParticle) baseElement)}, context)); + return false; + } + + // 3 R's occurrence range is a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). + if (!occurrenceRangeOK((SchemaParticle) baseElement, (SchemaParticle) derivedElement, errors, context)) { + // error already produced + return false; + } + + // 4 either B's declaration's {value constraint} is absent, or is not fixed, + // or R's declaration's {value constraint} is fixed with the same value. + if (!checkFixed(baseElement, derivedElement, errors, context)) { + // error already produced + return false; + } + + // 5 R's declaration's {identity-constraint definitions} is a subset of B's declaration's {identity-constraint definitions}, if any. + if (!checkIdentityConstraints(baseElement, derivedElement, errors, context)) { + // error already produced + return false; + } + + // 7 R's {type definition} is validly derived given {extension, list, union} from B's {type definition} as + // defined by Type Derivation OK (Complex) (�3.4.6) or Type Derivation OK (Simple) (�3.14.6), as appropriate. + if (!typeDerivationOK(baseElement.getType(), derivedElement.getType(), errors, context)) { + // error already produced + return false; + } + + // 6 R's declaration's {disallowed substitutions} is a superset of B's declaration's {disallowed substitutions}. + return blockSetOK(baseElement, derivedElement, errors, context); + } + + private static boolean blockSetOK(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { + if (baseElement.blockRestriction() && !derivedElement.blockRestriction()) { + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS, + new Object[]{printParticle((SchemaParticle) derivedElement), "restriction", printParticle((SchemaParticle) baseElement)}, + context)); + return false; + } + if (baseElement.blockExtension() && !derivedElement.blockExtension()) { + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS, + new Object[]{printParticle((SchemaParticle) derivedElement), "extension", printParticle((SchemaParticle) baseElement)}, + context)); + return false; + } + if (baseElement.blockSubstitution() && !derivedElement.blockSubstitution()) { + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS, + new Object[]{printParticle((SchemaParticle) derivedElement), "substitution", printParticle((SchemaParticle) baseElement)}, + context)); + return false; + } + return true; + } + + private static boolean typeDerivationOK(SchemaType baseType, SchemaType derivedType, Collection errors, XmlObject context) { + boolean typeDerivationOK; + // 1 If B and D are not the same type definition, then the {derivation method} of D must not be in the subset. + // 2 One of the following must be true: + // 2.1 B and D must be the same type definition. + // 2.2 B must be D's {base type definition}. + // 2.3 All of the following must be true: + // 2.3.1 D's {base type definition} must not be the �ur-type definition�. + // 2.3.2 The appropriate case among the following must be true: + // 2.3.2.1 If D's {base type definition} is complex, then it must be validly derived from B given the subset as defined by this constraint. + // 2.3.2.2 If D's {base type definition} is simple, then it must be validly derived from B given the subset as defined in Type Derivation OK (Simple) (�3.14.6). + // This line will check if derivedType is a subType of baseType (should handle all of the 2.xx checks above) + if (baseType.isAssignableFrom(derivedType)) { + // Ok derived type is subtype but need to make sure that all of the derivations between the two types are by + // Restriction. + typeDerivationOK = checkAllDerivationsForRestriction(baseType, derivedType, errors, context); + } else { + // derived type is not a sub-type of base type + typeDerivationOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$TYPE_VALID, + new Object[]{printType(derivedType), printType(baseType)}, context)); + } + + return typeDerivationOK; + } + + private static boolean checkAllDerivationsForRestriction(SchemaType baseType, SchemaType derivedType, Collection errors, XmlObject context) { + boolean allDerivationsAreRestrictions = true; + SchemaType currentType = derivedType; + + // XMLBEANS-66: if baseType is a union, check restriction is of one of the constituant types + Set possibleTypes = null; + if (baseType.getSimpleVariety() == SchemaType.UNION) { + possibleTypes = new HashSet<>(Arrays.asList(baseType.getUnionConstituentTypes())); + } + + // run up the types hierarchy from derived Type to base Type and make sure that all are derived by + // restriction. If any are not then this is not a valid restriction. + while (!baseType.equals(currentType) && + possibleTypes != null && !possibleTypes.contains(currentType)) { + if (currentType.getDerivationType() == SchemaType.DT_RESTRICTION) { + currentType = currentType.getBaseType(); + } else { + allDerivationsAreRestrictions = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$TYPE_RESTRICTED, + new Object[]{printType(derivedType), printType(baseType), printType(currentType)}, context)); + break; + } + } + return allDerivationsAreRestrictions; + } + + private static boolean checkIdentityConstraints(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { + // 5 R's declaration's {identity-constraint definitions} is a subset of B's declaration's {identity-constraint definitions}, if any. + boolean identityConstraintsOK = true; + + SchemaIdentityConstraint[] baseConstraints = baseElement.getIdentityConstraints(); + SchemaIdentityConstraint[] derivedConstraints = derivedElement.getIdentityConstraints(); + // cycle thru derived's identity constraints and check each to assure they in the array of base constraints + for (SchemaIdentityConstraint derivedConstraint : derivedConstraints) { + if (checkForIdentityConstraintExistence(baseConstraints, derivedConstraint)) { + identityConstraintsOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$IDENTITY_CONSTRAINTS, + new Object[]{printParticle((SchemaParticle) derivedElement), printParticle((SchemaParticle) baseElement)}, + context)); + break; + } + } + return identityConstraintsOK; + } + + private static boolean checkForIdentityConstraintExistence(SchemaIdentityConstraint[] baseConstraints, SchemaIdentityConstraint derivedConstraint) { + // spin thru the base identity constraints check to see if derived constraint exists + boolean identityConstraintExists = false; + for (SchemaIdentityConstraint baseConstraint : baseConstraints) { + if (baseConstraint.getName().equals(derivedConstraint.getName())) { + identityConstraintExists = true; + break; + } + } + return identityConstraintExists; + } + + + private static boolean checkFixed(SchemaLocalElement baseModel, SchemaLocalElement derivedModel, Collection errors, XmlObject context) { + // 4 either B's declaration's {value constraint} is absent, or is not fixed, + // or R's declaration's {value constraint} is fixed with the same value. + boolean checkFixed; + if (baseModel.isFixed()) { + if (baseModel.getDefaultText().equals(derivedModel.getDefaultText())) { + // R's declaration's {value constraint} is fixed with the same value. + checkFixed = true; + } else { + // The derived element has a fixed value that is different than the base element + errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$FIXED, + new Object[]{printParticle((SchemaParticle) derivedModel), derivedModel.getDefaultText(), + printParticle((SchemaParticle) baseModel), baseModel.getDefaultText()}, + context)); + checkFixed = false; + } + } else { + // B's declaration's {value constraint} is absent, or is not fixed, + checkFixed = true; + } + return checkFixed; + } + + private static boolean occurrenceRangeOK(SchemaParticle baseParticle, SchemaParticle derivedParticle, Collection errors, XmlObject context) { + boolean occurrenceRangeOK; + // Note: in the following comments (from the schema spec) other is the baseModel + // 1 Its {min occurs} is greater than or equal to the other's {min occurs}. + if (derivedParticle.getMinOccurs().compareTo(baseParticle.getMinOccurs()) >= 0) { + // 2 one of the following must be true: + // 2.1 The other's {max occurs} is unbounded. + if (baseParticle.getMaxOccurs() == null) { + occurrenceRangeOK = true; + } else { + // 2.2 Both {max occurs} are numbers, and the particle's is less than or equal to the other's. + if (derivedParticle.getMaxOccurs() != null && baseParticle.getMaxOccurs() != null && + derivedParticle.getMaxOccurs().compareTo(baseParticle.getMaxOccurs()) <= 0) { + occurrenceRangeOK = true; + } else { + occurrenceRangeOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX, + new Object[]{printParticle(derivedParticle), printMaxOccurs(derivedParticle.getMaxOccurs()), + printParticle(baseParticle), printMaxOccurs(baseParticle.getMaxOccurs())}, + context)); + } + } + } else { + occurrenceRangeOK = false; + errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MIN_GTE_MIN, + new Object[]{printParticle(derivedParticle), derivedParticle.getMinOccurs().toString(), + printParticle(baseParticle), baseParticle.getMinOccurs().toString()}, + context)); + } + return occurrenceRangeOK; + } + + private static String printParticles(List parts) { + return printParticles(parts.toArray(new SchemaParticle[0])); + } + + private static String printParticles(SchemaParticle[] parts) { + return printParticles(parts, 0, parts.length); + } + + private static String printParticles(SchemaParticle[] parts, int start) { + return printParticles(parts, start, parts.length); + } + + private static String printParticles(SchemaParticle[] parts, int start, int end) { + StringBuilder buf = new StringBuilder(parts.length * 30); + for (int i = start; i < end; ) { + buf.append(printParticle(parts[i])); + if (++i != end) { + buf.append(", "); + } + } + return buf.toString(); + } + + private static String printParticle(SchemaParticle part) { + switch (part.getParticleType()) { + case SchemaParticle.ALL: + return ""; + case SchemaParticle.CHOICE: + return ""; + case SchemaParticle.ELEMENT: + return ""; + case SchemaParticle.SEQUENCE: + return ""; + case SchemaParticle.WILDCARD: + return ""; + default: + return "??"; + } + } + + private static String printMaxOccurs(BigInteger bi) { + if (bi == null) { + return "unbounded"; + } + return bi.toString(); + } + + private static String printType(SchemaType type) { + if (type.getName() != null) { + return QNameHelper.pretty(type.getName()); + } + return type.toString(); + } + + private static void checkSubstitutionGroups(SchemaGlobalElement[] elts) { + StscState state = StscState.get(); + + for (SchemaGlobalElement elt : elts) { + SchemaGlobalElement head = elt.substitutionGroup(); + + if (head != null) { + SchemaType headType = head.getType(); + SchemaType tailType = elt.getType(); + XmlObject parseTree = ((SchemaGlobalElementImpl) elt)._parseObject; + + if (!headType.isAssignableFrom(tailType)) { + state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_VALID, + new Object[]{QNameHelper.pretty(elt.getName()), + QNameHelper.pretty(head.getName())}, + parseTree); + } else if (head.finalExtension() && head.finalRestriction()) { + state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_FINAL, + new Object[]{QNameHelper.pretty(elt.getName()), + QNameHelper.pretty(head.getName()), + "#all"}, parseTree); + } else if (!headType.equals(tailType)) { + if (head.finalExtension() && + tailType.getDerivationType() == SchemaType.DT_EXTENSION) { + state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_FINAL, + new Object[]{QNameHelper.pretty(elt.getName()), + QNameHelper.pretty(head.getName()), + "extension"}, parseTree); + } else if (head.finalRestriction() && + tailType.getDerivationType() == SchemaType.DT_RESTRICTION) { + state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_FINAL, + new Object[]{QNameHelper.pretty(elt.getName()), + QNameHelper.pretty(head.getName()), + "restriction"}, parseTree); + } + } + } + + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java new file mode 100644 index 0000000..d51db24 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java @@ -0,0 +1,1902 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.xb.xsdschema.*; +import org.apache.xmlbeans.impl.xb.xsdschema.AnyDocument.Any; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.*; +import java.util.function.BinaryOperator; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class StscComplexTypeResolver { + public static Group getContentModel(ComplexType parseCt) { + return getContentModel(parseCt::getAll, parseCt::getSequence, parseCt::getChoice, parseCt::getGroup); + } + + public static Group getContentModel(ComplexRestrictionType parseRest) { + return getContentModel(parseRest::getAll, parseRest::getSequence, parseRest::getChoice, parseRest::getGroup); + } + + public static Group getContentModel(ExtensionType parseExt) { + return getContentModel(parseExt::getAll, parseExt::getSequence, parseExt::getChoice, parseExt::getGroup); + } + + @SafeVarargs + private static Group getContentModel(Supplier... grps) { + return Stream.of(grps).map(Supplier::get).filter(Objects::nonNull).findFirst().orElse(null); + } + + static Schema getSchema(XmlObject o) { + XmlCursor c = o.newCursor(); + + try { + while (c.toParent()) { + o = c.getObject(); + + if (o.schemaType().equals(Schema.type)) { + return (Schema) o; + } + } + } finally { + c.dispose(); + } + + return null; + } + + public static void resolveComplexType(SchemaTypeImpl sImpl) { + ComplexType parseCt = (ComplexType) sImpl.getParseObject(); + StscState state = StscState.get(); + Schema schema = getSchema(parseCt); + + // Set abstract & final flags + boolean abs = parseCt.isSetAbstract() && parseCt.getAbstract(); + boolean finalExt = false; + boolean finalRest = false; + boolean finalList = false; + boolean finalUnion = false; + + Object ds = null; + if (parseCt.isSetFinal()) { + ds = parseCt.getFinal(); + } + // Inspect the final default attribute on the schema + else if (schema != null && schema.isSetFinalDefault()) { + ds = schema.getFinalDefault(); + } + + if (ds != null) { + if (ds instanceof String && ds.equals("#all")) { + // #ALL value + finalExt = finalRest = finalList = finalUnion = true; + } else if (ds instanceof List) { + List dsl = (List) ds; + finalExt = dsl.contains("extension"); + finalRest = dsl.contains("restriction"); + +// Since complex types don't participate in list and unions, these can remain +// false. Perhaps we should throw an error. + +// if (((List)ds).contains("list")) +// finalList = true; +// +// if (((List)ds).contains("union")) +// finalUnion = true; + } + } + + sImpl.setAbstractFinal(abs, finalExt, finalRest, finalList, finalUnion); + + // Set block flags + boolean blockExt = false; + boolean blockRest = false; + Object block = null; + + if (parseCt.isSetBlock()) { + block = parseCt.getBlock(); + } else if (schema != null && schema.isSetBlockDefault()) { + block = schema.getBlockDefault(); + } + + if (block != null) { + if (block instanceof String && block.equals("#all")) { + // #ALL value + blockExt = blockRest = true; + } else if (block instanceof List) { + List blist = (List) block; + if (blist.contains("extension")) { + blockExt = true; + } + if (blist.contains("restriction")) { + blockRest = true; + } + } + } + + sImpl.setBlock(blockExt, blockRest); + + // Verify: have simpleContent, complexContent, or direct stuff + ComplexContentDocument.ComplexContent parseCc = parseCt.getComplexContent(); + SimpleContentDocument.SimpleContent parseSc = parseCt.getSimpleContent(); + final Group parseGroup = getContentModel(parseCt); + int count = + (parseCc != null ? 1 : 0) + + (parseSc != null ? 1 : 0) + + (parseGroup != null ? 1 : 0); + if (count > 1) { + // KHK: s4s should catch this? + state.error("A complex type must define either a content model, " + + "or a simpleContent or complexContent derivation: " + + "more than one found.", + XmlErrorCodes.REDUNDANT_CONTENT_MODEL, parseCt); + // recovery: treat it as the first of complexContent, simpleContent, model + if (parseCc != null && parseSc != null) { + parseSc = null; + } + } + + if (parseCc != null) { + // KHK: s4s should catch this? + if (parseCc.getExtension() != null && parseCc.getRestriction() != null) { + state.error("Restriction conflicts with extension", XmlErrorCodes.REDUNDANT_CONTENT_MODEL, parseCc.getRestriction()); + } + + // Mixed can be specified in two places: the rules are that Cc wins over Ct if present + // http://www.w3.org/TR/xmlschema-1/#c-mve + boolean mixed = parseCc.isSetMixed() ? parseCc.getMixed() : parseCt.getMixed(); + + if (parseCc.getExtension() != null) { + resolveCcExtension(sImpl, parseCc.getExtension(), mixed); + } else if (parseCc.getRestriction() != null) { + resolveCcRestriction(sImpl, parseCc.getRestriction(), mixed); + } else { + // KHK: s4s should catch this? + state.error("Missing restriction or extension", XmlErrorCodes.MISSING_RESTRICTION_OR_EXTENSION, parseCc); + resolveErrorType(sImpl); + } + } else if (parseSc != null) { + // KHK: s4s should catch this? + if (parseSc.getExtension() != null && parseSc.getRestriction() != null) { + state.error("Restriction conflicts with extension", XmlErrorCodes.REDUNDANT_CONTENT_MODEL, parseSc.getRestriction()); + } + + if (parseSc.getExtension() != null) { + resolveScExtension(sImpl, parseSc.getExtension()); + } else if (parseSc.getRestriction() != null) { + resolveScRestriction(sImpl, parseSc.getRestriction()); + } else { + // KHK: s4s should catch this? + state.error("Missing restriction or extension", XmlErrorCodes.MISSING_RESTRICTION_OR_EXTENSION, parseSc); + resolveErrorType(sImpl); + } + } else { + resolveBasicComplexType(sImpl); + } + } + + @SuppressWarnings("unused") + static void resolveErrorType(SchemaTypeImpl sImpl) { + throw new RuntimeException("This type of error recovery not yet implemented."); + } + + private static SchemaType.Ref[] makeRefArray(Collection typeList) { + return typeList.stream().map(SchemaType::getRef).toArray(SchemaType.Ref[]::new); + } + + + static void resolveBasicComplexType(SchemaTypeImpl sImpl) { + List anonymousTypes = new ArrayList<>(); + ComplexType parseTree = (ComplexType) sImpl.getParseObject(); + String targetNamespace = sImpl.getTargetNamespace(); + boolean chameleon = (sImpl.getChameleonNamespace() != null); + Group parseGroup = getContentModel(parseTree); + + if (sImpl.isRedefinition()) { + StscState.get().error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, + new Object[]{""}, parseTree); + // recovery: oh well. + } + + int particleCode = translateParticleCode(parseGroup); + + // build content model and anonymous types + SchemaParticle contentModel = translateContentModel(sImpl, + parseGroup, targetNamespace, chameleon, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), + particleCode, anonymousTypes, new LinkedHashMap<>(), false, null); + + // detect the nonempty "all" case (empty doesn't count - it needs to be eliminated to match XSD test cases) + boolean isAll = contentModel != null && contentModel.getParticleType() == SchemaParticle.ALL; + + // build attr model and anonymous types + SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); + translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), + anonymousTypes, sImpl, null, attrModel, null, true, null); + + // summarize wildcard information + WildcardResult wcElt = summarizeEltWildcards(contentModel); + WildcardResult wcAttr = summarizeAttrWildcards(attrModel); + + // build state machine and verify that content model is deterministic + if (contentModel != null) { + buildStateMachine(contentModel); + if (!StscState.get().noUpa() && !((SchemaParticleImpl) contentModel).isDeterministic()) { + StscState.get().error(XmlErrorCodes.UNIQUE_PARTICLE_ATTRIBUTION, null, parseGroup); + } + } + + // build property model + // emitDBG("Building content Model for " + sImpl); + Map elementPropertyModel = buildContentPropertyModelByQName(contentModel, sImpl); + + // add attribute property model + Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); + + // figure out content type + int complexVariety = + parseTree.getMixed() + ? SchemaType.MIXED_CONTENT + : contentModel == null + ? SchemaType.EMPTY_CONTENT + : SchemaType.ELEMENT_CONTENT; + + // now fill in the actual schema type implementation + sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef()); + sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_EXTENSION); + sImpl.setComplexTypeVariety(complexVariety); + sImpl.setContentModel(contentModel, attrModel, elementPropertyModel, attributePropertyModel, isAll); + sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); + sImpl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); + } + + static void resolveCcRestriction(SchemaTypeImpl sImpl, ComplexRestrictionType parseTree, boolean mixed) { + StscState state = StscState.get(); + String targetNamespace = sImpl.getTargetNamespace(); + boolean chameleon = (sImpl.getChameleonNamespace() != null); + + // BUGBUG: NOT YET REALLY IMPLEMENTED + // throw new RuntimeException("Not yet implemented."); + + SchemaTypeImpl baseType; + if (parseTree.getBase() == null) { + // KHK: s4s + state.error("A complexContent must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); + baseType = null; // recovery: no inheritance. + } else { + if (sImpl.isRedefinition()) { + baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); + if (baseType != null && !baseType.getName().equals(sImpl.getName())) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, + new Object[]{"", + QNameHelper.pretty(baseType.getName()), + QNameHelper.pretty(sImpl.getName()) + }, + parseTree); + } + } else { + baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); + } + + if (baseType == null) { + state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); + } + } + + if (baseType == null) { + baseType = BuiltinSchemaTypeSystem.ST_ANY_TYPE; + } + + if (baseType != null && baseType.finalRestriction()) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$FINAL, + new Object[]{QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName())}, + parseTree.xgetBase()); + // recovery: just keep going + } + + // Recursion + if (baseType != null) { + if (!StscResolver.resolveType(baseType)) { + baseType = null; // circular dependency: no inheritance + } + } + + List anonymousTypes = new ArrayList<>(); + Group parseEg = getContentModel(parseTree); + + // detect the "all" case + int particleCode = translateParticleCode(parseEg); + + // build content model and anonymous types + SchemaParticle contentModel = translateContentModel(sImpl, + parseEg, targetNamespace, chameleon, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), + particleCode, anonymousTypes, new LinkedHashMap<>(), false, null); + + // detect the nonempty "all" case (empty doesn't count - it needs to be eliminated to match XSD test cases) + boolean isAll = contentModel != null && contentModel.getParticleType() == SchemaParticle.ALL; + + // build attr model and anonymous types + SchemaAttributeModelImpl attrModel; + if (baseType == null) { + attrModel = new SchemaAttributeModelImpl(); + } else { + attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); + } + translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), + anonymousTypes, sImpl, null, attrModel, baseType, false, null); + + // summarize wildcard information + WildcardResult wcElt = summarizeEltWildcards(contentModel); + WildcardResult wcAttr = summarizeAttrWildcards(attrModel); + + // build state machine and verify that content model is deterministic + if (contentModel != null) { + buildStateMachine(contentModel); + if (!StscState.get().noUpa() && !((SchemaParticleImpl) contentModel).isDeterministic()) { + StscState.get().error(XmlErrorCodes.UNIQUE_PARTICLE_ATTRIBUTION, null, parseEg); + } + } + + // build property model + // emitDBG("Building content Model for " + sImpl); + Map elementPropertyModel = buildContentPropertyModelByQName(contentModel, sImpl); + + // add attribute property model + Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); + + // compute empty/element/mixed + // fix for XMLBEANS-414 + int complexVariety = (mixed ? SchemaType.MIXED_CONTENT : + (contentModel == null ? SchemaType.EMPTY_CONTENT : SchemaType.ELEMENT_CONTENT)); + + // now fill in the actual schema type implementation + if (baseType != null) { + sImpl.setBaseTypeRef(baseType.getRef()); + sImpl.setBaseDepth(baseType.getBaseDepth() + 1); + } + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + sImpl.setComplexTypeVariety(complexVariety); + sImpl.setContentModel(contentModel, attrModel, elementPropertyModel, attributePropertyModel, isAll); + sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); + sImpl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); + } + + static Map extractElementModel(SchemaType sType) { + if (sType == null) { + return new HashMap<>(); + } + return Stream.of(sType.getProperties()) + .filter(p -> !p.isAttribute()) + .collect(Collectors.toMap(SchemaProperty::getName, SchemaProperty::getType)); + } + + static void resolveCcExtension(SchemaTypeImpl sImpl, ExtensionType parseTree, boolean mixed) { + SchemaType baseType; + StscState state = StscState.get(); + String targetNamespace = sImpl.getTargetNamespace(); + boolean chameleon = (sImpl.getChameleonNamespace() != null); + + if (parseTree.getBase() == null) { + // KHK: s4s + state.error("A complexContent must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); + baseType = null; // recovery: no inheritance. + } else { + if (sImpl.isRedefinition()) { + baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); + if (baseType != null && !baseType.getName().equals(sImpl.getName())) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, + new Object[]{"", + QNameHelper.pretty(baseType.getName()), + QNameHelper.pretty(sImpl.getName()) + }, + parseTree); + } + } else { + baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); + } + if (baseType == null) { + state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); + } + } + + // Recursion + if (baseType != null) { + if (!StscResolver.resolveType((SchemaTypeImpl) baseType)) { + baseType = null; // circular dependency: no inheritance + } + } + + if (baseType != null && baseType.isSimpleType()) { + state.recover(XmlErrorCodes.SCHEMA_COMPLEX_TYPE$COMPLEX_CONTENT, + new Object[]{QNameHelper.pretty(baseType.getName())}, + parseTree.xgetBase()); + baseType = null; // recovery: no inheritance. + } + + if (baseType != null && baseType.finalExtension()) { + state.error(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$FINAL, + new Object[]{QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName())}, + parseTree.xgetBase()); + // recovery: just keep going + } + + // get base content model + SchemaParticle baseContentModel = (baseType == null ? null : baseType.getContentModel()); + // TODO: attribute model also + + List anonymousTypes = new ArrayList<>(); + Map baseElementModel = extractElementModel(baseType); + Group parseEg = getContentModel(parseTree); + + if (baseType != null && + (baseType.getContentType() == SchemaType.SIMPLE_CONTENT)) { + if (parseEg != null) { + // if this type has complexContent, baseType is complexType + // but with non-empty simpleContent then this type cannot + // add extra elements + state.recover(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$EXTENDING_SIMPLE_CONTENT, + new Object[]{QNameHelper.pretty(baseType.getName())}, + parseTree.xgetBase()); + baseType = null; // recovery: no inheritance. + } else { + // No extra elements, the type is a complex type with simple content + resolveScExtensionPart2(sImpl, baseType, parseTree, targetNamespace, chameleon); + return; + } + } + + // build extension model + SchemaParticle extensionModel = translateContentModel(sImpl, + parseEg, targetNamespace, chameleon, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), + translateParticleCode(parseEg), anonymousTypes, baseElementModel, false, null); + + // apply rule #2 near http://www.w3.org/TR/xmlschema-1/#c-mve: empty ext model -> mixed taken from base + if (extensionModel == null && !mixed) { + mixed = (baseType != null && baseType.getContentType() == SchemaType.MIXED_CONTENT); + } + + // apply Derivation Valid (Extension) rule 1.4.2.2 + if (baseType != null && (baseType.getContentType() != SchemaType.EMPTY_CONTENT) && + ((baseType.getContentType() == SchemaType.MIXED_CONTENT) != mixed)) { + state.error(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$BOTH_ELEMEMENT_OR_MIXED, null, parseTree.xgetBase()); + // recovery: just keep going + } + + // detect the "all" base case + if (baseType != null && baseType.hasAllContent() && extensionModel != null) { + // KHK: which rule? cos-particle-extend.2 or cos-all-limited.1.2. I think the limited one. + state.error("Cannot extend a type with 'all' content model", XmlErrorCodes.CANNOT_EXTEND_ALL, parseTree.xgetBase()); + extensionModel = null; // recovery: drop extension + } + + // build content model and anonymous types + SchemaParticle contentModel = extendContentModel(baseContentModel, extensionModel, parseTree); + + // detect the nonempty "all" case (empty doesn't count - it needs to be eliminated to match XSD test cases) + boolean isAll = contentModel != null && contentModel.getParticleType() == SchemaParticle.ALL; + + // build attr model and anonymous types + SchemaAttributeModelImpl attrModel; + if (baseType == null) { + attrModel = new SchemaAttributeModelImpl(); + } else { + attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); + } + translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), + anonymousTypes, sImpl, null, attrModel, baseType, true, null); + + // summarize wildcard information + WildcardResult wcElt = summarizeEltWildcards(contentModel); + WildcardResult wcAttr = summarizeAttrWildcards(attrModel); + + // build state machine and verify that content model is deterministic + if (contentModel != null) { + buildStateMachine(contentModel); + if (!StscState.get().noUpa() && !((SchemaParticleImpl) contentModel).isDeterministic()) { + StscState.get().error(XmlErrorCodes.UNIQUE_PARTICLE_ATTRIBUTION, null, parseEg); + } + } + + // build property model + // emitDBG("Building content Model for " + sImpl); + Map elementPropertyModel = buildContentPropertyModelByQName(contentModel, sImpl); + + // add attribute property model + Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); + + // compute empty/element/mixed + int complexVariety; + if (contentModel == null && baseType != null && + baseType.getContentType() == SchemaType.SIMPLE_CONTENT) { + complexVariety = SchemaType.SIMPLE_CONTENT; + sImpl.setContentBasedOnTypeRef(baseType.getContentBasedOnType().getRef()); + } else { + complexVariety = (mixed ? SchemaType.MIXED_CONTENT : + (contentModel == null ? SchemaType.EMPTY_CONTENT : SchemaType.ELEMENT_CONTENT)); + } + + // now fill in the actual schema type implementation + if (baseType == null) { + baseType = XmlObject.type; + } + sImpl.setBaseTypeRef(baseType.getRef()); + sImpl.setBaseDepth(((SchemaTypeImpl) baseType).getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_EXTENSION); + sImpl.setComplexTypeVariety(complexVariety); + sImpl.setContentModel(contentModel, attrModel, elementPropertyModel, attributePropertyModel, isAll); + sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); + sImpl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); + } + + static void resolveScRestriction(SchemaTypeImpl sImpl, SimpleRestrictionType parseTree) { + SchemaTypeImpl baseType; + SchemaTypeImpl contentType = null; + StscState state = StscState.get(); + String targetNamespace = sImpl.getTargetNamespace(); + boolean chameleon = (sImpl.getChameleonNamespace() != null); + List anonymousTypes = new ArrayList<>(); + if (parseTree.getSimpleType() != null) { + LocalSimpleType typedef = parseTree.getSimpleType(); + contentType = StscTranslator. + translateAnonymousSimpleType(typedef, targetNamespace, chameleon, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), + anonymousTypes, sImpl); + } + if (parseTree.getBase() == null) { + state.error("A simpleContent restriction must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); + // recovery: extends ANY_SIMPLE type + baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } else { + if (sImpl.isRedefinition()) { + baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); + if (baseType != null && !baseType.getName().equals(sImpl.getName())) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, + new Object[]{"", + QNameHelper.pretty(baseType.getName()), + QNameHelper.pretty(sImpl.getName()) + }, + parseTree); + } + } else { + baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); + } + } + if (baseType == null) { + state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); + // recovery: extends ANY_SIMPLE type + baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + // Recursion + StscResolver.resolveType(baseType); + if (contentType != null) { + StscResolver.resolveType(contentType); + } else { + contentType = baseType; + } + + if (baseType.isSimpleType()) { + // src-ct.2: complex types with simple content cannot restrict simple types + state.recover(XmlErrorCodes.COMPLEX_TYPE_PROPERTIES$SIMPLE_TYPE_EXTENSION, + new Object[]{QNameHelper.pretty(baseType.getName())}, + parseTree); + // recovery: extends ANY_SIMPLE type + baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + if (baseType != null && baseType.finalRestriction()) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$FINAL, + new Object[]{QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName())}, + parseTree.xgetBase()); + // recovery: just keep going + } + + // build attr model and anonymous types + SchemaAttributeModelImpl attrModel; + if (baseType == null) { + attrModel = new SchemaAttributeModelImpl(); + } else { + attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); + } + translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), + anonymousTypes, sImpl, null, attrModel, baseType, false, null); + + // summarize wildcard information + WildcardResult wcAttr = summarizeAttrWildcards(attrModel); + + // add attribute property model + Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); + + // now fill in the actual schema type implementation + if (baseType != null) { + sImpl.setBaseTypeRef(baseType.getRef()); + sImpl.setBaseDepth(baseType.getBaseDepth() + 1); + } + sImpl.setContentBasedOnTypeRef(contentType.getRef()); + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); + sImpl.setWildcardSummary(QNameSet.EMPTY, false, wcAttr.typedWildcards, wcAttr.hasWildcards); + sImpl.setComplexTypeVariety(SchemaType.SIMPLE_CONTENT); + sImpl.setContentModel(null, attrModel, null, attributePropertyModel, false); + sImpl.setSimpleTypeVariety(contentType.getSimpleVariety()); + sImpl.setPrimitiveTypeRef(contentType.getPrimitiveType() == null ? null : contentType.getPrimitiveType().getRef()); + switch (sImpl.getSimpleVariety()) { + case SchemaType.LIST: { + SchemaType lit = contentType.getListItemType(); + if (lit != null) { + sImpl.setListItemTypeRef(lit.getRef()); + } + break; + } + + case SchemaType.UNION: + sImpl.setUnionMemberTypeRefs(makeRefArray(Arrays.asList(contentType.getUnionMemberTypes()))); + break; + } + + // deal with facets + StscSimpleTypeResolver.resolveFacets(sImpl, parseTree, contentType); + + // now compute our intrinsic properties + StscSimpleTypeResolver.resolveFundamentalFacets(sImpl); + } + + static void resolveScExtension(SchemaTypeImpl sImpl, SimpleExtensionType parseTree) { + SchemaTypeImpl baseType; + StscState state = StscState.get(); + String targetNamespace = sImpl.getTargetNamespace(); + boolean chameleon = (sImpl.getChameleonNamespace() != null); + if (parseTree.getBase() == null) { + state.error("A simpleContent extension must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); + // recovery: extends ANY_SIMPLE type + baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } else { + if (sImpl.isRedefinition()) { + baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); + if (baseType != null && !baseType.getName().equals(sImpl.getName())) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, + new Object[]{"", + QNameHelper.pretty(baseType.getName()), + QNameHelper.pretty(sImpl.getName()) + }, + parseTree); + } + } else { + baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); + } + if (baseType == null) { + state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); + // recovery: extends ANY_SIMPLE type + baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + } + + // Recursion + StscResolver.resolveType(baseType); + + if (!baseType.isSimpleType() && baseType.getContentType() != SchemaType.SIMPLE_CONTENT) { + // src-ct.2: complex types with simple content can only extend simple types + state.error(XmlErrorCodes.SCHEMA_COMPLEX_TYPE$SIMPLE_CONTENT, + new Object[]{QNameHelper.pretty(baseType.getName())}, + parseTree); + // recovery: extends ANY_SIMPLE type + baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + if (baseType != null && baseType.finalExtension()) { + state.error(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$FINAL, + new Object[]{QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName())}, + parseTree.xgetBase()); + // recovery: just keep going + } + + resolveScExtensionPart2(sImpl, baseType, parseTree, targetNamespace, chameleon); + } + + static void resolveScExtensionPart2(SchemaTypeImpl sImpl, SchemaType baseType, ExtensionType parseTree, + String targetNamespace, boolean chameleon) { + // build attr model and anonymous types + List anonymousTypes = new ArrayList<>(); + SchemaAttributeModelImpl attrModel; + attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); + translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), anonymousTypes, sImpl, null, attrModel, baseType, true, null); + + // summarize wildcard information + WildcardResult wcAttr = summarizeAttrWildcards(attrModel); + + // add attribute property model + Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); + + // now fill in the actual schema type implementation + sImpl.setBaseTypeRef(baseType.getRef()); + sImpl.setBaseDepth(((SchemaTypeImpl) baseType).getBaseDepth() + 1); + sImpl.setContentBasedOnTypeRef(baseType.getRef()); + sImpl.setDerivationType(SchemaType.DT_EXTENSION); + sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); + sImpl.setWildcardSummary(QNameSet.EMPTY, false, wcAttr.typedWildcards, wcAttr.hasWildcards); + sImpl.setComplexTypeVariety(SchemaType.SIMPLE_CONTENT); + sImpl.setContentModel(null, attrModel, null, attributePropertyModel, false); + sImpl.setSimpleTypeVariety(baseType.getSimpleVariety()); + sImpl.setPrimitiveTypeRef(baseType.getPrimitiveType() == null ? null : baseType.getPrimitiveType().getRef()); + switch (sImpl.getSimpleVariety()) { + case SchemaType.LIST: + sImpl.setListItemTypeRef(baseType.getListItemType().getRef()); + break; + + case SchemaType.UNION: + sImpl.setUnionMemberTypeRefs(makeRefArray(Arrays.asList(baseType.getUnionMemberTypes()))); + break; + } + + // deal with facets + StscSimpleTypeResolver.resolveFacets(sImpl, null, (SchemaTypeImpl) baseType); + + // now compute our intrinsic properties + StscSimpleTypeResolver.resolveFundamentalFacets(sImpl); + } + + static class WildcardResult { + WildcardResult(QNameSet typedWildcards, boolean hasWildcards) { + this.typedWildcards = typedWildcards; + this.hasWildcards = hasWildcards; + } + + QNameSet typedWildcards; + boolean hasWildcards; + } + + static WildcardResult summarizeAttrWildcards(SchemaAttributeModel attrModel) { + if (attrModel.getWildcardProcess() == SchemaAttributeModel.NONE) { + return new WildcardResult(QNameSet.EMPTY, false); + } + if (attrModel.getWildcardProcess() == SchemaAttributeModel.SKIP) { + return new WildcardResult(QNameSet.EMPTY, true); + } + return new WildcardResult(attrModel.getWildcardSet(), true); + } + + static WildcardResult summarizeEltWildcards(SchemaParticle contentModel) { + if (contentModel == null) { + return new WildcardResult(QNameSet.EMPTY, false); + } + + switch (contentModel.getParticleType()) { + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + case SchemaParticle.CHOICE: + QNameSetBuilder set = new QNameSetBuilder(); + boolean hasWildcards = false; + for (int i = 0; i < contentModel.countOfParticleChild(); i++) { + WildcardResult inner = summarizeEltWildcards(contentModel.getParticleChild(i)); + set.addAll(inner.typedWildcards); + hasWildcards |= inner.hasWildcards; + } + return new WildcardResult(set.toQNameSet(), hasWildcards); + case SchemaParticle.WILDCARD: + return new WildcardResult( + (contentModel.getWildcardProcess() == SchemaParticle.SKIP) ? + QNameSet.EMPTY : contentModel.getWildcardSet(), true); + // otherwise fallthrough + + default: + return new WildcardResult(QNameSet.EMPTY, false); + } + } + + static void translateAttributeModel(XmlObject parseTree, + String targetNamespace, boolean chameleon, String formDefault, + List anonymousTypes, SchemaType outerType, + Set seenAttributes, SchemaAttributeModelImpl result, + SchemaType baseType, boolean extension, + SchemaAttributeGroupImpl redefinitionFor) { + StscState state = StscState.get(); + if (seenAttributes == null) { + seenAttributes = new HashSet<>(); + } + boolean seenWildcard = false; + boolean seenRedefinition = false; + SchemaAttributeModel baseModel = null; + if (baseType != null) { + baseModel = baseType.getAttributeModel(); + } + + XmlCursor cur = parseTree.newCursor(); + + for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) { + switch (translateAttributeCode(cur.getName())) { + case ATTRIBUTE_CODE: { + Attribute xsdattr = (Attribute) cur.getObject(); + + SchemaLocalAttribute sAttr = StscTranslator.translateAttribute(xsdattr, targetNamespace, formDefault, chameleon, anonymousTypes, outerType, baseModel, true); + if (sAttr == null) { + continue; + } + + if (seenAttributes.contains(sAttr.getName())) { + state.error(XmlErrorCodes.COMPLEX_TYPE_PROPERTIES$DUPLICATE_ATTRIBUTE, + new Object[]{QNameHelper.pretty(sAttr.getName()), QNameHelper.pretty(outerType.getName())}, + xsdattr.xgetName()); + continue; // ignore the duplicate attr + } + + seenAttributes.add(sAttr.getName()); + + if (baseModel != null) { + SchemaLocalAttribute baseAttr = baseModel.getAttribute(sAttr.getName()); + if (baseAttr == null) { + if (!extension) { + if (!baseModel.getWildcardSet().contains(sAttr.getName())) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ATTR_IN_BASE_WILDCARD_SET, + new Object[]{QNameHelper.pretty(sAttr.getName()), QNameHelper.pretty(outerType.getName())}, xsdattr); + } + } + } else { + if (extension) { + // KHK: cos-ct-extends.1.2? + if (sAttr.getUse() == SchemaLocalAttribute.PROHIBITED) { + state.error("An extension cannot prohibit an attribute from the base type; use restriction instead.", XmlErrorCodes.DUPLICATE_ATTRIBUTE_NAME, xsdattr.xgetUse()); + } + } else { + if (sAttr.getUse() != SchemaLocalAttribute.REQUIRED) { + if (baseAttr.getUse() == SchemaLocalAttribute.REQUIRED) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ATTR_REQUIRED, + new Object[]{QNameHelper.pretty(sAttr.getName()), QNameHelper.pretty(outerType.getName())}, xsdattr); + } + + if (sAttr.getUse() == SchemaLocalAttribute.PROHIBITED) { + result.removeProhibitedAttribute(sAttr.getName()); + } + } + } + } + } + + if (sAttr.getUse() != SchemaLocalAttribute.PROHIBITED) { + result.addAttribute(sAttr); + } else { + // attribute is prohibited. If it has an anonymous type remove + // it from the list (this will prevent inclusion of any anonymous + // types defined within the prohibited attribute which would + // otherwise attempt to refer to the prohibited attribute at + // save() time) + SchemaType attrType = sAttr.getType(); + if (anonymousTypes != null) { + anonymousTypes.remove(attrType); + } + } + + if (sAttr.getDefaultText() != null && !sAttr.isFixed()) { + if (sAttr.getUse() != SchemaLocalAttribute.OPTIONAL) { + state.error(XmlErrorCodes.SCHEMA_ATTR$DEFAULT_AND_USE_OPTIONAL, + new Object[]{QNameHelper.pretty(sAttr.getName())}, xsdattr); + } + } + + + break; + } + case ANY_ATTRIBUTE_CODE: { + Wildcard xsdwc = (Wildcard) cur.getObject(); + if (seenWildcard) { + // KHK: ? + state.error("Only one attribute wildcard allowed", XmlErrorCodes.DUPLICATE_ANY_ATTRIBUTE, xsdwc); + continue; // ignore the extra wildcard + } + seenWildcard = true; + NamespaceList nsList = xsdwc.xgetNamespace(); + String nsText; + if (nsList == null) { + nsText = "##any"; + } else { + nsText = nsList.getStringValue(); + } + QNameSet wcset = QNameSet.forWildcardNamespaceString(nsText, targetNamespace); + + if (baseModel != null && !extension) { + if (baseModel.getWildcardSet() == null) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$BASE_HAS_ATTR_WILDCARD, null, xsdwc); + continue; // ignore the extra wildcard + } else if (!baseModel.getWildcardSet().containsAll(wcset)) { + state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ATTR_WILDCARD_SUBSET, + new Object[]{nsText}, xsdwc); + continue; // ignore the restriction + } + } + + int wcprocess = translateWildcardProcess(xsdwc.xgetProcessContents()); + if (result.getWildcardProcess() == SchemaAttributeModel.NONE) { + result.setWildcardSet(wcset); + result.setWildcardProcess(wcprocess); + } else { + if (extension) { + result.setWildcardSet(wcset.union(result.getWildcardSet())); + result.setWildcardProcess(wcprocess); + } else { + result.setWildcardSet(wcset.intersect(result.getWildcardSet())); + // keep old process + } + } + break; + } + case ATTRIBUTE_GROUP_CODE: { + AttributeGroupRef xsdag = (AttributeGroupRef) cur.getObject(); + QName ref = xsdag.getRef(); + if (ref == null) { + // KHK: s4s + state.error("Attribute group reference must have a ref attribute", XmlErrorCodes.ATTRIBUTE_GROUP_MISSING_REF, xsdag); + continue; + } + SchemaAttributeGroupImpl group; + if (redefinitionFor != null) { + group = state.findRedefinedAttributeGroup(ref, chameleon ? targetNamespace : null, redefinitionFor); + if (group != null && + redefinitionFor.getName().equals(group.getName())) { + if (seenRedefinition) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$ATTR_GROUP_SELF_REF, + new Object[]{QNameHelper.pretty(redefinitionFor.getName())}, xsdag); + } + seenRedefinition = true; + } + } else { + group = state.findAttributeGroup(ref, chameleon ? targetNamespace : null, targetNamespace); + } + if (group == null) { + state.notFoundError(ref, SchemaType.ATTRIBUTE_GROUP, xsdag.xgetRef(), true); + continue; + } + if (state.isProcessing(group)) { + state.error(XmlErrorCodes.SCHEMA_ATTR_GROUP$SELF_REF, + new Object[]{QNameHelper.pretty(group.getName())}, group.getParseObject()); + continue; + } + String subTargetNamespace = targetNamespace; + if (group.getTargetNamespace() != null) { + subTargetNamespace = group.getTargetNamespace(); + chameleon = group.getChameleonNamespace() != null; + } + + state.startProcessing(group); + SchemaAttributeGroupImpl nestedRedefinitionFor = null; + if (group.isRedefinition()) { + nestedRedefinitionFor = group; + } + translateAttributeModel(group.getParseObject(), subTargetNamespace, chameleon, + group.getFormDefault(), + anonymousTypes, outerType, seenAttributes, result, baseType, + extension, nestedRedefinitionFor); + state.finishProcessing(group); + break; + } + default: + // skip things that are not part of the attribute model. + break; + } + } + // If this is restriction and no wildcard was present, then + // we have to erase the inherited wildcards + if (!extension && !seenWildcard) { + result.setWildcardSet(null); + result.setWildcardProcess(SchemaAttributeModel.NONE); + } + } + + static SchemaParticle extendContentModel(SchemaParticle baseContentModel, SchemaParticle extendedContentModel, XmlObject parseTree) { + // http://www.w3.org/TR/xmlschema-1/#element-complexContent::extension + + // 2.1 If the explicit content is empty, then the {content type} of the type definition resolved to by the �actual value� of the base [attribute] + if (extendedContentModel == null) { + return baseContentModel; + } + + // 2.2 If the type definition resolved to by the actual value of the base [attribute] has a {content type} of empty, then a pair of mixed or elementOnly (determined as per clause 1.2.1 above) and the explicit content itself; + if (baseContentModel == null) { + return extendedContentModel; + } + + // 2.3 otherwise a pair of mixed or elementOnly (determined as per clause 1.2.1 above) and a particle whose properties are as follows: + SchemaParticleImpl sPart = new SchemaParticleImpl(); + sPart.setParticleType(SchemaParticle.SEQUENCE); + + List accumulate = new ArrayList<>(); + addMinusPointlessParticles(accumulate, baseContentModel, SchemaParticle.SEQUENCE); + addMinusPointlessParticles(accumulate, extendedContentModel, SchemaParticle.SEQUENCE); + sPart.setMinOccurs(BigInteger.ONE); + sPart.setMaxOccurs(BigInteger.ONE); + sPart.setParticleChildren(accumulate.toArray(new SchemaParticle[0])); + + return filterPointlessParticlesAndVerifyAllParticles(sPart, parseTree); + } + + static BigInteger extractMinOccurs(XmlNonNegativeInteger nni) { + if (nni == null) { + return BigInteger.ONE; + } + BigInteger result = nni.getBigIntegerValue(); + if (result == null) { + return BigInteger.ONE; + } + return result; + } + + static BigInteger extractMaxOccurs(AllNNI allNNI) { + if (allNNI == null) { + return BigInteger.ONE; + } + + if (allNNI.instanceType().getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) { + return ((XmlInteger) allNNI).getBigIntegerValue(); + } else { + return null; + } + } + + private static class RedefinitionForGroup { + private final SchemaModelGroupImpl group; + private boolean seenRedefinition = false; + + public RedefinitionForGroup(SchemaModelGroupImpl group) { + this.group = group; + } + + public SchemaModelGroupImpl getGroup() { + return group; + } + + public boolean isSeenRedefinition() { + return seenRedefinition; + } + + public void setSeenRedefinition(boolean seenRedefinition) { + this.seenRedefinition = seenRedefinition; + } + } + + static SchemaParticle translateContentModel( + SchemaType outerType, + XmlObject parseTree, String targetNamespace, boolean chameleon, + String elemFormDefault, String attFormDefault, + int particleCode, List anonymousTypes, Map elementModel, + boolean allowElt, RedefinitionForGroup redefinitionFor) { + if (parseTree == null || particleCode == 0) { + return null; + } + + StscState state = StscState.get(); + + // emitDBG("Translating content model for " + outerType); + // indentDBG(); + + boolean hasChildren = false; + BigInteger minOccurs; + BigInteger maxOccurs; + SchemaModelGroupImpl group = null; + + SchemaParticleImpl sPart; + + if (particleCode == SchemaParticle.ELEMENT) { + if (!allowElt) { + state.error("Must be a sequence, choice or all here", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, parseTree); + } + + // TODO: detect substitution group for this element and construct a choice + + LocalElement parseElt = (LocalElement) parseTree; + sPart = StscTranslator.translateElement(parseElt, targetNamespace, chameleon, + elemFormDefault, attFormDefault, anonymousTypes, outerType); + if (sPart == null) { + return null; + } + minOccurs = extractMinOccurs(parseElt.xgetMinOccurs()); + maxOccurs = extractMaxOccurs(parseElt.xgetMaxOccurs()); + + SchemaType oldType = elementModel.get(sPart.getName()); + if (oldType == null) { + elementModel.put(sPart.getName(), sPart.getType()); + } else if (!sPart.getType().equals(oldType)) { + state.error(XmlErrorCodes.ELEM_CONSISTANT, new Object[]{QNameHelper.pretty(sPart.getName())}, parseTree); + return null; + } + } else if (particleCode == SchemaParticle.WILDCARD) { + if (!allowElt) { + state.error("Must be a sequence, choice or all here", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, parseTree); + } + Any parseAny = (Any) parseTree; + sPart = new SchemaParticleImpl(); + sPart.setParticleType(SchemaParticle.WILDCARD); + QNameSet wcset; + NamespaceList nslist = parseAny.xgetNamespace(); + if (nslist == null) { + wcset = QNameSet.ALL; + } else { + wcset = QNameSet.forWildcardNamespaceString(nslist.getStringValue(), targetNamespace); + } + sPart.setWildcardSet(wcset); + sPart.setWildcardProcess(translateWildcardProcess(parseAny.xgetProcessContents())); + minOccurs = extractMinOccurs(parseAny.xgetMinOccurs()); + maxOccurs = extractMaxOccurs(parseAny.xgetMaxOccurs()); + } else { + final Group parseGroup = (Group) parseTree; + sPart = new SchemaParticleImpl(); + + // grab min/maxOccurs before dereferencign group ref + minOccurs = extractMinOccurs(parseGroup.xgetMinOccurs()); + maxOccurs = extractMaxOccurs(parseGroup.xgetMaxOccurs()); + + if (particleCode == MODEL_GROUP_CODE) { + QName ref = parseGroup.getRef(); + if (ref == null) { + // KHK: s4s + state.error("Group reference must have a ref attribute", XmlErrorCodes.GROUP_MISSING_REF, parseTree); + return null; + } + + if (redefinitionFor != null) { + group = state.findRedefinedModelGroup(ref, chameleon ? targetNamespace : null, redefinitionFor.getGroup()); + if (group != null && group.getName().equals(redefinitionFor.getGroup().getName())) { + if (redefinitionFor.isSeenRedefinition()) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$GROUP_SELF_REF, + new Object[]{QNameHelper.pretty(group.getName())}, parseTree); + } + if (!BigInteger.ONE.equals(maxOccurs) || !BigInteger.ONE.equals(minOccurs)) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$GROUP_SELF_REF_MIN_MAX_1, + new Object[]{QNameHelper.pretty(group.getName())}, parseTree); + } + redefinitionFor.setSeenRedefinition(true); + } + } else { + group = state.findModelGroup(ref, chameleon ? targetNamespace : null, targetNamespace); + } + if (group == null) { + state.notFoundError(ref, SchemaType.MODEL_GROUP, ((Group) parseTree).xgetRef(), true); + return null; + } + if (state.isProcessing(group)) { + state.error(XmlErrorCodes.MODEL_GROUP_PROPERTIES$CIRCULAR, + new Object[]{QNameHelper.pretty(group.getName())}, group.getParseObject()); + return null; + } + + // no go to the child. + XmlCursor cur = group.getParseObject().newCursor(); + for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) { + particleCode = translateParticleCode(cur.getName()); + if (particleCode != 0) { + parseTree = cur.getObject(); + break; + } + } + if (particleCode == 0) { + // KHK: s4s + state.error("Model group " + QNameHelper.pretty(group.getName()) + " is empty", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, group.getParseObject()); + return null; + } + if (particleCode != SchemaParticle.ALL && particleCode != SchemaParticle.SEQUENCE && particleCode != SchemaParticle.CHOICE) { + // KHK: s4s + state.error("Model group " + QNameHelper.pretty(group.getName()) + " is not a sequence, all, or choice", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, group.getParseObject()); + } + + String newTargetNamespace = group.getTargetNamespace(); + if (newTargetNamespace != null) { + targetNamespace = newTargetNamespace; + } + elemFormDefault = group.getElemFormDefault(); + attFormDefault = group.getAttFormDefault(); + chameleon = group.getChameleonNamespace() != null; + } + + switch (particleCode) { + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + case SchemaParticle.CHOICE: + sPart.setParticleType(particleCode); + hasChildren = true; + break; + + default: + assert (false); + throw new IllegalStateException(); + } + } + + if (maxOccurs != null && minOccurs.compareTo(maxOccurs) > 0) { + state.error(XmlErrorCodes.PARTICLE_PROPERTIES$MIN_LTE_MAX, null, parseTree); + maxOccurs = minOccurs; // remedy: pin max up to min + } + + if (maxOccurs != null && maxOccurs.compareTo(BigInteger.ONE) < 0) { + state.warning(XmlErrorCodes.PARTICLE_PROPERTIES$MAX_GTE_1, null, parseTree); + + // remove from the list of anonymous types if it was added + anonymousTypes.remove(sPart.getType()); + return null; // maxOccurs == minOccurs == 0, same as no particle at all. + } + + sPart.setMinOccurs(minOccurs); + sPart.setMaxOccurs(maxOccurs); + + if (group != null) { + state.startProcessing(group); + redefinitionFor = null; + if (group.isRedefinition()) { + redefinitionFor = new RedefinitionForGroup(group); + } + } + + if (hasChildren) { + XmlCursor cur = parseTree.newCursor(); + List accumulate = new ArrayList<>(); + for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) { + int code = translateParticleCode(cur.getName()); + if (code == 0) { + continue; + } + addMinusPointlessParticles(accumulate, + translateContentModel(outerType, + cur.getObject(), targetNamespace, chameleon, + elemFormDefault, attFormDefault, code, + anonymousTypes, elementModel, true, redefinitionFor), + sPart.getParticleType()); + } + sPart.setParticleChildren(accumulate.toArray(new SchemaParticle[0])); + cur.dispose(); + } + + + SchemaParticle result = filterPointlessParticlesAndVerifyAllParticles(sPart, parseTree); + + if (group != null) { + state.finishProcessing(group); + } + // outdentDBG(); + return result; + } + + static int translateWildcardProcess(Any.ProcessContents process) { + if (process == null) { + return SchemaParticle.STRICT; + } + + String processValue = process.getStringValue(); + + if ("lax".equals(processValue)) { + return SchemaParticle.LAX; + } + + if ("skip".equals(processValue)) { + return SchemaParticle.SKIP; + } + + return SchemaParticle.STRICT; + } + + static SchemaParticle filterPointlessParticlesAndVerifyAllParticles(SchemaParticle part, XmlObject parseTree) { + if (part.getMaxOccurs() != null && part.getMaxOccurs().signum() == 0) { + return null; + } + + switch (part.getParticleType()) { + case SchemaParticle.SEQUENCE: + case SchemaParticle.ALL: + if (part.getParticleChildren().length == 0) { + return null; + } + if (part.isSingleton() && part.countOfParticleChild() == 1) { + return part.getParticleChild(0); + } + break; + + case SchemaParticle.CHOICE: + if (part.getParticleChildren().length == 0 && + part.getMinOccurs().compareTo(BigInteger.ZERO) == 0) { + return null; + } + if (part.isSingleton() && part.countOfParticleChild() == 1) { + return part.getParticleChild(0); + } + break; + + case SchemaParticle.ELEMENT: + case SchemaParticle.WILDCARD: + return part; + + default: + assert (false); + throw new IllegalStateException(); + } + + boolean isAll = part.getParticleType() == SchemaParticle.ALL; + + if (isAll) { + // http://www.w3.org/TR/xmlschema-1/#cos-all-limited + if (part.getMaxOccurs() == null || part.getMaxOccurs().compareTo(BigInteger.ONE) > 0) { + // An all group must have maxOccurs <= 1 + // KHK: review + StscState.get().error(XmlErrorCodes.ALL_GROUP_LIMITED$IN_MIN_MAX_1_PARTICLE, null, parseTree); + } + } + + for (int i = 0; i < part.countOfParticleChild(); i++) { + SchemaParticle child = part.getParticleChild(i); + if (child.getParticleType() == SchemaParticle.ALL) { + // An all group is only allowed at the top level of the content model + // KHK: review + StscState.get().error(XmlErrorCodes.ALL_GROUP_LIMITED$IN_COMPLEX_TYPE_DEF_PARTICLE, null, parseTree); + } else if (isAll && (child.getParticleType() != SchemaParticle.ELEMENT || child.getMaxOccurs() == null || child.getMaxOccurs().compareTo(BigInteger.ONE) > 0)) { + // An all group can contain only element particles with maxOccurs <= 1 + // KHK: review + StscState.get().error(XmlErrorCodes.ALL_GROUP_LIMITED$CHILD_PARTICLES_MAX_LTE_1, null, parseTree); + } + } + + return part; + } + + static void addMinusPointlessParticles( + List list, SchemaParticle part, int parentParticleType) { + if (part == null) { + return; + } + + switch (part.getParticleType()) { + case SchemaParticle.SEQUENCE: + if (parentParticleType == SchemaParticle.SEQUENCE && part.isSingleton()) { + // emitDBG("dropping redundant sequence"); + list.addAll(Arrays.asList(part.getParticleChildren())); + return; + } + break; + + case SchemaParticle.CHOICE: + if (parentParticleType == SchemaParticle.CHOICE && part.isSingleton()) { + // emitDBG("dropping redundant choice"); + list.addAll(Arrays.asList(part.getParticleChildren())); + return; + } + break; + + case SchemaParticle.ALL: + default: + } + list.add(part); + } + + private static BinaryOperator throwingMerger() { + return (u,v) -> { throw new IllegalStateException("Duplicate key "+u.toString()); }; + } + + static Map buildAttributePropertyModelByQName(SchemaAttributeModel attrModel, SchemaType owner) { + return Stream.of(attrModel.getAttributes()) + .collect(Collectors.toMap(SchemaLocalAttribute::getName, a -> buildUseProperty(a, owner), throwingMerger(), LinkedHashMap::new)); + } + + static Map buildContentPropertyModelByQName(SchemaParticle part, SchemaType owner) { + if (part == null) { + return Collections.emptyMap(); + } + + boolean asSequence = false; + Map model = null; + + switch (part.getParticleType()) { + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + asSequence = true; + break; + case SchemaParticle.CHOICE: + asSequence = false; + break; + case SchemaParticle.ELEMENT: + model = buildElementPropertyModel((SchemaLocalElement) part, owner); + break; + case SchemaParticle.WILDCARD: + model = Collections.emptyMap(); + break; + default: + assert (false); + throw new IllegalStateException(); + } + + if (model == null) { + // build model for children + model = new LinkedHashMap<>(); + SchemaParticle[] children = part.getParticleChildren(); + + for (SchemaParticle child : children) { + // indentDBG(); + Map childModel = buildContentPropertyModelByQName(child, owner); + // outdentDBG(); + for (SchemaProperty iProp : childModel.values()) { + SchemaPropertyImpl oProp = (SchemaPropertyImpl) model.get(iProp.getName()); + if (oProp == null) { + if (!asSequence) { + ((SchemaPropertyImpl) iProp).setMinOccurs(BigInteger.ZERO); + } + model.put(iProp.getName(), iProp); + continue; + } + // consistency verified in an earlier step + assert (oProp.getType().equals(iProp.getType())); + + mergeProperties(oProp, iProp, asSequence); + } + } + + // finally deal with minOccurs, maxOccurs over whole group + BigInteger min = part.getMinOccurs(); + BigInteger max = part.getMaxOccurs(); + + for (SchemaProperty oProp : model.values()) { + BigInteger minOccurs = oProp.getMinOccurs(); + BigInteger maxOccurs = oProp.getMaxOccurs(); + + minOccurs = minOccurs.multiply(min); + if (max != null && max.equals(BigInteger.ZERO)) { + maxOccurs = BigInteger.ZERO; + } else if (maxOccurs != null && !maxOccurs.equals(BigInteger.ZERO)) { + maxOccurs = max == null ? null : maxOccurs.multiply(max); + } + + ((SchemaPropertyImpl) oProp).setMinOccurs(minOccurs); + ((SchemaPropertyImpl) oProp).setMaxOccurs(maxOccurs); + } + } + + return model; + } + + static Map buildElementPropertyModel(SchemaLocalElement epart, SchemaType owner) { + SchemaProperty sProp = buildUseProperty(epart, owner); + return Collections.singletonMap(sProp.getName(), sProp); + } + + static SchemaProperty buildUseProperty(SchemaField use, SchemaType owner) { + SchemaPropertyImpl sPropImpl = new SchemaPropertyImpl(); + sPropImpl.setName(use.getName()); + sPropImpl.setContainerTypeRef(owner.getRef()); + sPropImpl.setTypeRef(use.getType().getRef()); + sPropImpl.setAttribute(use.isAttribute()); + sPropImpl.setDefault(use.isDefault() ? SchemaProperty.CONSISTENTLY : SchemaProperty.NEVER); + sPropImpl.setFixed(use.isFixed() ? SchemaProperty.CONSISTENTLY : SchemaProperty.NEVER); + sPropImpl.setNillable(use.isNillable() ? SchemaProperty.CONSISTENTLY : SchemaProperty.NEVER); + sPropImpl.setDefaultText(use.getDefaultText()); + sPropImpl.setMinOccurs(use.getMinOccurs()); + sPropImpl.setMaxOccurs(use.getMaxOccurs()); + + if (use instanceof SchemaLocalElementImpl) { + SchemaLocalElementImpl elt = (SchemaLocalElementImpl) use; + sPropImpl.setAcceptedNames(elt.acceptedStartNames()); + } + + return sPropImpl; + } + + static void mergeProperties(SchemaPropertyImpl into, SchemaProperty from, boolean asSequence) { + // minoccur, maxoccur + BigInteger minOccurs = into.getMinOccurs(); + BigInteger maxOccurs = into.getMaxOccurs(); + if (asSequence) { + minOccurs = minOccurs.add(from.getMinOccurs()); + if (maxOccurs != null) { + maxOccurs = (from.getMaxOccurs() == null ? null : + maxOccurs.add(from.getMaxOccurs())); + } + } else { + minOccurs = minOccurs.min(from.getMinOccurs()); + if (maxOccurs != null) { + maxOccurs = (from.getMaxOccurs() == null ? null : + maxOccurs.max(from.getMaxOccurs())); + } + } + into.setMinOccurs(minOccurs); + into.setMaxOccurs(maxOccurs); + + // nillable, default, fixed + if (from.hasNillable() != into.hasNillable()) { + into.setNillable(SchemaProperty.VARIABLE); + } + if (from.hasDefault() != into.hasDefault()) { + into.setDefault(SchemaProperty.VARIABLE); + } + if (from.hasFixed() != into.hasFixed()) { + into.setFixed(SchemaProperty.VARIABLE); + } + + // default value + if (into.getDefaultText() != null) { + if (from.getDefaultText() == null || + !into.getDefaultText().equals(from.getDefaultText())) { + into.setDefaultText(null); + } + } + } + + static SchemaParticle[] ensureStateMachine(SchemaParticle[] children) { + for (SchemaParticle child : children) { + buildStateMachine(child); + } + return children; + } + + static void buildStateMachine(SchemaParticle contentModel) { + if (contentModel == null) { + return; + } + + SchemaParticleImpl partImpl = (SchemaParticleImpl) contentModel; + if (partImpl.hasTransitionNotes()) { + return; + } + + QNameSetBuilder start = new QNameSetBuilder(); + QNameSetBuilder excludenext = new QNameSetBuilder(); + boolean deterministic = true; + SchemaParticle[] children; + boolean canskip = (partImpl.getMinOccurs().signum() == 0); + + switch (partImpl.getParticleType()) { + case SchemaParticle.ELEMENT: + // compute start and excludeNext; canskip is already correct + if (partImpl.hasTransitionRules()) { + start.addAll(partImpl.acceptedStartNames()); + } else { + start.add(partImpl.getName()); + } + + break; + + case SchemaParticle.WILDCARD: + // compute start and excludeNext; canskip is already correct + start.addAll(partImpl.getWildcardSet()); + break; + + case SchemaParticle.SEQUENCE: + children = ensureStateMachine(partImpl.getParticleChildren()); + + // adjust canskip if all children are skippable + canskip = true; + for (int i = 0; canskip && i < children.length; i++) { + if (!(children[i]).isSkippable()) { + canskip = false; + } + } + + // bubble up nondeterministic bit + for (SchemaParticle child : children) { + if (!((SchemaParticleImpl) child).isDeterministic()) { + deterministic = false; + break; + } + } + + // verify deterministic and compute excludeNext set + for (int i = 1; i < children.length; i++) { + excludenext.addAll(((SchemaParticleImpl) children[i - 1]).getExcludeNextSet()); + if (deterministic && !excludenext.isDisjoint((children[i]).acceptedStartNames())) { + deterministic = false; + } + if ((children[i]).isSkippable()) { + excludenext.addAll((children[i]).acceptedStartNames()); + } else { + excludenext.clear(); + } + } + + // next, compute start set + for (SchemaParticle child : children) { + start.addAll(child.acceptedStartNames()); + if (!child.isSkippable()) { + break; + } + } + break; + + case SchemaParticle.CHOICE: + children = ensureStateMachine(partImpl.getParticleChildren()); + + // adjust canskip if any children are skippable + canskip = false; + for (SchemaParticle schemaParticle : children) { + if (schemaParticle.isSkippable()) { + canskip = true; + break; + } + } + + // bubble up nondeterministic bit + for (SchemaParticle child : children) { + if (!((SchemaParticleImpl) child).isDeterministic()) { + deterministic = false; + break; + } + } + + // compute start and excludeNext sets, verify deterministic + for (SchemaParticle child : children) { + if (deterministic && !start.isDisjoint(child.acceptedStartNames())) { + deterministic = false; + } + start.addAll(child.acceptedStartNames()); + excludenext.addAll(((SchemaParticleImpl) child).getExcludeNextSet()); + } + + break; + + case SchemaParticle.ALL: + children = ensureStateMachine(partImpl.getParticleChildren()); + + // adjust canskip if all children are skippable + canskip = true; + for (SchemaParticle child : children) { + if (!child.isSkippable()) { + canskip = false; + break; + } + } + + // bubble up nondeterministic bit + for (SchemaParticle child : children) { + if (!((SchemaParticleImpl) child).isDeterministic()) { + deterministic = false; + break; + } + } + + // compute start and excludeNext sets, verify deterministic + for (SchemaParticle child : children) { + if (deterministic && !start.isDisjoint(child.acceptedStartNames())) { + deterministic = false; + } + start.addAll(child.acceptedStartNames()); + excludenext.addAll(((SchemaParticleImpl) child).getExcludeNextSet()); + } + if (canskip) { + excludenext.addAll(start); + } + + break; + + default: + throw new IllegalStateException("Unrecognized schema particle"); + } + + // apply looping logic + + BigInteger minOccurs = partImpl.getMinOccurs(); + BigInteger maxOccurs = partImpl.getMaxOccurs(); + boolean canloop = (maxOccurs == null || maxOccurs.compareTo(BigInteger.ONE) > 0); + boolean varloop = (maxOccurs == null || minOccurs.compareTo(maxOccurs) < 0); + + if (canloop && deterministic && !excludenext.isDisjoint(start)) { + // we have a possible looping nondeterminism. + // let's take some time now to see if it's actually caused + // by non-unique-particle-attribute or not. + QNameSet suspectSet = excludenext.intersect(start); + + // compute the set of all particles that could start this group + Map startMap = new HashMap<>(); + particlesMatchingStart(partImpl, suspectSet, startMap, new QNameSetBuilder()); + + // compute the set of all particles that could have been repeated rather than ending this group + Map afterMap = new HashMap<>(); + particlesMatchingAfter(partImpl, suspectSet, afterMap, new QNameSetBuilder(), true); + + // see if we can find a member of after that is not a member of start + // if we can, then particle attribution is not unique + deterministic = afterMapSubsumedByStartMap(startMap, afterMap); + } + + if (varloop) { + excludenext.addAll(start); + } + + canskip = canskip || minOccurs.signum() == 0; + + partImpl.setTransitionRules(start.toQNameSet(), canskip); + partImpl.setTransitionNotes(excludenext.toQNameSet(), deterministic); + } + + private static boolean afterMapSubsumedByStartMap(Map startMap, Map afterMap) { + if (afterMap.size() > startMap.size()) { + return false; + } + + if (afterMap.isEmpty()) { + return true; + } + + for (SchemaParticle part : startMap.keySet()) { + if (part.getParticleType() == SchemaParticle.WILDCARD) { + if (afterMap.containsKey(part)) { + QNameSet startSet = startMap.get(part); + QNameSet afterSet = afterMap.get(part); + if (!startSet.containsAll(afterSet)) { + return false; + } + } + } + afterMap.remove(part); + if (afterMap.isEmpty()) { + return true; + } + } + return false; + } + + private static void particlesMatchingStart(SchemaParticle part, QNameSetSpecification suspectSet, Map result, QNameSetBuilder eliminate) { + switch (part.getParticleType()) { + case SchemaParticle.ELEMENT: + if (!suspectSet.contains(part.getName())) { + return; + } + result.put(part, null); + eliminate.add(part.getName()); + return; + + case SchemaParticle.WILDCARD: + if (suspectSet.isDisjoint(part.getWildcardSet())) { + return; + } + result.put(part, part.getWildcardSet().intersect(suspectSet)); + eliminate.addAll(part.getWildcardSet()); + return; + + case SchemaParticle.CHOICE: + case SchemaParticle.ALL: { + SchemaParticle[] children = part.getParticleChildren(); + for (SchemaParticle child : children) { + particlesMatchingStart(child, suspectSet, result, eliminate); + } + return; + } + + case SchemaParticle.SEQUENCE: { + SchemaParticle[] children = part.getParticleChildren(); + if (children.length == 0) { + return; + } + if (!children[0].isSkippable()) { + particlesMatchingStart(children[0], suspectSet, result, eliminate); + return; + } + QNameSetBuilder remainingSuspects = new QNameSetBuilder(suspectSet); + QNameSetBuilder suspectsToEliminate = new QNameSetBuilder(); + for (SchemaParticle child : children) { + particlesMatchingStart(child, remainingSuspects, result, suspectsToEliminate); + eliminate.addAll(suspectsToEliminate); + if (!child.isSkippable()) { + return; + } + remainingSuspects.removeAll(suspectsToEliminate); + if (remainingSuspects.isEmpty()) { + return; + } + suspectsToEliminate.clear(); + } + } + } + } + + private static void particlesMatchingAfter(SchemaParticle part, QNameSetSpecification suspectSet, Map result, QNameSetBuilder eliminate, boolean top) { + recurse: + switch (part.getParticleType()) { + case SchemaParticle.CHOICE: + case SchemaParticle.ALL: { + SchemaParticle[] children = part.getParticleChildren(); + for (SchemaParticle child : children) { + particlesMatchingAfter(child, suspectSet, result, eliminate, false); + } + break; + } + + case SchemaParticle.SEQUENCE: { + SchemaParticle[] children = part.getParticleChildren(); + if (children.length == 0) { + break; + } + if (!children[children.length - 1].isSkippable()) { + particlesMatchingAfter(children[0], suspectSet, result, eliminate, false); + break; + } + QNameSetBuilder remainingSuspects = new QNameSetBuilder(suspectSet); + QNameSetBuilder suspectsToEliminate = new QNameSetBuilder(); + for (int i = children.length - 1; i >= 0; i--) { + particlesMatchingAfter(children[i], remainingSuspects, result, suspectsToEliminate, false); + eliminate.addAll(suspectsToEliminate); + if (!children[i].isSkippable()) { + break recurse; + } + remainingSuspects.removeAll(suspectsToEliminate); + if (remainingSuspects.isEmpty()) { + break recurse; + } + suspectsToEliminate.clear(); + } + break; + } + } + + if (!top) { + BigInteger minOccurs = part.getMinOccurs(); + BigInteger maxOccurs = part.getMaxOccurs(); + boolean varloop = (maxOccurs == null || minOccurs.compareTo(maxOccurs) < 0); + if (varloop) { + particlesMatchingStart(part, suspectSet, result, eliminate); + } + } + } + + private static class CodeForNameEntry { + CodeForNameEntry(QName name, int code) { + this.name = name; + this.code = code; + } + + public QName name; + public int code; + } + + private static final int MODEL_GROUP_CODE = 100; + + private static final CodeForNameEntry[] particleCodes = { + new CodeForNameEntry(QNameHelper.forLNS("all", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.ALL), + new CodeForNameEntry(QNameHelper.forLNS("sequence", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.SEQUENCE), + new CodeForNameEntry(QNameHelper.forLNS("choice", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.CHOICE), + new CodeForNameEntry(QNameHelper.forLNS("element", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.ELEMENT), + new CodeForNameEntry(QNameHelper.forLNS("any", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.WILDCARD), + new CodeForNameEntry(QNameHelper.forLNS("group", "http://www.w3.org/2001/XMLSchema"), MODEL_GROUP_CODE), + }; + + private static final Map particleCodeMap = + Stream.of(particleCodes).collect(Collectors.toMap(pc -> pc.name, pc -> pc.code)); + + private static int translateParticleCode(Group parseEg) { + if (parseEg == null) { + return 0; + } + return translateParticleCode(parseEg.newCursor().getName()); + } + + private static int translateParticleCode(QName name) { + return particleCodeMap.getOrDefault(name, 0); + } + + private static final int ATTRIBUTE_CODE = 100; + private static final int ATTRIBUTE_GROUP_CODE = 101; + private static final int ANY_ATTRIBUTE_CODE = 102; + + private static final CodeForNameEntry[] attributeCodes = { + new CodeForNameEntry(QNameHelper.forLNS("attribute", "http://www.w3.org/2001/XMLSchema"), ATTRIBUTE_CODE), + new CodeForNameEntry(QNameHelper.forLNS("attributeGroup", "http://www.w3.org/2001/XMLSchema"), ATTRIBUTE_GROUP_CODE), + new CodeForNameEntry(QNameHelper.forLNS("anyAttribute", "http://www.w3.org/2001/XMLSchema"), ANY_ATTRIBUTE_CODE), + }; + + private static final Map attributeCodeMap = + Stream.of(attributeCodes).collect(Collectors.toMap(ac -> ac.name, ac -> ac.code)); + + static int translateAttributeCode(QName currentName) { + return attributeCodeMap.getOrDefault(currentName, 0); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java new file mode 100644 index 0000000..e731d5a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java @@ -0,0 +1,892 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.IOUtil; +import org.apache.xmlbeans.impl.common.XmlEncodingSniffer; +import org.apache.xmlbeans.impl.xb.xsdschema.ImportDocument.Import; +import org.apache.xmlbeans.impl.xb.xsdschema.IncludeDocument.Include; +import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.*; + +public class StscImporter { + public static SchemaToProcess[] resolveImportsAndIncludes(Schema[] startWith, boolean forceSrcSave) { + DownloadTable engine = new DownloadTable(startWith); + return engine.resolveImportsAndIncludes(forceSrcSave); + } + + public static class SchemaToProcess { + private final Schema schema; + private final String chameleonNamespace; + // list of SchemaToProcess objects directly included by this + private List includes; + // list of SchemaToProcess objects directly redefined by this + private List redefines; + // list of Redefine objects associated to each redefinition + private List redefineObjects; + // set of SchemaToProcess objects directly/indirectly included by this + private Set indirectIncludes; + // set of SchemaToProcess objects that include this directly/indirectly + private Set indirectIncludedBy; + + public SchemaToProcess(Schema schema, String chameleonNamespace) { + this.schema = schema; + this.chameleonNamespace = chameleonNamespace; + } + + /** + * The schema to parse. + */ + public Schema getSchema() { + return schema; + } + + /** + * The base URI for this stp + */ + public String getSourceName() { + return schema.documentProperties().getSourceName(); + } + + /** + * The chameleon namespace. Null if this schema is not being treated + * as a chameleon. (The ordinary targetNamespace will just be extracted + * from the syntax of the schema.) + */ + public String getChameleonNamespace() { + return chameleonNamespace; + } + + /** + * This method and the remaining methods are used to represent a + * directed graph of includes/redefines. This is required in order + * to establish identity component by component, as required in + * xmlschema-1, chapter 4.2.2 + */ + public List getRedefines() { + return redefines; + } + + public List getRedefineObjects() { + return redefineObjects; + } + + private void addInclude(SchemaToProcess include) { + if (includes == null) { + includes = new ArrayList<>(); + } + includes.add(include); + } + + private void addRedefine(SchemaToProcess redefine, Redefine object) { + if (redefines == null || redefineObjects == null) { + redefines = new ArrayList<>(); + redefineObjects = new ArrayList<>(); + } + redefines.add(redefine); + redefineObjects.add(object); + } + + private void buildIndirectReferences() { + if (includes != null) { + for (SchemaToProcess schemaToProcess : includes) { + /* We have a this-schemaToProcess vertex + * This means that all nodes accessible from schemaToProcess are + * also accessible from this and all nodes that have access to + * this also have access to schemaToProcess */ + this.addIndirectIncludes(schemaToProcess); + } + } + // Repeat the same algorithm for redefines, since redefines are also includes + if (redefines != null) { + for (SchemaToProcess schemaToProcess : redefines) { + this.addIndirectIncludes(schemaToProcess); + } + } + } + + private void addIndirectIncludes(SchemaToProcess schemaToProcess) { + if (indirectIncludes == null) { + indirectIncludes = new HashSet<>(); + } + indirectIncludes.add(schemaToProcess); + if (schemaToProcess.indirectIncludedBy == null) { + schemaToProcess.indirectIncludedBy = new HashSet<>(); + } + schemaToProcess.indirectIncludedBy.add(this); + addIndirectIncludesHelper(this, schemaToProcess); + if (indirectIncludedBy != null) { + for (SchemaToProcess stp : indirectIncludedBy) { + stp.indirectIncludes.add(schemaToProcess); + schemaToProcess.indirectIncludedBy.add(stp); + addIndirectIncludesHelper(stp, schemaToProcess); + } + } + } + + private static void addIndirectIncludesHelper(SchemaToProcess including, + SchemaToProcess schemaToProcess) { + if (schemaToProcess.indirectIncludes != null) { + for (SchemaToProcess stp : schemaToProcess.indirectIncludes) { + including.indirectIncludes.add(stp); + stp.indirectIncludedBy.add(including); + } + } + } + + public boolean indirectIncludes(SchemaToProcess schemaToProcess) { + return indirectIncludes != null && indirectIncludes.contains(schemaToProcess); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof SchemaToProcess)) { + return false; + } + + final SchemaToProcess schemaToProcess = (SchemaToProcess) o; + + if (!Objects.equals(chameleonNamespace, schemaToProcess.chameleonNamespace)) { + return false; + } + return schema == schemaToProcess.schema; + } + + public int hashCode() { + int result; + result = schema.hashCode(); + result = 29 * result + (chameleonNamespace != null ? chameleonNamespace.hashCode() : 0); + return result; + } + } + + private final static String PROJECT_URL_PREFIX = "project://local"; + + private static String baseURLForDoc(XmlObject obj) { + String path = obj.documentProperties().getSourceName(); + + if (path == null) { + return null; + } + + if (path.startsWith("/")) { + return PROJECT_URL_PREFIX + path.replace('\\', '/'); + } + + // looks like a URL? + int colon = path.indexOf(':'); + if (colon > 1 && path.substring(0, colon).matches("^\\w+$")) { + return path; + } + + return PROJECT_URL_PREFIX + "/" + path.replace('\\', '/'); + } + + private static URI parseURI(String s) { + if (s == null) { + return null; + } + + try { + return new URI(s); + } catch (URISyntaxException syntax) { + return null; + } + } + + //workaround for Sun bug # 4723726 + public static URI resolve(URI base, String child) + throws URISyntaxException { + URI childUri = new URI(child); + URI ruri = base.resolve(childUri); + + // if the child fragment is relative (which we'll assume is the case + // if URI.resolve doesn't do anything useful with it) and the base + // URI is pointing at something nested inside a jar, we seem to have + // to this ourselves to make sure that the nested jar url gets + // resolved correctly + if (childUri.equals(ruri) && !childUri.isAbsolute() && + (base.getScheme().equals("jar") || base.getScheme().equals("zip"))) { + String r = base.toString(); + int lastslash = r.lastIndexOf('/'); + r = r.substring(0, lastslash) + "/" + childUri; + // Sun's implementation of URI doesn't support references to the + // parent directory ("/..") in the part after "!/" so we have to + // remove these ourselves + int exclPointSlashIndex = r.lastIndexOf("!/"); + if (exclPointSlashIndex > 0) { + int slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex); + while (slashDotDotIndex > 0) { + int prevSlashIndex = r.lastIndexOf("/", slashDotDotIndex - 1); + if (prevSlashIndex >= exclPointSlashIndex) { + String temp = r.substring(slashDotDotIndex + 3); + r = r.substring(0, prevSlashIndex).concat(temp); + } + slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex); + } + } + return URI.create(r); + } + + //fix up normalization bug + if ("file".equals(ruri.getScheme()) && !child.equals(ruri.getPath())) { + if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//")) { + String path = "///".concat(ruri.getPath()); + try { + ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment()); + } catch (URISyntaxException ignored) { + } + } + } + return ruri; + } + + public static class DownloadTable { + /** + * Namespace/schemaLocation pair. + *

      + * Downloaded schemas are indexed by namespace, schemaLocation, and both. + *

      + * A perfect match is preferred, but a match-by-namespace is accepted. + * A match-by-schemaLocation is only accepted for includes (not imports). + */ + private static class NsLocPair { + private final String namespaceURI; + private final String locationURL; + + public NsLocPair(String namespaceURI, String locationURL) { + this.namespaceURI = namespaceURI; + this.locationURL = locationURL; + } + + /** + * Empty string for no-namespace, null for namespace-not-part-of-key + */ + public String getNamespaceURI() { + return namespaceURI; + } + + public String getLocationURL() { + return locationURL; + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof NsLocPair)) { + return false; + } + + final NsLocPair nsLocPair = (NsLocPair) o; + + if (!Objects.equals(locationURL, nsLocPair.locationURL)) { + return false; + } + return Objects.equals(namespaceURI, nsLocPair.namespaceURI); + } + + public int hashCode() { + int result; + result = (namespaceURI != null ? namespaceURI.hashCode() : 0); + result = 29 * result + (locationURL != null ? locationURL.hashCode() : 0); + return result; + } + } + + private static class DigestKey { + byte[] _digest; + int _hashCode; + + DigestKey(byte[] digest) { + _digest = digest; + for (int i = 0; i < 4 && i < digest.length; i++) { + _hashCode = _hashCode << 8; + _hashCode = _hashCode + digest[i]; + } + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DigestKey)) { + return false; + } + return Arrays.equals(_digest, ((DigestKey) o)._digest); + } + + public int hashCode() { + return _hashCode; + } + } + + private final Map schemaByNsLocPair = new HashMap<>(); + private final Map schemaByDigestKey = new HashMap<>(); + private final LinkedList scanNeeded = new LinkedList<>(); + private final Set emptyNamespaceSchemas = new HashSet<>(); + private final Map scannedAlready = new HashMap<>(); + private final Set failedDownloads = new HashSet<>(); + + private Schema downloadSchema(XmlObject referencedBy, String targetNamespace, String locationURL) { + // no location URL provided? Then nothing to do. + if (locationURL == null) { + return null; + } + + StscState state = StscState.get(); + + // First resolve relative URLs with respect to base URL for doc + URI baseURI = parseURI(baseURLForDoc(referencedBy)); + final String absoluteURL; + try { + absoluteURL = baseURI == null ? locationURL : resolve(baseURI, locationURL).toString(); + } catch (URISyntaxException e) { + state.error("Could not find resource - invalid location URL: " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); + return null; + } + + assert (absoluteURL != null); + + // probe 0: this url is already processed, from a previous compile + if (state.isFileProcessed(absoluteURL)) { + return null; + } + + // probe 1: ns+url - perfect match + if (targetNamespace != null) { + Schema result = schemaByNsLocPair.get(new NsLocPair(targetNamespace, absoluteURL)); + if (result != null) { + return result; + } + } + + // probe 2: we have preexisting knowledge of this namespace, + // either from another schema file or from the linker. + // If we're not downloading the given URL, skip it silently if the + // namespace is already represented by a file we have. + // Also, suppress downloads of URLs to namespaces that are already + // known by the linker. + // (We never assume preexisting knowledge of the no-namespace, + // even if we have some definitions, since it's likely that + // more than one person is playing in the no-namespace at once.) + if (targetNamespace != null && !targetNamespace.equals("")) { + // the URL is not one to download; should we assume we know about the namespace? + if (!state.shouldDownloadURI(absoluteURL)) { + // If we already have a schema representing this namespace, + // then skip this URL silently without producing an error. + Schema result = schemaByNsLocPair.get(new NsLocPair(targetNamespace, null)); + if (result != null) { + return result; + } + } + + // If the linker already knows about this namespace, skip + // this URL. + if (state.linkerDefinesNamespace(targetNamespace)) { + return null; + } + } + + // probe 3: url only + final Schema result2 = schemaByNsLocPair.get(new NsLocPair(null, absoluteURL)); + if (result2 != null) { + return result2; + } + + // no match: error if we can't or won't download. + if (previouslyFailedToDownload(absoluteURL)) { + // an error message has already been produced. + return null; + } + + if (!state.shouldDownloadURI(absoluteURL)) { + state.error("Could not load resource \"" + absoluteURL + "\" (network downloads disabled).", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); + addFailedDownload(absoluteURL); + return null; + } + + // try to download + download: + try { + XmlObject xdoc = downloadDocument(state.getS4SLoader(), targetNamespace, absoluteURL); + + Schema result = findMatchByDigest(xdoc); + String shortname = state.relativize(absoluteURL); + if (result != null) { + // if an exactly-the-same document has already been loaded, use the original and spew + String dupname = state.relativize(result.documentProperties().getSourceName()); + if (dupname != null) { + state.info(shortname + " is the same as " + dupname + " (ignoring the duplicate file)"); + } else { + state.info(shortname + " is the same as another schema"); + } + } else { + // otherwise, it's a new document: validate it and grab the contents + XmlOptions voptions = new XmlOptions(); + voptions.setErrorListener(state.getErrorListener()); + if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) { + state.error("Referenced document is not a valid schema", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); + break download; + } + + SchemaDocument sDoc = (SchemaDocument) xdoc; + + result = sDoc.getSchema(); + state.info("Loading referenced file " + shortname); + } + NsLocPair key = new NsLocPair(emptyStringIfNull(result.getTargetNamespace()), absoluteURL); + addSuccessfulDownload(key, result); + return result; + } catch (MalformedURLException malformed) { + state.error("URL \"" + absoluteURL + "\" is not well-formed", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); + } catch (IOException connectionProblem) { + state.error(connectionProblem.toString(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); + } catch (XmlException e) { + state.error("Problem parsing referenced XML resource - " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); + } + + // record failure so that we don't try to download this URL again + addFailedDownload(absoluteURL); + return null; + } + + static XmlObject downloadDocument(SchemaTypeLoader loader, String namespace, String absoluteURL) + throws IOException, XmlException { + StscState state = StscState.get(); + + EntityResolver resolver = state.getEntityResolver(); + if (resolver != null) { + InputSource source; + try { + source = resolver.resolveEntity(namespace, absoluteURL); + } catch (SAXException e) { + throw new XmlException(e); + } + + if (source != null) { + state.addSourceUri(absoluteURL, null); + + // first preference for InputSource contract: character stream + Reader reader = source.getCharacterStream(); + if (reader != null) { + reader = copySchemaSource(absoluteURL, reader, state); + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setDocumentSourceName(absoluteURL); + return loader.parse(reader, null, options); + } + + // second preference for InputSource contract: + InputStream bytes = source.getByteStream(); + if (bytes != null) { + bytes = copySchemaSource(absoluteURL, bytes, state); + String encoding = source.getEncoding(); + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setLoadMessageDigest(); + options.setDocumentSourceName(absoluteURL); + if (encoding != null) { + options.setCharacterEncoding(encoding); + } + return loader.parse(bytes, null, options); + } + + // third preference: use the (possibly redirected) url + String urlToLoad = source.getSystemId(); + if (urlToLoad == null) { + throw new IOException("EntityResolver unable to resolve " + absoluteURL + " (for namespace " + namespace + ")"); + } + + copySchemaSource(absoluteURL, state, false); + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setLoadMessageDigest(); + options.setDocumentSourceName(absoluteURL); + URL urlDownload = new URL(urlToLoad); + return loader.parse(urlDownload, null, options); + } + } + + // no resolver - just use the URL directly, no substitution + state.addSourceUri(absoluteURL, null); + copySchemaSource(absoluteURL, state, false); + + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setLoadMessageDigest(); + URL urlDownload = new URL(absoluteURL); + + return loader.parse(urlDownload, null, options); + } + + private void addSuccessfulDownload(NsLocPair key, Schema schema) { + byte[] digest = schema.documentProperties().getMessageDigest(); + if (digest == null) { + StscState.get().addSchemaDigest(null); + } else { + DigestKey dk = new DigestKey(digest); + if (!schemaByDigestKey.containsKey(dk)) { + schemaByDigestKey.put(new DigestKey(digest), schema); + StscState.get().addSchemaDigest(digest); + } + } + + schemaByNsLocPair.put(key, schema); + NsLocPair key1 = new NsLocPair(key.getNamespaceURI(), null); + if (!schemaByNsLocPair.containsKey(key1)) { + schemaByNsLocPair.put(key1, schema); + } + NsLocPair key2 = new NsLocPair(null, key.getLocationURL()); + if (!schemaByNsLocPair.containsKey(key2)) { + schemaByNsLocPair.put(key2, schema); + } + } + + private Schema findMatchByDigest(XmlObject original) { + byte[] digest = original.documentProperties().getMessageDigest(); + if (digest == null) { + return null; + } + return schemaByDigestKey.get(new DigestKey(digest)); + } + + private void addFailedDownload(String locationURL) { + failedDownloads.add(locationURL); + } + + private boolean previouslyFailedToDownload(String locationURL) { + return failedDownloads.contains(locationURL); + } + + private static boolean nullableStringsMatch(String s1, String s2) { + if (s1 == null && s2 == null) { + return true; + } + if (s1 == null || s2 == null) { + return false; + } + return (s1.equals(s2)); + } + + private static String emptyStringIfNull(String s) { + if (s == null) { + return ""; + } + return s; + } + + private SchemaToProcess addScanNeeded(SchemaToProcess stp) { + if (!scannedAlready.containsKey(stp)) { + scannedAlready.put(stp, stp); + scanNeeded.add(stp); + return stp; + } else { + return scannedAlready.get(stp); + } + } + + private void addEmptyNamespaceSchema(Schema s) { + emptyNamespaceSchemas.add(s); + } + + private void usedEmptyNamespaceSchema(Schema s) { + emptyNamespaceSchemas.remove(s); + } + + private boolean fetchRemainingEmptyNamespaceSchemas() { + if (emptyNamespaceSchemas.isEmpty()) { + return false; + } + + for (Schema schema : emptyNamespaceSchemas) { + addScanNeeded(new SchemaToProcess(schema, null)); + } + + emptyNamespaceSchemas.clear(); + return true; + } + + private boolean hasNextToScan() { + return !scanNeeded.isEmpty(); + } + + private SchemaToProcess nextToScan() { + return scanNeeded.removeFirst(); + } + + public DownloadTable(Schema[] startWith) { + for (Schema schema : startWith) { + String targetNamespace = schema.getTargetNamespace(); + NsLocPair key = new NsLocPair(targetNamespace, baseURLForDoc(schema)); + addSuccessfulDownload(key, schema); + if (targetNamespace != null) { + addScanNeeded(new SchemaToProcess(schema, null)); + } else { + addEmptyNamespaceSchema(schema); + } + } + } + + public SchemaToProcess[] resolveImportsAndIncludes(boolean forceSave) { + StscState state = StscState.get(); + List result = new ArrayList<>(); + boolean hasRedefinitions = false; + + // algorithm is to scan through each schema document and + // 1. download each import and include (if not already downloaded) + // 2. queue each imported or included schema to be process (if not already queued) + + // The algorithm is run twice: first we begin with non-empty + // namespace schemas only. Then we repeat starting with any + // empty empty-namespace schemas that have NOT been chameleon- + // included by other schemas and process them. + + do { + while (hasNextToScan()) { + SchemaToProcess stp = nextToScan(); + String uri = stp.getSourceName(); + state.addSourceUri(uri, null); + result.add(stp); + copySchemaSource(uri, state, forceSave); + + { + // handle imports + Import[] imports = stp.getSchema().getImportArray(); + for (Import anImport : imports) { + Schema imported = downloadSchema(anImport, emptyStringIfNull(anImport.getNamespace()), anImport.getSchemaLocation()); + + // if download fails, an error has already been reported. + if (imported == null) { + continue; + } + + if (!nullableStringsMatch(imported.getTargetNamespace(), anImport.getNamespace())) { + StscState.get().error("Imported schema has a target namespace \"" + imported.getTargetNamespace() + "\" that does not match the specified \"" + anImport.getNamespace() + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, anImport); + } else { + addScanNeeded(new SchemaToProcess(imported, null)); + } + } + } + + { + // handle includes + Include[] includes = stp.getSchema().getIncludeArray(); + String sourceNamespace = stp.getChameleonNamespace(); + if (sourceNamespace == null) { + sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace()); + } + + for (Include include : includes) { + Schema included = downloadSchema(include, null, include.getSchemaLocation()); + // if download fails, an error has already been reported. + if (included == null) { + continue; + } + + if (emptyStringIfNull(included.getTargetNamespace()).equals(sourceNamespace)) { + // non-chameleon case - just like an import + SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, null)); + stp.addInclude(s); + } else if (included.getTargetNamespace() != null) { + // illegal include: included schema in wrong namespace. + StscState.get().error("Included schema has a target namespace \"" + included.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, include); + } else { + // chameleon include + SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, sourceNamespace)); + stp.addInclude(s); + usedEmptyNamespaceSchema(included); + } + } + } + + { + // handle redefines + Redefine[] redefines = stp.getSchema().getRedefineArray(); + String sourceNamespace = stp.getChameleonNamespace(); + if (sourceNamespace == null) { + sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace()); + } + for (Redefine redefine : redefines) { + Schema redefined = downloadSchema(redefine, null, redefine.getSchemaLocation()); + // if download fails, an error has already been reported. + if (redefined == null) { + continue; + } + + if (emptyStringIfNull(redefined.getTargetNamespace()).equals(sourceNamespace)) { + // non-chameleon case + SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, null)); + stp.addRedefine(s, redefine); + hasRedefinitions = true; + } else if (redefined.getTargetNamespace() != null) { + // illegal include: included schema in wrong namespace. + StscState.get().error("Redefined schema has a target namespace \"" + redefined.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, redefine); + } else { + // chameleon redefine + SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, sourceNamespace)); + stp.addRedefine(s, redefine); + usedEmptyNamespaceSchema(redefined); + hasRedefinitions = true; + } + } + } + } + + } while (fetchRemainingEmptyNamespaceSchemas()); + + // Build the lists of indirect references + // Make all the effort only if there are redefinitions + if (hasRedefinitions) { + for (SchemaToProcess schemaToProcess : result) { + schemaToProcess.buildIndirectReferences(); + } + } + return result.toArray(new SchemaToProcess[0]); + } + + private static Reader copySchemaSource(String url, Reader reader, StscState state) { + //Copy the schema file if it wasn't already copied + if (state.getSchemasDir() == null) { + return reader; + } + + String schemalocation = state.sourceNameForUri(url); + File targetFile = new File(state.getSchemasDir(), schemalocation); + if (targetFile.exists()) { + return reader; + } + + try { + File parentDir = new File(targetFile.getParent()); + IOUtil.createDir(parentDir, null); + + CharArrayReader car = copy(reader); + XmlEncodingSniffer xes = new XmlEncodingSniffer(car, null); + Writer out = new OutputStreamWriter(new FileOutputStream(targetFile), xes.getXmlEncoding()); + IOUtil.copyCompletely(car, out); + + car.reset(); + return car; + } catch (IOException e) { + System.err.println("IO Error " + e); + return reader; + } + } + + private static InputStream copySchemaSource(String url, InputStream bytes, StscState state) { + //Copy the schema file if it wasn't already copied + if (state.getSchemasDir() == null) { + return bytes; + } + + String schemalocation = state.sourceNameForUri(url); + File targetFile = new File(state.getSchemasDir(), schemalocation); + if (targetFile.exists()) { + return bytes; + } + + try { + File parentDir = new File(targetFile.getParent()); + IOUtil.createDir(parentDir, null); + + ByteArrayInputStream bais = copy(bytes); + + FileOutputStream out = new FileOutputStream(targetFile); + IOUtil.copyCompletely(bais, out); + + bais.reset(); + return bais; + } catch (IOException e) { + System.err.println("IO Error " + e); + return bytes; + } + } + + private static void copySchemaSource(String urlLoc, StscState state, boolean forceCopy) { + //Copy the schema file if it wasn't already copied + if (state.getSchemasDir() != null) { + String schemalocation = state.sourceNameForUri(urlLoc); + + File targetFile = new File(state.getSchemasDir(), schemalocation); + if (forceCopy || !targetFile.exists()) { + try { + File parentDir = new File(targetFile.getParent()); + IOUtil.createDir(parentDir, null); + + InputStream in = null; + URL url = new URL(urlLoc); + // Copy the file from filepath to schema[METADATA_PACKAGE_GEN]/src/ + try { + in = url.openStream(); + } catch (FileNotFoundException fnfe) { + if (forceCopy && targetFile.exists()) { + targetFile.delete(); + } else { + throw fnfe; + } + } + if (in != null) { + FileOutputStream out = new FileOutputStream(targetFile); + IOUtil.copyCompletely(in, out); + } + } catch (IOException e) { + System.err.println("IO Error " + e); + // failure = true; - not cause for failure + } + } + } + } + + private static ByteArrayInputStream copy(InputStream is) throws IOException { + byte[] buf = new byte[1024]; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + int bytesRead; + while ((bytesRead = is.read(buf, 0, 1024)) > 0) { + baos.write(buf, 0, bytesRead); + } + + return new ByteArrayInputStream(baos.toByteArray()); + } + + private static CharArrayReader copy(Reader is) throws IOException { + char[] buf = new char[1024]; + CharArrayWriter baos = new CharArrayWriter(); + + int bytesRead; + while ((bytesRead = is.read(buf, 0, 1024)) > 0) { + baos.write(buf, 0, bytesRead); + } + + return new CharArrayReader(baos.toCharArray()); + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java new file mode 100644 index 0000000..f3c4b3a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscJavaizer.java @@ -0,0 +1,883 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.NameUtil; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.*; + +public class StscJavaizer { + + /** + * XMLBEANS-307 + * if enumeration count is greater than 3668, + * xmlbeans scomp will fail with a code too large error + */ + private static final int MAX_ENUM_COUNT = 3668; + + /** + * Does a topo walk of all the types to resolve them. + */ + public static void javaizeAllTypes(boolean javaize) { + StscState state = StscState.get(); + + List allSeenTypes = new ArrayList<>(); + allSeenTypes.addAll(Arrays.asList(state.documentTypes())); + allSeenTypes.addAll(Arrays.asList(state.attributeTypes())); + allSeenTypes.addAll(Arrays.asList(state.globalTypes())); + + // First distribute the global names among the top entities. + if (javaize) { + assignGlobalJavaNames(allSeenTypes); + } + + // now fully javaize everything deeply. + for (int i = 0; i < allSeenTypes.size(); i++) { + SchemaType gType = allSeenTypes.get(i); + if (javaize) { + javaizeType((SchemaTypeImpl) gType); + String className = gType.getFullJavaName(); + if (className != null) { + state.addClassname(className.replace('$', '.'), gType); + } + } else { + skipJavaizingType((SchemaTypeImpl) gType); + } + allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); + // We need to javaize the anonymous types defined inside redefined types + // since redefined type do not get a Java class of their own. + // The exception is complex types derived by restriction, since in this case + // anonymous types are not inherited + addAnonymousTypesFromRedefinition(gType, allSeenTypes); + } + } + + static void assignGlobalJavaNames(Collection schemaTypes) { + HashSet usedNames = new HashSet<>(); + StscState state = StscState.get(); + + for (SchemaType schemaType : schemaTypes) { + SchemaTypeImpl sImpl = (SchemaTypeImpl) schemaType; + QName topName = findTopName(sImpl); + String pickedName = state.getJavaname(topName, sImpl.isDocumentType() ? + BindingConfig.QNAME_DOCUMENT_TYPE : BindingConfig.QNAME_TYPE); + if (sImpl.isUnjavaized()) { + sImpl.setFullJavaName(pickFullJavaClassName(usedNames, findTopName(sImpl), pickedName, sImpl.isDocumentType(), sImpl.isAttributeType())); + sImpl.setFullJavaImplName(pickFullJavaImplName(usedNames, sImpl.getFullJavaName())); + + setUserTypes(sImpl, state); + + setExtensions(sImpl, state); + } + } + + verifyInterfaceNameCollisions(usedNames, state); + } + + private static void verifyInterfaceNameCollisions(Set usedNames, StscState state) { + BindingConfig config = state.getBindingConfig(); + if (config == null) { + return; + } + + InterfaceExtension[] exts = config.getInterfaceExtensions(); + for (InterfaceExtension ext : exts) { + if (usedNames.contains(ext.getInterface().toLowerCase(Locale.ROOT))) { + state.error("InterfaceExtension interface '" + ext.getInterface() + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null); + } + + String handler = ext.getStaticHandler(); + if (handler != null && usedNames.contains(handler.toLowerCase(Locale.ROOT))) { + state.error("InterfaceExtension handler class '" + handler + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null); + } + } + + PrePostExtension[] prepost = config.getPrePostExtensions(); + for (PrePostExtension prePostExtension : prepost) { + String handler = prePostExtension.getStaticHandler(); + if (handler != null && usedNames.contains(handler.toLowerCase(Locale.ROOT))) { + state.error("PrePostExtension handler class '" + handler + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null); + } + } + } + + private static void setUserTypes(SchemaTypeImpl sImpl, StscState state) { + BindingConfig config = state.getBindingConfig(); + + if (config != null) { + UserType utype = config.lookupUserTypeForQName(sImpl.getName()); + if (utype != null) { + sImpl.setUserTypeName(utype.getJavaName()); + sImpl.setUserTypeHandlerName(utype.getStaticHandler()); + } + } + } + + private static void setExtensions(SchemaTypeImpl sImpl, StscState state) { + String javaName = sImpl.getFullJavaName(); + BindingConfig config = state.getBindingConfig(); + + if (javaName != null && config != null) { + sImpl.setInterfaceExtensions(config.getInterfaceExtensions(javaName)); + sImpl.setPrePostExtension(config.getPrePostExtension(javaName)); + } + } + + private static boolean isStringType(SchemaType type) { + if (type == null || type.getSimpleVariety() != SchemaType.ATOMIC) { + return false; + } + return (type.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_STRING); + } + + static String pickConstantName(Set usedNames, String words) { + String base = NameUtil.upperCaseUnderbar(words); + + if (base.length() == 0) { + base = "X"; + } + + if (base.startsWith("INT_")) { + // reserved for int codes + base = "X_" + base; + } + + String uniqName; + int index = 1; + for (uniqName = base; usedNames.contains(uniqName); ) { + index++; + uniqName = base + "_" + index; + } + + usedNames.add(uniqName); + + return uniqName; + } + + static void skipJavaizingType(SchemaTypeImpl sImpl) { + if (sImpl.isJavaized()) { + return; + } + + SchemaTypeImpl baseType = (SchemaTypeImpl) sImpl.getBaseType(); + if (baseType != null) { + skipJavaizingType(baseType); + } + + sImpl.startJavaizing(); + secondPassProcessType(sImpl); + sImpl.finishJavaizing(); + } + + static void secondPassProcessType(SchemaTypeImpl sImpl) { + if (!isStringType(sImpl)) { + return; + } + + XmlAnySimpleType[] enumVals = sImpl.getEnumerationValues(); + + // if this is an enumerated string type, values are to be + // javaized as constants. + if (enumVals == null) { + return; + } + + // ERROR is found at > 3668 + if (enumVals.length > MAX_ENUM_COUNT) { + StscState.get().warning("SchemaType Enumeration found with too many enumeration values to create a Java " + + "enumeration. The base SchemaType \"" + sImpl.getBaseEnumType() + "\" will be used instead", XmlError.SEVERITY_WARNING, null); + return; + } + SchemaType basedOn = sImpl.getBaseEnumType(); + if (basedOn == null) { + return; + } + + SchemaStringEnumEntry[] entryArray = new SchemaStringEnumEntry[enumVals.length]; + if (basedOn == sImpl) { + Set usedNames = new HashSet<>(); + for (int i = 0; i < enumVals.length; i++) { + String val = enumVals[i].getStringValue(); + entryArray[i] = new SchemaStringEnumEntryImpl(val, i + 1, pickConstantName(usedNames, val)); + } + } else { + for (int i = 0; i < enumVals.length; i++) { + String val = enumVals[i].getStringValue(); + entryArray[i] = basedOn.enumEntryForString(val); + } + } + sImpl.setStringEnumEntries(entryArray); + } + + static void javaizeType(SchemaTypeImpl sImpl) { + if (sImpl.isJavaized()) { + return; + } + + SchemaTypeImpl baseType = (SchemaTypeImpl) sImpl.getBaseType(); + if (baseType != null) { + javaizeType(baseType); + } + if (sImpl.getContentBasedOnType() != null && sImpl.getContentBasedOnType() != baseType) { + javaizeType((SchemaTypeImpl) sImpl.getContentBasedOnType()); + } + + sImpl.startJavaizing(); + + sImpl.setCompiled(true); + + secondPassProcessType(sImpl); + + if (!sImpl.isSimpleType()) { + SchemaProperty[] eltProps = sImpl.getElementProperties(); + SchemaProperty[] attrProps = sImpl.getAttributeProperties(); + + // Handing out java names - this permits us to avoid collisions. + Set usedPropNames = new HashSet<>(); + + // First, copy all used property names from base, since these + // cannnot be changed at this point and they may be arbitrary + // because of derivation by restriction and the "nopvr" switch + SchemaProperty[] baseProps = baseType.getProperties(); + for (SchemaProperty baseProp : baseProps) { + String name = baseProp.getJavaPropertyName(); + assert !usedPropNames.contains(name); + usedPropNames.add(name); + } + + // count in the methods from extension interfaces + avoidExtensionMethods(usedPropNames, sImpl); + + // Assign names in two passes: first inherited names, then others. + for (boolean doInherited = true; ; doInherited = false) { + if (eltProps.length > 0) { + assignJavaPropertyNames(usedPropNames, eltProps, baseType, doInherited); + } + + assignJavaPropertyNames(usedPropNames, attrProps, baseType, doInherited); + + if (!doInherited) { + break; + } + } + + SchemaProperty[] allprops = sImpl.getProperties(); + + // determine whether order insensitive + boolean insensitive = isPropertyModelOrderInsensitive(allprops); + + // Fill in the java type codes now. + // This depends on recursive type information, so it's done in typechecking + assignJavaTypeCodes(allprops); + + sImpl.setOrderSensitive(!insensitive); + } + + // assign java type names to anonymous types + // for redefined types, this step was performed when javaizing the redefinition + if (sImpl.getFullJavaName() != null || sImpl.getOuterType() != null) { + assignJavaAnonymousTypeNames(sImpl); + } + + sImpl.finishJavaizing(); + } + + private static final String[] PREFIXES = new String[]{"get", "xget", "isNil", "isSet", "sizeOf", "set", + "xset", "addNew", "setNil", "unset", "insert", "add", "insertNew", "addNew", "remove"}; + + private static void avoidExtensionMethods(Set usedPropNames, SchemaTypeImpl sImpl) { + InterfaceExtension[] exts = sImpl.getInterfaceExtensions(); + if (exts != null) { + for (InterfaceExtension ext : exts) { + InterfaceExtension.MethodSignature[] methods = ext.getMethods(); + for (InterfaceExtension.MethodSignature method : methods) { + String methodName = method.getName(); + for (String prefix : PREFIXES) { + if (methodName.startsWith(prefix)) { + usedPropNames.add(methodName.substring(prefix.length())); + } + } + } + } + } + } + + static void assignJavaAnonymousTypeNames(SchemaTypeImpl outerType) { + Set usedTypeNames = new HashSet<>(); + SchemaType[] anonymousTypes = outerType.getAnonymousTypes(); + StscState state = StscState.get(); + + int nrOfAnonTypes = anonymousTypes.length; + if (outerType.isRedefinition()) { + // We have to add the anonymous types for redefinitions to the list + // since they don't have another outer class + ArrayList list = new ArrayList<>(); + addAnonymousTypesFromRedefinition(outerType, list); + if (list.size() > 0) { + SchemaType[] temp = new SchemaType[nrOfAnonTypes + list.size()]; + list.toArray(temp); + System.arraycopy(anonymousTypes, 0, temp, list.size(), nrOfAnonTypes); + anonymousTypes = temp; + } + } + + // Because we generate nested java interfaces, and nested + // interface names must not be the same as an ancestor, use up + // the ancestors + + for (SchemaType scanOuterType = outerType; + scanOuterType != null; + scanOuterType = scanOuterType.getOuterType()) { + usedTypeNames.add(scanOuterType.getShortJavaName()); + } + + for (SchemaType scanOuterType = outerType; + scanOuterType != null; + scanOuterType = scanOuterType.getOuterType()) { + usedTypeNames.add(scanOuterType.getShortJavaImplName()); + } + + // and because things are problematic if an inner type name + // is the same as a top-level package name, also get rid of that + // collision + usedTypeNames.add(getOutermostPackage(outerType.getFullJavaName())); + + // assign names + for (int i = 0; i < anonymousTypes.length; i++) { + SchemaTypeImpl sImpl = (SchemaTypeImpl) anonymousTypes[i]; + if (sImpl == null) // already handled in first pass + { + continue; + } + if (sImpl.isSkippedAnonymousType()) { + continue; + } + String localname = null; + String javaname; + + SchemaField containerField = sImpl.getContainerField(); + if (containerField != null) { + QName qname = sImpl.getContainerField().getName(); + localname = qname.getLocalPart(); + javaname = state.getJavaname(sImpl.getContainerField().getName(), BindingConfig.QNAME_TYPE); + } else { + // not defined inside an Elt or Attr: must be a nested simple type + switch (sImpl.getOuterType().getSimpleVariety()) { + case SchemaType.UNION: + javaname = "Member"; + break; + case SchemaType.LIST: + javaname = "Item"; + break; + case SchemaType.ATOMIC: + default: + assert (false) : "Weird type " + sImpl.toString(); + javaname = "Base"; + break; + } + } + + if (i < nrOfAnonTypes) { + sImpl.setShortJavaName( + pickInnerJavaClassName(usedTypeNames, localname, javaname)); + sImpl.setShortJavaImplName( + pickInnerJavaImplName(usedTypeNames, localname, javaname == null ? null : javaname + "Impl")); + } else { + // This comes from redefined types, so we have to compute the + // full name here + sImpl.setFullJavaName(outerType.getFullJavaName() + "$" + + pickInnerJavaClassName(usedTypeNames, localname, javaname)); + sImpl.setFullJavaImplName(outerType.getFullJavaImplName() + "$" + + pickInnerJavaImplName(usedTypeNames, localname, javaname == null ? null : javaname + "Impl")); + } + + // TODO(radup) why is this inside this loop here? + setExtensions(sImpl, state); + } + } + + static void assignJavaPropertyNames(Set usedNames, SchemaProperty[] props, SchemaType baseType, boolean doInherited) { + StscState state = StscState.get(); + + // two passes: first deal with inherited properties, then with new ones. + // this ensures that we match up with base class definitions cleanly + // BUGBUG(radup) We have to look for particles that have been removed + // in the derivation tree for this type using derivation by restriction, + // because they have not been removed in Java and may collide with + // this type's properties. + + for (SchemaProperty prop : props) { + SchemaPropertyImpl sImpl = (SchemaPropertyImpl) prop; + + SchemaProperty baseProp = + (sImpl.isAttribute() ? + baseType.getAttributeProperty(sImpl.getName()) : + baseType.getElementProperty(sImpl.getName())); + + if ((baseProp == null) == doInherited) { + continue; + } + + QName propQName = sImpl.getName(); + + String theName; + + if (baseProp == null) { + theName = pickJavaPropertyName(usedNames, propQName.getLocalPart(), + state.getJavaname(propQName, sImpl.isAttribute() ? BindingConfig.QNAME_ACCESSOR_ATTRIBUTE : + BindingConfig.QNAME_ACCESSOR_ELEMENT)); + } else { + theName = baseProp.getJavaPropertyName(); + } + + sImpl.setJavaPropertyName(theName); + + boolean isArray = (sImpl.getMaxOccurs() == null || + sImpl.getMaxOccurs().compareTo(BigInteger.ONE) > 0); + boolean isSingleton = !isArray && (sImpl.getMaxOccurs().signum() > 0); + boolean isOption = isSingleton && (sImpl.getMinOccurs().signum() == 0); + SchemaType javaBasedOnType = sImpl.getType(); + + if (baseProp != null) { + if (baseProp.extendsJavaArray()) { + isSingleton = false; + isOption = false; + isArray = true; + } + if (baseProp.extendsJavaSingleton()) { + isSingleton = true; + } + if (baseProp.extendsJavaOption()) { + isOption = true; + } + javaBasedOnType = baseProp.javaBasedOnType(); + } + + sImpl.setExtendsJava(javaBasedOnType.getRef(), isSingleton, isOption, isArray); + } + + } + + static void assignJavaTypeCodes(SchemaProperty[] properties) { + for (SchemaProperty property : properties) { + SchemaPropertyImpl sImpl = (SchemaPropertyImpl) property; + SchemaType sType = sImpl.javaBasedOnType(); + sImpl.setJavaTypeCode(javaTypeCodeForType(sType)); + } + } + + static int javaTypeCodeInCommon(SchemaType[] types) { + if (types == null || types.length == 0) { + return SchemaProperty.XML_OBJECT; + } + + int code = javaTypeCodeForType(types[0]); + if (code == SchemaProperty.JAVA_OBJECT) { + return code; + } + for (int i = 1; i < types.length; i++) { + // if any two are different, the answer is java.lang.Object + if (code != javaTypeCodeForType(types[i])) { + return SchemaProperty.JAVA_OBJECT; + } + } + return code; + } + + static int javaTypeCodeForType(SchemaType sType) { + if (!sType.isSimpleType()) { + return SchemaProperty.XML_OBJECT; + } + + if (((SchemaTypeImpl) sType).getUserTypeHandlerName() != null) { + return SchemaProperty.JAVA_USER; + } + + if (sType.getSimpleVariety() == SchemaType.UNION) { + // see if we can find an interesting common base type, e.g., for string enums + SchemaType baseType = sType.getUnionCommonBaseType(); + if (baseType != null && !baseType.isURType()) { + sType = baseType; + } else { + return javaTypeCodeInCommon(sType.getUnionConstituentTypes()); + } + } + + if (sType.getSimpleVariety() == SchemaType.LIST) { + return SchemaProperty.JAVA_LIST; + } + + if (sType.isURType()) { + return SchemaProperty.XML_OBJECT; + } + + switch (sType.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_ANY_SIMPLE: + // return SchemaProperty.XML_OBJECT; + return SchemaProperty.JAVA_STRING; + + case SchemaType.BTC_BOOLEAN: + return SchemaProperty.JAVA_BOOLEAN; + + case SchemaType.BTC_BASE_64_BINARY: + return SchemaProperty.JAVA_BYTE_ARRAY; + + case SchemaType.BTC_HEX_BINARY: + return SchemaProperty.JAVA_BYTE_ARRAY; + + case SchemaType.BTC_ANY_URI: + return SchemaProperty.JAVA_STRING; + + case SchemaType.BTC_QNAME: + return SchemaProperty.JAVA_QNAME; + + case SchemaType.BTC_NOTATION: + return SchemaProperty.XML_OBJECT; + + case SchemaType.BTC_FLOAT: + return SchemaProperty.JAVA_FLOAT; + + case SchemaType.BTC_DOUBLE: + return SchemaProperty.JAVA_DOUBLE; + + case SchemaType.BTC_DECIMAL: + switch (sType.getDecimalSize()) { + case SchemaType.SIZE_BYTE: + return SchemaProperty.JAVA_BYTE; + case SchemaType.SIZE_SHORT: + return SchemaProperty.JAVA_SHORT; + case SchemaType.SIZE_INT: + return SchemaProperty.JAVA_INT; + case SchemaType.SIZE_LONG: + return SchemaProperty.JAVA_LONG; + case SchemaType.SIZE_BIG_INTEGER: + return SchemaProperty.JAVA_BIG_INTEGER; + case SchemaType.SIZE_BIG_DECIMAL: + default: + return SchemaProperty.JAVA_BIG_DECIMAL; + } + + case SchemaType.BTC_STRING: + if (isStringType(sType.getBaseEnumType())) { + // This is necessary for local types, etc. + // schema enums with > ~3668 cause a Java Src file to be created + // that cannot be compiled due to JVM restrictions + // FIXFIX: http://issues.apache.org/jira/browse/XMLBEANS-307 + // FIXFIX: XMLBeans scomp throws error "code too large" + if (sType.getEnumerationValues() != null && + sType.getEnumerationValues().length > MAX_ENUM_COUNT) { + return SchemaProperty.JAVA_STRING; + } else { + return SchemaProperty.JAVA_ENUM; + } + } + return SchemaProperty.JAVA_STRING; + + case SchemaType.BTC_DURATION: + return SchemaProperty.JAVA_GDURATION; + + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_DATE: + // return SchemaProperty.JAVA_DATE; // converted to calendar + + case SchemaType.BTC_TIME: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + // return SchemaProperty.JAVA_GDATE; // converted to calendar (JAX-B) + return SchemaProperty.JAVA_CALENDAR; + + default: + assert (false) : "unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode(); + throw new IllegalStateException("unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode() + " of " + sType.getPrimitiveType().getName()); + } + } + + static boolean isPropertyModelOrderInsensitive(SchemaProperty[] properties) { + for (SchemaProperty prop : properties) { + if (prop.hasNillable() == SchemaProperty.VARIABLE) { + return false; + } + if (prop.hasDefault() == SchemaProperty.VARIABLE) { + return false; + } + if (prop.hasFixed() == SchemaProperty.VARIABLE) { + return false; + } + if (prop.hasDefault() != SchemaProperty.NEVER && + prop.getDefaultText() == null) { + return false; + } + } + return true; + } + + static boolean protectReservedGlobalClassNames(String name) { + int i = name.lastIndexOf('.'); + String lastSegment = name.substring(i + 1); + return lastSegment.endsWith("Document") && !lastSegment.equals("Document"); + } + + static boolean protectReservedInnerClassNames(String name) { + return (name.equals("Enum") || name.equals("Factory")); + } + + static String[] PROTECTED_PROPERTIES = { + "StringValue", + "BooleanValue", + "ByteValue", + "ShortValue", + "IntValue", + "LongValue", + "BigIntegerValue", + "BigDecimalValue", + "FloatValue", + "DoubleValue", + "ByteArrayValue", + "EnumValue", + "CalendarValue", + "DateValue", + "GDateValue", + "GDurationValue", + "QNameValue", + "ListValue", + "ObjectValue", + "Class", + }; + static Set PROTECTED_PROPERTIES_SET = new HashSet<>(Arrays.asList(PROTECTED_PROPERTIES)); + + static boolean protectReservedPropertyNames(String name) { + return PROTECTED_PROPERTIES_SET.contains(name) || + (name.endsWith("Array") && !name.equals("Array")); + } + + static String pickFullJavaClassName(Set usedNames, QName qName, String configname, boolean isDocument, boolean isAttrType) { + String base; + boolean protect; + + if (configname != null && configname.indexOf('.') >= 0) { + // a configname with dots defines the fully qualified java class name + base = configname; + protect = protectReservedGlobalClassNames(base); + } else { + StscState state = StscState.get(); + String uri = qName.getNamespaceURI(); + + base = NameUtil.getClassNameFromQName(qName); + + // Check to see if we have a mapping from namespace URI to Java package + // name. If so, apply the mapped package prefix at the beginning of + // the base name + + String pkgPrefix = state.getPackageOverride(uri); + + if (pkgPrefix != null) { + // Form the new qualified class name from the new package name + // and the old class name + base = pkgPrefix + "." + base.substring(base.lastIndexOf('.') + 1); + } + + // See if there is a prefix... + String javaPrefix = state.getJavaPrefix(uri); + if (javaPrefix != null) { + base = base.substring(0, base.lastIndexOf('.') + 1) + javaPrefix + base.substring(base.lastIndexOf('.') + 1); + } + + // a configname without dots may override the shortname part. + if (configname != null) { + base = base.substring(0, base.lastIndexOf('.') + 1) + configname; + } + + protect = protectReservedGlobalClassNames(base); + if (configname == null) { + // add special suffix + if (isDocument) { + base = base + "Document"; + } else if (isAttrType) { + base = base + "Attribute"; + } + + // add configured suffix + String javaSuffix = state.getJavaSuffix(uri); + if (javaSuffix != null) { + base = base + javaSuffix; + } + } + } + + String outermostPkg = getOutermostPackage(base); + + int index = 1; + String uniqName; + if (protect) { + uniqName = base + index; + } else { + uniqName = base; + } + while (usedNames.contains(uniqName.toLowerCase(Locale.ROOT)) || uniqName.equals(outermostPkg)) { + index++; + uniqName = base + index; + } + + usedNames.add(uniqName.toLowerCase(Locale.ROOT)); + + return uniqName; + } + + static String getOutermostPackage(String fqcn) { + if (fqcn == null) { + return ""; + } + + // remove class name + int lastdot = fqcn.indexOf('.'); + if (lastdot < 0) { + return ""; + } + + // remove outer package names + return fqcn.substring(0, lastdot); + } + + static String pickFullJavaImplName(Set usedNames, String intfName) { + // Strip off the package from the class name so we can replace it + String className = intfName; + String pkgName = null; + int index = intfName.lastIndexOf('.'); + if (index >= 0) { + className = intfName.substring(index + 1); + pkgName = intfName.substring(0, index); + } + + // Form the new qualified class name from the new package name + // and the old class name + String base = pkgName + ".impl." + className + "Impl"; + + index = 1; + String uniqName = base; + while (usedNames.contains(uniqName.toLowerCase(Locale.ROOT))) { + index++; + uniqName = base + index; + } + + usedNames.add(uniqName.toLowerCase(Locale.ROOT)); + + return uniqName; + } + + static String pickJavaPropertyName(Set usedNames, String localName, String javaName) { + if (javaName == null) { + javaName = NameUtil.upperCamelCase(localName); + } + boolean protect = protectReservedPropertyNames(javaName); + String uniqName; + int index = 1; + if (protect) { + uniqName = javaName + index; + } else { + uniqName = javaName; + } + while (usedNames.contains(uniqName)) { + index++; + uniqName = javaName + index; + } + + usedNames.add(uniqName); + + return uniqName; + } + + static String pickInnerJavaClassName(Set usedNames, String localName, String javaName) { + if (javaName == null) { + javaName = NameUtil.upperCamelCase(localName); + } + boolean protect = protectReservedInnerClassNames(javaName); + String uniqName; + int index = 1; + if (protect) { + uniqName = javaName + index; + } else { + uniqName = javaName; + } + while (usedNames.contains(uniqName)) { + index++; + uniqName = javaName + index; + } + + usedNames.add(uniqName); + + return uniqName; + } + + static String pickInnerJavaImplName(Set usedNames, String localName, String javaName) { + if (javaName == null) { + javaName = NameUtil.upperCamelCase(localName) + "Impl"; + } + String uniqName = javaName; + int index = 1; + while (usedNames.contains(uniqName)) { + index++; + uniqName = javaName + index; + } + + usedNames.add(uniqName); + + return uniqName; + } + + static QName findTopName(SchemaType sType) { + if (sType.getName() != null) { + return sType.getName(); + } + + if (sType.isDocumentType()) { + // A document type must have a content model consisting of a single elt + if (sType.getContentModel() == null || sType.getContentModel().getParticleType() != SchemaParticle.ELEMENT) { + throw new IllegalStateException(); + } + return (sType.getDocumentElementName()); + } + + if (sType.isAttributeType()) { + if (sType.getAttributeModel() == null || sType.getAttributeModel().getAttributes().length != 1) { + throw new IllegalStateException(); + } + return sType.getAttributeTypeAttributeName(); + } + + SchemaField sElt = sType.getContainerField(); + assert (sElt != null); + assert (sType.getOuterType() == null); + return sElt.getName(); + } + + static void addAnonymousTypesFromRedefinition(SchemaType sType, List result) { + while (((SchemaTypeImpl) sType).isRedefinition() && + (sType.getDerivationType() == SchemaType.DT_EXTENSION || + sType.isSimpleType())) { + sType = sType.getBaseType(); + SchemaType[] newAnonTypes = sType.getAnonymousTypes(); + if (newAnonTypes.length > 0) { + result.addAll(Arrays.asList(newAnonTypes)); + } + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscResolver.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscResolver.java new file mode 100644 index 0000000..5a945e5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscResolver.java @@ -0,0 +1,282 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.QNameSet; +import org.apache.xmlbeans.SchemaParticle; +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.impl.xb.xsdschema.Attribute; +import org.apache.xmlbeans.impl.xb.xsdschema.Element; +import org.apache.xmlbeans.impl.xb.xsdschema.KeyrefDocument.Keyref; +import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelElement; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.*; + +public class StscResolver { + /** + * Does a topo walk of all the types to resolve them. + */ + public static void resolveAll() { + // resolve tree of types + StscState state = StscState.get(); + + SchemaType[] documentTypes = state.documentTypes(); + for (int i = 0; i < documentTypes.length; i++) { + resolveSubstitutionGroup((SchemaTypeImpl) documentTypes[i]); + } + + List allSeenTypes = new ArrayList(); + allSeenTypes.addAll(Arrays.asList(state.documentTypes())); + allSeenTypes.addAll(Arrays.asList(state.attributeTypes())); + allSeenTypes.addAll(Arrays.asList(state.redefinedGlobalTypes())); + allSeenTypes.addAll(Arrays.asList(state.globalTypes())); + + for (int i = 0; i < allSeenTypes.size(); i++) { + SchemaType gType = (SchemaType) allSeenTypes.get(i); + resolveType((SchemaTypeImpl) gType); + allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); + } + + // Resolve all keyref refs + resolveIdentityConstraints(); + } + + public static boolean resolveType(SchemaTypeImpl sImpl) { + if (sImpl.isResolved()) { + return true; + } + if (sImpl.isResolving()) { + StscState.get().error("Cyclic dependency error", XmlErrorCodes.CYCLIC_DEPENDENCY, sImpl.getParseObject()); + return false; // cyclic dependency error + } + // System.out.println("Resolving " + sImpl); + + sImpl.startResolving(); + + if (sImpl.isDocumentType()) { + resolveDocumentType(sImpl); + } else if (sImpl.isAttributeType()) { + resolveAttributeType(sImpl); + } else if (sImpl.isSimpleType()) { + StscSimpleTypeResolver.resolveSimpleType(sImpl); + } else { + StscComplexTypeResolver.resolveComplexType(sImpl); + } + + sImpl.finishResolving(); + // System.out.println("Finished resolving " + sImpl); + return true; + } + + public static boolean resolveSubstitutionGroup(SchemaTypeImpl sImpl) { + assert sImpl.isDocumentType(); + + if (sImpl.isSGResolved()) { + return true; + } + if (sImpl.isSGResolving()) { + StscState.get().error("Cyclic dependency error", XmlErrorCodes.CYCLIC_DEPENDENCY, sImpl.getParseObject()); + return false; // cyclic dependency error + } + + sImpl.startResolvingSGs(); + + // Resolve substitution group + + TopLevelElement elt = (TopLevelElement) sImpl.getParseObject(); + SchemaTypeImpl substitutionGroup = null; + QName eltName = new QName(sImpl.getTargetNamespace(), elt.getName()); + + // BUG: How do I tell if the type is in this compilation unit? + if (elt.isSetSubstitutionGroup()) { + substitutionGroup = StscState.get().findDocumentType(elt.getSubstitutionGroup(), + sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); + + if (substitutionGroup == null) { + StscState.get().notFoundError(elt.getSubstitutionGroup(), SchemaType.ELEMENT, elt.xgetSubstitutionGroup(), true); + } + // recovery - ignore substitution group + else if (!resolveSubstitutionGroup(substitutionGroup)) { + substitutionGroup = null; + } else { + sImpl.setSubstitutionGroup(elt.getSubstitutionGroup()); + } + } + + // Walk up the chain of subtitution groups adding this schematype to each head's + // member list + while (substitutionGroup != null) { + + substitutionGroup.addSubstitutionGroupMember(eltName); + + if (substitutionGroup.getSubstitutionGroup() == null) { + break; + } + + substitutionGroup = StscState.get().findDocumentType( + substitutionGroup.getSubstitutionGroup(), substitutionGroup.getChameleonNamespace(), null/*no dependency added*/); + + assert substitutionGroup != null : "Could not find document type for: " + substitutionGroup.getSubstitutionGroup(); + + if (!resolveSubstitutionGroup(substitutionGroup)) { + substitutionGroup = null; // cyclic dependency - no subst group + } + + } + + sImpl.finishResolvingSGs(); + return true; + + } + + public static void resolveDocumentType(SchemaTypeImpl sImpl) { + assert sImpl.isResolving(); + + assert sImpl.isDocumentType(); + + + // translate the global element associated with this document type + // and construct a content model which allows just that element + + List anonTypes = new ArrayList<>(); + + SchemaGlobalElementImpl element = + (SchemaGlobalElementImpl) + StscTranslator.translateElement( + (Element) sImpl.getParseObject(), + sImpl.getTargetNamespace(), sImpl.isChameleon(), null, null, + anonTypes, sImpl); + + SchemaLocalElementImpl contentModel = null; + + if (element != null) { + StscState.get().addGlobalElement(element); + + contentModel = new SchemaLocalElementImpl(); + + contentModel.setParticleType(SchemaParticle.ELEMENT); + StscTranslator.copyGlobalElementToLocalElement(element, contentModel); + contentModel.setMinOccurs(BigInteger.ONE); + contentModel.setMaxOccurs(BigInteger.ONE); + + contentModel.setTransitionNotes(QNameSet.EMPTY, true); + } + + Map elementPropertyModel = + StscComplexTypeResolver.buildContentPropertyModelByQName( + contentModel, sImpl); + + SchemaTypeImpl baseType = sImpl.getSubstitutionGroup() == null ? + BuiltinSchemaTypeSystem.ST_ANY_TYPE : + StscState.get().findDocumentType(sImpl.getSubstitutionGroup(), + sImpl.isChameleon() ? sImpl.getTargetNamespace() : null, null/*already added*/); + + sImpl.setBaseTypeRef(baseType.getRef()); + sImpl.setBaseDepth(baseType.getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + sImpl.setComplexTypeVariety(SchemaType.ELEMENT_CONTENT); + + sImpl.setContentModel( + contentModel, new SchemaAttributeModelImpl(), + elementPropertyModel, Collections.EMPTY_MAP, false); + + sImpl.setWildcardSummary( + QNameSet.EMPTY, false, QNameSet.EMPTY, false); + + sImpl.setAnonymousTypeRefs(makeRefArray(anonTypes)); + + + } + + public static void resolveAttributeType(SchemaTypeImpl sImpl) { + assert sImpl.isResolving(); + + assert sImpl.isAttributeType(); + + List anonTypes = new ArrayList<>(); + + SchemaGlobalAttributeImpl attribute = + (SchemaGlobalAttributeImpl) StscTranslator.translateAttribute( + (Attribute) sImpl.getParseObject(), sImpl.getTargetNamespace(), null, + sImpl.isChameleon(), anonTypes, sImpl, null, false); + + SchemaAttributeModelImpl attributeModel = new SchemaAttributeModelImpl(); + + if (attribute != null) { + StscState.get().addGlobalAttribute(attribute); + + SchemaLocalAttributeImpl attributeCopy = new SchemaLocalAttributeImpl(); + StscTranslator.copyGlobalAttributeToLocalAttribute(attribute, attributeCopy); + attributeModel.addAttribute(attributeCopy); + } + + sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef()); + sImpl.setBaseDepth(sImpl.getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + sImpl.setComplexTypeVariety(SchemaType.EMPTY_CONTENT); + + Map attributePropertyModel = + StscComplexTypeResolver.buildAttributePropertyModelByQName( + attributeModel, sImpl); + + sImpl.setContentModel( + null, attributeModel, Collections.EMPTY_MAP, attributePropertyModel, false); + + sImpl.setWildcardSummary( + QNameSet.EMPTY, false, QNameSet.EMPTY, false); + + sImpl.setAnonymousTypeRefs(makeRefArray(anonTypes)); + } + + private static SchemaType.Ref[] makeRefArray(Collection typeList) { + return typeList.stream().map(SchemaType::getRef).toArray(SchemaType.Ref[]::new); + } + + + public static void resolveIdentityConstraints() { + StscState state = StscState.get(); + SchemaIdentityConstraintImpl[] idcs = state.idConstraints(); + + for (SchemaIdentityConstraintImpl idc : idcs) { + if (!idc.isResolved()) { + Keyref xsdkr = (Keyref) idc.getParseObject(); + QName keyName = xsdkr.getRefer(); + SchemaIdentityConstraintImpl key = null; + + key = state.findIdConstraint(keyName, idc.getChameleonNamespace(), idc.getTargetNamespace()); + if (key == null) { + state.notFoundError(keyName, SchemaType.IDENTITY_CONSTRAINT, xsdkr, true); + } else { + if (key.getConstraintCategory() == SchemaIdentityConstraintImpl.CC_KEYREF) { + state.error(XmlErrorCodes.IDENTITY_CONSTRAINT_PROPERTIES$KEYREF_REFERS_TO_KEYREF, + null, idc.getParseObject()); + } + + if (key.getFields().length != idc.getFields().length) { + state.error(XmlErrorCodes.IDENTITY_CONSTRAINT_PROPERTIES$KEY_KEYREF_FIELD_COUNT_EQ, + null, idc.getParseObject()); + } + + idc.setReferencedKey(key.getRef()); + } + } + } + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java new file mode 100644 index 0000000..e43c9fb --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java @@ -0,0 +1,1146 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.regex.ParseException; +import org.apache.xmlbeans.impl.regex.RegularExpression; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.apache.xmlbeans.impl.xb.xsdschema.*; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.*; + +public class StscSimpleTypeResolver { + + /************************************************************************** + * SIMPLE TYPE RESOLUTION HERE + * + * Simple types can be declared as lists, unions, or restrictions. + * These three cases are treated separately in resolveListType, + * resolveUnionType, and resolveSimpleRestrictionType. + * + * The intricate work with facets is done in the restriction case, + * using method called resolveFacets (the union and list cases have + * trivial facet rules). Then all simple types call resolveProperties + * in the end to have their "fundamental facets" resolved. + */ + + public static void resolveSimpleType(SchemaTypeImpl sImpl) { + SimpleType parseSt = (SimpleType) sImpl.getParseObject(); + + assert sImpl.isSimpleType(); + + Schema schema = StscComplexTypeResolver.getSchema(parseSt); + + // Verify: have list, union, or restriction, but not more than one + int count = + (parseSt.isSetList() ? 1 : 0) + + (parseSt.isSetUnion() ? 1 : 0) + + (parseSt.isSetRestriction() ? 1 : 0); + if (count > 1) { + StscState.get().error( + "A simple type must define either a list, a union, or a restriction: more than one found.", + XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN, + parseSt); + // recovery: treat it as the first of list, union, restr + } else if (count < 1) { + StscState.get().error("A simple type must define either a list, a union, or a restriction: none was found.", + XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN, + parseSt); + // recovery: treat it as restriction of anySimpleType + resolveErrorSimpleType(sImpl); + return; + } + + // Set final flags + boolean finalRest = false; + boolean finalList = false; + boolean finalUnion = false; + + Object finalValue = null; + if (parseSt.isSetFinal()) { + finalValue = parseSt.getFinal(); + } + // Inspect the finalDefault attribute on the schema + else if (schema != null && schema.isSetFinalDefault()) { + finalValue = schema.getFinalDefault(); + } + + if (finalValue != null) { + if (finalValue instanceof String) { + if ("#all".equals(finalValue)) { + finalRest = finalList = finalUnion = true; + } + } else if (finalValue instanceof List) { + @SuppressWarnings("unchecked") + List lFinalValue = (List) finalValue; + if (lFinalValue.contains("restriction")) { + finalRest = true; + } + + if (lFinalValue.contains("list")) { + finalList = true; + } + + if (lFinalValue.contains("union")) { + finalUnion = true; + } + } + } + + sImpl.setSimpleFinal(finalRest, finalList, finalUnion); + + List anonTypes = new ArrayList<>(); + + if (parseSt.getList() != null) { + resolveListType(sImpl, parseSt.getList(), anonTypes); + } else if (parseSt.getUnion() != null) { + resolveUnionType(sImpl, parseSt.getUnion(), anonTypes); + } else if (parseSt.getRestriction() != null) { + resolveSimpleRestrictionType(sImpl, parseSt.getRestriction(), anonTypes); + } + + sImpl.setAnonymousTypeRefs(makeRefArray(anonTypes)); + } + + private static SchemaType.Ref[] makeRefArray(List typeList) { + return typeList.stream().map(SchemaType::getRef).toArray(SchemaType.Ref[]::new); + } + + static void resolveErrorSimpleType(SchemaTypeImpl sImpl) { + sImpl.setSimpleTypeVariety(SchemaType.ATOMIC); + sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1); + sImpl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + } + + static void resolveListType(SchemaTypeImpl sImpl, org.apache.xmlbeans.impl.xb.xsdschema.ListDocument.List parseList, List anonTypes) { + StscState state = StscState.get(); + + sImpl.setSimpleTypeVariety(SchemaType.LIST); + sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + + if (sImpl.isRedefinition()) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, + new Object[]{"list"}, parseList); + // recovery: oh well. + } + + QName itemName = parseList.getItemType(); + LocalSimpleType parseInner = parseList.getSimpleType(); + + if (itemName != null && parseInner != null) { + state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$LIST_HAS_BOTH_ITEM_OR_SIMPLE_TYPE, null, parseList); + // recovery: ignore the inner simple type. + parseInner = null; + } + + SchemaTypeImpl itemImpl; + XmlObject errorLoc; + + if (itemName != null) { + itemImpl = state.findGlobalType(itemName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); + errorLoc = parseList.xgetItemType(); + if (itemImpl == null) { + state.notFoundError(itemName, SchemaType.TYPE, parseList.xgetItemType(), true); + // recovery: treat it as a list of anySimpleType + itemImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + } else if (parseInner != null) { + itemImpl = StscTranslator.translateAnonymousSimpleType(parseInner, + sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl); + errorLoc = parseInner; + } else { + state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$LIST_HAS_NEITHER_ITEM_OR_SIMPLE_TYPE, null, parseList); + // recovery: treat it as an extension of anySimpleType + resolveErrorSimpleType(sImpl); + return; + } + + // Verify final restrictions + if (itemImpl.finalList()) { + state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$LIST_FINAL, null, parseList); + } + + // Recursion... + StscResolver.resolveType(itemImpl); + + if (!itemImpl.isSimpleType()) { + state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_NOT_SIMPLE, null, errorLoc); + // recovery: treat the item type as anySimpleType + sImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + switch (itemImpl.getSimpleVariety()) { + case SchemaType.LIST: + state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_LIST, null, errorLoc); + // recovery: treat the list as an anySimpleType + resolveErrorSimpleType(sImpl); + return; + case SchemaType.UNION: + if (itemImpl.isUnionOfLists()) { + state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_UNION_OF_LIST, null, errorLoc); + resolveErrorSimpleType(sImpl); + return; + } + // fallthrough: nonlist unions are just like atomic items + case SchemaType.ATOMIC: + sImpl.setListItemTypeRef(itemImpl.getRef()); + // Check that the item type is not a plan NOTATION + if (sImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) { + state.recover(XmlErrorCodes.DATATYPE_ENUM_NOTATION, null, errorLoc); + } + break; + default: + assert (false); + sImpl.setListItemTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + } + + // now deal with facets + sImpl.setBasicFacets(StscState.FACETS_LIST, StscState.FIXED_FACETS_LIST); + sImpl.setWhiteSpaceRule(SchemaType.WS_COLLAPSE); + + // now compute our intrinsic properties + resolveFundamentalFacets(sImpl); + } + + + static void resolveUnionType(SchemaTypeImpl sImpl, UnionDocument.Union parseUnion, List anonTypes) { + sImpl.setSimpleTypeVariety(SchemaType.UNION); + sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); + sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + + StscState state = StscState.get(); + + if (sImpl.isRedefinition()) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, + new Object[]{"union"}, parseUnion); + // recovery: oh well. + } + + @SuppressWarnings("unchecked") + List memberTypes = (List) parseUnion.getMemberTypes(); + SimpleType[] simpleTypes = parseUnion.getSimpleTypeArray(); + + List memberImplList = new ArrayList<>(); + + if (simpleTypes.length == 0 && (memberTypes == null || memberTypes.size() == 0)) { + state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$UNION_HAS_MEMBER_TYPES_OR_SIMPLE_TYPES, null, parseUnion); + // recovery: oh well, zero member types is fine. + } + + if (memberTypes != null) { + for (QName mName : memberTypes) { + SchemaTypeImpl memberImpl = state.findGlobalType(mName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); + if (memberImpl == null) + // recovery: skip member + { + state.notFoundError(mName, SchemaType.TYPE, parseUnion.xgetMemberTypes(), true); + } else { + memberImplList.add(memberImpl); + } + } + } + + for (int i = 0; i < simpleTypes.length; i++) { + // BUGBUG: see if non children can leak through + SchemaTypeImpl mImpl = StscTranslator.translateAnonymousSimpleType(simpleTypes[i], + sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl); + memberImplList.add(mImpl); + mImpl.setAnonymousUnionMemberOrdinal(i + 1); + } + + // Recurse and resolve all member types + for (Iterator mImpls = memberImplList.iterator(); mImpls.hasNext(); ) { + SchemaTypeImpl mImpl = mImpls.next(); + if (!StscResolver.resolveType(mImpl)) { + // KHK: review + String memberName = ""; + XmlObject errorLoc; + if (Objects.equals(mImpl.getOuterType(), sImpl)) { + errorLoc = mImpl.getParseObject(); + } else { + memberName = QNameHelper.pretty(mImpl.getName()) + " "; + errorLoc = parseUnion.xgetMemberTypes(); + } + + state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$CYCLIC_UNION, new Object[]{memberName}, errorLoc); + + // recovery: ignore the errant union member + mImpls.remove(); + } + } + + // Now verify members + boolean isUnionOfLists = false; + + for (Iterator mImpls = memberImplList.iterator(); mImpls.hasNext(); ) { + SchemaTypeImpl mImpl = mImpls.next(); + + if (!mImpl.isSimpleType()) { + // KHK: review + String memberName = ""; + XmlObject errorLoc; + if (mImpl.getOuterType() != null && mImpl.getOuterType().equals(sImpl)) { + errorLoc = mImpl.getParseObject(); + } else { + memberName = QNameHelper.pretty(mImpl.getName()) + " "; + errorLoc = parseUnion.xgetMemberTypes(); + } + + state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$UNION_MEMBER_NOT_SIMPLE, new Object[]{memberName}, errorLoc); + + // recovery: ignore the errant union member + mImpls.remove(); + continue; + } + + if (mImpl.getSimpleVariety() == SchemaType.LIST || + mImpl.getSimpleVariety() == SchemaType.UNION && mImpl.isUnionOfLists()) { + isUnionOfLists = true; + } + } + + // Verify any final restrictions + for (SchemaTypeImpl schemaType : memberImplList) { + if (schemaType.finalUnion()) { + state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$UNION_FINAL, null, parseUnion); + } + } + + sImpl.setUnionOfLists(isUnionOfLists); + + sImpl.setUnionMemberTypeRefs(makeRefArray(memberImplList)); + + // now deal with facets + sImpl.setBasicFacets(StscState.FACETS_UNION, StscState.FIXED_FACETS_UNION); + + // now compute our intrinsic properties + resolveFundamentalFacets(sImpl); + } + + static void resolveSimpleRestrictionType(SchemaTypeImpl sImpl, RestrictionDocument.Restriction parseRestr, List anonTypes) { + QName baseName = parseRestr.getBase(); + SimpleType parseInner = parseRestr.getSimpleType(); + StscState state = StscState.get(); + + if (baseName != null && parseInner != null) { + state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_BOTH_BASE_OR_SIMPLE_TYPE, null, parseRestr); + // recovery: ignore the inner simple type. + parseInner = null; + } + + SchemaTypeImpl baseImpl; + + if (baseName != null) { + if (sImpl.isRedefinition()) { + baseImpl = state.findRedefinedGlobalType(parseRestr.getBase(), sImpl.getChameleonNamespace(), sImpl); + if (baseImpl != null && !baseImpl.getName().equals(sImpl.getName())) { + state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, + new Object[]{"", + QNameHelper.pretty(baseName), + QNameHelper.pretty(sImpl.getName()) + }, + parseRestr); + } + } else { + baseImpl = state.findGlobalType(baseName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); + } + if (baseImpl == null) { + state.notFoundError(baseName, SchemaType.TYPE, parseRestr.xgetBase(), true); + // recovery: treat it as an extension of anySimpleType + baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + } else if (parseInner != null) { + if (sImpl.isRedefinition()) { + StscState.get().error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, + new Object[]{""}, parseInner); + // recovery: oh well. + } + + baseImpl = StscTranslator.translateAnonymousSimpleType(parseInner, + sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null, + sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl); + } else { + state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_NEITHER_BASE_OR_SIMPLE_TYPE, null, parseRestr); + // recovery: treat it as an extension of anySimpleType + baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + // Recursion! + if (!StscResolver.resolveType(baseImpl)) { + // cyclic dependency recovery: treat it as an extension of anySimpleType + baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + if (baseImpl.finalRestriction()) { + state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$RESTRICTION_FINAL, null, parseRestr); + } + + sImpl.setBaseTypeRef(baseImpl.getRef()); + sImpl.setBaseDepth(baseImpl.getBaseDepth() + 1); + sImpl.setDerivationType(SchemaType.DT_RESTRICTION); + + if (!baseImpl.isSimpleType()) { + state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$ATOMIC_NOT_SIMPLE, null, parseRestr.xgetBase()); + // recovery: treat it as a restriction of anySimpleType + resolveErrorSimpleType(sImpl); + return; + } + + sImpl.setSimpleTypeVariety(baseImpl.getSimpleVariety()); + + // copy variety-specific properties + switch (baseImpl.getSimpleVariety()) { + case SchemaType.ATOMIC: + sImpl.setPrimitiveTypeRef(baseImpl.getPrimitiveType().getRef()); + break; + case SchemaType.UNION: + sImpl.setUnionOfLists(baseImpl.isUnionOfLists()); + sImpl.setUnionMemberTypeRefs(makeRefArray(Arrays.asList(baseImpl.getUnionMemberTypes()))); + break; + case SchemaType.LIST: + sImpl.setListItemTypeRef(baseImpl.getListItemType().getRef()); + break; + } + + // deal with facets + resolveFacets(sImpl, parseRestr, baseImpl); + + // now compute our intrinsic properties + resolveFundamentalFacets(sImpl); + } + + static int translateWhitespaceCode(XmlAnySimpleType value) { + // BUGBUG: add whitespace rule to textvalue. + String textval = value.getStringValue(); + + if (textval.equals("collapse")) { + return SchemaType.WS_COLLAPSE; + } + + if (textval.equals("preserve")) { + return SchemaType.WS_PRESERVE; + } + + if (textval.equals("replace")) { + return SchemaType.WS_REPLACE; + } + + // KHK: s4s + StscState.get().error("Unrecognized whitespace value \"" + textval + "\"", XmlErrorCodes.FACET_VALUE_MALFORMED, value); + return SchemaType.WS_UNSPECIFIED; + } + + static boolean isMultipleFacet(int facetcode) { + return (facetcode == SchemaType.FACET_ENUMERATION || + facetcode == SchemaType.FACET_PATTERN); + } + + static boolean facetAppliesToType(int facetCode, SchemaTypeImpl baseImpl) { + switch (baseImpl.getSimpleVariety()) { + case SchemaType.LIST: + switch (facetCode) { + case SchemaType.FACET_LENGTH: + case SchemaType.FACET_MIN_LENGTH: + case SchemaType.FACET_MAX_LENGTH: + case SchemaType.FACET_ENUMERATION: + case SchemaType.FACET_PATTERN: + case SchemaType.FACET_WHITE_SPACE: + return true; + } + return false; + + case SchemaType.UNION: + switch (facetCode) { + case SchemaType.FACET_ENUMERATION: + case SchemaType.FACET_PATTERN: + return true; + } + return false; + } + + // the atomic case + + switch (baseImpl.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_ANY_SIMPLE: + return false; + + case SchemaType.BTC_BOOLEAN: + switch (facetCode) { + case SchemaType.FACET_PATTERN: + case SchemaType.FACET_WHITE_SPACE: + return true; + } + return false; + + case SchemaType.BTC_FLOAT: + case SchemaType.BTC_DOUBLE: + case SchemaType.BTC_DURATION: + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + switch (facetCode) { + case SchemaType.FACET_MIN_EXCLUSIVE: + case SchemaType.FACET_MIN_INCLUSIVE: + case SchemaType.FACET_MAX_INCLUSIVE: + case SchemaType.FACET_MAX_EXCLUSIVE: + case SchemaType.FACET_ENUMERATION: + case SchemaType.FACET_PATTERN: + case SchemaType.FACET_WHITE_SPACE: + return true; + } + return false; + + case SchemaType.BTC_DECIMAL: + switch (facetCode) { + case SchemaType.FACET_MIN_EXCLUSIVE: + case SchemaType.FACET_MIN_INCLUSIVE: + case SchemaType.FACET_MAX_INCLUSIVE: + case SchemaType.FACET_MAX_EXCLUSIVE: + case SchemaType.FACET_TOTAL_DIGITS: + case SchemaType.FACET_FRACTION_DIGITS: + case SchemaType.FACET_ENUMERATION: + case SchemaType.FACET_PATTERN: + case SchemaType.FACET_WHITE_SPACE: + return true; + } + return false; + + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: + case SchemaType.BTC_ANY_URI: + case SchemaType.BTC_QNAME: + case SchemaType.BTC_NOTATION: + case SchemaType.BTC_STRING: + switch (facetCode) { + case SchemaType.FACET_LENGTH: + case SchemaType.FACET_MIN_LENGTH: + case SchemaType.FACET_MAX_LENGTH: + case SchemaType.FACET_ENUMERATION: + case SchemaType.FACET_PATTERN: + case SchemaType.FACET_WHITE_SPACE: + return true; + } + return false; + + default: + assert (false); + return false; + } + } + + private static int other_similar_limit(int facetcode) { + switch (facetcode) { + case SchemaType.FACET_MIN_EXCLUSIVE: + return SchemaType.FACET_MIN_INCLUSIVE; + case SchemaType.FACET_MIN_INCLUSIVE: + return SchemaType.FACET_MIN_EXCLUSIVE; + case SchemaType.FACET_MAX_INCLUSIVE: + return SchemaType.FACET_MAX_EXCLUSIVE; + case SchemaType.FACET_MAX_EXCLUSIVE: + return SchemaType.FACET_MAX_INCLUSIVE; + default: + assert (false); + throw new IllegalStateException(); + } + } + + static void resolveFacets(SchemaTypeImpl sImpl, XmlObject restriction, SchemaTypeImpl baseImpl) { + StscState state = StscState.get(); + + boolean[] seenFacet = new boolean[SchemaType.LAST_FACET + 1]; + XmlAnySimpleType[] myFacets = baseImpl.getBasicFacets(); // makes a copy + boolean[] fixedFacets = baseImpl.getFixedFacets(); + int wsr = SchemaType.WS_UNSPECIFIED; + List enumeratedValues = null; + List patterns = null; + + if (restriction != null) { + XmlCursor cur = restriction.newCursor(); + for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) { + QName facetQName = cur.getName(); + String facetName = facetQName.getLocalPart(); + int code = translateFacetCode(facetQName); + if (code == -1) { + continue; + } + + Facet facet = (Facet) cur.getObject(); + + if (!facetAppliesToType(code, baseImpl)) { + state.error(XmlErrorCodes.FACETS_APPLICABLE, + new Object[]{facetName, QNameHelper.pretty(baseImpl.getName())}, facet); + continue; + } else if (baseImpl.getSimpleVariety() == SchemaType.ATOMIC && + baseImpl.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION + && (code == SchemaType.FACET_LENGTH || code == SchemaType.FACET_MIN_LENGTH || + code == SchemaType.FACET_MAX_LENGTH)) { + state.warning(XmlErrorCodes.FACETS_DEPRECATED_NOTATION, + new Object[]{facetName, QNameHelper.pretty(baseImpl.getName())}, facet); + } + if (seenFacet[code] && !isMultipleFacet(code)) { + state.error(XmlErrorCodes.DATATYPE_SINGLE_FACET_VALUE, null, facet); + continue; + } + seenFacet[code] = true; + + switch (code) { + case SchemaType.FACET_LENGTH: +// if (myFacets[SchemaType.FACET_MIN_LENGTH] != null || +// myFacets[SchemaType.FACET_MAX_LENGTH] != null) +// { +// state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); +// continue; +// } + XmlInteger len = StscTranslator.buildNnInteger(facet.getValue()); + if (len == null) { + state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); + continue; + } + if (fixedFacets[code] && !myFacets[code].valueEquals(len)) { + state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet); + continue; + } + if (myFacets[SchemaType.FACET_MIN_LENGTH] != null) { + // An error for 'length' and 'minLength' to be specified at the same time + // except if the base type had the same value for 'minLength' also + XmlAnySimpleType baseMinLength = baseImpl.getFacet(SchemaType.FACET_MIN_LENGTH); + if (!(baseMinLength != null && + baseMinLength.valueEquals(myFacets[SchemaType.FACET_MIN_LENGTH]) && + baseMinLength.compareValue(len) <= 0)) { + state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); + continue; + } + } + if (myFacets[SchemaType.FACET_MAX_LENGTH] != null) { + // An error for 'length' and 'maxLength' to be specified at the same time + // except if the base type had the same value for 'maxLength' also + XmlAnySimpleType baseMaxLength = baseImpl.getFacet(SchemaType.FACET_MAX_LENGTH); + if (!(baseMaxLength != null && + baseMaxLength.valueEquals(myFacets[SchemaType.FACET_MAX_LENGTH]) && + baseMaxLength.compareValue(len) >= 0)) { + state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); + continue; + } + } + myFacets[code] = len; + break; + + case SchemaType.FACET_MIN_LENGTH: + case SchemaType.FACET_MAX_LENGTH: + XmlInteger mlen = StscTranslator.buildNnInteger(facet.getValue()); + if (mlen == null) { + state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); + continue; + } + if (fixedFacets[code] && !myFacets[code].valueEquals(mlen)) { + state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet); + continue; + } + if (myFacets[SchemaType.FACET_LENGTH] != null) { + // It's an error for 'length' and 'minLength'/'maxLength' to be + // specified at the same time, except for the case when + // the base type had the same value for 'minLength'/'maxLength' + // and the two values are consistent + XmlAnySimpleType baseMinMaxLength = baseImpl.getFacet(code); + if (!(baseMinMaxLength != null && + baseMinMaxLength.valueEquals(mlen) && + (code == SchemaType.FACET_MIN_LENGTH ? + baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) <= 0 : + baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) >= 0))) { + state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); + continue; + } + } + if (myFacets[SchemaType.FACET_MAX_LENGTH] != null) { + if (mlen.compareValue(myFacets[SchemaType.FACET_MAX_LENGTH]) > 0) { + state.error(XmlErrorCodes.DATATYPE_MAX_LENGTH_RESTRICTION, null, facet); + continue; + } + } + if (myFacets[SchemaType.FACET_MIN_LENGTH] != null) { + if (mlen.compareValue(myFacets[SchemaType.FACET_MIN_LENGTH]) < 0) { + state.error(XmlErrorCodes.DATATYPE_MIN_LENGTH_RESTRICTION, null, facet); + continue; + } + } + myFacets[code] = mlen; + break; + + case SchemaType.FACET_TOTAL_DIGITS: + XmlPositiveInteger dig = StscTranslator.buildPosInteger(facet.getValue()); + if (dig == null) { + state.error("Must be a positive integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); + break; + } + if (fixedFacets[code] && !myFacets[code].valueEquals(dig)) { + state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet); + continue; + } + if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null) { + if (dig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0) { + state.error(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_RESTRICTION, null, facet); + } + } + myFacets[code] = dig; + break; + + case SchemaType.FACET_FRACTION_DIGITS: + XmlNonNegativeInteger fdig = StscTranslator.buildNnInteger(facet.getValue()); + if (fdig == null) { + state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); + break; + } + if (fixedFacets[code] && !myFacets[code].valueEquals(fdig)) { + state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet); + continue; + } + if (myFacets[SchemaType.FACET_FRACTION_DIGITS] != null) { + if (fdig.compareValue(myFacets[SchemaType.FACET_FRACTION_DIGITS]) > 0) { + state.error(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_RESTRICTION, null, facet); + } + } + if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null) { + if (fdig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0) { + state.error(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_LE_TOTAL_DIGITS, null, facet); + } + } + myFacets[code] = fdig; + break; + + case SchemaType.FACET_MIN_EXCLUSIVE: + case SchemaType.FACET_MIN_INCLUSIVE: + case SchemaType.FACET_MAX_INCLUSIVE: + case SchemaType.FACET_MAX_EXCLUSIVE: + + if (seenFacet[other_similar_limit(code)]) { + state.error("Cannot define both inclusive and exclusive limit in the same restriciton", XmlErrorCodes.FACET_DUPLICATED, facet); + continue; + } + boolean ismin = (code == SchemaType.FACET_MIN_EXCLUSIVE || code == SchemaType.FACET_MIN_INCLUSIVE); + boolean isexclusive = (code == SchemaType.FACET_MIN_EXCLUSIVE || code == SchemaType.FACET_MAX_EXCLUSIVE); + + XmlAnySimpleType limit; + try { + limit = baseImpl.newValue(facet.getValue(), true); + } catch (XmlValueOutOfRangeException e) { + // note: this guarantees that the limit is a valid number in the + // base data type!! + switch (code) { + case SchemaType.FACET_MIN_EXCLUSIVE: + state.error(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_RESTRICTION, + new Object[]{e.getMessage()}, facet); + break; + case SchemaType.FACET_MIN_INCLUSIVE: + state.error(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_RESTRICTION, + new Object[]{e.getMessage()}, facet); + break; + case SchemaType.FACET_MAX_INCLUSIVE: + state.error(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_RESTRICTION, + new Object[]{e.getMessage()}, facet); + break; + case SchemaType.FACET_MAX_EXCLUSIVE: + state.error(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_RESTRICTION, + new Object[]{e.getMessage()}, facet); + break; + } + + // BUGBUG: if there are actual schemas that redefine min/maxExclusive, + // they will need this rule relaxed for them!! + continue; + } + if (fixedFacets[code] && !myFacets[code].valueEquals(limit)) { + state.error(XmlErrorCodes.FACET_FIXED, new Object[]{facetName}, facet); + continue; + } + if (myFacets[code] != null) { + SchemaType limitSType = limit.schemaType(); + if (limitSType != null && !limitSType.isSimpleType() && + limitSType.getContentType() == SchemaType.SIMPLE_CONTENT) { + // in the case of complex types with simple content that has facets + // we need to compare values based on the content type + limit = baseImpl.getContentBasedOnType().newValue(facet.getValue()); + } + + int comparison = limit.compareValue(myFacets[code]); + if (comparison == 2 || comparison == (ismin ? -1 : 1)) { + state.error(ismin ? + (isexclusive ? + "Must be greater than or equal to previous minExclusive" : + "Must be greater than or equal to previous minInclusive") : + (isexclusive ? + "Must be less than or equal to previous maxExclusive" : + "Must be less than or equal to previous maxInclusive"), + XmlErrorCodes.FACET_VALUE_MALFORMED, facet); + continue; + } + } + myFacets[code] = limit; + myFacets[other_similar_limit(code)] = null; + break; + + case SchemaType.FACET_WHITE_SPACE: + wsr = translateWhitespaceCode(facet.getValue()); + if (baseImpl.getWhiteSpaceRule() > wsr) { + wsr = SchemaType.WS_UNSPECIFIED; + state.error(XmlErrorCodes.DATATYPE_WHITESPACE_RESTRICTION, null, facet); + continue; + } + myFacets[code] = StscState.build_wsstring(wsr).get(); + break; + + case SchemaType.FACET_ENUMERATION: + XmlAnySimpleType enumval; + try { + enumval = baseImpl.newValue(facet.getValue(), true); + // enumval.set(facet.getValue()); + // ((XmlObjectBase)enumval).setImmutable(); + } catch (XmlValueOutOfRangeException e) { + state.error(XmlErrorCodes.DATATYPE_ENUM_RESTRICTION, new Object[]{facet.getValue().getStringValue(), e.getMessage()}, facet); + continue; + } + if (enumeratedValues == null) { + enumeratedValues = new ArrayList<>(); + } + enumeratedValues.add(enumval); + break; + + case SchemaType.FACET_PATTERN: + RegularExpression p; + try { + p = new RegularExpression(facet.getValue().getStringValue(), "X"); + } catch (ParseException e) { + state.error(XmlErrorCodes.PATTERN_REGEX, new Object[]{facet.getValue().getStringValue(), e.getMessage()}, facet); + continue; + } + if (patterns == null) { + patterns = new ArrayList<>(); + } + patterns.add(p); + break; + } + + if (facet.getFixed()) { + fixedFacets[code] = true; + } + } + } + + // Store the array of basic facets + + sImpl.setBasicFacets(makeValueRefArray(myFacets), fixedFacets); + + // Update the numeric whitespace rule + if (wsr == SchemaType.WS_UNSPECIFIED) { + wsr = baseImpl.getWhiteSpaceRule(); + } + sImpl.setWhiteSpaceRule(wsr); + + // store away the enumerated values + if (enumeratedValues != null) { + sImpl.setEnumerationValues(makeValueRefArray(enumeratedValues.toArray(new XmlAnySimpleType[0]))); + + SchemaType beType = sImpl; + if (sImpl.isRedefinition()) { + beType = sImpl.getBaseType().getBaseEnumType(); + if (beType == null || sImpl.getBaseType() == beType) { + beType = sImpl; + } + } else if (sImpl.getBaseType().getBaseEnumType() != null) { + beType = sImpl.getBaseType().getBaseEnumType(); + } + sImpl.setBaseEnumTypeRef(beType.getRef()); + } else { + sImpl.copyEnumerationValues(baseImpl); + } + + // store the pattern list + RegularExpression[] patternArray = patterns != null ? patterns.toArray(EMPTY_REGEX_ARRAY) : EMPTY_REGEX_ARRAY; + sImpl.setPatternFacet((patternArray.length > 0 || baseImpl.hasPatternFacet())); + sImpl.setPatterns(patternArray); + + // Check that, if the base type is NOTATION, there is an enumeration facet + // http://www.w3.org/TR/xmlschema-2/#NOTATION + if (baseImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) { + if (sImpl.getEnumerationValues() == null) { + state.recover(XmlErrorCodes.DATATYPE_ENUM_NOTATION, null, restriction); + } + } + } + + private static XmlValueRef[] makeValueRefArray(XmlAnySimpleType[] source) { + XmlValueRef[] result = new XmlValueRef[source.length]; + for (int i = 0; i < result.length; i++) { + result[i] = (source[i] == null ? null : new XmlValueRef(source[i])); + } + return result; + } + + private static final RegularExpression[] EMPTY_REGEX_ARRAY = new RegularExpression[0]; + + private static boolean isDiscreteType(SchemaTypeImpl sImpl) { + if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) != null) { + return true; + } + // BUGBUG: spec is silent on enumerations; they're finite too. + switch (sImpl.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + case SchemaType.BTC_BOOLEAN: + return true; + } + return false; + } + + private static boolean isNumericPrimitive(SchemaType sImpl) { + switch (sImpl.getBuiltinTypeCode()) { + case SchemaType.BTC_DECIMAL: + case SchemaType.BTC_FLOAT: + case SchemaType.BTC_DOUBLE: + return true; + } + return false; + } + + private static int decimalSizeOfType(SchemaTypeImpl sImpl) { + int size = mathematicalSizeOfType(sImpl); + + // byte and short are inconvenient, because setByte((byte)4) requires a cast. + // So use "int" unless you're really a xs:byte, xs:short, or an xs:unsignedByte + // (the last case is included for alignment with JAXB) + + if (size == SchemaType.SIZE_BYTE && !XmlByte.type.isAssignableFrom(sImpl)) { + size = SchemaType.SIZE_SHORT; + } + if (size == SchemaType.SIZE_SHORT && !XmlShort.type.isAssignableFrom(sImpl) && !XmlUnsignedByte.type.isAssignableFrom(sImpl)) { + size = SchemaType.SIZE_INT; + } + + return size; + } + + private static int mathematicalSizeOfType(SchemaTypeImpl sImpl) { + if (sImpl.getPrimitiveType().getBuiltinTypeCode() != SchemaType.BTC_DECIMAL) { + return SchemaType.NOT_DECIMAL; + } + + if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) == null || + ((SimpleValue) sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS)).getBigIntegerValue().signum() != 0) { + return SchemaType.SIZE_BIG_DECIMAL; + } + + BigInteger min = null; + BigInteger max = null; + + if (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null) { + min = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)).getBigIntegerValue(); // .add(BigInteger.ONE); + } + if (sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE) != null) { + min = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE)).getBigIntegerValue(); + } + if (sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE) != null) { + max = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE)).getBigIntegerValue(); + } + if (sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE) != null) { + max = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)).getBigIntegerValue(); // .subtract(BigInteger.ONE); + } + + if (sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS) != null) { + BigInteger peg = null; + try { + BigInteger totalDigits = ((SimpleValue) sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS)).getBigIntegerValue(); + + switch (totalDigits.intValue()) { + case 0: + case 1: + case 2: + peg = BigInteger.valueOf(99L); // BYTE size + break; + case 3: + case 4: + peg = BigInteger.valueOf(9999L); // SHORT size + break; + case 5: + case 6: + case 7: + case 8: + case 9: + peg = BigInteger.valueOf(999999999L); // INT size + break; + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + peg = BigInteger.valueOf(999999999999999999L); // LONG size + break; + } + } catch (XmlValueOutOfRangeException ignored) { + } + if (peg != null) { + min = (min == null ? peg.negate() : min.max(peg.negate())); + max = (max == null ? peg : max.min(peg)); + } + } + + if (min != null && max != null) { + // find the largest "absolute value" number that must be dealt with + if (min.signum() < 0) { + min = min.negate().subtract(BigInteger.ONE); + } + if (max.signum() < 0) { + max = max.negate().subtract(BigInteger.ONE); + } + + max = max.max(min); + if (max.compareTo(BigInteger.valueOf(Byte.MAX_VALUE)) <= 0) { + return SchemaType.SIZE_BYTE; + } + if (max.compareTo(BigInteger.valueOf(Short.MAX_VALUE)) <= 0) { + return SchemaType.SIZE_SHORT; + } + if (max.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) <= 0) { + return SchemaType.SIZE_INT; + } + if (max.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) <= 0) { + return SchemaType.SIZE_LONG; + } + } + + return SchemaType.SIZE_BIG_INTEGER; + } + + + static void resolveFundamentalFacets(SchemaTypeImpl sImpl) { + // deal with, isOrdered, isBounded, isFinite, isNumeric + // also deal with + switch (sImpl.getSimpleVariety()) { + case SchemaType.ATOMIC: + SchemaTypeImpl baseImpl = (SchemaTypeImpl) sImpl.getBaseType(); + sImpl.setOrdered(baseImpl.ordered()); + sImpl.setBounded( + (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null || + sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE) != null) && + (sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE) != null || + sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE) != null)); + sImpl.setFinite(baseImpl.isFinite() || + sImpl.isBounded() && isDiscreteType(sImpl)); + sImpl.setNumeric(baseImpl.isNumeric() || + isNumericPrimitive(sImpl.getPrimitiveType())); + sImpl.setDecimalSize(decimalSizeOfType(sImpl)); + break; + case SchemaType.UNION: + SchemaType[] mTypes = sImpl.getUnionMemberTypes(); + int ordered = SchemaType.UNORDERED; + boolean isBounded = true; + boolean isFinite = true; + boolean isNumeric = true; + // ordered if any is ordered, bounded if all are bounded. + for (SchemaType mType : mTypes) { + if (mType.ordered() != SchemaType.UNORDERED) { + ordered = SchemaType.PARTIAL_ORDER; + } + if (!mType.isBounded()) { + isBounded = false; + } + if (!mType.isFinite()) { + isFinite = false; + } + if (!mType.isNumeric()) { + isNumeric = false; + } + } + sImpl.setOrdered(ordered); + sImpl.setBounded(isBounded); + sImpl.setFinite(isFinite); + sImpl.setNumeric(isNumeric); + sImpl.setDecimalSize(SchemaType.NOT_DECIMAL); + break; + case SchemaType.LIST: + sImpl.setOrdered(SchemaType.UNORDERED); + // BUGBUG: the schema spec is wrong here: MIN_LENGTH is not needed, beause len >=0 + sImpl.setBounded(sImpl.getFacet(SchemaType.FACET_LENGTH) != null || + sImpl.getFacet(SchemaType.FACET_MAX_LENGTH) != null); + // BUGBUG: the schema spec is wrong here: finite cardinality requires item type is finite + sImpl.setFinite(sImpl.getListItemType().isFinite() && sImpl.isBounded()); + sImpl.setNumeric(false); + sImpl.setDecimalSize(SchemaType.NOT_DECIMAL); + break; + } + } + + private static class CodeForNameEntry { + CodeForNameEntry(QName name, int code) { + this.name = name; + this.code = code; + } + + public QName name; + public int code; + } + + private static final CodeForNameEntry[] facetCodes = { + new CodeForNameEntry(QNameHelper.forLNS("length", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_LENGTH), + new CodeForNameEntry(QNameHelper.forLNS("minLength", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_LENGTH), + new CodeForNameEntry(QNameHelper.forLNS("maxLength", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_LENGTH), + new CodeForNameEntry(QNameHelper.forLNS("pattern", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_PATTERN), + new CodeForNameEntry(QNameHelper.forLNS("enumeration", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_ENUMERATION), + new CodeForNameEntry(QNameHelper.forLNS("whiteSpace", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_WHITE_SPACE), + new CodeForNameEntry(QNameHelper.forLNS("maxInclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_INCLUSIVE), + new CodeForNameEntry(QNameHelper.forLNS("maxExclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_EXCLUSIVE), + new CodeForNameEntry(QNameHelper.forLNS("minInclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_INCLUSIVE), + new CodeForNameEntry(QNameHelper.forLNS("minExclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_EXCLUSIVE), + new CodeForNameEntry(QNameHelper.forLNS("totalDigits", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_TOTAL_DIGITS), + new CodeForNameEntry(QNameHelper.forLNS("fractionDigits", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_FRACTION_DIGITS), + }; + + private static final Map facetCodeMap = buildFacetCodeMap(); + + private static Map buildFacetCodeMap() { + Map result = new HashMap<>(); + for (CodeForNameEntry facetCode : facetCodes) { + result.put(facetCode.name, facetCode.code); + } + return result; + } + + private static int translateFacetCode(QName name) { + return facetCodeMap.getOrDefault(name, -1); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java new file mode 100644 index 0000000..f9227c9 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java @@ -0,0 +1,1404 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ResolverUtil; +import org.apache.xmlbeans.impl.util.HexBin; +import org.apache.xmlbeans.impl.values.XmlStringImpl; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.xml.sax.EntityResolver; + +import javax.xml.namespace.QName; +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.function.Consumer; + +/** + * This class represents the state of the SchemaTypeSystemCompiler as it's + * going. + */ +public class StscState { + private final static XmlValueRef XMLSTR_PRESERVE = buildString("preserve"); + private final static XmlValueRef XMLSTR_REPLACE = buildString("preserve"); + private final static XmlValueRef XMLSTR_COLLAPSE = buildString("preserve"); + + static final SchemaType[] EMPTY_ST_ARRAY = new SchemaType[0]; + + private static final XmlValueRef[] FACETS_NONE = new XmlValueRef[12]; + private static final boolean[] FIXED_FACETS_NONE = new boolean[12]; + private static final boolean[] FIXED_FACETS_WS = new boolean[12]; + + private static final XmlValueRef[] FACETS_WS_COLLAPSE = { + null, null, null, null, null, null, null, null, null, + build_wsstring(SchemaType.WS_COLLAPSE), null, null + }; + + + final static XmlValueRef[] FACETS_UNION = FACETS_NONE; + final static boolean[] FIXED_FACETS_UNION = FIXED_FACETS_NONE; + final static XmlValueRef[] FACETS_LIST = FACETS_WS_COLLAPSE; + final static boolean[] FIXED_FACETS_LIST = FIXED_FACETS_WS; + + private static final ThreadLocal tl_stscStack = new ThreadLocal<>(); + + private final static String PROJECT_URL_PREFIX = "project://local"; + + + private String _givenStsName; + private Collection _errorListener; + private SchemaTypeSystemImpl _target; + private BindingConfig _config; + private Map _compatMap; + private boolean _doingDownloads; + private byte[] _digest = null; + private boolean _noDigest = false; + + // EXPERIMENTAL: recovery from compilation errors and partial type systems + private boolean _allowPartial = false; + private int _recoveredErrors = 0; + + private SchemaTypeLoader _importingLoader; + + private final Map _containers = new LinkedHashMap<>(); + private SchemaDependencies _dependencies; + + private final Map _redefinedGlobalTypes = new LinkedHashMap<>(); + private final Map _redefinedModelGroups = new LinkedHashMap<>(); + private final Map _redefinedAttributeGroups = new LinkedHashMap<>(); + + private final Map _globalTypes = new LinkedHashMap<>(); + private final Map _globalElements = new LinkedHashMap<>(); + private final Map _globalAttributes = new LinkedHashMap<>(); + private final Map _modelGroups = new LinkedHashMap<>(); + private final Map _attributeGroups = new LinkedHashMap<>(); + private final Map _documentTypes = new LinkedHashMap<>(); + private final Map _attributeTypes = new LinkedHashMap<>(); + private final Map _typesByClassname = new LinkedHashMap<>(); + private final Map _misspelledNames = new HashMap<>(); + private final Set _processingGroups = new LinkedHashSet<>(); + private final Map _idConstraints = new LinkedHashMap<>(); + private final Set _namespaces = new HashSet<>(); + private final List _annotations = new ArrayList<>(); + private boolean _noUpa; + private boolean _noPvr; + private boolean _noAnn; + private boolean _mdefAll; + private final Set _mdefNamespaces = buildDefaultMdefNamespaces(); + private EntityResolver _entityResolver; + private File _schemasDir; + + + private final Map _sourceForUri = new HashMap<>(); + private URI _baseURI = URI.create(PROJECT_URL_PREFIX + "/"); + private final SchemaTypeLoader _s4sloader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader()); + + + private static Set buildDefaultMdefNamespaces() { + // namespaces which are known to appear in WSDLs redundantly + return new HashSet<>( + Collections.singletonList("http://www.openuri.org/2002/04/soap/conversation/")); + } + + /** + * Only constructed via StscState.start(). + */ + private StscState() { + } + + /** + * Initializer for incremental compilation + */ + public void initFromTypeSystem(SchemaTypeSystemImpl system, Set newNamespaces) { +// setGivenTypeSystemName(system.getName().substring(14)); + + SchemaContainer[] containers = system.containers(); + for (SchemaContainer container : containers) { + if (!newNamespaces.contains(container.getNamespace())) { + // Copy data from the given container + addContainer(container); + } + } + } + + + /* CONTAINERS ================================================================*/ + + void addNewContainer(String namespace) { + if (_containers.containsKey(namespace)) { + return; + } + + SchemaContainer container = new SchemaContainer(namespace); + container.setTypeSystem(sts()); + addNamespace(namespace); + _containers.put(namespace, container); + } + + private void addContainer(SchemaContainer container) { + _containers.put(container.getNamespace(), container); + + // container.redefinedModelGroups() / .redefinedAttributeGroups() / .redefinedGlobalTypes() are always empty + // no need to copy them over to _redefinedModelGroups / _redefinedAttributeGroups / _redefinedGlobalTypes + + container.globalElements().forEach(g -> _globalElements.put(g.getName(), g)); + container.globalAttributes().forEach(g -> _globalAttributes.put(g.getName(), g)); + container.modelGroups().forEach(g -> _modelGroups.put(g.getName(), g)); + container.attributeGroups().forEach(g -> _attributeGroups.put(g.getName(), g)); + + container.globalTypes().forEach(mapTypes(_globalTypes, false)); + container.documentTypes().forEach(mapTypes(_documentTypes, true)); + container.attributeTypes().forEach(mapTypes(_attributeTypes, true)); + + container.identityConstraints().forEach(g -> _idConstraints.put(g.getName(), g)); + + _annotations.addAll(container.annotations()); + _namespaces.add(container.getNamespace()); + container.unsetImmutable(); + } + + private Consumer mapTypes(Map map, boolean useProperties) { + return (t) -> { + QName name = useProperties ? t.getProperties()[0].getName() : t.getName(); + map.put(name, t); + if (t.getFullJavaName() != null) { + addClassname(t.getFullJavaName(), t); + } + }; + } + + SchemaContainer getContainer(String namespace) { + return _containers.get(namespace); + } + + Map getContainerMap() { + return Collections.unmodifiableMap(_containers); + } + + /* DEPENDENCIES ================================================================*/ + + void registerDependency(String sourceNs, String targetNs) { + _dependencies.registerDependency(sourceNs, targetNs); + } + + void registerContribution(String ns, String fileUrl) { + _dependencies.registerContribution(ns, fileUrl); + } + + SchemaDependencies getDependencies() { + return _dependencies; + } + + void setDependencies(SchemaDependencies deps) { + _dependencies = deps; + } + + boolean isFileProcessed(String url) { + return _dependencies.isFileRepresented(url); + } + + + /** + * Initializer for schematypepath + */ + public void setImportingTypeLoader(SchemaTypeLoader loader) { + _importingLoader = loader; + } + + /** + * Initializer for error handling. + */ + public void setErrorListener(Collection errorListener) { + _errorListener = errorListener; + } + + /** + * Passes an error on to the current error listener. + * KHK: remove this + */ + public void error(String message, int code, XmlObject loc) { + addError(_errorListener, message, code, loc); + } + + /** + * Passes an error on to the current error listener. + */ + public void error(String code, Object[] args, XmlObject loc) { + addError(_errorListener, code, args, loc); + } + + /** + * Passes a recovered error on to the current error listener. + */ + public void recover(String code, Object[] args, XmlObject loc) { + addError(_errorListener, code, args, loc); + _recoveredErrors++; + } + + /** + * Passes an error on to the current error listener. + */ + public void warning(String message, int code, XmlObject loc) { + addWarning(_errorListener, message, code, loc); + } + + /** + * Passes an error on to the current error listener. + */ + public void warning(String code, Object[] args, XmlObject loc) { + // it's OK for XMLSchema.xsd itself to have reserved type names + if (XmlErrorCodes.RESERVED_TYPE_NAME.equals(code) && + loc.documentProperties().getSourceName() != null && + loc.documentProperties().getSourceName().indexOf("XMLSchema.xsd") > 0) { + return; + } + + addWarning(_errorListener, code, args, loc); + } + + /** + * Passes a warning on to the current error listener. + */ + public void info(String message) { + addInfo(_errorListener, message); + } + + /** + * Passes a warning on to the current error listener. + */ + public void info(String code, Object[] args) { + addInfo(_errorListener, code, args); + } + + // KHK: remove this + public static void addError(Collection errorListener, String message, int code, XmlObject location) { + XmlError err = + XmlError.forObject( + message, + XmlError.SEVERITY_ERROR, + location); + errorListener.add(err); + } + + public static void addError(Collection errorListener, String code, Object[] args, XmlObject location) { + XmlError err = + XmlError.forObject( + code, + args, + XmlError.SEVERITY_ERROR, + location); + errorListener.add(err); + } + + public static void addError(Collection errorListener, String code, Object[] args, File location) { + XmlError err = + XmlError.forLocation( + code, + args, + XmlError.SEVERITY_ERROR, + location.toURI().toString(), 0, 0, 0); + errorListener.add(err); + } + + public static void addError(Collection errorListener, String code, Object[] args, URL location) { + XmlError err = + XmlError.forLocation( + code, + args, + XmlError.SEVERITY_ERROR, + location.toString(), 0, 0, 0); + errorListener.add(err); + } + + // KHK: remove this + public static void addWarning(Collection errorListener, String message, int code, XmlObject location) { + XmlError err = + XmlError.forObject( + message, + XmlError.SEVERITY_WARNING, + location); + errorListener.add(err); + } + + public static void addWarning(Collection errorListener, String code, Object[] args, XmlObject location) { + XmlError err = + XmlError.forObject( + code, + args, + XmlError.SEVERITY_WARNING, + location); + errorListener.add(err); + } + + public static void addInfo(Collection errorListener, String message) { + XmlError err = XmlError.forMessage(message, XmlError.SEVERITY_INFO); + errorListener.add(err); + } + + public static void addInfo(Collection errorListener, String code, Object[] args) { + XmlError err = XmlError.forMessage(code, args, XmlError.SEVERITY_INFO); + errorListener.add(err); + } + + public void setGivenTypeSystemName(String name) { + _givenStsName = name; + } + + /** + * Initializer for references to the SchemaTypeLoader + */ + public void setTargetSchemaTypeSystem(SchemaTypeSystemImpl target) { + _target = target; + } + + /** + * Accumulates a schema digest... + */ + public void addSchemaDigest(byte[] digest) { + if (_noDigest) { + return; + } + + if (digest == null) { + _noDigest = true; + _digest = null; + return; + } + + if (_digest == null) { + _digest = new byte[128 / 8]; // 128 bits. + } + int len = _digest.length; + if (digest.length < len) { + len = digest.length; + } + for (int i = 0; i < len; i++) { + _digest[i] ^= digest[i]; + } + } + + /** + * The SchemaTypeSystem which we're building types on behalf of. + */ + public SchemaTypeSystemImpl sts() { + if (_target != null) { + return _target; + } + + String name = _givenStsName; + if (name == null && _digest != null) { + name = "s" + new String(HexBin.encode(_digest), StandardCharsets.ISO_8859_1); + } + + _target = new SchemaTypeSystemImpl(name); + return _target; + } + + /** + * True if the given URI is a local file + */ + public boolean shouldDownloadURI(String uriString) { + if (_doingDownloads) { + return true; + } + + if (uriString == null) { + return false; + } + + try { + URI uri = new URI(uriString); + if (uri.getScheme().equalsIgnoreCase("jar") || + uri.getScheme().equalsIgnoreCase("zip")) { + // It may be local or not, depending on the embedded URI + String s = uri.getSchemeSpecificPart(); + int i = s.lastIndexOf('!'); + return shouldDownloadURI(i > 0 ? s.substring(0, i) : s); + } + return uri.getScheme().equalsIgnoreCase("file"); + } catch (Exception e) { + return false; + } + } + + /** + * Initializer for compatMap. + */ + public void setOptions(XmlOptions options) { + if (options == null) { + return; // defaults are all false. + } + + _allowPartial = options.isCompilePartialTypesystem(); + + _compatMap = options.getCompileSubstituteNames(); + _noUpa = options.isCompileNoUpaRule() || + !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true")); + _noPvr = options.isCompileNoPvrRule() || + !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true")); + _noAnn = options.isCompileNoAnnotations() || + !"true".equals(SystemProperties.getProperty("xmlbean.schemaannotations", "true")); + _doingDownloads = options.isCompileDownloadUrls() || + "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false")); + _entityResolver = options.getEntityResolver(); + + if (_entityResolver == null) { + _entityResolver = ResolverUtil.getGlobalEntityResolver(); + } + + if (_entityResolver != null) { + _doingDownloads = true; + } + + Set mdef = options.getCompileMdefNamespaces(); + if (mdef != null) { + _mdefNamespaces.addAll(mdef); + + String local = "##local"; + String any = "##any"; + + if (_mdefNamespaces.contains(local)) { + _mdefNamespaces.remove(local); + _mdefNamespaces.add(""); + } + if (_mdefNamespaces.contains(any)) { + _mdefNamespaces.remove(any); + _mdefAll = true; + } + } + } + + /** + * May return null if there is no custom entity resolver. + */ + public EntityResolver getEntityResolver() { + return _entityResolver; + } + + /** + * True if no unique particle attribution option is set + */ + public boolean noUpa() { + return _noUpa; + } + + /** + * True if no particle valid (restriciton) option is set + */ + public boolean noPvr() { + return _noPvr; + } + + /** + * True if annotations should be skipped + */ + public boolean noAnn() { + return _noAnn; + } + + /** + * True if a partial SchemaTypeSystem should be produced + */ + // EXPERIMENTAL + public boolean allowPartial() { + return _allowPartial; + } + + /** + * Get count of recovered errors. Not for public. + */ + // EXPERIMENTAL + public int getRecovered() { + return _recoveredErrors; + } + + /** + * Intercepts XML names and translates them + * through the compat map, if any. + *

      + * Also looks for a default namespace for global definitions. + */ + private QName compatName(QName name, String chameleonNamespace) { + // first check for a chameleonNamespace namespace + if (name.getNamespaceURI().length() == 0 && chameleonNamespace != null && chameleonNamespace.length() > 0) { + name = new QName(chameleonNamespace, name.getLocalPart()); + } + + if (_compatMap == null) { + return name; + } + + QName subst = _compatMap.get(name); + if (subst == null) { + return name; + } + return subst; + } + + /** + * Initializer for the schema config object. + */ + public void setBindingConfig(BindingConfig config) + throws IllegalArgumentException { + _config = config; + } + + public BindingConfig getBindingConfig() + throws IllegalArgumentException { + return _config; + } + + /** + * Looks up package override for a namespace URI + */ + public String getPackageOverride(String namespace) { + if (_config == null) { + return null; + } + return _config.lookupPackageForNamespace(namespace); + } + + /** + * Looks up package override for a namespace URI + */ + public String getJavaPrefix(String namespace) { + if (_config == null) { + return null; + } + return _config.lookupPrefixForNamespace(namespace); + } + + /** + * Looks up package override for a namespace URI + */ + public String getJavaSuffix(String namespace) { + if (_config == null) { + return null; + } + return _config.lookupSuffixForNamespace(namespace); + } + + /** + * Looks up configured java name for the given qname. + */ + public String getJavaname(QName qname, int kind) { + if (_config == null) { + return null; + } + return _config.lookupJavanameForQName(qname, kind); + } + + /* SPELLINGS ======================================================*/ + + private static String crunchName(QName name) { + // lowercase, and drop namespace. + return name.getLocalPart().toLowerCase(Locale.ROOT); + } + + void addSpelling(QName name, SchemaComponent comp) { + _misspelledNames.put(crunchName(name), comp); + } + + SchemaComponent findSpelling(QName name) { + return _misspelledNames.get(crunchName(name)); + } + + /* NAMESPACES ======================================================*/ + + void addNamespace(String targetNamespace) { + _namespaces.add(targetNamespace); + } + + String[] getNamespaces() { + return _namespaces.toArray(new String[0]); + } + + boolean linkerDefinesNamespace(String namespace) { + return _importingLoader.isNamespaceDefined(namespace); + } + + /* TYPES ==========================================================*/ + + SchemaTypeImpl findGlobalType(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaTypeImpl result = (SchemaTypeImpl) _globalTypes.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaTypeImpl) _importingLoader.findType(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + SchemaTypeImpl findRedefinedGlobalType(QName name, String chameleonNamespace, SchemaTypeImpl redefinedBy) { + QName redefinedName = redefinedBy.getName(); + name = compatName(name, chameleonNamespace); + if (name.equals(redefinedName)) { + return _redefinedGlobalTypes.get(redefinedBy); + // BUGBUG: should also link against _importingLoader.findRedefinedType + } + SchemaTypeImpl result = (SchemaTypeImpl) _globalTypes.get(name); + if (result == null) { + result = (SchemaTypeImpl) _importingLoader.findType(name); + } + // no dependency is needed here, necause it's intra-namespace + return result; + } + + void addGlobalType(SchemaTypeImpl type, SchemaTypeImpl redefined) { + if (type != null) { + QName name = type.getName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == type.getContainer(); + + if (redefined != null) { + if (_redefinedGlobalTypes.containsKey(redefined)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global type", QNameHelper.pretty(name), _redefinedGlobalTypes.get(redefined).getSourceName()}, + type.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global type", QNameHelper.pretty(name), _redefinedGlobalTypes.get(redefined).getSourceName()}, + type.getParseObject()); + } + } + } else { + _redefinedGlobalTypes.put(redefined, type); + container.addRedefinedType(type.getRef()); + } + } else { + if (_globalTypes.containsKey(name)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global type", QNameHelper.pretty(name), _globalTypes.get(name).getSourceName()}, + type.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global type", QNameHelper.pretty(name), _globalTypes.get(name).getSourceName()}, + type.getParseObject()); + } + } + } else { + _globalTypes.put(name, type); + container.addGlobalType(type.getRef()); + addSpelling(name, type); + } + } + } + } + + private boolean ignoreMdef(QName name) { + return _mdefNamespaces.contains(name.getNamespaceURI()); + } + + SchemaType[] globalTypes() { + return _globalTypes.values().toArray(new SchemaType[0]); + } + + SchemaType[] redefinedGlobalTypes() { + return _redefinedGlobalTypes.values().toArray(new SchemaType[0]); + } + + /* DOCUMENT TYPES =================================================*/ + + SchemaTypeImpl findDocumentType(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaTypeImpl result = (SchemaTypeImpl) _documentTypes.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaTypeImpl) _importingLoader.findDocumentType(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + void addDocumentType(SchemaTypeImpl type, QName name) { + if (_documentTypes.containsKey(name)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global element", QNameHelper.pretty(name), _documentTypes.get(name).getSourceName()}, + type.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global element", QNameHelper.pretty(name), _documentTypes.get(name).getSourceName()}, + type.getParseObject()); + } + } + } else { + _documentTypes.put(name, type); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == type.getContainer(); + container.addDocumentType(type.getRef()); + } + } + + SchemaType[] documentTypes() { + return _documentTypes.values().toArray(new SchemaType[0]); + } + + /* ATTRIBUTE TYPES =================================================*/ + + SchemaTypeImpl findAttributeType(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaTypeImpl result = (SchemaTypeImpl) _attributeTypes.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaTypeImpl) _importingLoader.findAttributeType(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + void addAttributeType(SchemaTypeImpl type, QName name) { + if (_attributeTypes.containsKey(name)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global attribute", QNameHelper.pretty(name), _attributeTypes.get(name).getSourceName()}, + type.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"global attribute", QNameHelper.pretty(name), _attributeTypes.get(name).getSourceName()}, + type.getParseObject()); + } + } + } else { + _attributeTypes.put(name, type); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == type.getContainer(); + container.addAttributeType(type.getRef()); + } + } + + SchemaType[] attributeTypes() { + return _attributeTypes.values().toArray(new SchemaType[0]); + } + + /* ATTRIBUTES =====================================================*/ + + SchemaGlobalAttributeImpl findGlobalAttribute(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaGlobalAttributeImpl result = (SchemaGlobalAttributeImpl) _globalAttributes.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaGlobalAttributeImpl) _importingLoader.findAttribute(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + void addGlobalAttribute(SchemaGlobalAttributeImpl attribute) { + if (attribute != null) { + QName name = attribute.getName(); + _globalAttributes.put(name, attribute); + addSpelling(name, attribute); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == attribute.getContainer(); + container.addGlobalAttribute(attribute.getRef()); + } + } + + SchemaGlobalAttribute[] globalAttributes() { + return _globalAttributes.values().toArray(new SchemaGlobalAttribute[0]); + } + + /* ELEMENTS =======================================================*/ + + SchemaGlobalElementImpl findGlobalElement(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaGlobalElementImpl result = (SchemaGlobalElementImpl) _globalElements.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaGlobalElementImpl) _importingLoader.findElement(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + void addGlobalElement(SchemaGlobalElementImpl element) { + if (element != null) { + QName name = element.getName(); + _globalElements.put(name, element); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == element.getContainer(); + container.addGlobalElement(element.getRef()); + addSpelling(name, element); + } + } + + SchemaGlobalElement[] globalElements() { + return _globalElements.values().toArray(new SchemaGlobalElement[0]); + } + + /* ATTRIBUTE GROUPS ===============================================*/ + + SchemaAttributeGroupImpl findAttributeGroup(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl) _attributeGroups.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaAttributeGroupImpl) _importingLoader.findAttributeGroup(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + SchemaAttributeGroupImpl findRedefinedAttributeGroup(QName name, String chameleonNamespace, SchemaAttributeGroupImpl redefinedBy) { + QName redefinitionFor = redefinedBy.getName(); + name = compatName(name, chameleonNamespace); + if (name.equals(redefinitionFor)) { + return _redefinedAttributeGroups.get(redefinedBy); + // BUGBUG: should also link against _importingLoader.findRedefinedAttributeGroup + } + SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl) _attributeGroups.get(name); + if (result == null) { + result = (SchemaAttributeGroupImpl) _importingLoader.findAttributeGroup(name); + } + return result; + } + + void addAttributeGroup(SchemaAttributeGroupImpl attributeGroup, SchemaAttributeGroupImpl redefined) { + if (attributeGroup != null) { + QName name = attributeGroup.getName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == attributeGroup.getContainer(); + if (redefined != null) { + if (_redefinedAttributeGroups.containsKey(redefined)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"attribute group", QNameHelper.pretty(name), _redefinedAttributeGroups.get(redefined).getSourceName()}, + attributeGroup.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"attribute group", QNameHelper.pretty(name), _redefinedAttributeGroups.get(redefined).getSourceName()}, + attributeGroup.getParseObject()); + } + } + } else { + _redefinedAttributeGroups.put(redefined, attributeGroup); + container.addRedefinedAttributeGroup(attributeGroup.getRef()); + } + } else { + if (_attributeGroups.containsKey(name)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"attribute group", QNameHelper.pretty(name), _attributeGroups.get(name).getSourceName()}, + attributeGroup.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"attribute group", QNameHelper.pretty(name), _attributeGroups.get(name).getSourceName()}, + attributeGroup.getParseObject()); + } + } + } else { + _attributeGroups.put(attributeGroup.getName(), attributeGroup); + addSpelling(attributeGroup.getName(), attributeGroup); + container.addAttributeGroup(attributeGroup.getRef()); + } + } + } + } + + SchemaAttributeGroup[] attributeGroups() { + return _attributeGroups.values().toArray(new SchemaAttributeGroup[0]); + } + + SchemaAttributeGroup[] redefinedAttributeGroups() { + return _redefinedAttributeGroups.values().toArray(new SchemaAttributeGroup[0]); + } + + /* MODEL GROUPS ===================================================*/ + + SchemaModelGroupImpl findModelGroup(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + SchemaModelGroupImpl result = (SchemaModelGroupImpl) _modelGroups.get(name); + boolean foundOnLoader = false; + if (result == null) { + result = (SchemaModelGroupImpl) _importingLoader.findModelGroup(name); + foundOnLoader = result != null; + } + if (!foundOnLoader && sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return result; + } + + SchemaModelGroupImpl findRedefinedModelGroup(QName name, String chameleonNamespace, SchemaModelGroupImpl redefinedBy) { + QName redefinitionFor = redefinedBy.getName(); + name = compatName(name, chameleonNamespace); + if (name.equals(redefinitionFor)) { + return _redefinedModelGroups.get(redefinedBy); + // BUGBUG: should also link against _importingLoader.findRedefinedModelGroup + } + SchemaModelGroupImpl result = (SchemaModelGroupImpl) _modelGroups.get(name); + if (result == null) { + result = (SchemaModelGroupImpl) _importingLoader.findModelGroup(name); + } + return result; + } + + void addModelGroup(SchemaModelGroupImpl modelGroup, SchemaModelGroupImpl redefined) { + if (modelGroup != null) { + QName name = modelGroup.getName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == modelGroup.getContainer(); + if (redefined != null) { + if (_redefinedModelGroups.containsKey(redefined)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName()}, + modelGroup.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName()}, + modelGroup.getParseObject()); + } + } + } else { + _redefinedModelGroups.put(redefined, modelGroup); + container.addRedefinedModelGroup(modelGroup.getRef()); + } + } else { + if (_modelGroups.containsKey(name)) { + if (!ignoreMdef(name)) { + if (_mdefAll) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"model group", QNameHelper.pretty(name), _modelGroups.get(name).getSourceName()}, + modelGroup.getParseObject()); + } else { + error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"model group", QNameHelper.pretty(name), _modelGroups.get(name).getSourceName()}, + modelGroup.getParseObject()); + } + } + } else { + _modelGroups.put(modelGroup.getName(), modelGroup); + addSpelling(modelGroup.getName(), modelGroup); + container.addModelGroup(modelGroup.getRef()); + } + } + } + } + + SchemaModelGroup[] modelGroups() { + return _modelGroups.values().toArray(new SchemaModelGroup[0]); + } + + SchemaModelGroup[] redefinedModelGroups() { + return _redefinedModelGroups.values().toArray(new SchemaModelGroup[0]); + } + + /* IDENTITY CONSTRAINTS ===========================================*/ + + SchemaIdentityConstraintImpl findIdConstraint(QName name, String chameleonNamespace, String sourceNamespace) { + name = compatName(name, chameleonNamespace); + if (sourceNamespace != null) { + registerDependency(sourceNamespace, name.getNamespaceURI()); + } + return (SchemaIdentityConstraintImpl) _idConstraints.get(name); + } + + void addIdConstraint(SchemaIdentityConstraintImpl idc) { + if (idc != null) { + QName name = idc.getName(); + SchemaContainer container = getContainer(name.getNamespaceURI()); + assert container != null && container == idc.getContainer(); + if (_idConstraints.containsKey(name)) { + if (!ignoreMdef(name)) { + warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, + new Object[]{"identity constraint", QNameHelper.pretty(name), _idConstraints.get(name).getSourceName()}, + idc.getParseObject()); + } + } else { + _idConstraints.put(name, idc); + addSpelling(idc.getName(), idc); + container.addIdentityConstraint(idc.getRef()); + } + } + } + + SchemaIdentityConstraintImpl[] idConstraints() { + return _idConstraints.values().toArray(new SchemaIdentityConstraintImpl[0]); + } + + /* ANNOTATIONS ===========================================*/ + + void addAnnotation(SchemaAnnotationImpl ann, String targetNamespace) { + if (ann != null) { + SchemaContainer container = getContainer(targetNamespace); + assert container != null && container == ann.getContainer(); + _annotations.add(ann); + container.addAnnotation(ann); + } + } + + List annotations() { + return _annotations; + } + + /* RECURSION AVOIDANCE ============================================*/ + boolean isProcessing(SchemaComponent obj) { + return _processingGroups.contains(obj); + } + + void startProcessing(SchemaComponent obj) { + assert (!_processingGroups.contains(obj)); + _processingGroups.add(obj); + } + + void finishProcessing(SchemaComponent obj) { + assert (_processingGroups.contains(obj)); + _processingGroups.remove(obj); + } + + SchemaComponent[] getCurrentProcessing() { + return _processingGroups.toArray(new SchemaComponent[0]); + } + + /* JAVAIZATION ====================================================*/ + + Map typesByClassname() { + return Collections.unmodifiableMap(_typesByClassname); + } + + void addClassname(String classname, SchemaType type) { + _typesByClassname.put(classname, type); + } + + + /** + * Stack management if (heaven help us) we ever need to do + * nested compilation of schema type system. + */ + private static final class StscStack { + StscState current; + List stack = new ArrayList<>(); + + final StscState push() { + stack.add(current); + current = new StscState(); + return current; + } + + final void pop() { + current = stack.get(stack.size() - 1); + stack.remove(stack.size() - 1); + } + } + + public static void clearThreadLocals() { + tl_stscStack.remove(); + } + + public static StscState start() { + StscStack stscStack = tl_stscStack.get(); + + if (stscStack == null) { + stscStack = new StscStack(); + tl_stscStack.set(stscStack); + } + return stscStack.push(); + } + + public static StscState get() { + return tl_stscStack.get().current; + } + + public static void end() { + StscStack stscStack = tl_stscStack.get(); + stscStack.pop(); + if (stscStack.stack.size() == 0) { + // this is required to release all the references in this classloader + tl_stscStack.remove(); + } + // which will enable class unloading and avoid OOM in PermGen + } + + + static XmlValueRef build_wsstring(int wsr) { + switch (wsr) { + case SchemaType.WS_PRESERVE: + return XMLSTR_PRESERVE; + case SchemaType.WS_REPLACE: + return XMLSTR_REPLACE; + case SchemaType.WS_COLLAPSE: + return XMLSTR_COLLAPSE; + } + return null; + } + + static XmlValueRef buildString(String str) { + if (str == null) { + return null; + } + + try { + XmlStringImpl i = new XmlStringImpl(); + i.setStringValue(str); + i.setImmutable(); + return new XmlValueRef(i); + } catch (XmlValueOutOfRangeException e) { + return null; + } + } + + public void notFoundError(QName itemName, int code, XmlObject loc, boolean recovered) { + String expected; + String expectedName = QNameHelper.pretty(itemName); + String found = null; + String foundName = null; + String sourceName = null; + + if (recovered) { + _recoveredErrors++; + } + + switch (code) { + case SchemaType.TYPE: + expected = "type"; + break; + case SchemaType.ELEMENT: + expected = "element"; + break; + case SchemaType.ATTRIBUTE: + expected = "attribute"; + break; + case SchemaType.MODEL_GROUP: + expected = "model group"; + break; + case SchemaType.ATTRIBUTE_GROUP: + expected = "attribute group"; + break; + case SchemaType.IDENTITY_CONSTRAINT: + expected = "identity constraint"; + break; + default: + assert (false); + expected = "definition"; + break; + } + + SchemaComponent foundComponent = findSpelling(itemName); + QName name; + if (foundComponent != null) { + name = foundComponent.getName(); + if (name != null) { + switch (foundComponent.getComponentType()) { + case SchemaComponent.TYPE: + found = "type"; + sourceName = foundComponent.getSourceName(); + break; + case SchemaComponent.ELEMENT: + found = "element"; + sourceName = foundComponent.getSourceName(); + break; + case SchemaComponent.ATTRIBUTE: + found = "attribute"; + sourceName = foundComponent.getSourceName(); + break; + case SchemaComponent.ATTRIBUTE_GROUP: + found = "attribute group"; + break; + case SchemaComponent.MODEL_GROUP: + found = "model group"; + break; + } + + if (sourceName != null) { + sourceName = sourceName.substring(sourceName.lastIndexOf('/') + 1); + } + + if (!name.equals(itemName)) { + foundName = QNameHelper.pretty(name); + } + } + } + + if (found == null) { + // error with no help + error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE, + new Object[]{expected, expectedName}, loc); + } else { + // error with help + error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE$HELP, + new Object[]{ + expected, + expectedName, + found, + (foundName == null ? 0 : 1), + foundName, + (sourceName == null ? 0 : 1), + sourceName + }, + loc); + } + } + + + /** + * Produces the "sourceName" (to be used within the schema project + * source file copies) from the URI of the original source. + *

      + * Returns null if none. + */ + public String sourceNameForUri(String uri) { + return _sourceForUri.get(uri); + } + + /** + * Returns the whole sourceCopyMap, mapping URI's that have + * been read to "sourceName" local names that have been used + * to tag the types. + */ + public Map sourceCopyMap() { + return Collections.unmodifiableMap(_sourceForUri); + } + + /** + * The base URI to use for nice filenames when saving sources. + */ + public void setBaseUri(URI uri) { + _baseURI = uri; + } + + public String relativize(String uri) { + return relativize(uri, false); + } + + public String computeSavedFilename(String uri) { + return relativize(uri, true); + } + + private String relativize(String uri, boolean forSavedFilename) { + if (uri == null) { + return null; + } + + // deal with things that do not look like absolute uris + if (uri.startsWith("/")) { + uri = PROJECT_URL_PREFIX + uri.replace('\\', '/'); + } else { + // looks like a URL? + int colon = uri.indexOf(':'); + if (colon <= 1 || !uri.substring(0, colon).matches("^\\w+$")) { + uri = PROJECT_URL_PREFIX + "/" + uri.replace('\\', '/'); + } + } + + // now relativize against that... + if (_baseURI != null) { + try { + URI relative = _baseURI.relativize(new URI(uri)); + if (!relative.isAbsolute()) { + return relative.toString(); + } else { + uri = relative.toString(); + } + } catch (URISyntaxException ignored) { + } + } + + if (!forSavedFilename) { + return uri; + } + + int lastslash = uri.lastIndexOf('/'); + String dir = QNameHelper.hexsafe(lastslash == -1 ? "" : uri.substring(0, lastslash)); + + int question = uri.indexOf('?', lastslash + 1); + if (question == -1) { + return dir + "/" + uri.substring(lastslash + 1); + } + + String query = QNameHelper.hexsafe(uri.substring(question)); + + // if encoded query part is longer than 64 characters, just drop it + if (query.startsWith(QNameHelper.URI_SHA1_PREFIX)) { + return dir + "/" + uri.substring(lastslash + 1, question); + } else { + return dir + "/" + uri.substring(lastslash + 1, question) + query; + } + } + + /** + * Notes another URI that has been consumed during compilation + * (this is the URI that is in the document .NAME property) + */ + public void addSourceUri(String uri, String nameToUse) { + if (uri == null) { + return; + } + + if (nameToUse == null) { + nameToUse = computeSavedFilename(uri); + } + + _sourceForUri.put(uri, nameToUse); + } + + /** + * Returns the error listener being filled in during this compilation + */ + public Collection getErrorListener() { + return _errorListener; + } + + /** + * Returns the schema type loader to use for processing s4s + */ + public SchemaTypeLoader getS4SLoader() { + return _s4sloader; + } + + public File getSchemasDir() { + return _schemasDir; + } + + public void setSchemasDir(File _schemasDir) { + this._schemasDir = _schemasDir; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java new file mode 100644 index 0000000..34e41fc --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java @@ -0,0 +1,1572 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.XMLChar; +import org.apache.xmlbeans.impl.schema.StscImporter.SchemaToProcess; +import org.apache.xmlbeans.impl.values.NamespaceContext; +import org.apache.xmlbeans.impl.values.XmlNonNegativeIntegerImpl; +import org.apache.xmlbeans.impl.values.XmlPositiveIntegerImpl; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.apache.xmlbeans.impl.xb.xsdschema.*; +import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; +import org.apache.xmlbeans.impl.xpath.XPath; +import org.apache.xmlbeans.soap.SOAPArrayType; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.*; + +public class StscTranslator { + private static final QName WSDL_ARRAYTYPE_NAME = + QNameHelper.forLNS("arrayType", "http://schemas.xmlsoap.org/wsdl/"); + private static final String FORM_QUALIFIED = "qualified"; + + public static void addAllDefinitions(SchemaToProcess[] schemasAndChameleons) { + // Build all redefine objects + List redefinitions = new ArrayList<>(); + for (SchemaToProcess schemasAndChameleon : schemasAndChameleons) { + List redefines = schemasAndChameleon.getRedefines(); + if (redefines != null) { + List redefineObjects = schemasAndChameleon.getRedefineObjects(); + Iterator it = redefines.iterator(); + Iterator ito = redefineObjects.iterator(); + while (it.hasNext()) { + assert ito.hasNext() : + "The array of redefines and redefine objects have to have the same length"; + redefinitions.add(new RedefinitionHolder(it.next(), ito.next())); + } + } + } + RedefinitionMaster globalRedefinitions = new RedefinitionMaster(redefinitions.toArray(new RedefinitionHolder[0])); + + StscState state = StscState.get(); + for (SchemaToProcess schemasAndChameleon : schemasAndChameleons) { + Schema schema = schemasAndChameleon.getSchema(); + String givenTargetNamespace = schemasAndChameleon.getChameleonNamespace(); + + // quick check for a few unsupported features + + if (schema.sizeOfNotationArray() > 0) { + state.warning("Schema is not yet supported for this release.", XmlErrorCodes.UNSUPPORTED_FEATURE, schema.getNotationArray(0)); + } + + // figure namespace (taking into account chameleons) + String targetNamespace = schema.getTargetNamespace(); + boolean chameleon = false; + if (givenTargetNamespace != null && targetNamespace == null) { + targetNamespace = givenTargetNamespace; + chameleon = true; + } + if (targetNamespace == null) { + targetNamespace = ""; + } + + //SchemaContainer container = null; + if (targetNamespace.length() > 0 || !isEmptySchema(schema)) { + state.registerContribution(targetNamespace, schema.documentProperties().getSourceName()); + state.addNewContainer(targetNamespace); + //container = state.getContainer(targetNamespace); + } + + List redefChain = new ArrayList<>(); + TopLevelComplexType[] complexTypes = schema.getComplexTypeArray(); + for (TopLevelComplexType complexType : complexTypes) { + TopLevelComplexType type = complexType; + TopLevelComplexType redef; + // 1. Traverse the list of redefining Schemas putting all redefinitions + // of this type in a List + RedefinitionHolder[] rhArray = globalRedefinitions.getComplexTypeRedefinitions( + type.getName(), schemasAndChameleon); + for (RedefinitionHolder redefinitionHolder : rhArray) { + // In error cases, some redefinitions were nulled out in the list + // which is why we need to perform this check + if (redefinitionHolder != null) { + redef = redefinitionHolder.redefineComplexType(type.getName()); + assert redef != null; // This was already checked + redefChain.add(type); + type = redef; + } + } + + SchemaTypeImpl t = translateGlobalComplexType(type, targetNamespace, chameleon, redefChain.size() > 0); + state.addGlobalType(t, null); + SchemaTypeImpl r; + // 2. Traverse the List built in step 1 in reverse and add all the + // types in it to the list of redefined types + for (int k = redefChain.size() - 1; k >= 0; k--) { + redef = (TopLevelComplexType) redefChain.remove(k); + r = translateGlobalComplexType(redef, targetNamespace, chameleon, k > 0); + state.addGlobalType(r, t); + t = r; + } + } + + TopLevelSimpleType[] simpleTypes = schema.getSimpleTypeArray(); + for (TopLevelSimpleType simpleType : simpleTypes) { + TopLevelSimpleType type = simpleType; + TopLevelSimpleType redef; + RedefinitionHolder[] rhArray = globalRedefinitions.getSimpleTypeRedefinitions( + type.getName(), schemasAndChameleon); + for (RedefinitionHolder redefinitionHolder : rhArray) { + // In error cases, some redefinitions were nulled out in the list + // which is why we need to perform this check + if (redefinitionHolder != null) { + redef = redefinitionHolder.redefineSimpleType(type.getName()); + assert redef != null; // This was already checked + redefChain.add(type); + type = redef; + } + } + + SchemaTypeImpl t = translateGlobalSimpleType(type, targetNamespace, chameleon, redefChain.size() > 0); + state.addGlobalType(t, null); + SchemaTypeImpl r; + for (int k = redefChain.size() - 1; k >= 0; k--) { + redef = (TopLevelSimpleType) redefChain.remove(k); + r = translateGlobalSimpleType(redef, targetNamespace, chameleon, k > 0); + state.addGlobalType(r, t); + t = r; + } + } + + TopLevelElement[] elements = schema.getElementArray(); + for (TopLevelElement element : elements) { + state.addDocumentType(translateDocumentType(element, targetNamespace, chameleon), QNameHelper.forLNS(element.getName(), targetNamespace)); + } + + TopLevelAttribute[] attributes = schema.getAttributeArray(); + for (TopLevelAttribute attribute : attributes) { + state.addAttributeType(translateAttributeType(attribute, targetNamespace, chameleon), QNameHelper.forLNS(attribute.getName(), targetNamespace)); + } + + NamedGroup[] modelgroups = schema.getGroupArray(); + for (NamedGroup group : modelgroups) { + NamedGroup redef; + RedefinitionHolder[] rhArray = globalRedefinitions.getModelGroupRedefinitions( + group.getName(), schemasAndChameleon); + for (RedefinitionHolder redefinitionHolder : rhArray) { + // In error cases, some redefinitions were nulled out in the list + // which is why we need to perform this check + if (redefinitionHolder != null) { + redef = redefinitionHolder.redefineModelGroup(group.getName()); + assert redef != null; // This was already checked + redefChain.add(group); + group = redef; + } + } + + SchemaModelGroupImpl g = translateModelGroup(group, targetNamespace, chameleon, redefChain.size() > 0); + state.addModelGroup(g, null); + SchemaModelGroupImpl r; + for (int k = redefChain.size() - 1; k >= 0; k--) { + redef = (NamedGroup) redefChain.remove(k); + r = translateModelGroup(redef, targetNamespace, chameleon, k > 0); + state.addModelGroup(r, g); + g = r; + } + } + + NamedAttributeGroup[] attrgroups = schema.getAttributeGroupArray(); + for (NamedAttributeGroup group : attrgroups) { + NamedAttributeGroup redef; + RedefinitionHolder[] rhArray = globalRedefinitions.getAttributeGroupRedefinitions( + group.getName(), schemasAndChameleon); + for (RedefinitionHolder redefinitionHolder : rhArray) { + // In error cases, some redefinitions were nulled out in the list + // which is why we need to perform this check + if (redefinitionHolder != null) { + redef = redefinitionHolder.redefineAttributeGroup(group.getName()); + assert redef != null; // This was already checked + redefChain.add(group); + group = redef; + } + } + + SchemaAttributeGroupImpl g = translateAttributeGroup(group, targetNamespace, chameleon, redefChain.size() > 0); + state.addAttributeGroup(g, null); + SchemaAttributeGroupImpl r; + for (int k = redefChain.size() - 1; k >= 0; k--) { + redef = (NamedAttributeGroup) redefChain.remove(k); + r = translateAttributeGroup(redef, targetNamespace, chameleon, k > 0); + state.addAttributeGroup(r, g); + g = r; + } + } + + AnnotationDocument.Annotation[] annotations = schema.getAnnotationArray(); + for (AnnotationDocument.Annotation annotation : annotations) { + state.addAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), schema, annotation), targetNamespace); + } + } + + for (Object redefinition : redefinitions) { + ((RedefinitionHolder) redefinition).complainAboutMissingDefinitions(); + } + } + + private static class RedefinitionHolder { + // record redefinitions + private Map stRedefinitions = Collections.emptyMap(); + private Map ctRedefinitions = Collections.emptyMap(); + private Map agRedefinitions = Collections.emptyMap(); + private Map mgRedefinitions = Collections.emptyMap(); + private String schemaLocation = ""; + private final SchemaToProcess schemaRedefined; + + // first build set of redefined components + RedefinitionHolder(SchemaToProcess schemaToProcess, Redefine redefine) { + schemaRedefined = schemaToProcess; + if (redefine != null) { + StscState state = StscState.get(); + + stRedefinitions = new HashMap<>(); + ctRedefinitions = new HashMap<>(); + agRedefinitions = new HashMap<>(); + mgRedefinitions = new HashMap<>(); + if (redefine.getSchemaLocation() != null) { + schemaLocation = redefine.getSchemaLocation(); + } + + TopLevelComplexType[] complexTypes = redefine.getComplexTypeArray(); + for (TopLevelComplexType complexType : complexTypes) { + if (complexType.getName() != null) { + // KHK: which rule? sch-props-correct.2? + if (ctRedefinitions.containsKey(complexType.getName())) { + state.error("Duplicate type redefinition: " + complexType.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); + } else { + ctRedefinitions.put(complexType.getName(), complexType); + } + } + } + + TopLevelSimpleType[] simpleTypes = redefine.getSimpleTypeArray(); + for (TopLevelSimpleType simpleType : simpleTypes) { + if (simpleType.getName() != null) { + if (stRedefinitions.containsKey(simpleType.getName())) { + state.error("Duplicate type redefinition: " + simpleType.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); + } else { + stRedefinitions.put(simpleType.getName(), simpleType); + } + } + } + + NamedGroup[] modelgroups = redefine.getGroupArray(); + for (NamedGroup modelgroup : modelgroups) { + if (modelgroup.getName() != null) { + if (mgRedefinitions.containsKey(modelgroup.getName())) { + state.error("Duplicate type redefinition: " + modelgroup.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); + } else { + mgRedefinitions.put(modelgroup.getName(), modelgroup); + } + } + } + + NamedAttributeGroup[] attrgroups = redefine.getAttributeGroupArray(); + for (NamedAttributeGroup attrgroup : attrgroups) { + if (attrgroup.getName() != null) { + if (agRedefinitions.containsKey(attrgroup.getName())) { + state.error("Duplicate type redefinition: " + attrgroup.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); + } else { + agRedefinitions.put(attrgroup.getName(), attrgroup); + } + } + } + } + } + + public TopLevelSimpleType redefineSimpleType(String name) { + return name == null || !stRedefinitions.containsKey(name) ? null : stRedefinitions.remove(name); + } + + public TopLevelComplexType redefineComplexType(String name) { + return name == null || !ctRedefinitions.containsKey(name) ? null : ctRedefinitions.remove(name); + } + + public NamedGroup redefineModelGroup(String name) { + return name == null || !mgRedefinitions.containsKey(name) ? null : mgRedefinitions.remove(name); + } + + public NamedAttributeGroup redefineAttributeGroup(String name) { + return name == null || !agRedefinitions.containsKey(name) ? null : agRedefinitions.remove(name); + } + + public void complainAboutMissingDefinitions() { + if (stRedefinitions.isEmpty() && ctRedefinitions.isEmpty() && + agRedefinitions.isEmpty() && mgRedefinitions.isEmpty()) { + return; + } + + StscState state = StscState.get(); + + for (String name : stRedefinitions.keySet()) { + state.error("Redefined simple type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, stRedefinitions.get(name)); + } + + for (String name : ctRedefinitions.keySet()) { + state.error("Redefined complex type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, ctRedefinitions.get(name)); + } + + for (String name : agRedefinitions.keySet()) { + state.error("Redefined attribute group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, agRedefinitions.get(name)); + } + + for (String name : mgRedefinitions.keySet()) { + state.error("Redefined model group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, mgRedefinitions.get(name)); + } + } + } + + /** + * This is used to aggregate all redefinitions for a specific component name. + * The idea is to record the list of <redefine%gt; sections that could + * potentially redefine this component. When the list of actual redefinitions + * is requested, the potential redefinitions are first filtered based on + * accessibilty of the schema currently being processed from the redefining Schemas + * and then topologically sorted based on the inclusion relationship to + * ensure that redefinitions are applied in the right order. + */ + private static class RedefinitionMaster { + private static final short SIMPLE_TYPE = 1; + private static final short COMPLEX_TYPE = 2; + private static final short MODEL_GROUP = 3; + private static final short ATTRIBUTE_GROUP = 4; + + // record redefinitions + private Map> stRedefinitions = Collections.emptyMap(); + private Map> ctRedefinitions = Collections.emptyMap(); + private Map> agRedefinitions = Collections.emptyMap(); + private Map> mgRedefinitions = Collections.emptyMap(); + private static final RedefinitionHolder[] EMPTY_REDEFINTION_HOLDER_ARRAY = + new RedefinitionHolder[0]; + + + RedefinitionMaster(RedefinitionHolder[] redefHolders) { + if (redefHolders.length > 0) { + stRedefinitions = new HashMap<>(); + ctRedefinitions = new HashMap<>(); + agRedefinitions = new HashMap<>(); + mgRedefinitions = new HashMap<>(); + + for (RedefinitionHolder redefHolder : redefHolders) { + for (String key : redefHolder.stRedefinitions.keySet()) { + stRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder); + } + for (String key : redefHolder.ctRedefinitions.keySet()) { + ctRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder); + } + for (String key : redefHolder.agRedefinitions.keySet()) { + agRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder); + } + for (String key : redefHolder.mgRedefinitions.keySet()) { + mgRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder); + } + } + } + } + + RedefinitionHolder[] getSimpleTypeRedefinitions(String name, + SchemaToProcess schema) { + List redefines = stRedefinitions.get(name); + if (redefines == null) { + return EMPTY_REDEFINTION_HOLDER_ARRAY; + } + return doTopologicalSort(redefines, schema, name, SIMPLE_TYPE); + } + + RedefinitionHolder[] getComplexTypeRedefinitions(String name, + SchemaToProcess schema) { + List redefines = ctRedefinitions.get(name); + if (redefines == null) { + return EMPTY_REDEFINTION_HOLDER_ARRAY; + } + return doTopologicalSort(redefines, schema, name, COMPLEX_TYPE); + } + + RedefinitionHolder[] getAttributeGroupRedefinitions(String name, + SchemaToProcess schema) { + List redefines = agRedefinitions.get(name); + if (redefines == null) { + return EMPTY_REDEFINTION_HOLDER_ARRAY; + } + return doTopologicalSort(redefines, schema, name, ATTRIBUTE_GROUP); + } + + RedefinitionHolder[] getModelGroupRedefinitions(String name, + SchemaToProcess schema) { + List redefines = mgRedefinitions.get(name); + if (redefines == null) { + return EMPTY_REDEFINTION_HOLDER_ARRAY; + } + return doTopologicalSort(redefines, schema, name, MODEL_GROUP); + } + + private RedefinitionHolder[] doTopologicalSort(List genericRedefines, + SchemaToProcess schema, String name, short componentType) { + // We have a list of files that redefine this name + // Filter out the ones that don't redefine this file in particular + RedefinitionHolder[] specificRedefines = new RedefinitionHolder[genericRedefines.size()]; + int n = 0; + for (RedefinitionHolder h : genericRedefines) { + if (h.schemaRedefined == schema || + h.schemaRedefined.indirectIncludes(schema)) { + specificRedefines[n++] = h; + } + } + // Now we have the list of files that specifically redefine the + // name in the file that we are looking for + // Sort this list into topological order to get the right order + // and figure out if there are multiple redefinitions involved + RedefinitionHolder[] sortedRedefines = new RedefinitionHolder[n]; + int[] numberOfIncludes = new int[n]; + // Just count the number of inclusions for each redefinition + for (int i = 0; i < n - 1; i++) { + RedefinitionHolder current = specificRedefines[i]; + for (int j = i + 1; j < n; j++) { + if (current.schemaRedefined.indirectIncludes(specificRedefines[j].schemaRedefined)) { + numberOfIncludes[i]++; + } + if (specificRedefines[j].schemaRedefined.indirectIncludes(current.schemaRedefined)) { + numberOfIncludes[j]++; + } + } + } + // Eliminate members one by one, according to the number of schemas + // that they include, to complete the sort + int position = 0; + boolean errorReported = false; + while (position < n) { + int index = -1; + for (int i = 0; i < numberOfIncludes.length; i++) { + if (numberOfIncludes[i] == 0) { + if (index < 0) { + index = i; + } + } + } + if (index < 0) { + // Error! Circular redefinition + if (!errorReported) { + StringBuilder fileNameList = new StringBuilder(); + XmlObject location = null; + for (int i = 0; i < n; i++) { + if (specificRedefines[i] != null) { + fileNameList.append(specificRedefines[i].schemaLocation). + append(',').append(' '); + if (location == null) { + location = locationFromRedefinitionAndCode( + specificRedefines[i], name, componentType); + } + } + } + StscState.get().error("Detected circular redefinition of " + + componentNameFromCode(componentType) + " \"" + name + + "\"; Files involved: " + fileNameList.toString(), + XmlErrorCodes.GENERIC_ERROR, location); + errorReported = true; + } + int min = n; + for (int i = 0; i < n; i++) { + if (numberOfIncludes[i] > 0 && numberOfIncludes[i] < min) { + min = numberOfIncludes[i]; + index = i; + } + } + numberOfIncludes[index]--; + } else { + assert specificRedefines[index] != null; + sortedRedefines[position++] = specificRedefines[index]; + for (int i = 0; i < n; i++) { + if (specificRedefines[i] != null && + specificRedefines[i].schemaRedefined. + indirectIncludes(specificRedefines[index]. + schemaRedefined)) { + numberOfIncludes[i]--; + } + } + specificRedefines[index] = null; + numberOfIncludes[index]--; + } + } + // Nice. We now have all the redefinitions of this name in the list + // Each one has to transitively redefine the one before, otherwise + // it means we are attepting two different redefinitions for the same + // component + for (int i = 1; i < n; i++) { + // Find the previous index with non-null Schema + // Since i is never 0, such index always exists + int j; + for (j = i - 1; j >= 0; j--) { + if (sortedRedefines[j] != null) { + break; + } + } + + if (!sortedRedefines[i].schemaRedefined.indirectIncludes( + sortedRedefines[j].schemaRedefined)) { + StscState.get().error("Detected multiple redefinitions of " + + componentNameFromCode(componentType) + + " \"" + name + "\"; Files involved: " + + sortedRedefines[j].schemaRedefined.getSourceName() + ", " + + sortedRedefines[i].schemaRedefined.getSourceName(), + XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, + locationFromRedefinitionAndCode(sortedRedefines[i], name, componentType)); + // Ignore this redefinition + switch (componentType) { + case SIMPLE_TYPE: + sortedRedefines[i].redefineSimpleType(name); + break; + case COMPLEX_TYPE: + sortedRedefines[i].redefineComplexType(name); + break; + case ATTRIBUTE_GROUP: + sortedRedefines[i].redefineAttributeGroup(name); + break; + case MODEL_GROUP: + sortedRedefines[i].redefineModelGroup(name); + break; + } + sortedRedefines[i] = null; + } + } + + return sortedRedefines; + } + + private String componentNameFromCode(short code) { + String componentName; + switch (code) { + case SIMPLE_TYPE: + componentName = "simple type"; + break; + case COMPLEX_TYPE: + componentName = "complex type"; + break; + case MODEL_GROUP: + componentName = "model group"; + break; + case ATTRIBUTE_GROUP: + componentName = "attribute group"; + break; + default: + componentName = ""; + } + return componentName; + } + + private XmlObject locationFromRedefinitionAndCode(RedefinitionHolder redefinition, + String name, short code) { + XmlObject location; + switch (code) { + case SIMPLE_TYPE: + location = redefinition.stRedefinitions.get(name); + break; + case COMPLEX_TYPE: + location = redefinition.ctRedefinitions.get(name); + break; + case MODEL_GROUP: + location = redefinition.mgRedefinitions.get(name); + break; + case ATTRIBUTE_GROUP: + location = redefinition.agRedefinitions.get(name); + break; + default: + location = null; + } + return location; + } + } + + private static String findFilename(XmlObject xobj) { + return StscState.get().sourceNameForUri(xobj.documentProperties().getSourceName()); + } + + private static SchemaTypeImpl translateDocumentType(TopLevelElement xsdType, String targetNamespace, boolean chameleon) { + SchemaTypeImpl sType = new SchemaTypeImpl(StscState.get().getContainer(targetNamespace)); + + sType.setDocumentType(true); + sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, false); + sType.setFilename(findFilename(xsdType)); + + return sType; + } + + private static SchemaTypeImpl translateAttributeType(TopLevelAttribute xsdType, String targetNamespace, boolean chameleon) { + SchemaTypeImpl sType = new SchemaTypeImpl(StscState.get().getContainer(targetNamespace)); + + sType.setAttributeType(true); + sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, false); + sType.setFilename(findFilename(xsdType)); + + return sType; + } + + private static SchemaTypeImpl translateGlobalComplexType(TopLevelComplexType xsdType, String targetNamespace, boolean chameleon, boolean redefinition) { + StscState state = StscState.get(); + + String localname = xsdType.getName(); + if (localname == null) { + state.error(XmlErrorCodes.MISSING_NAME, new Object[]{"global type"}, xsdType); + // recovery: ignore unnamed types. + return null; + } + if (!XMLChar.isValidNCName(localname)) { + state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{localname, "name"}, xsdType.xgetName()); + // recovery: let the name go through anyway. + } + + QName name = QNameHelper.forLNS(localname, targetNamespace); + + if (isReservedTypeName(name)) { + state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[]{QNameHelper.pretty(name)}, xsdType); + return null; + } + // System.err.println("Recording type " + QNameHelper.pretty(name)); + + SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace)); + sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, redefinition); + sType.setFilename(findFilename(xsdType)); + sType.setName(QNameHelper.forLNS(localname, targetNamespace)); + sType.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdType)); + sType.setUserData(getUserData(xsdType)); + return sType; + } + + private static SchemaTypeImpl translateGlobalSimpleType(TopLevelSimpleType xsdType, String targetNamespace, boolean chameleon, boolean redefinition) { + StscState state = StscState.get(); + + String localname = xsdType.getName(); + if (localname == null) { + state.error(XmlErrorCodes.MISSING_NAME, new Object[]{"global type"}, xsdType); + // recovery: ignore unnamed types. + return null; + } + if (!XMLChar.isValidNCName(localname)) { + state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{localname, "name"}, xsdType.xgetName()); + // recovery: let the name go through anyway. + } + + QName name = QNameHelper.forLNS(localname, targetNamespace); + + if (isReservedTypeName(name)) { + state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[]{QNameHelper.pretty(name)}, xsdType); + return null; + } + // System.err.println("Recording type " + QNameHelper.pretty(name)); + + SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace)); + sType.setSimpleType(true); + sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, redefinition); + sType.setFilename(findFilename(xsdType)); + sType.setName(name); + sType.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdType)); + sType.setUserData(getUserData(xsdType)); + return sType; + } + + /*package*/ + static SchemaTypeImpl translateAnonymousSimpleType(SimpleType typedef, + String targetNamespace, boolean chameleon, String elemFormDefault, + String attFormDefault, List anonymousTypes, SchemaType outerType) { + StscState state = StscState.get(); + SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace)); + sType.setSimpleType(true); + sType.setParseContext(typedef, targetNamespace, chameleon, + elemFormDefault, attFormDefault, false); + sType.setOuterSchemaTypeRef(outerType.getRef()); + sType.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef)); + sType.setUserData(getUserData(typedef)); + anonymousTypes.add(sType); + return sType; + } + + static FormChoice findElementFormDefault(XmlObject obj) { + XmlCursor cur = obj.newCursor(); + while (cur.getObject().schemaType() != Schema.type) { + if (!cur.toParent()) { + return null; + } + } + return ((Schema) cur.getObject()).xgetElementFormDefault(); + } + + public static boolean uriMatch(String s1, String s2) { + if (s1 == null) { + return s2 == null || s2.equals(""); + } + if (s2 == null) { + return s1.equals(""); + } + return s1.equals(s2); + } + + public static void copyGlobalElementToLocalElement(SchemaGlobalElement referenced, SchemaLocalElementImpl target) { + + target.setNameAndTypeRef(referenced.getName(), referenced.getType().getRef()); + target.setNillable(referenced.isNillable()); + target.setDefault(referenced.getDefaultText(), referenced.isFixed(), ((SchemaGlobalElementImpl) referenced).getParseObject()); + target.setIdentityConstraints(((SchemaLocalElementImpl) referenced).getIdentityConstraintRefs()); + target.setBlock(referenced.blockExtension(), referenced.blockRestriction(), referenced.blockSubstitution()); + target.setAbstract(referenced.isAbstract()); + target.setTransitionRules(((SchemaParticle) referenced).acceptedStartNames(), + ((SchemaParticle) referenced).isSkippable()); + target.setAnnotation(referenced.getAnnotation()); + } + + public static void copyGlobalAttributeToLocalAttribute(SchemaGlobalAttributeImpl referenced, SchemaLocalAttributeImpl target) { + target.init( + referenced.getName(), referenced.getTypeRef(), referenced.getUse(), + referenced.getDefaultText(), + referenced.getParseObject(), referenced._defaultValue, + referenced.isFixed(), + referenced.getWSDLArrayType(), + referenced.getAnnotation(), null); + } + + /** + * Translates a local or global schema element. + */ + // check rule 3.3.3 + // http://www.w3c.org/TR/#section-Constraints-on-XML-Representations-of-Element-Declarations + public static SchemaLocalElementImpl translateElement( + Element xsdElt, String targetNamespace, boolean chameleon, + String elemFormDefault, String attFormDefault, + List anonymousTypes, SchemaType outerType) { + StscState state = StscState.get(); + + SchemaTypeImpl sgHead = null; + + // translate sg head + if (xsdElt.isSetSubstitutionGroup()) { + sgHead = state.findDocumentType(xsdElt.getSubstitutionGroup(), + ((SchemaTypeImpl) outerType).getChameleonNamespace(), targetNamespace); + + if (sgHead != null) { + StscResolver.resolveType(sgHead); + } + } + + String name = xsdElt.getName(); + QName ref = xsdElt.getRef(); + + + if (ref != null && name != null) { + // if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI())) + // state.warning("Element " + name + " specifies both a ref and a name", XmlErrorCodes.ELEMENT_EXTRA_REF, xsdElt.xgetRef()); + // else + state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_BOTH, new Object[]{name}, xsdElt.xgetRef()); + // ignore name + name = null; + } + if (ref == null && name == null) { + state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_NEITHER, null, xsdElt); + // recovery: ignore this element + return null; + } + if (name != null && !XMLChar.isValidNCName(name)) { + state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{name, "name"}, xsdElt.xgetName()); + // recovery: let the name go through anyway. + } + + if (ref != null) { + if (xsdElt.getType() != null) { + state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"type"}, xsdElt.xgetType()); + // recovery: let the name go through anyway. + } + + if (xsdElt.getSimpleType() != null) { + state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{""}, xsdElt.getSimpleType()); + // recovery: let the name go through anyway. + } + + if (xsdElt.getComplexType() != null) { + state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{""}, xsdElt.getComplexType()); + // recovery: let the name go through anyway. + } + + if (xsdElt.getForm() != null) { + state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"form"}, xsdElt.xgetForm()); + // recovery: let the name go through anyway. + } + + if (xsdElt.sizeOfKeyArray() > 0) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{""}, xsdElt); + // recovery: ignore + } + + if (xsdElt.sizeOfKeyrefArray() > 0) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{""}, xsdElt); + // recovery: ignore + } + + if (xsdElt.sizeOfUniqueArray() > 0) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{""}, xsdElt); + // recovery: ignore + } + + if (xsdElt.isSetDefault()) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"default"}, xsdElt.xgetDefault()); + // recovery: ignore + } + + if (xsdElt.isSetFixed()) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"fixed"}, xsdElt.xgetFixed()); + // recovery: ignore + } + + if (xsdElt.isSetBlock()) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"block"}, xsdElt.xgetBlock()); + // recovery: ignore + } + + if (xsdElt.isSetNillable()) { + state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"nillable"}, xsdElt.xgetNillable()); + // recovery: ignore + } + + assert (xsdElt instanceof LocalElement); + SchemaGlobalElement referenced = state.findGlobalElement(ref, chameleon ? targetNamespace : null, targetNamespace); + if (referenced == null) { + state.notFoundError(ref, SchemaType.ELEMENT, xsdElt.xgetRef(), true); + // recovery: ignore this element + return null; + } + SchemaLocalElementImpl target = new SchemaLocalElementImpl(); + target.setParticleType(SchemaParticle.ELEMENT); + target.setUserData(getUserData(xsdElt)); + copyGlobalElementToLocalElement(referenced, target); + return target; + } + + QName qname; + SchemaLocalElementImpl impl; + SchemaType sType = null; + + if (xsdElt instanceof LocalElement) { + impl = new SchemaLocalElementImpl(); + boolean qualified; + FormChoice form = xsdElt.xgetForm(); + if (form != null) { + qualified = form.getStringValue().equals(FORM_QUALIFIED); + } else if (elemFormDefault != null) { + qualified = elemFormDefault.equals(FORM_QUALIFIED); + } else { + form = findElementFormDefault(xsdElt); + qualified = form != null && form.getStringValue().equals(FORM_QUALIFIED); + } + + qname = qualified ? QNameHelper.forLNS(name, targetNamespace) : QNameHelper.forLN(name); + } else { + SchemaGlobalElementImpl gelt = new SchemaGlobalElementImpl(state.getContainer(targetNamespace)); + impl = gelt; + + // Set subst group head + if (sgHead != null) { + SchemaGlobalElementImpl head = state.findGlobalElement(xsdElt.getSubstitutionGroup(), chameleon ? targetNamespace : null, targetNamespace); + if (head != null) { + gelt.setSubstitutionGroup(head.getRef()); + } + } + + // Set subst group members + qname = QNameHelper.forLNS(name, targetNamespace); + SchemaTypeImpl docType = (SchemaTypeImpl) outerType; + + QName[] sgMembers = docType.getSubstitutionGroupMembers(); + QNameSetBuilder transitionRules = new QNameSetBuilder(); + transitionRules.add(qname); + + for (QName sgMember : sgMembers) { + gelt.addSubstitutionGroupMember(sgMember); + transitionRules.add(sgMember); + } + + impl.setTransitionRules(QNameSet.forSpecification(transitionRules), false); + impl.setTransitionNotes(QNameSet.EMPTY, true); + + boolean finalExt = false; + boolean finalRest = false; + Object ds = xsdElt.getFinal(); + if (ds != null) { + if (ds instanceof String && ds.equals("#all")) { + // #ALL value + finalExt = finalRest = true; + } else if (ds instanceof List) { + List dsList = (List) ds; + if (dsList.contains("extension")) { + finalExt = true; + } + if (dsList.contains("restriction")) { + finalRest = true; + } + } + } + + gelt.setFinal(finalExt, finalRest); + gelt.setAbstract(xsdElt.getAbstract()); + gelt.setFilename(findFilename(xsdElt)); + gelt.setParseContext(xsdElt, targetNamespace, chameleon); + } + + SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdElt); + impl.setAnnotation(ann); + impl.setUserData(getUserData(xsdElt)); + if (xsdElt.getType() != null) { + sType = state.findGlobalType(xsdElt.getType(), chameleon ? targetNamespace : null, targetNamespace); + if (sType == null) { + state.notFoundError(xsdElt.getType(), SchemaType.TYPE, xsdElt.xgetType(), true); + } + } + + boolean simpleTypedef = false; + Annotated typedef = xsdElt.getComplexType(); + if (typedef == null) { + typedef = xsdElt.getSimpleType(); + simpleTypedef = true; + } + + if ((sType != null) && typedef != null) { + state.error(XmlErrorCodes.SCHEMA_ELEM$TYPE_ATTR_OR_NESTED_TYPE, null, typedef); + typedef = null; + } + + if (typedef != null) { + Object[] grps = state.getCurrentProcessing(); + QName[] context = new QName[grps.length]; + for (int i = 0; i < context.length; i++) { + if (grps[i] instanceof SchemaModelGroupImpl) { + context[i] = ((SchemaModelGroupImpl) grps[i]).getName(); + } + } + SchemaType repeat = checkRecursiveGroupReference(context, qname, (SchemaTypeImpl) outerType); + if (repeat != null) { + sType = repeat; + } else { + SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace)); + sType = sTypeImpl; + sTypeImpl.setContainerField(impl); + sTypeImpl.setOuterSchemaTypeRef(outerType == null ? null : outerType.getRef()); + sTypeImpl.setGroupReferenceContext(context); + // leave the anonymous type unresolved: it will be resolved later. + anonymousTypes.add(sType); + sTypeImpl.setSimpleType(simpleTypedef); + sTypeImpl.setParseContext(typedef, targetNamespace, chameleon, + elemFormDefault, attFormDefault, false); + sTypeImpl.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef)); + sTypeImpl.setUserData(getUserData(typedef)); + } + } + + if (sType == null) { + // type may inherit from substitution group head + if (sgHead != null) { + SchemaGlobalElement head = state.findGlobalElement(xsdElt.getSubstitutionGroup(), chameleon ? targetNamespace : null, targetNamespace); + + // Bug - Do I need to copy the type if it's anonymous? + // If element does not exist, error has already been reported + if (head != null) { + sType = head.getType(); + } + } + + } + + + if (sType == null) { + sType = BuiltinSchemaTypeSystem.ST_ANY_TYPE; + } + + SOAPArrayType wat = null; + XmlCursor c = xsdElt.newCursor(); + String arrayType = c.getAttributeText(WSDL_ARRAYTYPE_NAME); + c.dispose(); + if (arrayType != null) { + try { + wat = new SOAPArrayType(arrayType, new NamespaceContext(xsdElt)); + } catch (XmlValueOutOfRangeException e) { + state.error(XmlErrorCodes.SOAPARRAY, new Object[]{arrayType}, xsdElt); + } + } + impl.setWsdlArrayType(wat); + + boolean isFixed = xsdElt.isSetFixed(); + if (xsdElt.isSetDefault() && isFixed) { + state.error(XmlErrorCodes.SCHEMA_ELEM$DEFAULT_OR_FIXED, null, xsdElt.xgetFixed()); + // recovery: ignore fixed + isFixed = false; + } + impl.setParticleType(SchemaParticle.ELEMENT); + impl.setNameAndTypeRef(qname, sType.getRef()); + impl.setNillable(xsdElt.getNillable()); + impl.setDefault(isFixed ? xsdElt.getFixed() : xsdElt.getDefault(), isFixed, xsdElt); + + Object block = xsdElt.getBlock(); + boolean blockExt = false; + boolean blockRest = false; + boolean blockSubst = false; + + if (block != null) { + if (block instanceof String && block.equals("#all")) { + // #ALL value + blockExt = blockRest = blockSubst = true; + } else if (block instanceof List) { + List blockList = (List) block; + if (blockList.contains("extension")) { + blockExt = true; + } + if (blockList.contains("restriction")) { + blockRest = true; + } + if (blockList.contains("substitution")) { + blockSubst = true; + } + } + } + + impl.setBlock(blockExt, blockRest, blockSubst); + + boolean constraintFailed = false; + + // Translate Identity constraints + + int length = xsdElt.sizeOfKeyArray() + xsdElt.sizeOfKeyrefArray() + xsdElt.sizeOfUniqueArray(); + SchemaIdentityConstraintImpl[] constraints = new SchemaIdentityConstraintImpl[length]; + int cur = 0; + + // Handle key constraints + Keybase[] keys = xsdElt.getKeyArray(); + for (int i = 0; i < keys.length; i++, cur++) { + constraints[cur] = translateIdentityConstraint(keys[i], targetNamespace, chameleon); + if (constraints[cur] != null) { + constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_KEY); + } else { + constraintFailed = true; + } + } + + // Handle unique constraints + Keybase[] uc = xsdElt.getUniqueArray(); + for (int i = 0; i < uc.length; i++, cur++) { + constraints[cur] = translateIdentityConstraint(uc[i], targetNamespace, chameleon); + if (constraints[cur] != null) { + constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_UNIQUE); + } else { + constraintFailed = true; + } + } + + // Handle keyref constraints + KeyrefDocument.Keyref[] krs = xsdElt.getKeyrefArray(); + for (int i = 0; i < krs.length; i++, cur++) { + constraints[cur] = translateIdentityConstraint(krs[i], targetNamespace, chameleon); + if (constraints[cur] != null) { + constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_KEYREF); + } else { + constraintFailed = true; + } + } + + if (!constraintFailed) { + SchemaIdentityConstraint.Ref[] refs = new SchemaIdentityConstraint.Ref[length]; + for (int i = 0; i < refs.length; i++) { + refs[i] = constraints[i].getRef(); + } + + impl.setIdentityConstraints(refs); + } + + return impl; + } + + /** + * We need to do this because of the following kind of Schemas: + * + * + * + * + * + * + * + * + * + * (see JIRA bug XMLBEANS-35) + * Even though this should not be allowed because it produces an infinite + * number of anonymous types and local elements nested within each other, + * the de facto consensus among Schema processors is that this should be + * valid, therefore we have to detect this situation and "patch up" the + * Schema object model so that instead of creating a new anonymous type, + * we refer to the one that was already created earlier. + * In order to accomplish that, we store inside every anonymous type the + * list of groups that were dereferenced at the moment the type was created + * and if the same pattern is about to repeat, it means that we are in a + * case similar to the above. + */ + private static SchemaType checkRecursiveGroupReference(QName[] context, QName containingElement, SchemaTypeImpl outerType) { + if (context.length < 1) { + return null; + } + SchemaTypeImpl type = outerType; + + while (type != null) { + if (type.getName() != null || type.isDocumentType()) { + return null; // not anonymous + } + if (containingElement.equals(type.getContainerField().getName())) { + QName[] outerContext = type.getGroupReferenceContext(); + if (outerContext != null && outerContext.length == context.length) { + // Smells like trouble + boolean equal = true; + for (int i = 0; i < context.length; i++) { + if (!(context[i] == null && outerContext[i] == null || + context[i] != null && context[i].equals(outerContext[i]))) { + equal = false; + break; + } + } + if (equal) { + return type; + } + } + } + type = (SchemaTypeImpl) type.getOuterType(); + } + return null; + } + + private static String removeWhitespace(String xpath) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < xpath.length(); i++) { + char ch = xpath.charAt(i); + if (XMLChar.isSpace(ch)) { + continue; + } + sb.append(ch); + } + return sb.toString(); + } + + public static final org.apache.xmlbeans.impl.regex.RegularExpression XPATH_REGEXP = new org.apache.xmlbeans.impl.regex.RegularExpression("(\\.//)?((((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*|\\*)))))*", "X"); + + private static boolean checkXPathSyntax(String xpath) { + if (xpath == null) { + return false; + } + + // strip whitespace from xpath + xpath = removeWhitespace(xpath); + + // apply regexp + synchronized (XPATH_REGEXP) { + return (XPATH_REGEXP.matches(xpath)); + } + } + + private static SchemaIdentityConstraintImpl translateIdentityConstraint(Keybase parseIC, + String targetNamespace, boolean chameleon) { + StscState state = StscState.get(); + + // first do some checking + String selector = parseIC.getSelector() == null ? null : parseIC.getSelector().getXpath(); + if (!checkXPathSyntax(selector)) { + state.error(XmlErrorCodes.SELECTOR_XPATH, new Object[]{selector}, parseIC.getSelector().xgetXpath()); + return null; + } + + FieldDocument.Field[] fieldElts = parseIC.getFieldArray(); + for (FieldDocument.Field fieldElt : fieldElts) { + if (!checkXPathSyntax(fieldElt.getXpath())) { + state.error(XmlErrorCodes.FIELDS_XPATH, new Object[]{fieldElt.getXpath()}, fieldElt.xgetXpath()); + return null; + } + } + + // then translate. + SchemaIdentityConstraintImpl ic = new SchemaIdentityConstraintImpl(state.getContainer(targetNamespace)); + ic.setName(QNameHelper.forLNS(parseIC.getName(), targetNamespace)); + ic.setSelector(parseIC.getSelector().getXpath()); + ic.setParseContext(parseIC, targetNamespace, chameleon); + SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), parseIC); + ic.setAnnotation(ann); + ic.setUserData(getUserData(parseIC)); + + // Set the ns map + XmlCursor c = parseIC.newCursor(); + Map nsMap = new HashMap<>(); + + c.getAllNamespaces(nsMap); + nsMap.remove(""); // Remove the default mapping. This cannot be used by the xpath expressions. + ic.setNSMap(nsMap); + c.dispose(); + + String[] fields = new String[fieldElts.length]; + for (int j = 0; j < fields.length; j++) { + fields[j] = fieldElts[j].getXpath(); + } + ic.setFields(fields); + + try { + ic.buildPaths(); + } catch (XPath.XPathCompileException e) { + state.error(XmlErrorCodes.INVALID_XPATH, new Object[]{e.getMessage()}, parseIC); + return null; + } + + state.addIdConstraint(ic); + ic.setFilename(findFilename(parseIC)); + + return state.findIdConstraint(ic.getName(), targetNamespace, null); + + } + + public static SchemaModelGroupImpl translateModelGroup(NamedGroup namedGroup, String targetNamespace, boolean chameleon, boolean redefinition) { + String name = namedGroup.getName(); + if (name == null) { + StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[]{"model group"}, namedGroup); + return null; + } + SchemaContainer c = StscState.get().getContainer(targetNamespace); + SchemaModelGroupImpl result = new SchemaModelGroupImpl(c); + SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(c, namedGroup); + FormChoice elemFormDefault = findElementFormDefault(namedGroup); + FormChoice attFormDefault = findAttributeFormDefault(namedGroup); + result.init(QNameHelper.forLNS(name, targetNamespace), targetNamespace, chameleon, + elemFormDefault == null ? null : elemFormDefault.getStringValue(), + attFormDefault == null ? null : attFormDefault.getStringValue(), + redefinition, namedGroup, ann, getUserData(namedGroup)); + result.setFilename(findFilename(namedGroup)); + return result; + } + + public static SchemaAttributeGroupImpl translateAttributeGroup(AttributeGroup attrGroup, String targetNamespace, boolean chameleon, boolean redefinition) { + String name = attrGroup.getName(); + if (name == null) { + StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[]{"attribute group"}, attrGroup); + return null; + } + SchemaContainer c = StscState.get().getContainer(targetNamespace); + SchemaAttributeGroupImpl result = new SchemaAttributeGroupImpl(c); + SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(c, attrGroup); + FormChoice formDefault = findAttributeFormDefault(attrGroup); + result.init(QNameHelper.forLNS(name, targetNamespace), targetNamespace, chameleon, + formDefault == null ? null : formDefault.getStringValue(), + redefinition, attrGroup, ann, getUserData(attrGroup)); + result.setFilename(findFilename(attrGroup)); + return result; + } + + static FormChoice findAttributeFormDefault(XmlObject obj) { + XmlCursor cur = obj.newCursor(); + while (cur.getObject().schemaType() != Schema.type) { + if (!cur.toParent()) { + return null; + } + } + return ((Schema) cur.getObject()).xgetAttributeFormDefault(); + } + + static SchemaLocalAttributeImpl translateAttribute( + Attribute xsdAttr, String targetNamespace, String formDefault, boolean chameleon, + List anonymousTypes, SchemaType outerType, SchemaAttributeModel baseModel, + boolean local) { + StscState state = StscState.get(); + + String name = xsdAttr.getName(); + QName ref = xsdAttr.getRef(); + + if (ref != null && name != null) { + if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI())) { + state.warning(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[]{name}, xsdAttr.xgetRef()); + } else { + state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[]{name}, xsdAttr.xgetRef()); + } + // ignore name + name = null; + } + if (ref == null && name == null) { + state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_NEITHER, null, xsdAttr); + // recovery: ignore this element + return null; + } + if (name != null && !XMLChar.isValidNCName(name)) { + state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{name, "name"}, xsdAttr.xgetName()); + // recovery: let the name go through anyway. + } + + boolean isFixed = false; + String deftext = null; + String fmrfixedtext = null; + QName qname; + SchemaLocalAttributeImpl sAttr; + SchemaType sType = null; + int use = SchemaLocalAttribute.OPTIONAL; + + if (local) { + sAttr = new SchemaLocalAttributeImpl(); + } else { + sAttr = new SchemaGlobalAttributeImpl(StscState.get().getContainer(targetNamespace)); + ((SchemaGlobalAttributeImpl) sAttr).setParseContext(xsdAttr, targetNamespace, chameleon); + } + + if (ref != null) { + if (xsdAttr.getType() != null) { + state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[]{"type"}, xsdAttr.xgetType()); + // recovery: ignore type, simpleType + } + + if (xsdAttr.getSimpleType() != null) { + state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[]{""}, xsdAttr.getSimpleType()); + // recovery: ignore type, simpleType + } + + if (xsdAttr.getForm() != null) { + state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[]{"form"}, xsdAttr.xgetForm()); + // recovery: ignore form + } + + SchemaGlobalAttribute referenced = state.findGlobalAttribute(ref, chameleon ? targetNamespace : null, targetNamespace); + if (referenced == null) { + state.notFoundError(ref, SchemaType.ATTRIBUTE, xsdAttr.xgetRef(), true); + // recovery: ignore this element + return null; + } + + qname = ref; + use = referenced.getUse(); + sType = referenced.getType(); + deftext = referenced.getDefaultText(); + if (deftext != null) { + isFixed = referenced.isFixed(); + if (isFixed) { + fmrfixedtext = deftext; + } + } + } else { + if (local) { + boolean qualified; + FormChoice form = xsdAttr.xgetForm(); + if (form != null) { + qualified = form.getStringValue().equals(FORM_QUALIFIED); + } else if (formDefault != null) { + qualified = formDefault.equals(FORM_QUALIFIED); + } else { + form = findAttributeFormDefault(xsdAttr); + qualified = form != null && form.getStringValue().equals(FORM_QUALIFIED); + } + + qname = qualified ? QNameHelper.forLNS(name, targetNamespace) : QNameHelper.forLN(name); + } else { + qname = QNameHelper.forLNS(name, targetNamespace); + } + + if (xsdAttr.getType() != null) { + sType = state.findGlobalType(xsdAttr.getType(), chameleon ? targetNamespace : null, targetNamespace); + if (sType == null) { + state.notFoundError(xsdAttr.getType(), SchemaType.TYPE, xsdAttr.xgetType(), true); + } + } + + if (qname.getNamespaceURI().equals("http://www.w3.org/2001/XMLSchema-instance")) { + state.error(XmlErrorCodes.NO_XSI, new Object[]{"http://www.w3.org/2001/XMLSchema-instance"}, xsdAttr.xgetName()); + } + + if (qname.getNamespaceURI().length() == 0 && qname.getLocalPart().equals("xmlns")) { + state.error(XmlErrorCodes.NO_XMLNS, null, xsdAttr.xgetName()); + } + + LocalSimpleType typedef = xsdAttr.getSimpleType(); + + if ((sType != null) && typedef != null) { + state.error(XmlErrorCodes.SCHEMA_ATTR$TYPE_ATTR_OR_NESTED_TYPE, null, typedef); + typedef = null; + } + + if (typedef != null) { + SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace)); + sType = sTypeImpl; + sTypeImpl.setContainerField(sAttr); + sTypeImpl.setOuterSchemaTypeRef(outerType == null ? null : outerType.getRef()); + // leave the anonymous type unresolved: it will be resolved later. + anonymousTypes.add(sType); + sTypeImpl.setSimpleType(true); + sTypeImpl.setParseContext(typedef, targetNamespace, chameleon, null, null, false); + sTypeImpl.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef)); + sTypeImpl.setUserData(getUserData(typedef)); + } + + if (sType == null && baseModel != null && baseModel.getAttribute(qname) != null) { + sType = baseModel.getAttribute(qname).getType(); + } + } + + if (sType == null) { + sType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + if (!sType.isSimpleType()) { + // KHK: which rule? could use #a-simple_type_definition + state.error("Attributes must have a simple type (not complex).", XmlErrorCodes.INVALID_SCHEMA, xsdAttr); + // recovery: switch to the any-type + sType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + if (xsdAttr.isSetUse()) { + use = translateUseCode(xsdAttr.xgetUse()); + + // ignore referenced default if no longer optional + if (use != SchemaLocalAttribute.OPTIONAL && !isFixed) { + deftext = null; + } + } + + if (xsdAttr.isSetDefault() || xsdAttr.isSetFixed()) { + if (isFixed && !xsdAttr.isSetFixed()) { + state.error("A use of a fixed attribute definition must also be fixed", XmlErrorCodes.REDUNDANT_DEFAULT_FIXED, xsdAttr.xgetFixed()); + } + + isFixed = xsdAttr.isSetFixed(); + + if (xsdAttr.isSetDefault() && isFixed) { + state.error(XmlErrorCodes.SCHEMA_ATTR$DEFAULT_OR_FIXED, null, xsdAttr.xgetFixed()); + // recovery: ignore fixed + isFixed = false; + } + deftext = isFixed ? xsdAttr.getFixed() : xsdAttr.getDefault(); + // BUGBUG(radup) this is not good, since they should be compared by value + // in StscChecker; but there we don't have yet access to the referred attr + if (fmrfixedtext != null && !fmrfixedtext.equals(deftext)) { + state.error(XmlErrorCodes.SCHEMA_ATTR$FIXED_NOT_MATCH, null, xsdAttr.xgetFixed()); + // recovery: reset fixed to the original value + deftext = fmrfixedtext; + } + } + + if (!local) { + ((SchemaGlobalAttributeImpl) sAttr).setFilename(findFilename(xsdAttr)); + } + + SOAPArrayType wat = null; + XmlCursor c = xsdAttr.newCursor(); + String arrayType = c.getAttributeText(WSDL_ARRAYTYPE_NAME); + c.dispose(); + if (arrayType != null) { + try { + wat = new SOAPArrayType(arrayType, new NamespaceContext(xsdAttr)); + } catch (XmlValueOutOfRangeException e) { + state.error(XmlErrorCodes.SOAPARRAY, new Object[]{arrayType}, xsdAttr); + } + } + + SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdAttr); + sAttr.init( + qname, + sType.getRef(), + use, + deftext, xsdAttr, null, isFixed, + wat, ann, getUserData(xsdAttr)); + + return sAttr; + } + + static int translateUseCode(Attribute.Use attruse) { + if (attruse == null) { + return SchemaLocalAttribute.OPTIONAL; + } + + String val = attruse.getStringValue(); + if (val.equals("optional")) { + return SchemaLocalAttribute.OPTIONAL; + } + if (val.equals("required")) { + return SchemaLocalAttribute.REQUIRED; + } + if (val.equals("prohibited")) { + return SchemaLocalAttribute.PROHIBITED; + } + return SchemaLocalAttribute.OPTIONAL; + } + + static BigInteger buildBigInt(XmlAnySimpleType value) { + if (value == null) { + return null; + } + String text = value.getStringValue(); + BigInteger bigInt; + try { + bigInt = new BigInteger(text); + } catch (NumberFormatException e) { + StscState.get().error(XmlErrorCodes.INVALID_VALUE_DETAIL, new Object[]{text, "nonNegativeInteger", e.getMessage()}, value); + return null; + } + + if (bigInt.signum() < 0) { + StscState.get().error(XmlErrorCodes.INVALID_VALUE, new Object[]{text, "nonNegativeInteger"}, value); + return null; + } + + return bigInt; + } + + + static XmlNonNegativeInteger buildNnInteger(XmlAnySimpleType value) { + BigInteger bigInt = buildBigInt(value); + try { + XmlNonNegativeIntegerImpl i = new XmlNonNegativeIntegerImpl(); + i.setBigIntegerValue(bigInt); + i.setImmutable(); + return i; + } catch (XmlValueOutOfRangeException e) { + StscState.get().error("Internal error processing number", XmlErrorCodes.MALFORMED_NUMBER, value); + return null; + } + } + + static XmlPositiveInteger buildPosInteger(XmlAnySimpleType value) { + BigInteger bigInt = buildBigInt(value); + try { + XmlPositiveIntegerImpl i = new XmlPositiveIntegerImpl(); + i.setBigIntegerValue(bigInt); + i.setImmutable(); + return i; + } catch (XmlValueOutOfRangeException e) { + StscState.get().error("Internal error processing number", XmlErrorCodes.MALFORMED_NUMBER, value); + return null; + } + } + + + private static Object getUserData(XmlObject pos) { + XmlCursor.XmlBookmark b = pos.newCursor().getBookmark(SchemaBookmark.class); + if (b instanceof SchemaBookmark) { + return ((SchemaBookmark) b).getValue(); + } else { + return null; + } + } + + private static boolean isEmptySchema(Schema schema) { + XmlCursor cursor = schema.newCursor(); + boolean result = !cursor.toFirstChild(); + cursor.dispose(); + return result; + } + + private static boolean isReservedTypeName(QName name) { + return (BuiltinSchemaTypeSystem.get().findType(name) != null); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java b/src/main/java/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java new file mode 100644 index 0000000..774484c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java @@ -0,0 +1,50 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.schema; + +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; + +/** + * This class is the hook which causes the SchemaTypeSystem to be loaded when + * a generated class is used. It isn't used by the runtime directly, instead + * this class is used by the schema compiler as a template class. By using a + * template class, the SchemaTypeSystemImpl can create all the binary files + * required without needing to rely on javac. The generated source still + * requires a java compiler. + * + * @see SchemaTypeSystemImpl#save(org.apache.xmlbeans.Filer) + */ +// +// !!! It's important that there never NEVER be any references to this class because +// !!! the static initializer will fail. This class must only be used as a class file. +// !!! If this scares you, turn back now !!! +// +// !!! If you modify this class, you will have to run bootstrap. +// !!! If this scares you, turn back now !!! +// +public final class TypeSystemHolder extends SchemaTypeSystemImpl { + // TODO: provide parameter-less parent constructor + private TypeSystemHolder() { super(TypeSystemHolder.class); } + + // the type system + public static final TypeSystemHolder typeSystem = new TypeSystemHolder(); + + // Commenting out this line has the effect of not loading all components in a + // typesystem upfront, but just as they are needed, which may improve + // performance significantly + //static { typeSystem.resolve(); } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java b/src/main/java/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java similarity index 78% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java rename to src/main/java/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java index 41aed8d..e53e066 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java +++ b/src/main/java/org/apache/xmlbeans/impl/schema/XQuerySchemaTypeSystem.java @@ -15,6 +15,13 @@ package org.apache.xmlbeans.impl.schema; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.values.XmlIntegerImpl; +import org.apache.xmlbeans.impl.values.XmlStringImpl; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; + +import javax.xml.namespace.QName; import java.io.File; import java.io.InputStream; import java.math.BigInteger; @@ -22,40 +29,20 @@ import java.util.HashMap; import java.util.Map; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.Filer; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.values.XmlIntegerImpl; -import org.apache.xmlbeans.impl.values.XmlStringImpl; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - /** * Same as {@link BuiltinSchemaTypeSystem} but adds three extra types - * (dayTimeDuration, yearMonthDuration and anyAtomicType) + * (dayTimeDuration, yearMonthDuration and anyAtomicType) * and makes all the primitives extend anyAtomicType. - * - * @author Radu Preotiuc * + * @author Radu Preotiuc */ +@SuppressWarnings("unused") public class XQuerySchemaTypeSystem extends SchemaTypeLoaderBase implements - SchemaTypeSystem -{ + SchemaTypeSystem { // The global builtin type system - public static SchemaTypeSystem get() - { return _global; } + public static SchemaTypeSystem get() { + return _global; + } // Extra constants; since the extra types are going to be part of XMLSchema 1.1 // we will want to eventually move these to SchemaType @@ -74,7 +61,7 @@ public static SchemaTypeSystem get() private static final SchemaAttributeGroup[] EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY = new SchemaAttributeGroup[0]; private static final SchemaAnnotation[] EMPTY_SCHEMAANNOTATION_ARRAY = new SchemaAnnotation[0]; - private static XQuerySchemaTypeSystem _global = new XQuerySchemaTypeSystem(); + private static final XQuerySchemaTypeSystem _global = new XQuerySchemaTypeSystem(); // UR types public static final SchemaTypeImpl ST_ANY_TYPE = _global.getBuiltinType(SchemaType.BTC_ANY_TYPE); @@ -144,88 +131,88 @@ public static SchemaTypeSystem get() private final static XmlValueRef XMLSTR_COLLAPSE = buildString("preserve"); private final static XmlValueRef[] FACETS_NONE = new XmlValueRef[] - { null, null, null, null, null, null, null, null, null, - null, null, null }; + {null, null, null, null, null, null, null, null, null, + null, null, null}; private final static boolean[] FIXED_FACETS_NONE = new boolean[] - { false, false, false, false, false, false, false, false, false, - false, false, false }; + {false, false, false, false, false, false, false, false, false, + false, false, false}; private final static XmlValueRef[] FACETS_WS_COLLAPSE = new XmlValueRef[] - { null, null, null, null, null, null, null, null, null, - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, null, null, null, null, null, + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_WS_REPLACE = new XmlValueRef[] - { null, null, null, null, null, null, null, null, null, - build_wsstring(SchemaType.WS_REPLACE), null, null }; + {null, null, null, null, null, null, null, null, null, + build_wsstring(SchemaType.WS_REPLACE), null, null}; private final static XmlValueRef[] FACETS_WS_PRESERVE = new XmlValueRef[] - { null, null, null, null, null, null, null, null, null, - build_wsstring(SchemaType.WS_PRESERVE), null, null }; + {null, null, null, null, null, null, null, null, null, + build_wsstring(SchemaType.WS_PRESERVE), null, null}; private final static XmlValueRef[] FACETS_INTEGER = new XmlValueRef[] - { null, null, null, null, null, null, null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, null, null, null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_LONG = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.valueOf(Long.MIN_VALUE)), buildInteger(BigInteger.valueOf(Long.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.valueOf(Long.MIN_VALUE)), buildInteger(BigInteger.valueOf(Long.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_INT = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.valueOf(Integer.MIN_VALUE)), buildInteger(BigInteger.valueOf(Integer.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.valueOf(Integer.MIN_VALUE)), buildInteger(BigInteger.valueOf(Integer.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_SHORT = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.valueOf(Short.MIN_VALUE)), buildInteger(BigInteger.valueOf(Short.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.valueOf(Short.MIN_VALUE)), buildInteger(BigInteger.valueOf(Short.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_BYTE = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.valueOf(Byte.MIN_VALUE)), buildInteger(BigInteger.valueOf(Byte.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.valueOf(Byte.MIN_VALUE)), buildInteger(BigInteger.valueOf(Byte.MAX_VALUE)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_NONNEGATIVE = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.ZERO), null, null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.ZERO), null, null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_POSITIVE = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.ONE), null, null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.ONE), null, null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_NONPOSITIVE = new XmlValueRef[] - { null, null, null, null, null, buildInteger(BigInteger.ZERO), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, null, buildInteger(BigInteger.ZERO), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_NEGATIVE = new XmlValueRef[] - { null, null, null, null, null, buildInteger(BigInteger.ONE.negate()), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, null, buildInteger(BigInteger.ONE.negate()), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_UNSIGNED_LONG = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(new BigInteger("18446744073709551615")), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(new BigInteger("18446744073709551615")), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_UNSIGNED_INT = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(BigInteger.valueOf(4294967295L)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(BigInteger.valueOf(4294967295L)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_UNSIGNED_SHORT = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(BigInteger.valueOf(65535)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(BigInteger.valueOf(65535)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_UNSIGNED_BYTE = new XmlValueRef[] - { null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(BigInteger.valueOf(255)), null, null, buildNnInteger(BigInteger.ZERO), - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, null, null, null, buildInteger(BigInteger.ZERO), buildInteger(BigInteger.valueOf(255)), null, null, buildNnInteger(BigInteger.ZERO), + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static XmlValueRef[] FACETS_BUILTIN_LIST = new XmlValueRef[] - { null, buildNnInteger(BigInteger.ONE), null, null, null, null, null, null, null, - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; + {null, buildNnInteger(BigInteger.ONE), null, null, null, null, null, null, null, + build_wsstring(SchemaType.WS_COLLAPSE), null, null}; private final static boolean[] FIXED_FACETS_WS = new boolean[] - { false, false, false, false, false, false, false, false, false, - true, false, false }; + {false, false, false, false, false, false, false, false, false, + true, false, false}; private final static boolean[] FIXED_FACETS_INTEGER = new boolean[] - { false, false, false, false, false, false, false, false, true, - true, false, false }; + {false, false, false, false, false, false, false, false, true, + true, false, false}; final static XmlValueRef[] FACETS_UNION = FACETS_NONE; final static boolean[] FIXED_FACETS_UNION = FIXED_FACETS_NONE; @@ -238,31 +225,27 @@ public static SchemaTypeSystem get() * LAST Static initializer */ static { - for (int i = SchemaType.BTC_NOT_BUILTIN; i <= SchemaType.BTC_LAST_BUILTIN; i++) - { + for (int i = SchemaType.BTC_NOT_BUILTIN; i <= SchemaType.BTC_LAST_BUILTIN; i++) { _global.fillInType(i); } - for (int i = BTC_FIRST_XQUERY; i <= BTC_LAST_XQUERY; i++) - { + for (int i = BTC_FIRST_XQUERY; i <= BTC_LAST_XQUERY; i++) { _global.fillInType(i); } } - private Map _typeMap = new HashMap(); - private SchemaTypeImpl[] _typeArray = new SchemaTypeImpl[SchemaType.BTC_LAST_BUILTIN + 1 + - BTC_LAST_XQUERY - BTC_FIRST_XQUERY + 1]; - private Map _handlesToObjects = new HashMap(); - private Map _objectsToHandles = new HashMap(); - private Map _typesByClassname = new HashMap(); - private SchemaContainer _container = new SchemaContainer("http://www.w3.org/2001/XMLSchema"); + private final Map _typeMap = new HashMap<>(); + private final SchemaTypeImpl[] _typeArray = new SchemaTypeImpl[SchemaType.BTC_LAST_BUILTIN + 1 + + BTC_LAST_XQUERY - BTC_FIRST_XQUERY + 1]; + private final Map _handlesToObjects = new HashMap<>(); + private final Map _objectsToHandles = new HashMap<>(); + private final Map _typesByClassname = new HashMap<>(); + private final SchemaContainer _container = new SchemaContainer("http://www.w3.org/2001/XMLSchema"); - private SchemaTypeImpl getBuiltinType(int btc) - { + private SchemaTypeImpl getBuiltinType(int btc) { return _typeArray[arrayIndexForBtc(btc)]; } - private XQuerySchemaTypeSystem() - { + private XQuerySchemaTypeSystem() { _container.setTypeSystem(this); // UR types setupType(SchemaType.BTC_ANY_TYPE, "anyType", "org.apache.xmlbeans.XmlObject"); @@ -333,98 +316,80 @@ private XQuerySchemaTypeSystem() /** * Returns the name of this loader. */ - public String getName() - { + public String getName() { return "xquery.typesystem.builtin"; } - public boolean isNamespaceDefined(String namespace) - { + public boolean isNamespaceDefined(String namespace) { return namespace.equals("http://www.w3.org/2001/XMLSchema"); } - public SchemaType findType(QName name) - { - return (SchemaType)_typeMap.get(name); + public SchemaType findType(QName name) { + return _typeMap.get(name); } - public SchemaType findDocumentType(QName name) - { + public SchemaType findDocumentType(QName name) { return null; } - public SchemaType findAttributeType(QName name) - { + public SchemaType findAttributeType(QName name) { return null; } - public SchemaGlobalElement findElement(QName name) - { + public SchemaGlobalElement findElement(QName name) { return null; } - public SchemaGlobalAttribute findAttribute(QName name) - { + public SchemaGlobalAttribute findAttribute(QName name) { return null; } - public SchemaType.Ref findTypeRef(QName name) - { + public SchemaType.Ref findTypeRef(QName name) { SchemaType type = findType(name); return (type == null ? null : type.getRef()); } - public SchemaType.Ref findDocumentTypeRef(QName name) - { + public SchemaType.Ref findDocumentTypeRef(QName name) { return null; } - public SchemaType.Ref findAttributeTypeRef(QName name) - { + public SchemaType.Ref findAttributeTypeRef(QName name) { return null; } - public SchemaGlobalElement.Ref findElementRef(QName name) - { + public SchemaGlobalElement.Ref findElementRef(QName name) { return null; } - public SchemaGlobalAttribute.Ref findAttributeRef(QName name) - { + public SchemaGlobalAttribute.Ref findAttributeRef(QName name) { return null; } - public SchemaModelGroup.Ref findModelGroupRef(QName name) - { + public SchemaModelGroup.Ref findModelGroupRef(QName name) { return null; } - public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) - { + public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) { return null; } - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) - { + public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { return null; } - public SchemaType typeForClassname(String classname) - { - return (SchemaType)_typesByClassname.get(classname); + public SchemaType typeForClassname(String classname) { + return _typesByClassname.get(classname); } - public InputStream getSourceAsStream(String sourceName) - { + public InputStream getSourceAsStream(String sourceName) { return null; // builtin schema type system has no source. } /** * Returns the global types defined in this loader. */ - public SchemaType[] globalTypes() - { + public SchemaType[] globalTypes() { SchemaType[] result = new SchemaType[_typeArray.length - 1]; System.arraycopy(_typeArray, 1, result, 0, result.length); return result; @@ -433,101 +398,87 @@ public SchemaType[] globalTypes() /** * Returns the document types defined in this loader. */ - public SchemaType[] documentTypes() - { + public SchemaType[] documentTypes() { return EMPTY_SCHEMATYPE_ARRAY; } /** * Returns the attribute types defined in this loader. */ - public SchemaType[] attributeTypes() - { + public SchemaType[] attributeTypes() { return EMPTY_SCHEMATYPE_ARRAY; } /** * Returns the global elements defined in this loader. */ - public SchemaGlobalElement[] globalElements() - { + public SchemaGlobalElement[] globalElements() { return EMPTY_SCHEMAELEMENT_ARRAY; } /** * Returns the global attributes defined in this loader. */ - public SchemaGlobalAttribute[] globalAttributes() - { + public SchemaGlobalAttribute[] globalAttributes() { return EMPTY_SCHEMAATTRIBUTE_ARRAY; } /** * Returns the model groups defined in this loader. */ - public SchemaModelGroup[] modelGroups() - { + public SchemaModelGroup[] modelGroups() { return EMPTY_SCHEMAMODELGROUP_ARRAY; } /** * Returns the attribute groups defined in this loader. */ - public SchemaAttributeGroup[] attributeGroups() - { + public SchemaAttributeGroup[] attributeGroups() { return EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY; } /* * Returns the top-level annotations. */ - public SchemaAnnotation[] annotations() - { + public SchemaAnnotation[] annotations() { return EMPTY_SCHEMAANNOTATION_ARRAY; } /** * Returns the handle for the given type within this loader. */ - public String handleForType(SchemaType type) - { - return (String)_objectsToHandles.get(type); + public String handleForType(SchemaType type) { + return _objectsToHandles.get(type); } /** * Returns the classloader used by this loader for resolving types. */ - public ClassLoader getClassLoader() - { + public ClassLoader getClassLoader() { return BuiltinSchemaTypeSystem.class.getClassLoader(); } /** * Saves this type to a directory. */ - public void saveToDirectory(File classDir) - { + public void saveToDirectory(File classDir) { throw new UnsupportedOperationException("The builtin schema type system cannot be saved."); } /** * Saves this type system using a Filer */ - public void save(Filer filer) - { + public void save(Filer filer) { throw new UnsupportedOperationException("The builtin schema type system cannot be saved."); } - private int arrayIndexForBtc(int btc) - { + private int arrayIndexForBtc(int btc) { return btc > SchemaType.BTC_LAST_BUILTIN ? btc - BTC_FIRST_XQUERY + SchemaType.BTC_LAST_BUILTIN + 1 : btc; } - private static XmlValueRef build_wsstring(int wsr) - { - switch (wsr) - { + private static XmlValueRef build_wsstring(int wsr) { + switch (wsr) { case SchemaType.WS_PRESERVE: return XMLSTR_PRESERVE; case SchemaType.WS_REPLACE: @@ -538,107 +489,95 @@ private static XmlValueRef build_wsstring(int wsr) return null; } - private static XmlValueRef buildNnInteger(BigInteger bigInt) - { - if (bigInt == null) + private static XmlValueRef buildNnInteger(BigInteger bigInt) { + if (bigInt == null) { return null; - if (bigInt.signum() < 0) + } + if (bigInt.signum() < 0) { return null; - try - { + } + try { XmlIntegerImpl i = new XmlIntegerImpl(); i.setBigIntegerValue(bigInt); i.setImmutable(); return new XmlValueRef(i); - } - catch (XmlValueOutOfRangeException e) - { + } catch (XmlValueOutOfRangeException e) { return null; } } - private static XmlValueRef buildInteger(BigInteger bigInt) - { - if (bigInt == null) + private static XmlValueRef buildInteger(BigInteger bigInt) { + if (bigInt == null) { return null; - try - { + } + try { XmlIntegerImpl i = new XmlIntegerImpl(); i.setBigIntegerValue(bigInt); i.setImmutable(); return new XmlValueRef(i); - } - catch (XmlValueOutOfRangeException e) - { + } catch (XmlValueOutOfRangeException e) { return null; } } - private static XmlValueRef buildString(String str) - { - if (str == null) + private static XmlValueRef buildString(String str) { + if (str == null) { return null; + } - try - { + try { XmlStringImpl i = new XmlStringImpl(); i.setStringValue(str); i.setImmutable(); return new XmlValueRef(i); - } - catch (XmlValueOutOfRangeException e) - { + } catch (XmlValueOutOfRangeException e) { return null; } } - private void setupType(int btc, String localname, String classname) - { + private void setupType(int btc, String localname, String classname) { SchemaTypeImpl result = new SchemaTypeImpl(_container, true); _container.addGlobalType(result.getRef()); QName name = localname == null ? null : QNameHelper.forLNS(localname, "http://www.w3.org/2001/XMLSchema"); String handle = "_BI_" + (localname == null ? "NO_TYPE" : localname); result.setName(name); result.setBuiltinTypeCode(btc); - if (classname != null) + if (classname != null) { result.setFullJavaName(classname); + } _typeArray[arrayIndexForBtc(btc)] = result; _typeMap.put(name, result); _handlesToObjects.put(handle, result); _objectsToHandles.put(result, handle); - if (classname != null) + if (classname != null) { _typesByClassname.put(classname, result); + } } - public void resolve() - { + public void resolve() { // we're born resolved and don't need to do anything. } - public SchemaType typeForHandle(String handle) - { - return (SchemaType)_handlesToObjects.get(handle); + public SchemaType typeForHandle(String handle) { + return _handlesToObjects.get(handle); } - public SchemaComponent resolveHandle(String handle) - { - return (SchemaComponent)_handlesToObjects.get(handle); + public SchemaComponent resolveHandle(String handle) { + return _handlesToObjects.get(handle); } /** * Links a type. */ - public void fillInType(int btc) - { + public void fillInType(int btc) { SchemaTypeImpl result = getBuiltinType(btc); SchemaType base; SchemaType item = null; int variety = SchemaType.ATOMIC; int derivationType = SchemaType.DT_RESTRICTION; - switch (btc) - { + switch (btc) { case SchemaType.BTC_NOT_BUILTIN: variety = SchemaType.NOT_SIMPLE; base = ST_ANY_TYPE; @@ -651,13 +590,15 @@ public void fillInType(int btc) break; default: - assert(false); + assert (false); case SchemaType.BTC_ANY_SIMPLE: - base = ST_ANY_TYPE; break; + base = ST_ANY_TYPE; + break; case BTC_ANY_ATOMIC: base = ST_ANY_SIMPLE; + break; case SchemaType.BTC_BOOLEAN: case SchemaType.BTC_BASE_64_BINARY: @@ -678,81 +619,102 @@ public void fillInType(int btc) case SchemaType.BTC_G_MONTH_DAY: case SchemaType.BTC_G_DAY: case SchemaType.BTC_G_MONTH: - base = ST_ANY_ATOMIC; break; + base = ST_ANY_ATOMIC; + break; // derived numerics case SchemaType.BTC_INTEGER: - base = ST_DECIMAL; break; + base = ST_DECIMAL; + break; case SchemaType.BTC_LONG: - base = ST_INTEGER; break; + base = ST_INTEGER; + break; case SchemaType.BTC_INT: - base = ST_LONG; break; + base = ST_LONG; + break; case SchemaType.BTC_SHORT: - base = ST_INT; break; + base = ST_INT; + break; case SchemaType.BTC_BYTE: - base = ST_SHORT; break; + base = ST_SHORT; + break; case SchemaType.BTC_NON_POSITIVE_INTEGER: - base = ST_INTEGER; break; + base = ST_INTEGER; + break; case SchemaType.BTC_NEGATIVE_INTEGER: - base = ST_NON_POSITIVE_INTEGER; break; + base = ST_NON_POSITIVE_INTEGER; + break; case SchemaType.BTC_NON_NEGATIVE_INTEGER: - base = ST_INTEGER; break; + base = ST_INTEGER; + break; case SchemaType.BTC_POSITIVE_INTEGER: - base = ST_NON_NEGATIVE_INTEGER; break; + base = ST_NON_NEGATIVE_INTEGER; + break; case SchemaType.BTC_UNSIGNED_LONG: - base = ST_NON_NEGATIVE_INTEGER; break; + base = ST_NON_NEGATIVE_INTEGER; + break; case SchemaType.BTC_UNSIGNED_INT: - base = ST_UNSIGNED_LONG; break; + base = ST_UNSIGNED_LONG; + break; case SchemaType.BTC_UNSIGNED_SHORT: - base = ST_UNSIGNED_INT; break; + base = ST_UNSIGNED_INT; + break; case SchemaType.BTC_UNSIGNED_BYTE: - base = ST_UNSIGNED_SHORT; break; + base = ST_UNSIGNED_SHORT; + break; // derived strings case SchemaType.BTC_NORMALIZED_STRING: - base = ST_STRING; break; + base = ST_STRING; + break; case SchemaType.BTC_TOKEN: - base = ST_NORMALIZED_STRING; break; + base = ST_NORMALIZED_STRING; + break; case SchemaType.BTC_NAME: - base = ST_TOKEN; break; + base = ST_TOKEN; + break; case SchemaType.BTC_NCNAME: - base = ST_NAME; break; + base = ST_NAME; + break; case SchemaType.BTC_ID: case SchemaType.BTC_IDREF: case SchemaType.BTC_ENTITY: - base = ST_NCNAME; break; + base = ST_NCNAME; + break; case SchemaType.BTC_LANGUAGE: case SchemaType.BTC_NMTOKEN: - base = ST_TOKEN; break; + base = ST_TOKEN; + break; case SchemaType.BTC_IDREFS: case SchemaType.BTC_ENTITIES: case SchemaType.BTC_NMTOKENS: variety = SchemaType.LIST; base = ST_ANY_SIMPLE; - if (btc == SchemaType.BTC_IDREFS) + if (btc == SchemaType.BTC_IDREFS) { item = ST_IDREF; - else if (btc == SchemaType.BTC_ENTITIES) + } else if (btc == SchemaType.BTC_ENTITIES) { item = ST_ENTITY; - else + } else { item = ST_NMTOKEN; + } break; // derived durations @@ -765,26 +727,24 @@ else if (btc == SchemaType.BTC_ENTITIES) result.setDerivationType(derivationType); result.setSimpleTypeVariety(variety); - if (variety != SchemaType.NOT_SIMPLE) - { + if (variety != SchemaType.NOT_SIMPLE) { result.setSimpleType(true); - } - else - { + } else { assert (btc == SchemaType.BTC_ANY_TYPE || btc == SchemaType.BTC_NOT_BUILTIN); } result.setBaseTypeRef(base == null ? null : base.getRef()); - result.setBaseDepth(base == null ? 0 : ((SchemaTypeImpl)base).getBaseDepth() + 1); + result.setBaseDepth(base == null ? 0 : ((SchemaTypeImpl) base).getBaseDepth() + 1); result.setListItemTypeRef(item == null ? null : item.getRef()); if (btc >= SchemaType.BTC_FIRST_PRIMITIVE && btc <= SchemaType.BTC_LAST_PRIMITIVE || - btc == BTC_ANY_ATOMIC) + btc == BTC_ANY_ATOMIC) { result.setPrimitiveTypeRef(result.getRef()); - else if (variety == SchemaType.ATOMIC) - { - if (base == null) + } else if (variety == SchemaType.ATOMIC) { + if (base == null) { throw new IllegalStateException("Base was null for " + btc); - if (base.getPrimitiveType() == null) + } + if (base.getPrimitiveType() == null) { throw new IllegalStateException("Base.gpt was null for " + btc); + } result.setPrimitiveTypeRef(base.getPrimitiveType().getRef()); } @@ -794,10 +754,9 @@ else if (variety == SchemaType.ATOMIC) int decimalSize = SchemaType.NOT_DECIMAL; // now set up facets - switch (btc) - { + switch (btc) { default: - assert(false); + assert (false); case SchemaType.BTC_ANY_TYPE: case SchemaType.BTC_ANY_SIMPLE: @@ -955,7 +914,7 @@ else if (variety == SchemaType.ATOMIC) fixedf = FIXED_FACETS_WS; wsr = SchemaType.WS_COLLAPSE; break; - + } // fundamental facets @@ -964,10 +923,9 @@ else if (variety == SchemaType.ATOMIC) boolean isFinite = false; boolean isBounded = false; - switch (btc) - { + switch (btc) { default: - assert(false); + assert (false); case SchemaType.BTC_ANY_TYPE: case SchemaType.BTC_NOT_BUILTIN: @@ -1051,14 +1009,13 @@ else if (variety == SchemaType.ATOMIC) String pattern = null; boolean hasPattern = false; - switch (btc) - { + switch (btc) { case SchemaType.BTC_LANGUAGE: - pattern = "[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"; // we used to have ([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{1,8})*", but s4s uses the more lenient pattern to the left. + pattern = "[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"; // we used to have ([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{1,8})*", but s4s uses the more lenient pattern to the left. hasPattern = true; break; case SchemaType.BTC_NMTOKEN: - pattern = "\\c+"; + pattern = "\\c+"; hasPattern = true; break; case SchemaType.BTC_NAME: @@ -1086,20 +1043,20 @@ else if (variety == SchemaType.ATOMIC) break; } - if (pattern != null) - { + if (pattern != null) { org.apache.xmlbeans.impl.regex.RegularExpression p = null; - try { p = org.apache.xmlbeans.impl.regex.SchemaRegularExpression.forPattern(pattern); } - catch (org.apache.xmlbeans.impl.regex.ParseException e) { assert false; } - result.setPatterns(new org.apache.xmlbeans.impl.regex.RegularExpression[] {p}); + try { + p = org.apache.xmlbeans.impl.regex.SchemaRegularExpression.forPattern(pattern); + } catch (org.apache.xmlbeans.impl.regex.ParseException e) { + assert false; + } + result.setPatterns(new org.apache.xmlbeans.impl.regex.RegularExpression[]{p}); } result.setPatternFacet(hasPattern); - // ANY_TYPE has to be able to act like a complex type - if (btc == SchemaType.BTC_ANY_TYPE) - { + if (btc == SchemaType.BTC_ANY_TYPE) { SchemaParticleImpl contentModel = new SchemaParticleImpl(); contentModel.setParticleType(SchemaParticle.WILDCARD); contentModel.setWildcardSet(QNameSet.ALL); @@ -1117,9 +1074,7 @@ else if (variety == SchemaType.ATOMIC) result.setContentModel(contentModel, attrModel, Collections.EMPTY_MAP, Collections.EMPTY_MAP, false); result.setAnonymousTypeRefs(EMPTY_SCHEMATYPEREF_ARRAY); result.setWildcardSummary(QNameSet.ALL, true, QNameSet.ALL, true); - } - else if (btc == SchemaType.BTC_NOT_BUILTIN) - { + } else if (btc == SchemaType.BTC_NOT_BUILTIN) { // so does the no_type : it permits no contents (and even empty contents is invalid, but that's special-cased) SchemaParticleImpl contentModel = null; // empty SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); // empty @@ -1132,8 +1087,7 @@ else if (btc == SchemaType.BTC_NOT_BUILTIN) result.setOrderSensitive(false); } - public static SchemaType getNoType() - { + public static SchemaType getNoType() { return ST_NO_TYPE; } } diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/XmlValueRef.java b/src/main/java/org/apache/xmlbeans/impl/schema/XmlValueRef.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/schema/XmlValueRef.java rename to src/main/java/org/apache/xmlbeans/impl/schema/XmlValueRef.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/AttachmentPart.java b/src/main/java/org/apache/xmlbeans/impl/soap/AttachmentPart.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/AttachmentPart.java rename to src/main/java/org/apache/xmlbeans/impl/soap/AttachmentPart.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/Detail.java b/src/main/java/org/apache/xmlbeans/impl/soap/Detail.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/Detail.java rename to src/main/java/org/apache/xmlbeans/impl/soap/Detail.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/DetailEntry.java b/src/main/java/org/apache/xmlbeans/impl/soap/DetailEntry.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/DetailEntry.java rename to src/main/java/org/apache/xmlbeans/impl/soap/DetailEntry.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/FactoryFinder.java b/src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java similarity index 85% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/FactoryFinder.java rename to src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java index c826933..b5798a4 100644 --- a/src/saaj_api/org/apache/xmlbeans/impl/soap/FactoryFinder.java +++ b/src/main/java/org/apache/xmlbeans/impl/soap/FactoryFinder.java @@ -15,14 +15,11 @@ package org.apache.xmlbeans.impl.soap; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; +import org.apache.xmlbeans.SystemProperties; +import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.Properties; -import org.apache.xmlbeans.SystemProperties; /** * This class is used to locate factory classes for javax.xml.soap. @@ -38,7 +35,7 @@ class FactoryFinder { * @throws SOAPException */ private static Object newInstance(String factoryClassName) throws SOAPException { - ClassLoader classloader = null; + ClassLoader classloader; try { classloader = Thread.currentThread().getContextClassLoader(); } catch (Exception exception) { @@ -52,13 +49,14 @@ private static Object newInstance(String factoryClassName) throws SOAPException } else { try { factory = classloader.loadClass(factoryClassName); - } catch (ClassNotFoundException cnfe) {} + } catch (ClassNotFoundException ignored) { + } } if (factory == null) { classloader = FactoryFinder.class.getClassLoader(); factory = classloader.loadClass(factoryClassName); } - return factory.newInstance(); + return factory.getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException classnotfoundexception) { throw new SOAPException("Provider " + factoryClassName + " not found", classnotfoundexception); } catch (Exception exception) { @@ -81,7 +79,8 @@ static Object find(String factoryPropertyName, String defaultFactoryClassName) t if (factoryClassName != null) { return newInstance(factoryClassName); } - } catch (SecurityException securityexception) {} + } catch (SecurityException ignored) { + } try { String propertiesFileName = SystemProperties.getProperty("java.home") @@ -96,21 +95,23 @@ static Object find(String factoryPropertyName, String defaultFactoryClassName) t String factoryClassName = properties.getProperty(factoryPropertyName); return newInstance(factoryClassName); } - } catch (Exception exception1) {} + } catch (Exception ignored) { + } String factoryResource = "META-INF/services/" + factoryPropertyName; try { InputStream inputstream = getResource(factoryResource); if (inputstream != null) { - BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream, "UTF-8")); + BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8)); String factoryClassName = bufferedreader.readLine(); bufferedreader.close(); if ((factoryClassName != null) && !"".equals(factoryClassName)) { return newInstance(factoryClassName); } } - } catch (Exception exception2) {} + } catch (Exception ignored) { + } if (defaultFactoryClassName == null) { throw new SOAPException("Provider for " + factoryPropertyName + " cannot be found", null); @@ -129,15 +130,16 @@ static Object find(String factoryPropertyName, String defaultFactoryClassName) t * getResourceAsStream() on * FactoryFinder.class.getClassLoader(). * - * @param factoryResource the resource name - * @return an InputStream that can be used to read that resource, or - * null if the resource could not be resolved + * @param factoryResource the resource name + * @return an InputStream that can be used to read that resource, or + * null if the resource could not be resolved */ private static InputStream getResource(String factoryResource) { ClassLoader classloader = null; try { classloader = Thread.currentThread().getContextClassLoader(); - } catch (SecurityException securityexception) {} + } catch (SecurityException ignored) { + } InputStream inputstream; if (classloader == null) { @@ -149,6 +151,9 @@ private static InputStream getResource(String factoryResource) { if (inputstream == null) { inputstream = FactoryFinder.class.getResourceAsStream(factoryResource); } + if (inputstream == null && FactoryFinder.class.getClassLoader() != null) { + inputstream = FactoryFinder.class.getClassLoader().getResourceAsStream(factoryResource); + } return inputstream; } } diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/MessageFactory.java b/src/main/java/org/apache/xmlbeans/impl/soap/MessageFactory.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/MessageFactory.java rename to src/main/java/org/apache/xmlbeans/impl/soap/MessageFactory.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/MimeHeader.java b/src/main/java/org/apache/xmlbeans/impl/soap/MimeHeader.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/MimeHeader.java rename to src/main/java/org/apache/xmlbeans/impl/soap/MimeHeader.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/MimeHeaders.java b/src/main/java/org/apache/xmlbeans/impl/soap/MimeHeaders.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/MimeHeaders.java rename to src/main/java/org/apache/xmlbeans/impl/soap/MimeHeaders.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/Name.java b/src/main/java/org/apache/xmlbeans/impl/soap/Name.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/Name.java rename to src/main/java/org/apache/xmlbeans/impl/soap/Name.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/Node.java b/src/main/java/org/apache/xmlbeans/impl/soap/Node.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/Node.java rename to src/main/java/org/apache/xmlbeans/impl/soap/Node.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPBody.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPBody.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPBody.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPBody.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPBodyElement.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPBodyElement.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPBodyElement.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPBodyElement.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPConnection.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPConnection.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPConnection.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPConnection.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPConnectionFactory.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPConnectionFactory.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPConnectionFactory.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPConnectionFactory.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPConstants.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPConstants.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPConstants.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPConstants.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPElement.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPElement.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPElement.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPElement.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPEnvelope.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPEnvelope.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPEnvelope.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPEnvelope.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPException.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPException.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPException.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPException.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPFactory.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPFactory.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPFactory.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPFactory.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPFault.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPFault.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPFault.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPFault.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPFaultElement.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPFaultElement.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPFaultElement.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPFaultElement.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPHeader.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPHeader.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPHeader.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPHeader.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPHeaderElement.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPHeaderElement.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPHeaderElement.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPHeaderElement.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPMessage.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPMessage.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPMessage.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPMessage.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPPart.java b/src/main/java/org/apache/xmlbeans/impl/soap/SOAPPart.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPPart.java rename to src/main/java/org/apache/xmlbeans/impl/soap/SOAPPart.java diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/Text.java b/src/main/java/org/apache/xmlbeans/impl/soap/Text.java similarity index 100% rename from src/saaj_api/org/apache/xmlbeans/impl/soap/Text.java rename to src/main/java/org/apache/xmlbeans/impl/soap/Text.java diff --git a/src/main/java/org/apache/xmlbeans/impl/store/AttrIdXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/AttrIdXobj.java new file mode 100644 index 0000000..77d092d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/AttrIdXobj.java @@ -0,0 +1,27 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.xmlbeans.impl.store; + +import javax.xml.namespace.QName; + +class AttrIdXobj extends AttrXobj { + AttrIdXobj(Locale l, QName name) { + super(l, name); + } + + public boolean isId() { + return true; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/AttrXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/AttrXobj.java new file mode 100644 index 0000000..f7cb0b5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/AttrXobj.java @@ -0,0 +1,72 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.TypeInfo; + +import javax.xml.namespace.QName; + +import static org.apache.xmlbeans.impl.store.Cur.ATTR; + +class AttrXobj extends NamedNodeXobj implements Attr { + AttrXobj(Locale l, QName name) { + super(l, ATTR, DomImpl.ATTR); + _name = name; + } + + Xobj newNode(Locale l) { + return new AttrXobj(l, _name); + } + + // + public Node getNextSibling() { + return null; + } + // + + public String getName() { + return DomImpl._node_getNodeName(this); + } + + public Element getOwnerElement() { + return DomImpl._attr_getOwnerElement(this); + } + + public boolean getSpecified() { + return DomImpl._attr_getSpecified(this); + } + + public String getValue() { + return DomImpl._node_getNodeValue(this); + } + + public void setValue(String value) { + DomImpl._node_setNodeValue(this, value); + } + + // DOM Level 3 + public TypeInfo getSchemaTypeInfo() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public boolean isId() { + return false; + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Bookmark.java b/src/main/java/org/apache/xmlbeans/impl/store/Bookmark.java new file mode 100644 index 0000000..542dbb5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Bookmark.java @@ -0,0 +1,109 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.XmlCursor; + +class Bookmark implements XmlCursor.XmlMark { + boolean isOnList(Bookmark head) { + for (; head != null; head = head._next) + if (head == this) + return true; + + return false; + } + + Bookmark listInsert(Bookmark head) { + assert _next == null && _prev == null; + + if (head == null) + head = _prev = this; + else { + _prev = head._prev; + head._prev = head._prev._next = this; + } + + return head; + } + + Bookmark listRemove(Bookmark head) { + assert _prev != null && isOnList(head); + + if (_prev == this) { + head = null; + } else { + if (head == this) { + head = _next; + } else { + _prev._next = _next; + } + + if (_next == null) { + if (head != null) { + head._prev = _prev; + } + } else { + _next._prev = _prev; + _next = null; + } + } + + _prev = null; + assert _next == null; + + return head; + } + + void moveTo(Xobj x, int p) { + assert isOnList(_xobj._bookmarks); + + if (_xobj != x) { + _xobj._bookmarks = listRemove(_xobj._bookmarks); + x._bookmarks = listInsert(x._bookmarks); + + _xobj = x; + } + + _pos = p; + } + + // + // XmlCursor.XmlMark method + // + + public XmlCursor createCursor() { + if (_xobj == null) { + throw new IllegalStateException( + "Attempting to create a cursor on a bookmark that " + + "has been cleared or replaced."); + } + + return Cursor.newCursor(_xobj, _pos); + } + + // + // + // + + Xobj _xobj; + int _pos; + + Bookmark _next; + Bookmark _prev; + + Object _key; + Object _value; +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/CdataNode.java b/src/main/java/org/apache/xmlbeans/impl/store/CdataNode.java new file mode 100644 index 0000000..e0d3380 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/CdataNode.java @@ -0,0 +1,33 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.CDATASection; + +class CdataNode extends TextNode implements CDATASection { + CdataNode(Locale l) { + super(l); + } + + public int nodeType() { + return DomImpl.CDATA; + } + + public String name() { + return "#cdata-section"; + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/CharNode.java b/src/main/java/org/apache/xmlbeans/impl/store/CharNode.java new file mode 100644 index 0000000..67b1d6c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/CharNode.java @@ -0,0 +1,421 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.CharacterData; +import org.w3c.dom.*; + +import javax.xml.namespace.QName; +import java.io.PrintStream; + +abstract class CharNode implements DomImpl.Dom, Node, CharacterData { + + public CharNode(Locale l) { + assert l != null; + + _locale = l; + } + + public QName getQName() { + return null; + } + + public Locale locale() { + assert isValid(); + + return _locale == null ? ((DomImpl.Dom) _src).locale() : _locale; + } + + public void setChars(Object src, int off, int cch) { + assert CharUtil.isValid(src, off, cch); + assert (_locale != null || _src instanceof DomImpl.Dom); + + if (_locale == null) { + _locale = ((DomImpl.Dom) _src).locale(); + } + + _src = src; + _off = off; + _cch = cch; + } + + public DomImpl.Dom getDom() { + assert isValid(); + + if (_src instanceof DomImpl.Dom) + return (DomImpl.Dom) _src; + + return null; + } + + public void setDom(DomImpl.Dom d) { + assert d != null; + + _src = d; + _locale = null; + } + + public Cur tempCur() { + assert isValid(); + + if (!(_src instanceof DomImpl.Dom)) + return null; + + Cur c = locale().tempCur(); + c.moveToCharNode(this); + + return c; + } + + private boolean isValid() { + return (_src instanceof DomImpl.Dom) == (_locale == null); + + } + + public static boolean isOnList(CharNode nodes, CharNode node) { + assert node != null; + + for (CharNode cn = nodes; cn != null; cn = cn._next) { + if (cn == node) { + return true; + } + } + + return false; + } + + public static CharNode remove(CharNode nodes, CharNode node) { + assert isOnList(nodes, node); + + if (nodes == node) { + nodes = node._next; + } else { + node._prev._next = node._next; + } + + if (node._next != null) { + node._next._prev = node._prev; + } + + node._prev = node._next = null; + + return nodes; + } + + public static CharNode insertNode(CharNode nodes, CharNode newNode, CharNode before) { + assert !isOnList(nodes, newNode); + assert before == null || isOnList(nodes, before); + assert newNode != null; + assert newNode._prev == null && newNode._next == null; + + if (nodes == null) { + assert before == null; + nodes = newNode; + } else if (nodes == before) { + nodes._prev = newNode; + newNode._next = nodes; + nodes = newNode; + } else { + CharNode n = nodes; + + while (n._next != before) + n = n._next; + + if ((newNode._next = n._next) != null) + n._next._prev = newNode; + + newNode._prev = n; + n._next = newNode; + } + + return nodes; + } + + public static CharNode appendNode(CharNode nodes, CharNode newNode) { + return insertNode(nodes, newNode, null); + } + + public static CharNode appendNodes(CharNode nodes, CharNode newNodes) { + assert newNodes != null; + assert newNodes._prev == null; + + if (nodes == null) + return newNodes; + + CharNode n = nodes; + + while (n._next != null) + n = n._next; + + n._next = newNodes; + newNodes._prev = n; + + return nodes; + } + + public static CharNode copyNodes(CharNode nodes, Object newSrc) { + CharNode newNodes = null; + + for (CharNode n = null; nodes != null; nodes = nodes._next) { + CharNode newNode; + + if (nodes instanceof TextNode) + newNode = nodes.locale().createTextNode(); + else + newNode = nodes.locale().createCdataNode(); + + // How to deal with entity refs?? + + newNode.setChars(newSrc, nodes._off, nodes._cch); + + if (newNodes == null) + newNodes = newNode; + + if (n != null) { + n._next = newNode; + newNode._prev = n; + } + + n = newNode; + } + + return newNodes; + } + + public boolean nodeCanHavePrefixUri() { + return false; + } + + public boolean isNodeAftertext() { + assert _src instanceof Xobj : + "this method is to only be used for nodes backed up by Xobjs"; + Xobj src = (Xobj) _src; + return src._charNodesValue == null ? true : + src._charNodesAfter == null ? false : + CharNode.isOnList(src._charNodesAfter, this); + } + + public void dump(PrintStream o, Object ref) { + if (_src instanceof DomImpl.Dom) + ((DomImpl.Dom) _src).dump(o, ref); + else + o.println("Lonely CharNode: \"" + CharUtil.getString(_src, _off, _cch) + "\""); + } + + public void dump(PrintStream o) { + dump(o, (Object) this); + } + + public void dump() { + dump(System.out); + } + + public Node appendChild(Node newChild) { + return DomImpl._node_appendChild(this, newChild); + } + + public Node cloneNode(boolean deep) { + return DomImpl._node_cloneNode(this, deep); + } + + public NamedNodeMap getAttributes() { + return null; + } + + public NodeList getChildNodes() { + return DomImpl._emptyNodeList; + } + + public Node getParentNode() { + return DomImpl._node_getParentNode(this); + } + + public Node removeChild(Node oldChild) { + return DomImpl._node_removeChild(this, oldChild); + } + + public Node getFirstChild() { + return null; + } + + public Node getLastChild() { + return null; + } + + public String getLocalName() { + return DomImpl._node_getLocalName(this); + } + + public String getNamespaceURI() { + return DomImpl._node_getNamespaceURI(this); + } + + public Node getNextSibling() { + return DomImpl._node_getNextSibling(this); + } + + public String getNodeName() { + return DomImpl._node_getNodeName(this); + } + + public short getNodeType() { + return DomImpl._node_getNodeType(this); + } + + public String getNodeValue() { + return DomImpl._node_getNodeValue(this); + } + + public Document getOwnerDocument() { + return DomImpl._node_getOwnerDocument(this); + } + + public String getPrefix() { + return DomImpl._node_getPrefix(this); + } + + public Node getPreviousSibling() { + return DomImpl._node_getPreviousSibling(this); + } + + public boolean hasAttributes() { + return false; + } + + public boolean hasChildNodes() { + return false; + } + + public Node insertBefore(Node newChild, Node refChild) { + return DomImpl._node_insertBefore(this, newChild, refChild); + } + + public boolean isSupported(String feature, String version) { + return DomImpl._node_isSupported(this, feature, version); + } + + public void normalize() { + DomImpl._node_normalize(this); + } + + public Node replaceChild(Node newChild, Node oldChild) { + return DomImpl._node_replaceChild(this, newChild, oldChild); + } + + public void setNodeValue(String nodeValue) { + DomImpl._node_setNodeValue(this, nodeValue); + } + + public void setPrefix(String prefix) { + DomImpl._node_setPrefix(this, prefix); + } + + // DOM Level 3 + public Object getUserData(String key) { + return DomImpl._node_getUserData(this, key); + } + + public Object setUserData(String key, Object data, UserDataHandler handler) { + return DomImpl._node_setUserData(this, key, data, handler); + } + + public Object getFeature(String feature, String version) { + return DomImpl._node_getFeature(this, feature, version); + } + + public boolean isEqualNode(Node arg) { + return DomImpl._node_isEqualNode(this, arg); + } + + public boolean isSameNode(Node arg) { + return DomImpl._node_isSameNode(this, arg); + } + + public String lookupNamespaceURI(String prefix) { + return DomImpl._node_lookupNamespaceURI(this, prefix); + } + + public String lookupPrefix(String namespaceURI) { + return DomImpl._node_lookupPrefix(this, namespaceURI); + } + + public boolean isDefaultNamespace(String namespaceURI) { + return DomImpl._node_isDefaultNamespace(this, namespaceURI); + } + + public void setTextContent(String textContent) { + DomImpl._node_setTextContent(this, textContent); + } + + public String getTextContent() { + return DomImpl._node_getTextContent(this); + } + + public short compareDocumentPosition(Node other) { + return DomImpl._node_compareDocumentPosition(this, other); + } + + public String getBaseURI() { + return DomImpl._node_getBaseURI(this); + } + + public void appendData(String arg) { + DomImpl._characterData_appendData(this, arg); + } + + public void deleteData(int offset, int count) { + DomImpl._characterData_deleteData(this, offset, count); + } + + public String getData() { + return DomImpl._characterData_getData(this); + } + + public int getLength() { + return DomImpl._characterData_getLength(this); + } + + public void insertData(int offset, String arg) { + DomImpl._characterData_insertData(this, offset, arg); + } + + public void replaceData(int offset, int count, String arg) { + DomImpl._characterData_replaceData(this, offset, count, arg); + } + + public void setData(String data) { + DomImpl._characterData_setData(this, data); + } + + public String substringData(int offset, int count) { + return DomImpl._characterData_substringData(this, offset, count); + } + + Object getObject() { + return _src; + } + + private Locale _locale; + + CharNode _next; + CharNode _prev; + + private Object _src; + + int _off; + int _cch; +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/CharUtil.java b/src/main/java/org/apache/xmlbeans/impl/store/CharUtil.java new file mode 100755 index 0000000..e258188 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/CharUtil.java @@ -0,0 +1,874 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.xmlbeans.impl.store; + +import java.io.PrintStream; +import java.lang.ref.SoftReference; + +public final class CharUtil { + public CharUtil(int charBufSize) { + _charBufSize = charBufSize; + } + + public CharIterator getCharIterator(Object src, int off, int cch) { + _charIter.init(src, off, cch); + return _charIter; + } + + public CharIterator getCharIterator(Object src, int off, int cch, int start) { + _charIter.init(src, off, cch, start); + return _charIter; + } + + public static CharUtil getThreadLocalCharUtil() { + SoftReference softRef = tl_charUtil.get(); + CharUtil charUtil = softRef.get(); + if (charUtil == null) { + charUtil = new CharUtil(CHARUTIL_INITIAL_BUFSIZE); + tl_charUtil.set(new SoftReference<>(charUtil)); + } + return charUtil; + } + + public static void getString(StringBuffer sb, Object src, int off, int cch) { + assert isValid(src, off, cch); + + if (cch == 0) { + return; + } + + if (src instanceof char[]) { + sb.append((char[]) src, off, cch); + } else if (src instanceof String) { + String s = (String) src; + + if (off == 0 && cch == s.length()) { + sb.append(s); + } else { + sb.append(s, off, off + cch); + } + } else { + ((CharJoin) src).getString(sb, off, cch); + } + } + + public static void getChars(char[] chars, int start, Object src, int off, int cch) { + assert isValid(src, off, cch); + assert chars != null && start >= 0 && start <= chars.length; + + if (cch == 0) { + return; + } + + if (src instanceof char[]) { + char[] cs = (char[]) src; + System.arraycopy(cs, off, chars, start, cch); + } else if (src instanceof String) { + ((String) src).getChars(off, off + cch, chars, start); + } else { + ((CharJoin) src).getChars(chars, start, off, cch); + } + } + + public static String getString(Object src, int off, int cch) { + assert isValid(src, off, cch); + + if (cch == 0) { + return ""; + } + + if (src instanceof char[]) { + return new String((char[]) src, off, cch); + } + + if (src instanceof String) { + String s = (String) src; + + if (off == 0 && cch == s.length()) { + return s; + } + + return s.substring(off, off + cch); + } + + StringBuffer sb = new StringBuffer(); + + ((CharJoin) src).getString(sb, off, cch); + + return sb.toString(); + } + + public static boolean isWhiteSpace(char ch) { + switch (ch) { + case ' ': + case '\t': + case '\n': + case '\r': + return true; + default: + return false; + } + } + + public final boolean isWhiteSpace(Object src, int off, int cch) { + assert isValid(src, off, cch); + + if (cch <= 0) { + return true; + } + + if (src instanceof char[]) { + for (char[] chars = (char[]) src; cch > 0; cch--) { + if (!isWhiteSpace(chars[off++])) { + return false; + } + } + + return true; + } + + if (src instanceof String) { + for (String s = (String) src; cch > 0; cch--) { + if (!isWhiteSpace(s.charAt(off++))) { + return false; + } + } + + return true; + } + + boolean isWhite = true; + + for (_charIter.init(src, off, cch); _charIter.hasNext(); ) { + if (!isWhiteSpace(_charIter.next())) { + isWhite = false; + break; + } + } + + _charIter.release(); + + return isWhite; + } + + public Object stripLeft(Object src, int off, int cch) { + assert isValid(src, off, cch); + + if (cch > 0) { + if (src instanceof char[]) { + char[] chars = (char[]) src; + + while (cch > 0 && isWhiteSpace(chars[off])) { + cch--; + off++; + } + } else if (src instanceof String) { + String s = (String) src; + + while (cch > 0 && isWhiteSpace(s.charAt(off))) { + cch--; + off++; + } + } else { + int count = 0; + + for (_charIter.init(src, off, cch); _charIter.hasNext(); count++) { + if (!isWhiteSpace(_charIter.next())) { + break; + } + } + + _charIter.release(); + + off += count; + } + } + + if (cch == 0) { + _offSrc = 0; + _cchSrc = 0; + + return null; + } + + _offSrc = off; + _cchSrc = cch; + + return src; + } + + public Object stripRight(Object src, int off, int cch) { + assert isValid(src, off, cch); + + if (cch > 0) { + for (_charIter.init(src, off, cch, cch); _charIter.hasPrev(); cch--) { + if (!isWhiteSpace(_charIter.prev())) { + break; + } + } + + _charIter.release(); + } + + if (cch == 0) { + _offSrc = 0; + _cchSrc = 0; + + return null; + } + + _offSrc = off; + _cchSrc = cch; + + return src; + } + + public Object insertChars( + int posInsert, + Object src, int off, int cch, + Object srcInsert, int offInsert, int cchInsert) { + assert isValid(src, off, cch); + assert isValid(srcInsert, offInsert, cchInsert); + assert posInsert >= 0 && posInsert <= cch; + + // TODO - at some point, instead of creating joins, I should + // normalize all the text into a single buffer to stop large + // tree's from being built when many modifications happen... + + // TODO - actually, I should see if the size of the new char + // sequence is small enough to simply allocate a new contigous + // sequence, either in a common char[] managed by the master, + // or just create a new string ... this goes for remove chars + // as well. + + if (cchInsert == 0) { + _cchSrc = cch; + _offSrc = off; + return src; + } + + if (cch == 0) { + _cchSrc = cchInsert; + _offSrc = offInsert; + return srcInsert; + } + + _cchSrc = cch + cchInsert; + + Object newSrc; + + if (_cchSrc <= MAX_COPY && canAllocate(_cchSrc)) { + char[] c = allocate(_cchSrc); + + getChars(c, _offSrc, src, off, posInsert); + getChars(c, _offSrc + posInsert, srcInsert, offInsert, cchInsert); + getChars(c, _offSrc + posInsert + cchInsert, src, off + posInsert, cch - posInsert); + + newSrc = c; + } else { + _offSrc = 0; + + CharJoin newJoin; + + if (posInsert == 0) { + newJoin = new CharJoin(srcInsert, offInsert, cchInsert, src, off); + } else if (posInsert == cch) { + newJoin = new CharJoin(src, off, cch, srcInsert, offInsert); + } else { + CharJoin j = new CharJoin(src, off, posInsert, srcInsert, offInsert); + newJoin = new CharJoin(j, 0, posInsert + cchInsert, src, off + posInsert); + } + + if (newJoin._depth > CharJoin.MAX_DEPTH) { + newSrc = saveChars(newJoin, _offSrc, _cchSrc); + } else { + newSrc = newJoin; + } + } + + assert isValid(newSrc, _offSrc, _cchSrc); + + return newSrc; + } + + public Object removeChars(int posRemove, int cchRemove, Object src, int off, int cch) { + assert isValid(src, off, cch); + assert posRemove >= 0 && posRemove <= cch; + assert cchRemove >= 0 && posRemove + cchRemove <= cch; + + Object newSrc; + + _cchSrc = cch - cchRemove; + + if (_cchSrc == 0) { + newSrc = null; + _offSrc = 0; + } else if (posRemove == 0) { + newSrc = src; + _offSrc = off + cchRemove; + } else if (posRemove + cchRemove == cch) { + newSrc = src; + _offSrc = off; + } else { + int cchAfter = cch - cchRemove; + + if (cchAfter <= MAX_COPY && canAllocate(cchAfter)) { + char[] chars = allocate(cchAfter); + + getChars(chars, _offSrc, src, off, posRemove); + + + getChars( + chars, _offSrc + posRemove, + src, off + posRemove + cchRemove, cch - posRemove - cchRemove); + + newSrc = chars; + // _offSrc = _offSrc; + } else { + CharJoin j = new CharJoin(src, off, posRemove, src, off + posRemove + cchRemove); + + if (j._depth > CharJoin.MAX_DEPTH) { + newSrc = saveChars(j, 0, _cchSrc); + } else { + newSrc = j; + _offSrc = 0; + } + } + } + + assert isValid(newSrc, _offSrc, _cchSrc); + + return newSrc; + } + + private boolean canAllocate(int cch) { + return _currentBuffer == null || _currentBuffer.length - _currentOffset >= cch; + } + + private char[] allocate(int cch) { + assert _currentBuffer == null || _currentBuffer.length - _currentOffset > 0; + + if (_currentBuffer == null) { + _currentBuffer = new char[Math.max(cch, _charBufSize)]; + _currentOffset = 0; + } + + _offSrc = _currentOffset; + _cchSrc = Math.min(_currentBuffer.length - _currentOffset, cch); + + char[] retBuf = _currentBuffer; + + assert _currentOffset + _cchSrc <= _currentBuffer.length; + + if ((_currentOffset += _cchSrc) == _currentBuffer.length) { + _currentBuffer = null; + _currentOffset = 0; + } + + return retBuf; + } + + public Object saveChars(Object srcSave, int offSave, int cchSave) { + return saveChars(srcSave, offSave, cchSave, null, 0, 0); + } + + public Object saveChars( + Object srcSave, int offSave, int cchSave, + Object srcPrev, int offPrev, int cchPrev) { + // BUGBUG (ericvas) + // + // There is a severe degenerate situation which can deveol here. The cases is where + // there is a long strings of calls to saveChars, where the caller passes in prev text + // to be prepended. In this cases, the buffer breaks and a join is made, but because the + // join is created, subsequent calls willproduce additional joins. I need to figure + // out a way that a whole bunch of joins are not created. I really only want to create + // joins in situations where large amount of text is manipulated. + + assert isValid(srcSave, offSave, cchSave); + assert isValid(srcPrev, offPrev, cchPrev); + + // Allocate some space to save the text and copy it there. This may not allocate all + // the space I need. This happens when I run out of buffer space. Deal with this later. + + char[] srcAlloc = allocate(cchSave); + int offAlloc = _offSrc; + int cchAlloc = _cchSrc; + + assert cchAlloc <= cchSave; + + getChars(srcAlloc, offAlloc, srcSave, offSave, cchAlloc); + + Object srcNew; + int offNew; + + int cchNew = cchAlloc + cchPrev; + + // The prev arguments specify a chunk of text which the caller wants prepended to the + // text to be saved. The optimization here is to detect the case where the prev text + // and the newly allcoated and saved text are adjacent, so that I can avoid copying + // or joining the two pieces. The situation where this happens most is when a parser + // reports a big piece of text in chunks, perhaps because there are entities in the + // big chunk of text. + + CharJoin j; + + if (cchPrev == 0) { + srcNew = srcAlloc; + offNew = offAlloc; + } else if (srcPrev == srcAlloc && offPrev + cchPrev == offAlloc) { + //noinspection ConstantConditions + assert srcPrev instanceof char[]; + + srcNew = srcPrev; + offNew = offPrev; + } else if (srcPrev instanceof CharJoin && (j = (CharJoin) srcPrev)._srcRight == srcAlloc && + offPrev + cchPrev - j._cchLeft + j._offRight == offAlloc) { + assert j._srcRight instanceof char[]; + + srcNew = srcPrev; + offNew = offPrev; + } else { + j = new CharJoin(srcPrev, offPrev, cchPrev, srcAlloc, offAlloc); + + offNew = 0; + srcNew = j._depth > CharJoin.MAX_DEPTH ? saveChars(j, 0, cchNew) : j; + } + + // Now, srcNew and offNew specify the two parts of the triple which has the prev text and + // part of the text to save (if not all of it). Here I compute cchMore which is any + // remaining text which was not allocated for earlier. Effectively, this code deals with + // the case where the text to save was greater than the remaining space in the buffer and + // I need to allocate another buffer to save away the second part and then join the two. + + int cchMore = cchSave - cchAlloc; + + if (cchMore > 0) { + // If we're here the the buffer got consumed. So, this time it must allocate a new + // buffer capable of containing all of the remaining text (no matter how large) and + // return the beginning part of it. + + srcAlloc = allocate(cchMore); + offAlloc = _offSrc; + cchAlloc = _cchSrc; + + assert cchAlloc == cchMore; + assert offAlloc == 0; + + getChars(srcAlloc, offAlloc, srcSave, offSave + (cchSave - cchMore), cchMore); + + j = new CharJoin(srcNew, offNew, cchNew, srcAlloc, offAlloc); + + offNew = 0; + cchNew += cchMore; + srcNew = j._depth > CharJoin.MAX_DEPTH ? saveChars(j, 0, cchNew) : j; + } + + _offSrc = offNew; + _cchSrc = cchNew; + + assert isValid(srcNew, _offSrc, _cchSrc); + + return srcNew; + } + + private static void dumpText(PrintStream o, String s) { + o.print("\""); + + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + + if (i == 36) { + o.print("..."); + break; + } + + switch (ch) { + case '\n': + o.print("\\n"); + break; + case '\r': + o.print("\\r"); + break; + case '\t': + o.print("\\t"); + break; + case '\f': + o.print("\\f"); + break; + case '"': + o.print("\\\""); + break; + default: + o.print(ch); + break; + } + } + + o.print("\""); + } + + public static void dump(Object src, int off, int cch) { + dumpChars(System.out, src, off, cch); + System.out.println(); + } + + public static void dumpChars(PrintStream p, Object src, int off, int cch) { + p.print("off=" + off + ", cch=" + cch + ", "); + + if (src == null) { + p.print(""); + } else if (src instanceof String) { + String s = (String) src; + + p.print("String"); + + if (off != 0 || cch != s.length()) { + if (off < 0 || off > s.length() || off + cch < 0 || off + cch > s.length()) { + p.print(" (Error)"); + return; + } + } + + //p.print( ": " ); + dumpText(p, s.substring(off, off + cch)); + } else if (src instanceof char[]) { + char[] chars = (char[]) src; + + p.print("char[]"); + + if (off != 0 || cch != chars.length) { + if (off < 0 || off > chars.length || off + cch < 0 || off + cch > chars.length) { + p.print(" (Error)"); + return; + } + } + + //p.print( ": " ); + dumpText(p, new String(chars, off, cch)); + } else if (src instanceof CharJoin) { + p.print("CharJoin"); + + ((CharJoin) src).dumpChars(p, off, cch); + } else { + p.print("Unknown text source"); + } + } + + public static boolean isValid(Object src, int off, int cch) { + if (cch < 0 || off < 0) { + return false; + } + + if (src == null) { + return off == 0 && cch == 0; + } + + if (src instanceof char[]) { + char[] c = (char[]) src; + return off <= c.length && off + cch <= c.length; + } + + if (src instanceof String) { + String s = (String) src; + return off <= s.length() && off + cch <= s.length(); + } + + if (src instanceof CharJoin) { + return ((CharJoin) src).isValid(off, cch); + } + + return false; + } + + // + // Private stuff + // + + public static final class CharJoin { + public CharJoin( + Object srcLeft, int offLeft, int cchLeft, Object srcRight, int offRight) { + _srcLeft = srcLeft; + _offLeft = offLeft; + _cchLeft = cchLeft; + _srcRight = srcRight; + _offRight = offRight; + + int depth = 0; + + if (srcLeft instanceof CharJoin) { + depth = ((CharJoin) srcLeft)._depth; + } + + if (srcRight instanceof CharJoin) { + int rightDepth = ((CharJoin) srcRight)._depth; + + if (rightDepth > depth) { + depth = rightDepth; + } + } + + _depth = depth + 1; + + assert _depth <= MAX_DEPTH + 2; + } + + private int cchRight(int off, int cch) { + return Math.max(0, cch - _cchLeft - off); + } + + public int depth() { + int depth = 0; + + if (_srcLeft instanceof CharJoin) { + depth = ((CharJoin) _srcLeft).depth(); + } + + if (_srcRight instanceof CharJoin) { + depth = Math.max(((CharJoin) _srcRight).depth(), depth); + } + + return depth + 1; + } + + public boolean isValid(int off, int cch) { + // Deep trees cause this to take forever + + if (_depth > 2) { + return true; + } + + assert _depth == depth(); + + if (off < 0 || cch < 0) { + return false; + } + + if (!CharUtil.isValid(_srcLeft, _offLeft, _cchLeft)) { + return false; + } + + return CharUtil.isValid(_srcRight, _offRight, cchRight(off, cch)); + } + + private void getString(StringBuffer sb, int off, int cch) { + assert cch > 0; + + if (off < _cchLeft) { + int cchL = Math.min(_cchLeft - off, cch); + + CharUtil.getString(sb, _srcLeft, _offLeft + off, cchL); + + if (cch > cchL) { + CharUtil.getString(sb, _srcRight, _offRight, cch - cchL); + } + } else { + CharUtil.getString(sb, _srcRight, _offRight + off - _cchLeft, cch); + } + } + + private void getChars(char[] chars, int start, int off, int cch) { + assert cch > 0; + + if (off < _cchLeft) { + int cchL = Math.min(_cchLeft - off, cch); + + CharUtil.getChars(chars, start, _srcLeft, _offLeft + off, cchL); + + if (cch > cchL) { + CharUtil.getChars(chars, start + cchL, _srcRight, _offRight, cch - cchL); + } + } else { + CharUtil.getChars(chars, start, _srcRight, _offRight + off - _cchLeft, cch); + } + } + + private void dumpChars(PrintStream p, int off, int cch) { + p.print("( "); + CharUtil.dumpChars(p, _srcLeft, _offLeft, _cchLeft); + p.print(", "); + CharUtil.dumpChars(p, _srcRight, _offRight, cchRight(off, cch)); + p.print(" )"); + } + + // + // + // + + public final Object _srcLeft; + public final int _offLeft; + public final int _cchLeft; + + public final Object _srcRight; + public final int _offRight; + + public final int _depth; + + static final int MAX_DEPTH = 64; + } + + // + // + // + + public final static class CharIterator { + public void init(Object src, int off, int cch) { + init(src, off, cch, 0); + } + + public void init(Object src, int off, int cch, int startPos) { + assert isValid(src, off, cch); + + release(); + + _srcRoot = src; + _offRoot = off; + _cchRoot = cch; + + _minPos = _maxPos = -1; + + movePos(startPos); + } + + public void release() { + _srcRoot = null; + _srcLeafString = null; + _srcLeafChars = null; + } + + public boolean hasNext() { + return _pos < _cchRoot; + } + + public boolean hasPrev() { + return _pos > 0; + } + + public char next() { + assert hasNext(); + + char ch = currentChar(); + + movePos(_pos + 1); + + return ch; + } + + public char prev() { + assert hasPrev(); + + movePos(_pos - 1); + + return currentChar(); + } + + public void movePos(int newPos) { + assert newPos >= 0 && newPos <= _cchRoot; + + if (newPos < _minPos || newPos > _maxPos) { + // if newPos out of cached leaf, recache new leaf + Object src = _srcRoot; + int off = _offRoot + newPos; + int cch = _cchRoot; + + for (_offLeaf = _offRoot; src instanceof CharJoin; ) { + CharJoin j = (CharJoin) src; + + if (off < j._cchLeft) { + src = j._srcLeft; + _offLeaf = j._offLeft; + off = off + j._offLeft; + cch = j._cchLeft; + } else { + src = j._srcRight; + _offLeaf = j._offRight; + off = off - (j._cchLeft - j._offRight); + cch = cch - j._cchLeft; + } + } + +// _offLeaf = off - Math.min( off - _offLeaf, newPos ); + _minPos = newPos - (off - _offLeaf); +// _maxPos = newPos + Math.min( _cchRoot - newPos, sizeof( src ) - off ); + _maxPos = _minPos + cch; + + if (newPos < _cchRoot) { + _maxPos--; + } + + // Cache the leaf src to avoid instanceof for every char + + _srcLeafChars = null; + _srcLeafString = null; + + if (src instanceof char[]) { + _srcLeafChars = (char[]) src; + } else { + _srcLeafString = (String) src; + } + + assert newPos >= _minPos && newPos <= _maxPos; + } + + _pos = newPos; + } + + private char currentChar() { + int i = _offLeaf + _pos - _minPos; + + return _srcLeafChars == null ? _srcLeafString.charAt(i) : _srcLeafChars[i]; + } + + private Object _srcRoot; // Original triple + private int _offRoot; + private int _cchRoot; + + private int _pos; // Current position + + private int _minPos; // Min/max poses for current cached leaf + private int _maxPos; + + private int _offLeaf; + + private String _srcLeafString; // Cached leaf - either a char[] or a string + private char[] _srcLeafChars; + } + + private static final int CHARUTIL_INITIAL_BUFSIZE = 1024 * 32; + private static final ThreadLocal> tl_charUtil = + ThreadLocal.withInitial(() -> new SoftReference<>(new CharUtil(CHARUTIL_INITIAL_BUFSIZE))); + + public static void clearThreadLocals() { + tl_charUtil.remove(); + } + + private final CharIterator _charIter = new CharIterator(); + + // TODO - 64 is kinda arbitrary. Perhaps it should be configurable. + private static final int MAX_COPY = 64; + + // Current char buffer we're allcoating new chars to + + private final int _charBufSize; + private int _currentOffset; + private char[] _currentBuffer; + + // These members are used to communicate offset and character count + // information back to a caller of various methods on CharUtil. + // Usually, the methods returns the src Object, and these two hold + // the offset and the char count. + + public int _offSrc; + public int _cchSrc; +} \ No newline at end of file diff --git a/src/main/java/org/apache/xmlbeans/impl/store/CommentXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/CommentXobj.java new file mode 100644 index 0000000..332b6b0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/CommentXobj.java @@ -0,0 +1,73 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.Comment; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import static org.apache.xmlbeans.impl.store.Cur.COMMENT; + +class CommentXobj extends NodeXobj implements Comment { + CommentXobj(Locale l) { + super(l, COMMENT, DomImpl.COMMENT); + } + + Xobj newNode(Locale l) { + return new CommentXobj(l); + } + + public NodeList getChildNodes() { + return DomImpl._emptyNodeList; + } + + public void appendData(String arg) { + DomImpl._characterData_appendData(this, arg); + } + + public void deleteData(int offset, int count) { + DomImpl._characterData_deleteData(this, offset, count); + } + + public String getData() { + return DomImpl._characterData_getData(this); + } + + public int getLength() { + return DomImpl._characterData_getLength(this); + } + + public Node getFirstChild() { + return null; + } + + public void insertData(int offset, String arg) { + DomImpl._characterData_insertData(this, offset, arg); + } + + public void replaceData(int offset, int count, String arg) { + DomImpl._characterData_replaceData(this, offset, count, arg); + } + + public void setData(String data) { + DomImpl._characterData_setData(this, data); + } + + public String substringData(int offset, int count) { + return DomImpl._characterData_substringData(this, offset, count); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Cur.java b/src/main/java/org/apache/xmlbeans/impl/store/Cur.java new file mode 100755 index 0000000..dfadc7d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Cur.java @@ -0,0 +1,3428 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.XmlCursor.XmlBookmark; +import org.apache.xmlbeans.impl.soap.*; +import org.apache.xmlbeans.impl.store.DomImpl.Dom; +import org.apache.xmlbeans.impl.store.Locale.LoadContext; +import org.apache.xmlbeans.impl.values.TypeStoreUser; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; + +import javax.xml.namespace.QName; +import java.io.PrintStream; +import java.util.Map; + +import static org.apache.xmlbeans.impl.values.TypeStore.WS_PRESERVE; + +// DOM Level 3 + + +public final class Cur { + static final int TEXT = 0; // Must be 0 + static final int ROOT = 1; + static final int ELEM = 2; + static final int ATTR = 3; + static final int COMMENT = 4; + static final int PROCINST = 5; + + static final int POOLED = 0; + static final int REGISTERED = 1; + static final int EMBEDDED = 2; + static final int DISPOSED = 3; + + static final int END_POS = -1; + static final int NO_POS = -2; + + Locale _locale; + + Xobj _xobj; + int _pos; + + int _state; + + String _id; + + Cur _nextTemp; + Cur _prevTemp; + int _tempFrame; + + Cur _next; + Cur _prev; + + Locale.Ref _ref; + + int _stackTop; + + int _selectionFirst; + int _selectionN; + int _selectionLoc; + int _selectionCount; + + private int _posTemp; + + int _offSrc; + int _cchSrc; + + + Cur(Locale l) { + _locale = l; + _pos = NO_POS; + + _tempFrame = -1; + + _state = POOLED; + + _stackTop = Locations.NULL; + _selectionFirst = -1; + _selectionN = -1; + _selectionLoc = Locations.NULL; + _selectionCount = 0; + } + + public boolean isPositioned() { + assert isNormal(); + return _xobj != null; + } + + static boolean kindIsContainer(int k) { + return k == ELEM || k == ROOT; + } + + static boolean kindIsFinish(int k) { + return k == -ELEM || k == -ROOT; + } + + public int kind() { + assert isPositioned(); + int kind = _xobj.kind(); + return _pos == 0 ? kind : (_pos == END_POS ? -kind : TEXT); + } + + public boolean isRoot() { + assert isPositioned(); + return _pos == 0 && _xobj.kind() == ROOT; + } + + public boolean isElem() { + assert isPositioned(); + return _pos == 0 && _xobj.kind() == ELEM; + } + + public boolean isAttr() { + assert isPositioned(); + return _pos == 0 && _xobj.kind() == ATTR; + } + + public boolean isComment() { + assert isPositioned(); + return _pos == 0 && _xobj.kind() == COMMENT; + } + + public boolean isProcinst() { + assert isPositioned(); + return _pos == 0 && _xobj.kind() == PROCINST; + } + + public boolean isText() { + assert isPositioned(); + return _pos > 0; + } + + public boolean isEnd() { + assert isPositioned(); + return _pos == END_POS && _xobj.kind() == ELEM; + } + + public boolean isEndRoot() { + assert isPositioned(); + return _pos == END_POS && _xobj.kind() == ROOT; + } + + public boolean isNode() { + assert isPositioned(); + return _pos == 0; + } + + public boolean isContainer() { + assert isPositioned(); + return _pos == 0 && kindIsContainer(_xobj.kind()); + } + + public boolean isFinish() { + assert isPositioned(); + return _pos == END_POS && kindIsContainer(_xobj.kind()); + } + + public boolean isUserNode() { + assert isPositioned(); + int k = kind(); + return k == ELEM || k == ROOT || (k == ATTR && !isXmlns()); + } + + public boolean isContainerOrFinish() { + assert isPositioned(); + + if (_pos != 0 && _pos != END_POS) { + return false; + } + + int kind = _xobj.kind(); + return kind == ELEM || kind == -ELEM || kind == ROOT || kind == -ROOT; + } + + public boolean isNormalAttr() { + return isNode() && _xobj.isNormalAttr(); + } + + public boolean isXmlns() { + return isNode() && _xobj.isXmlns(); + } + + public boolean isTextCData() { + return _xobj.hasBookmark(CDataBookmark.class, _pos); + } + + public QName getName() { + assert isNode() || isEnd(); + return _xobj._name; + } + + public String getLocal() { + return getName().getLocalPart(); + } + + public String getUri() { + return getName().getNamespaceURI(); + } + + public String getXmlnsPrefix() { + assert isXmlns(); + return _xobj.getXmlnsPrefix(); + } + + public String getXmlnsUri() { + assert isXmlns(); + return _xobj.getXmlnsUri(); + } + + public boolean isDomDocRoot() { + return isRoot() && _xobj.getDom() instanceof Document; + } + + public boolean isDomFragRoot() { + return isRoot() && _xobj.getDom() instanceof DocumentFragment; + } + + public int cchRight() { + assert isPositioned(); + return _xobj.cchRight(_pos); + } + + public int cchLeft() { + assert isPositioned(); + return _xobj.cchLeft(_pos); + } + + // + // Creation methods + // + + void createRoot() { + createDomDocFragRoot(); + } + + void createDomDocFragRoot() { + moveTo(new DocumentFragXobj(_locale)); + } + + void createDomDocumentRoot() { + moveTo(createDomDocumentRootXobj(_locale)); + } + + void createAttr(QName name) { + createHelper(new AttrXobj(_locale, name)); + } + + void createComment() { + createHelper(new CommentXobj(_locale)); + } + + void createProcinst(String target) { + createHelper(new ProcInstXobj(_locale, target)); + } + + void createElement(QName name) { + createElement(name, null); + } + + void createElement(QName name, QName parentName) { + createHelper(createElementXobj(_locale, name, parentName)); + } + + static Xobj createDomDocumentRootXobj(Locale l) { + return createDomDocumentRootXobj(l, false); + } + + static Xobj createDomDocumentRootXobj(Locale l, boolean fragment) { + Xobj xo; + + if (l._saaj == null) { + if (fragment) { + xo = new DocumentFragXobj(l); + } else { + xo = new DocumentXobj(l); + } + } else { + xo = new SoapPartDocXobj(l); + } + + if (l._ownerDoc == null) { + l._ownerDoc = xo.getDom(); + } + + return xo; + } + + static Xobj createElementXobj(Locale l, QName name, QName parentName) { + if (l._saaj == null) { + return new ElementXobj(l, name); + } + + Class c = l._saaj.identifyElement(name, parentName); + + if (c == SOAPElement.class) { + return new SoapElementXobj(l, name); + } + if (c == SOAPBody.class) { + return new SoapBodyXobj(l, name); + } + if (c == SOAPBodyElement.class) { + return new SoapBodyElementXobj(l, name); + } + if (c == SOAPEnvelope.class) { + return new SoapEnvelopeXobj(l, name); + } + if (c == SOAPHeader.class) { + return new SoapHeaderXobj(l, name); + } + if (c == SOAPHeaderElement.class) { + return new SoapHeaderElementXobj(l, name); + } + if (c == SOAPFaultElement.class) { + return new SoapFaultElementXobj(l, name); + } + if (c == Detail.class) { + return new DetailXobj(l, name); + } + if (c == DetailEntry.class) { + return new DetailEntryXobj(l, name); + } + if (c == SOAPFault.class) { + return new SoapFaultXobj(l, name); + } + + throw new IllegalStateException("Unknown SAAJ element class: " + c); + } + + private void createHelper(Xobj x) { + assert x._locale == _locale; + + // insert the new Xobj into an exisiting tree. + + if (isPositioned()) { + Cur from = tempCur(x, 0); + from.moveNode(this); + from.release(); + } + + moveTo(x); + } + + // + // General operations + // + + boolean isSamePos(Cur that) { + assert isNormal() && (that == null || that.isNormal()); + + return _xobj == that._xobj && _pos == that._pos; + } + + // is this just after the end of that (that must be the start of a node) + + boolean isJustAfterEnd(Cur that) { + assert isNormal() && that != null && that.isNormal() && that.isNode(); + + return that._xobj.isJustAfterEnd(_xobj, _pos); + } + + boolean isJustAfterEnd(Xobj x) { + return x.isJustAfterEnd(_xobj, _pos); + } + + boolean isAtEndOf(Cur that) { + assert that != null && that.isNormal() && that.isNode(); + + return _xobj == that._xobj && _pos == END_POS; + } + + boolean isInSameTree(Cur that) { + assert isPositioned() && that.isPositioned(); + + return _xobj.isInSameTree(that._xobj); + } + + // Retunr -1, 0 or 1 for relative cursor positions. Return 2 is not in sames trees. + + int comparePosition(Cur that) { + assert isPositioned() && that.isPositioned(); + + // If in differnet locales, then can't comapre + + if (_locale != that._locale) { + return 2; + } + + // No need to denormalize, but I want positions which I can compare (no END_POS) + + Xobj xThis = _xobj; + int pThis = _pos == END_POS ? xThis.posAfter() - 1 : _pos; + + Xobj xThat = that._xobj; + int pThat = that._pos == END_POS ? xThat.posAfter() - 1 : that._pos; + + // There are several cases: + // + // 1. Cursors are on the same xobj + // 2. One cursor is a child of the other + // 3. Cursors share a common parent + // 4. Cursors are not in the same trees + // + // Check for the first, trivial, case. Then, compute the depths of the nodes the + // cursors are on, checkin for case 2 + // + + if (xThis == xThat) { + return Integer.compare(pThis, pThat); + } + + // Compute the depth of xThis. See if I hit xThat (case 2) + + int dThis = 0; + + for (Xobj x = xThis._parent; x != null; x = x._parent) { + dThis++; + + if (x == xThat) { + return pThat < xThat.posAfter() - 1 ? 1 : -1; + } + } + + // Compute the depth of xThat. See if I hit xThis (case 2) + + int dThat = 0; + + for (Xobj x = xThat._parent; x != null; x = x._parent) { + dThat++; + + if (x == xThis) { + return pThis < xThis.posAfter() - 1 ? -1 : 1; + } + } + + // Must be case 3 or 4 now. Find a common parent. If none, then it's case 4 + + while (dThis > dThat) { + dThis--; + assert (xThis != null); + xThis = xThis._parent; + } + while (dThat > dThis) { + dThat--; + assert (xThat != null); + xThat = xThat._parent; + } + + assert dThat == dThis; + + if (dThat == 0) { + return 2; + } + + assert xThis != null && xThis._parent != null && xThat != null && xThat._parent != null; + + while (xThis._parent != xThat._parent) { + if ((xThis = xThis._parent) == null) { + return 2; + } + + xThat = xThat._parent; + } + + // Now, see where xThis and XThat are relative to eachother in the childlist. Apply + // some quick common checks before iterating. + + if (xThis._prevSibling == null || xThat._nextSibling == null) { + return -1; + } + + if (xThis._nextSibling == null || xThat._prevSibling == null) { + return 1; + } + + while (xThis != null) { + if ((xThis = xThis._prevSibling) == xThat) { + return 1; + } + } + + return -1; + } + + void setName(QName newName) { + assert isNode() && newName != null; + + _xobj.setName(newName); + } + + void moveTo(Xobj x) { + moveTo(x, 0); + } + + void moveTo(Xobj x, int p) { + // This cursor may not be normalized upon entry, don't assert isNormal() here + + assert x == null || _locale == x._locale; + assert x != null || p == NO_POS; + assert x == null || x.isNormal(p) || (x.isVacant() && x._cchValue == 0 && x._user == null); + assert _state == REGISTERED || _state == EMBEDDED; + assert _state == EMBEDDED || (_xobj == null || !isOnList(_xobj._embedded)); + assert _state == REGISTERED || (_xobj != null && isOnList(_xobj._embedded)); + + moveToNoCheck(x, p); + + assert isNormal() || (_xobj.isVacant() && _xobj._cchValue == 0 && _xobj._user == null); + } + + void moveToNoCheck(Xobj x, int p) { + if (_state == EMBEDDED && x != _xobj) { + _xobj._embedded = listRemove(_xobj._embedded); + _locale._registered = listInsert(_locale._registered); + _state = REGISTERED; + } + + _xobj = x; + _pos = p; + } + + void moveToCur(Cur to) { + assert isNormal() && (to == null || to.isNormal()); + + if (to == null) { + moveTo(null, NO_POS); + } else { + moveTo(to._xobj, to._pos); + } + } + + void moveToDom(Dom d) { + assert _locale == d.locale(); + assert d instanceof Xobj || d instanceof SoapPartDom; + + moveTo(d instanceof Xobj ? (Xobj) d : ((SoapPartDom) d)._docXobj); + } + + static final class Locations { + private static final int NULL = -1; + + Locations(Locale l) { + _locale = l; + + _xobjs = new Xobj[_initialSize]; + _poses = new int[_initialSize]; + _curs = new Cur[_initialSize]; + _next = new int[_initialSize]; + _prev = new int[_initialSize]; + _nextN = new int[_initialSize]; + _prevN = new int[_initialSize]; + + for (int i = _initialSize - 1; i >= 0; i--) { + assert _xobjs[i] == null; + _poses[i] = NO_POS; + _next[i] = i + 1; + _prev[i] = NULL; + _nextN[i] = NULL; + _prevN[i] = NULL; + } + + _next[_initialSize - 1] = NULL; + + _free = 0; + _naked = NULL; + } + + boolean isSamePos(int i, Cur c) { + if (_curs[i] == null) { + return c._xobj == _xobjs[i] && c._pos == _poses[i]; + } else { + return c.isSamePos(_curs[i]); + } + } + + boolean isAtEndOf(int i, Cur c) { + assert _curs[i] != null || _poses[i] == 0; + assert _curs[i] == null || _curs[i].isNode(); + + if (_curs[i] == null) { + return c._xobj == _xobjs[i] && c._pos == END_POS; + } else { + return c.isAtEndOf(_curs[i]); + } + } + + void moveTo(int i, Cur c) { + if (_curs[i] == null) { + c.moveTo(_xobjs[i], _poses[i]); + } else { + c.moveToCur(_curs[i]); + } + } + + int insert(int head, int before, int i) { + return insert(head, before, i, _next, _prev); + } + + int remove(int head, int i) { + Cur c = _curs[i]; + + assert c != null || _xobjs[i] != null; + assert c != null || _xobjs[i] != null; + + if (c != null) { + _curs[i].release(); + _curs[i] = null; + + assert _xobjs[i] == null; + assert _poses[i] == NO_POS; + } else { + assert _xobjs[i] != null && _poses[i] != NO_POS; + + _xobjs[i] = null; + _poses[i] = NO_POS; + + _naked = remove(_naked, i, _nextN, _prevN); + } + + head = remove(head, i, _next, _prev); + + _next[i] = _free; + _free = i; + + return head; + } + + int allocate(Cur addThis) { + assert addThis.isPositioned(); + + if (_free == NULL) { + makeRoom(); + } + + int i = _free; + + _free = _next[i]; + + _next[i] = NULL; + assert _prev[i] == NULL; + + assert _curs[i] == null; + assert _xobjs[i] == null; + assert _poses[i] == NO_POS; + + _xobjs[i] = addThis._xobj; + _poses[i] = addThis._pos; + + _naked = insert(_naked, NULL, i, _nextN, _prevN); + + return i; + } + + private static int insert(int head, int before, int i, int[] next, int[] prev) { + if (head == NULL) { + assert before == NULL; + prev[i] = i; + head = i; + } else if (before != NULL) { + prev[i] = prev[before]; + next[i] = before; + prev[before] = i; + + if (head == before) { + head = i; + } + } else { + prev[i] = prev[head]; + assert next[i] == NULL; + next[prev[head]] = i; + prev[head] = i; + } + + return head; + } + + private static int remove(int head, int i, int[] next, int[] prev) { + if (prev[i] == i) { + assert head == i; + head = NULL; + } else { + if (head == i) { + head = next[i]; + } else { + next[prev[i]] = next[i]; + } + + if (next[i] == NULL) { + prev[head] = prev[i]; + } else { + prev[next[i]] = prev[i]; + next[i] = NULL; + } + } + + prev[i] = NULL; + assert next[i] == NULL; + + return head; + } + + void notifyChange() { + for (int i; (i = _naked) != NULL; ) { + assert _curs[i] == null && _xobjs[i] != null && _poses[i] != NO_POS; + + _naked = remove(_naked, i, _nextN, _prevN); + + _curs[i] = _locale.getCur(); + _curs[i].moveTo(_xobjs[i], _poses[i]); + + _xobjs[i] = null; + _poses[i] = NO_POS; + } + } + + int next(int i) { + return _next[i]; + } + + int prev(int i) { + return _prev[i]; + } + + private void makeRoom() { + assert _free == NULL; + + int l = _xobjs.length; + + Xobj[] oldXobjs = _xobjs; + int[] oldPoses = _poses; + Cur[] oldCurs = _curs; + int[] oldNext = _next; + int[] oldPrev = _prev; + int[] oldNextN = _nextN; + int[] oldPrevN = _prevN; + + _xobjs = new Xobj[l * 2]; + _poses = new int[l * 2]; + _curs = new Cur[l * 2]; + _next = new int[l * 2]; + _prev = new int[l * 2]; + _nextN = new int[l * 2]; + _prevN = new int[l * 2]; + + System.arraycopy(oldXobjs, 0, _xobjs, 0, l); + System.arraycopy(oldPoses, 0, _poses, 0, l); + System.arraycopy(oldCurs, 0, _curs, 0, l); + System.arraycopy(oldNext, 0, _next, 0, l); + System.arraycopy(oldPrev, 0, _prev, 0, l); + System.arraycopy(oldNextN, 0, _nextN, 0, l); + System.arraycopy(oldPrevN, 0, _prevN, 0, l); + + for (int i = l * 2 - 1; i >= l; i--) { + _next[i] = i + 1; + _prev[i] = NULL; + _nextN[i] = NULL; + _prevN[i] = NULL; + _poses[i] = NO_POS; + } + + _next[l * 2 - 1] = NULL; + + _free = l; + } + + private static final int _initialSize = 32; + + private final Locale _locale; + + private Xobj[] _xobjs; + private int[] _poses; + private Cur[] _curs; + private int[] _next; + private int[] _prev; + private int[] _nextN; + private int[] _prevN; + + private int _free; // Unused entries + private int _naked; // Entries without Curs + } + + public void push() { + assert isPositioned(); + + int i = _locale._locations.allocate(this); + _stackTop = _locale._locations.insert(_stackTop, _stackTop, i); + } + + void popButStay() { + if (_stackTop != Locations.NULL) { + _stackTop = _locale._locations.remove(_stackTop, _stackTop); + } + } + + boolean pop() { + if (_stackTop == Locations.NULL) { + return false; + } + + _locale._locations.moveTo(_stackTop, this); + _stackTop = _locale._locations.remove(_stackTop, _stackTop); + + return true; + } + + boolean isAtLastPush() { + assert _stackTop != Locations.NULL; + + return _locale._locations.isSamePos(_stackTop, this); + } + + public boolean isAtEndOfLastPush() { + assert _stackTop != Locations.NULL; + + return _locale._locations.isAtEndOf(_stackTop, this); + } + + public void addToSelection(Cur that) { + assert that != null && that.isNormal(); + assert isPositioned() && that.isPositioned(); + + int i = _locale._locations.allocate(that); + _selectionFirst = _locale._locations.insert(_selectionFirst, Locations.NULL, i); + + _selectionCount++; + } + + public void addToSelection() { + assert isPositioned(); + + int i = _locale._locations.allocate(this); + _selectionFirst = _locale._locations.insert(_selectionFirst, Locations.NULL, i); + + _selectionCount++; + } + + private int selectionIndex(int i) { + assert _selectionN >= -1 && i >= 0 && i < _selectionCount; + + if (_selectionN == -1) { + _selectionN = 0; + _selectionLoc = _selectionFirst; + } + + while (_selectionN < i) { + _selectionLoc = _locale._locations.next(_selectionLoc); + _selectionN++; + } + + while (_selectionN > i) { + _selectionLoc = _locale._locations.prev(_selectionLoc); + _selectionN--; + } + + return _selectionLoc; + } + + void removeFirstSelection() { + final int i = 0; + assert i < _selectionCount; + + int j = selectionIndex(i); + + // Update the nth selection indices to accomodate the deletion + + if (i < _selectionN) { + _selectionN--; + } else if (i == _selectionN) { + _selectionN--; + _selectionLoc = Locations.NULL; + } + + _selectionFirst = _locale._locations.remove(_selectionFirst, j); + + _selectionCount--; + } + + public int selectionCount() { + return _selectionCount; + } + + public void moveToSelection(int i) { + assert i >= 0 && i < _selectionCount; + + _locale._locations.moveTo(selectionIndex(i), this); + } + + public void clearSelection() { + assert _selectionCount >= 0; + + while (_selectionCount > 0) { + removeFirstSelection(); + } + } + + public boolean toParent() { + return toParent(false); + } + + public boolean toParentRaw() { + return toParent(true); + } + + public Xobj getParent() { + return getParent(false); + } + + public Xobj getParentRaw() { + return getParent(true); + } + + public boolean hasParent() { + assert isPositioned(); + + if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) { + return true; + } + + assert _pos == 0 || _xobj._parent != null; + + return _xobj._parent != null; + } + + public Xobj getParentNoRoot() { + assert isPositioned(); + + if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) { + return _xobj; + } + + assert _pos == 0 || _xobj._parent != null; + + if (_xobj._parent != null) { + return _xobj._parent; + } + + return null; + } + + public Xobj getParent(boolean raw) { + assert isPositioned(); + + if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) { + return _xobj; + } + + assert _pos == 0 || _xobj._parent != null; + + if (_xobj._parent != null) { + return _xobj._parent; + } + + if (raw || _xobj.isRoot()) { + return null; + } + + Cur r = _locale.tempCur(); + + r.createRoot(); + + Xobj root = r._xobj; + + r.next(); + moveNode(r); + r.release(); + + return root; + } + + public boolean toParent(boolean raw) { + Xobj parent = getParent(raw); + + if (parent == null) { + return false; + } + + moveTo(parent); + + return true; + } + + public void toRoot() { + Xobj xobj = _xobj; + while (!xobj.isRoot()) { + if (xobj._parent == null) { + Cur r = _locale.tempCur(); + + r.createRoot(); + + Xobj root = r._xobj; + + r.next(); + moveNode(r); + r.release(); + + xobj = root; + break; + } + xobj = xobj._parent; + } + moveTo(xobj); + } + + public boolean hasText() { + assert isNode(); + + return _xobj.hasTextEnsureOccupancy(); + } + + public boolean hasAttrs() { + assert isNode(); + + return _xobj.hasAttrs(); + } + + public boolean hasChildren() { + assert isNode(); + + return _xobj.hasChildren(); + } + + public boolean toFirstChild() { + assert isNode(); + + if (!_xobj.hasChildren()) { + return false; + } + + for (Xobj x = _xobj._firstChild; ; x = x._nextSibling) { + if (!x.isAttr()) { + moveTo(x); + return true; + } + } + } + + public boolean toLastChild() { + assert isNode(); + + if (!_xobj.hasChildren()) { + return false; + } + + moveTo(_xobj._lastChild); + + return true; + } + + public boolean toNextSibling() { + assert isNode(); + + if (_xobj.isAttr()) { + if (_xobj._nextSibling != null && _xobj._nextSibling.isAttr()) { + moveTo(_xobj._nextSibling); + return true; + } + } else if (_xobj._nextSibling != null) { + moveTo(_xobj._nextSibling); + return true; + } + + return false; + } + + public void setValueAsQName(QName qname) { + assert isNode(); + + String value = qname.getLocalPart(); + String ns = qname.getNamespaceURI(); + + String prefix = + prefixForNamespace( + ns, qname.getPrefix().length() > 0 ? qname.getPrefix() : null, true); + + if (prefix.length() > 0) { + value = prefix + ":" + value; + } + + setValue(value); + } + + public void setValue(String value) { + assert isNode(); + + moveNodeContents(null, false); + + next(); + + insertString(value); + + toParent(); + } + + public void removeFollowingAttrs() { + assert isAttr(); + + QName attrName = getName(); + + push(); + + if (toNextAttr()) { + while (isAttr()) { + if (getName().equals(attrName)) { + moveNode(null); + } else if (!toNextAttr()) { + break; + } + } + } + + pop(); + } + + public String getAttrValue(QName name) { + String s = null; + + push(); + + if (toAttr(name)) { + s = getValueAsString(); + } + + pop(); + + return s; + } + + public void setAttrValueAsQName(QName value) { + assert isContainer(); + + final QName name = Locale._xsiType; + + if (value == null) { + _xobj.removeAttr(name); + return; + } + + if (toAttr(name)) { + removeFollowingAttrs(); + } else { + next(); + createAttr(name); + } + setValueAsQName(value); + toParent(); + } + + public boolean removeAttr(QName name) { + assert isContainer(); + + return _xobj.removeAttr(name); + } + + public void setAttrValue(QName name, String value) { + assert isContainer(); + + _xobj.setAttr(name, value); + } + + public boolean toAttr(QName name) { + assert isNode(); + + Xobj a = _xobj.getAttr(name); + + if (a == null) { + return false; + } + + moveTo(a); + + return true; + } + + public boolean toFirstAttr() { + assert isNode(); + + Xobj firstAttr = _xobj.firstAttr(); + + if (firstAttr == null) { + return false; + } + + moveTo(firstAttr); + + return true; + } + + public boolean toLastAttr() { + assert isNode(); + + if (!toFirstAttr()) { + return false; + } + + //noinspection StatementWithEmptyBody + while (toNextAttr()) { + } + + return true; + } + + public boolean toNextAttr() { + assert isAttr() || isContainer(); + + Xobj nextAttr = _xobj.nextAttr(); + + if (nextAttr == null) { + return false; + } + + moveTo(nextAttr); + + return true; + } + + @SuppressWarnings("UnusedReturnValue") + public boolean toPrevAttr() { + if (isAttr()) { + if (_xobj._prevSibling == null) { + moveTo(_xobj.ensureParent()); + } else { + moveTo(_xobj._prevSibling); + } + + return true; + } + + prev(); + + if (!isContainer()) { + next(); + return false; + } + + return toLastAttr(); + } + + @SuppressWarnings("UnusedReturnValue") + public boolean skipWithAttrs() { + assert isNode(); + + if (skip()) { + return true; + } + + if (_xobj.isRoot()) { + return false; + } + + assert _xobj.isAttr(); + + toParent(); + + next(); + + return true; + } + + public boolean skip() { + assert isNode(); + + if (_xobj.isRoot()) { + return false; + } + + if (_xobj.isAttr()) { + if (_xobj._nextSibling == null || !_xobj._nextSibling.isAttr()) { + return false; + } + + moveTo(_xobj._nextSibling, 0); + } else { + moveTo(getNormal(_xobj, _xobj.posAfter()), _posTemp); + } + + return true; + } + + public void toEnd() { + assert isNode(); + + moveTo(_xobj, END_POS); + } + + public void moveToCharNode(CharNode node) { + assert node.getDom() != null && node.getDom().locale() == _locale; + + moveToDom(node.getDom()); + + CharNode n; + + _xobj.ensureOccupancy(); + + n = _xobj._charNodesValue = + updateCharNodes(_locale, _xobj, _xobj._charNodesValue, _xobj._cchValue); + + for (; n != null; n = n._next) { + if (node == n) { + moveTo(getNormal(_xobj, n._off + 1), _posTemp); + return; + } + } + + n = _xobj._charNodesAfter = + updateCharNodes(_locale, _xobj, _xobj._charNodesAfter, _xobj._cchAfter); + + for (; n != null; n = n._next) { + if (node == n) { + moveTo(getNormal(_xobj, n._off + _xobj._cchValue + 2), _posTemp); + return; + } + } + + assert false; + } + + @SuppressWarnings("UnusedReturnValue") + public boolean prevWithAttrs() { + if (prev()) { + return true; + } + + if (!isAttr()) { + return false; + } + + toParent(); + + return true; + } + + public boolean prev() { + assert isPositioned(); + + if (_xobj.isRoot() && _pos == 0) { + return false; + } + + if (_xobj.isAttr() && _pos == 0 && _xobj._prevSibling == null) { + return false; + } + + Xobj x = getDenormal(); + int p = _posTemp; + + assert p > 0; + + int pa = x.posAfter(); + + if (p > pa) { + p = pa; + } else if (p == pa) { + // Text after an attr is allowed only on the last attr, + // and that text belongs to the parent container.. + // + // If we're a thte end of the last attr, then we were just + // inside the container, and we need to skip the attrs. + + if (x.isAttr() && + (x._cchAfter > 0 || x._nextSibling == null || !x._nextSibling.isAttr())) { + x = x.ensureParent(); + p = 0; + } else { + p = END_POS; + } + } else if (p == pa - 1) { + x.ensureOccupancy(); + p = x._cchValue > 0 ? 1 : 0; + } else if (p > 1) { + p = 1; + } else { + //noinspection ConstantConditions + assert p == 1; + p = 0; + } + + moveTo(getNormal(x, p), _posTemp); + + return true; + } + + @SuppressWarnings("UnusedReturnValue") + public boolean next(boolean withAttrs) { + return withAttrs ? nextWithAttrs() : next(); + } + + public boolean nextWithAttrs() { + int k = kind(); + + if (kindIsContainer(k)) { + if (toFirstAttr()) { + return true; + } + } else if (k == -ATTR) { + if (next()) { + return true; + } + + toParent(); + + if (!toParentRaw()) { + return false; + } + } + + return next(); + } + + public boolean next() { + assert isNormal(); + + Xobj x = _xobj; + int p = _pos; + + int pa = x.posAfter(); + + if (p >= pa) { + p = _xobj.posMax(); + } else if (p == END_POS) { + if (x.isRoot() || (x.isAttr() && (x._nextSibling == null || !x._nextSibling.isAttr()))) { + return false; + } + + p = pa; + } else if (p > 0) { + assert x._firstChild == null || !x._firstChild.isAttr(); + + if (x._firstChild != null) { + x = x._firstChild; + p = 0; + } else { + p = END_POS; + } + } else { + assert p == 0; + + x.ensureOccupancy(); + + p = 1; + + if (x._cchValue == 0) { + if (x._firstChild != null) { + if (x._firstChild.isAttr()) { + Xobj a = x._firstChild; + + while (a._nextSibling != null && a._nextSibling.isAttr()) { + a = a._nextSibling; + } + + if (a._cchAfter > 0) { + x = a; + p = a.posAfter(); + } else if (a._nextSibling != null) { + x = a._nextSibling; + p = 0; + } + } else { + x = x._firstChild; + p = 0; + } + } + } + } + + moveTo(getNormal(x, p), _posTemp); + + return true; + } + + int prevChars(int cch) { + assert isPositioned(); + + int cchLeft = cchLeft(); + + if (cch < 0 || cch > cchLeft) { + cch = cchLeft; + } + + // Dang, I love this stmt :-) + + if (cch != 0) { + moveTo(getNormal(getDenormal(), _posTemp - cch), _posTemp); + } + + return cch; + } + + int nextChars(int cch) { + assert isPositioned(); + + int cchRight = cchRight(); + + if (cchRight == 0) { + return 0; + } + + if (cch < 0 || cch >= cchRight) { + // Use next to not skip over children + next(); + return cchRight; + } + + moveTo(getNormal(_xobj, _pos + cch), _posTemp); + + return cch; + } + + void setCharNodes(CharNode nodes) { + assert nodes == null || _locale == nodes.locale(); + assert isPositioned(); + + Xobj x = getDenormal(); + int p = _posTemp; + + assert !x.isRoot() || (p > 0 && p < x.posAfter()); + + if (p >= x.posAfter()) { + x._charNodesAfter = nodes; + } else { + x._charNodesValue = nodes; + } + + for (; nodes != null; nodes = nodes._next) { + nodes.setDom((Dom) x); + } + + // No Need to notify text change or alter version, text nodes are + // not part of the infoset + } + + CharNode getCharNodes() { + assert isPositioned(); + assert !isRoot(); + + Xobj x = getDenormal(); + + CharNode nodes; + + if (_posTemp >= x.posAfter()) { + nodes = x._charNodesAfter = + updateCharNodes(_locale, x, x._charNodesAfter, x._cchAfter); + } else { + x.ensureOccupancy(); + + nodes = x._charNodesValue = + updateCharNodes(_locale, x, x._charNodesValue, x._cchValue); + } + + return nodes; + } + + // private + static CharNode updateCharNodes(Locale l, Xobj x, CharNode nodes, int cch) { + assert nodes == null || nodes.locale() == l; + + CharNode node = nodes; + int i = 0; + + while (node != null && cch > 0) { + assert node.getDom() == x; + + if (node._cch > cch) { + node._cch = cch; + } + + node._off = i; + i += node._cch; + cch -= node._cch; + + node = node._next; + } + + if (cch <= 0) { + for (; node != null; node = node._next) { + assert node.getDom() == x; + + if (node._cch != 0) { + node._cch = 0; + } + + node._off = i; + } + } else { + node = l.createTextNode(); + node.setDom((Dom) x); + node._cch = cch; + node._off = i; + nodes = CharNode.appendNode(nodes, node); + } + + return nodes; + } + + final QName getXsiTypeName() { + assert isNode(); + + return _xobj.getXsiTypeName(); + } + + final void setXsiType(QName value) { + assert isContainer(); + + setAttrValueAsQName(value); + } + + final String namespaceForPrefix(String prefix, boolean defaultAlwaysMapped) { + return _xobj.namespaceForPrefix(prefix, defaultAlwaysMapped); + } + + final String prefixForNamespace(String ns, String suggestion, boolean createIfMissing) { + return + (isContainer() ? _xobj : getParent()). + prefixForNamespace(ns, suggestion, createIfMissing); + } + + // Does the node at this cursor properly contain the position specified by the argument + + boolean contains(Cur that) { + assert isNode(); + assert that != null && that.isPositioned(); + + return _xobj.contains(that); + } + + void insertString(String s) { + if (s != null) { + insertChars(s, 0, s.length()); + } + } + + void insertChars(Object src, int off, int cch) { + assert isPositioned() && !isRoot(); + assert CharUtil.isValid(src, off, cch); + + // Check for nothing to insert + + if (cch <= 0) { + return; + } + + _locale.notifyChange(); + + // The only situation where I need to ensure occupancy is when I'm at the end of a node. + // All other positions will require occupancy. For example, if I'm at the beginning of a + // node, then I will either insert in the after text of the previous sibling, or I will + // insert in the value of the parent. In the latter case, because the parent has a child, + // it cannot be vacant. + + if (_pos == END_POS) { + _xobj.ensureOccupancy(); + } + + // Get the denormailized Xobj and pos. This is the Xobj which will actually receive + // the new chars. Note that a denormalized position can never be <= 0. + + Xobj x = getDenormal(); + int p = _posTemp; + + assert p > 0; + + // This will move "this" cursor to be after the inserted text. No worries, I'll update its + // position after. This insertChars takes care of all the appropriate invalidations + // (passing true as last arg). + + x.insertCharsHelper(p, src, off, cch, true); + + // Reposition the cursor to be just before the newly inserted text. It's current + // position could have been shifted, or it may have been just before the end tag, or + // normalized on another Xobj. + + moveTo(x, p); + + _locale._versionAll++; + } + + // Move the chars just after this Cur to the "to" Cur. If no "to" Cur is specified, + // then remove the chars. + + Object moveChars(Cur to, int cchMove) { + assert isPositioned(); + assert cchMove <= 0 || cchMove <= cchRight(); + assert to == null || (to.isPositioned() && !to.isRoot()); + + if (cchMove < 0) { + cchMove = cchRight(); + } + + // If we're instructed to move 0 characters, then return the null triple. + + if (cchMove == 0) { + _offSrc = 0; + _cchSrc = 0; + + return null; + } + + // Here I record the triple of the chars to move. I will return this. No need to save + // cch 'cause cchMove will be that value. + + Object srcMoved = getChars(cchMove); + int offMoved = _offSrc; + + // Either I'm moving text from the value or the after text. If after, then the container + // must be occupied. If in the value, because we're just before text, it must be occupied. + + assert isText() && (_pos >= _xobj.posAfter() ? _xobj._parent : _xobj).isOccupied(); + + if (to == null) { + // In this case, I'm removing chars vs moving them. Normally I would like to blow + // them away entirely, but if there are any references to those chars via a bookmark + // I need to keep them alive. I do this by moving these chars to a new root. Note + // that because Curs will stay behind, I don't have to check for them. + + for (Bookmark b = _xobj._bookmarks; b != null; b = b._next) { + if (inChars(b, cchMove, false)) { + Cur c = _locale.tempCur(); + + c.createRoot(); + c.next(); + + Object chars = moveChars(c, cchMove); + + c.release(); + + return chars; + } + } + } else { + // If the target, "to", is inside or on the edge of the text to be moved, then this + // is a no-op. In this case, I still want to return the text "moved". + // + // Note how I move "to" and this cur around. I move "to" to be at the beginning of the + // chars moved and "this" to be at the end. If the text were really moving to a + // different location, then "to" would be at the beginning of the newly moved chars, + // and "this" would be at the gap left by the newly removed chars. + + if (inChars(to, cchMove, true)) { + // BUGBUG - may want to consider shuffling the interior cursors to the right just + // like I move "this" to the right... + + to.moveToCur(this); + nextChars(cchMove); + + _offSrc = offMoved; + _cchSrc = cchMove; + + return srcMoved; + } + + // Copy the chars here, I'll remove the originals next + + to.insertChars(srcMoved, offMoved, cchMove); + } + + // Notice that I can delay the general change notification to this point because any + // modifications up to this point are made by calling other high level operations which + // generate this notification themselves. Also, no need to notify of general change in + // the "to" locale because the insertion of chars above handles that. + + _locale.notifyChange(); + + // + //if ( _xobj != null ) + { + if (to == null) { + _xobj.removeCharsHelper(_pos, cchMove, null, NO_POS, false, true); + } else { + _xobj.removeCharsHelper(_pos, cchMove, to._xobj, to._pos, false, true); + } + } + + // Need to update the position of this cursor even though it did not move anywhere. This + // needs to happen because it may not be properly normalized anymore. Note that because + // of the removal of the text, this cur may not be normal any more, thus I call moveTo + // which does not assume this. + + _locale._versionAll++; + + _offSrc = offMoved; + _cchSrc = cchMove; + + return srcMoved; + } + + void moveNode(Cur to) { + assert isNode() && !isRoot(); + assert to == null || to.isPositioned(); + assert to == null || !contains(to); + assert to == null || !to.isRoot(); + + // TODO - should assert that is an attr is being moved, it is ok there + + + // Record the node to move and skip this cur past it. This moves this cur to be after + // the move to move/remove -- it's final resting place. The only piece of information + // about the source of the move is the node itself. + + Xobj x = _xobj; + + skip(); + + // I call another function here to move the node. I do this because I don't have to + // worry about messing with "this" here given that it not should be treated like any other + // cursor after this point. + + moveNode(x, to); + } + + // Moves text from one place to another in a low-level way, used as a helper for the higher + // level functions. Takes care of moving bookmarks and cursors. In the high level content + // manipulation functions, cursors do not follow content, but this helper moves them. The + // arguments are denormalized. The Xobj's must be different from eachother but from the same + // locale. The destination must not be not be vacant. + + private static void transferChars(Xobj xFrom, int pFrom, Xobj xTo, int pTo, int cch) { + assert xFrom != xTo; + assert xFrom._locale == xTo._locale; + assert pFrom > 0 && pFrom < xFrom.posMax(); + assert pTo > 0 && pTo <= xTo.posMax(); + assert cch > 0 && cch <= xFrom.cchRight(pFrom); + assert pTo >= xTo.posAfter() || xTo.isOccupied(); + + // Copy the chars from -> to without performing any invalidations. This will scoot curs + // and marks around appropriately. Note that I get the cars with getCharsHelper which + // does not check for normalization because the state of the tree at this moment may not + // exactly be "correct" here. + + xTo.insertCharsHelper( + pTo, xFrom.getCharsHelper(pFrom, cch), + xFrom._locale._offSrc, xFrom._locale._cchSrc, false); + + xFrom.removeCharsHelper(pFrom, cch, xTo, pTo, true, false); + } + + // Moves the node x to "to", or removes it if to is null. + + static void moveNode(Xobj x, Cur to) { + assert x != null && !x.isRoot(); + assert to == null || to.isPositioned(); + assert to == null || !x.contains(to); + assert to == null || !to.isRoot(); + + if (to != null) { + // Before I go much further, I want to make sure that if "to" is in the container of + // a vacant node, I get it occupied. I do not need to worry about the source being + // vacant. + + if (to._pos == END_POS) { + to._xobj.ensureOccupancy(); + } + + // See if the destination is on the edge of the node to be moved (a no-op). It is + // illegal to call this fcn when to is contained within the node to be moved. Note + // that I make sure that to gets oved to the beginning of the node. The position of + // to in all operations should leave to just before the content moved/inserted. + + if ((to._pos == 0 && to._xobj == x) || to.isJustAfterEnd(x)) { + // TODO - should shuffle contained curs to the right??? + + to.moveTo(x); + return; + } + } + + // Notify the locale(s) about the change I am about to make. + + x._locale.notifyChange(); + + x._locale._versionAll++; + x._locale._versionSansText++; + + if (to != null && to._locale != x._locale) { + to._locale.notifyChange(); + + to._locale._versionAll++; + to._locale._versionSansText++; + } + + // Node is going away. Invalidate the parent (the text around the node is merging). + // Also, this node may be an attribute -- invalidate special attrs ... + + if (x.isAttr()) { + x.invalidateSpecialAttr(to == null ? null : to.getParentRaw()); + } else { + if (x._parent != null) { + x._parent.invalidateUser(); + } + + if (to != null && to.hasParent()) { + to.getParent().invalidateUser(); + } + } + + // If there is any text after x, I move it to be before x. This frees me to extract x + // and it's contents with out this text coming along for the ride. Note that if this + // node is the last attr and there is text after it, transferText will move the text + // to a potential previous attr. This is an invalid state for a short period of time. + // I need to move this text away here so that when I walk the tree next, *all* curs + // embedded in this node or deeper will be moved off this node. + + if (x._cchAfter > 0) { + transferChars(x, x.posAfter(), x.getDenormal(0), x.posTemp(), x._cchAfter); + } + + assert x._cchAfter == 0; + + // Walk the node tree, moving curs out, disconnecting users and relocating to a, possibly, + // new locale. I embed the cursors in this locale before itersting to just cause the + // embed to happen once. + + x._locale.embedCurs(); + + for (Xobj y = x; y != null; y = y.walk(x, true)) { + while (y._embedded != null) { + y._embedded.moveTo(x.getNormal(x.posAfter())); + } + + y.disconnectUser(); + + if (to != null) { + y._locale = to._locale; + } + } + + // Now, actually remove the node + + x.removeXobj(); + + // Now, if there is a destination, insert the node there and shuffle the text in the + // vicinity of the destination appropriately. + + if (to != null) { + // To know where I should insert/append the node to move, I need to see where "to" + // would be if there were no text after it. However, I need to keep "to" where it + // is when I move the text after it later. + + Xobj here = to._xobj; + boolean append = to._pos != 0; + + int cchRight = to.cchRight(); + + if (cchRight > 0) { + to.push(); + to.next(); + here = to._xobj; + append = to._pos != 0; + to.pop(); + } + + if (append) { + here.appendXobj(x); + } else { + here.insertXobj(x); + } + + // The only text I need to move is that to the right of "to". Even considering all + // the cases where an attribute is involed! + + if (cchRight > 0) { + transferChars(to._xobj, to._pos, x, x.posAfter(), cchRight); + } + + to.moveTo(x); + } + } + + void moveNodeContents(Cur to, boolean moveAttrs) { + assert _pos == 0; + assert to == null || !to.isRoot(); + + // By calling this helper, I do not have to deal with this Cur any longer. Basically, + // this Cur is out of the picture, it behaves like any other cur at this point. + + moveNodeContents(_xobj, to, moveAttrs); + } + + static void moveNodeContents(Xobj x, Cur to, boolean moveAttrs) { + // TODO - should assert that is an attr is being moved, it is ok there + + assert to == null || !to.isRoot(); + + // Collect a bit of information about the contents to move first. Note that the collection + // of this info must not cause a vacant value to become occupied. + + boolean hasAttrs = x.hasAttrs(); + boolean noSubNodesToMove = !x.hasChildren() && (!moveAttrs || !hasAttrs); + + // Deal with the cases where only text is involved in the move + + if (noSubNodesToMove) { + // If we're vacant and there is no place to move a potential value, then I can avoid + // acquiring the text from the TypeStoreUser. Otherwise, there may be text here I + // need to move somewhere else. + + if (x.isVacant() && to == null) { + x.clearBit(Xobj.VACANT); + + x.invalidateUser(); + x.invalidateSpecialAttr(null); + x._locale._versionAll++; + } else if (x.hasTextEnsureOccupancy()) { + Cur c = x.tempCur(); + c.next(); + c.moveChars(to, -1); + c.release(); + } + + return; + } + + // Here I check to see if "to" is just inside x. In this case this is a no-op. Note that + // the value of x may still be vacant. + + if (to != null) { + // Quick check of the right edge. If it is there, I need to move "to" to the left edge + // so that it is positioned at the beginning of the "moved" content. + + if (x == to._xobj && to._pos == END_POS) { + // TODO - shuffle interior curs? + + to.moveTo(x); + to.next(moveAttrs && hasAttrs); + + return; + } + + // Here I need to see if to is at the left edge. I push to's current position and + // then navigate it to the left edge then compare it to the pushed position... + // Note: gotta be careful to make sure to and x are not in different locales, curs + // may not go to a different locale. + + boolean isAtLeftEdge = false; + + if (to._locale == x._locale) { + to.push(); + to.moveTo(x); + to.next(moveAttrs && hasAttrs); + isAtLeftEdge = to.isAtLastPush(); + to.pop(); + } + + // TODO - shuffle interior curs? + + if (isAtLeftEdge) { + return; + } + + // Now, after dealing with the edge condition, I can assert that to is not inside x + + assert !x.contains(to); + + // So, at this point, I've taken case of the no-op cases and the movement of just text. + // Also, to must be occupied because I took care of the text only and nothing to move + // cases. + + assert to.getParent().isOccupied(); + } + + // TODO - did I forget to put a changeNotification here? Look more closely ... + + // Deal with the value text of x which is either on x or the last attribute of x. + // I need to get it out of the way to properly deal with the walk of the contents. + // In order to reposition "to" properly later, I need to record how many chars were moved. + + int valueMovedCch = 0; + + if (x.hasTextNoEnsureOccupancy()) { + Cur c = x.tempCur(); + c.next(); + c.moveChars(to, -1); + c.release(); + + if (to != null) { + to.nextChars(valueMovedCch = c._cchSrc); + } + } + + // Now, walk all the contents, invalidating special attrs, reportioning cursors, + // disconnecting users and relocating to a potentially different locale. Because I moved + // the value text above, no top level attrs should have any text. + + x._locale.embedCurs(); + + Xobj firstToMove = x.walk(x, true); + boolean sawBookmark = false; + + for (Xobj y = firstToMove; y != null; y = y.walk(x, true)) { + if (y._parent == x && y.isAttr()) { + assert y._cchAfter == 0; + + if (!moveAttrs) { + firstToMove = y._nextSibling; + continue; + } + + y.invalidateSpecialAttr(to == null ? null : to.getParent()); + } + + for (Cur c; (c = y._embedded) != null; ) { + c.moveTo(x, END_POS); + } + + y.disconnectUser(); + + if (to != null) { + y._locale = to._locale; + } + + sawBookmark = sawBookmark || y._bookmarks != null; + } + + Xobj lastToMove = x._lastChild; + + // If there were any bookmarks in the tree to remove, to preserve the content that these + // bookmarks reference, move the contents to a new root. Note that I already moved the + // first piece of text above elsewhere. Note: this has the effect of keeping all of the + // contents alive even if there is one bookmark deep into the tree. I should really + // disband all the content, except for the pieces which are bookmarked. + + Cur surragateTo = null; + + if (sawBookmark && to == null) { + surragateTo = to = x._locale.tempCur(); + to.createRoot(); + to.next(); + } + + // Perform the rest of the invalidations. If only attrs are moving, then no user + // invalidation needed. If I've move text to "to" already, no need to invalidate + // again. + + if (!lastToMove.isAttr()) { + x.invalidateUser(); + } + + x._locale._versionAll++; + x._locale._versionSansText++; + + if (to != null && valueMovedCch == 0) { + to.getParent().invalidateUser(); + to._locale._versionAll++; + to._locale._versionSansText++; + } + + // Remove the children and, if needed, move them + + x.removeXobjs(firstToMove, lastToMove); + + if (to != null) { + // To know where I should insert/append the contents to move, I need to see where "to" + // would be if there were no text after it. + + Xobj here = to._xobj; + boolean append = to._pos != 0; + + int cchRight = to.cchRight(); + + if (cchRight > 0) { + to.push(); + to.next(); + here = to._xobj; + append = to._pos != 0; + to.pop(); + } + + // Now, I have to shuffle the text around "to" in special ways. A complication is + // the insertion of attributes. First, if I'm inserting attrs here then, logically, + // there can be no text to the left because attrs can only live after another attr + // or just inside a container. So, If attrs are being inserted and there is value + // text on the target container, I will need to move this value text to be after + // the lew last attribute. Note that this value text may already live on a current + // last attr (before the inserting). Also, I need to figure this all out before I + // move the text after "to" because this text may end up being sent to the same place + // as the containers value text when the last new node being inserted is an attr! + // Whew! + + if (firstToMove.isAttr()) { + Xobj lastNewAttr = firstToMove; + + while (lastNewAttr._nextSibling != null && lastNewAttr._nextSibling.isAttr()) { + lastNewAttr = lastNewAttr._nextSibling; + } + + // Get to's parnet now before I potentially move him with the next transfer + + Xobj y = to.getParent(); + + if (cchRight > 0) { + transferChars(to._xobj, to._pos, lastNewAttr, lastNewAttr.posMax(), cchRight); + } + + if (y.hasTextNoEnsureOccupancy()) { + int p, cch; + + if (y._cchValue > 0) { + p = 1; + cch = y._cchValue; + } else { + y = y.lastAttr(); + assert (y != null); + p = y.posAfter(); + cch = y._cchAfter; + } + + transferChars(y, p, lastNewAttr, lastNewAttr.posAfter(), cch); + } + } else if (cchRight > 0) { + transferChars(to._xobj, to._pos, lastToMove, lastToMove.posMax(), cchRight); + } + + // After mucking with the text, splice the new tree in + + if (append) { + here.appendXobjs(firstToMove, lastToMove); + } else { + here.insertXobjs(firstToMove, lastToMove); + } + + // Position "to" to be at the beginning of the newly inserted contents + + to.moveTo(firstToMove); + to.prevChars(valueMovedCch); + } + + // If I consed up a to, release it here + + if (surragateTo != null) { + surragateTo.release(); + } + } + + protected final Bookmark setBookmark(Object key, Object value) { + assert isNormal(); + assert key != null; + + return _xobj.setBookmark(_pos, key, value); + } + + Object getBookmark(Object key) { + assert isNormal(); + assert key != null; + + for (Bookmark b = _xobj._bookmarks; b != null; b = b._next) { + if (b._pos == _pos && b._key == key) { + return b._value; + } + } + + return null; + } + + int firstBookmarkInChars(Object key, int cch) { + assert isNormal(); + assert key != null; + assert cch > 0; + assert cch <= cchRight(); + + int d = -1; + + if (isText()) { + for (Bookmark b = _xobj._bookmarks; b != null; b = b._next) { + if (b._key == key && inChars(b, cch, false)) { + d = (d == -1 || b._pos - _pos < d) ? b._pos - _pos : d; + } + } + } + + return d; + } + + int firstBookmarkInCharsLeft(Object key, int cch) { + assert isNormal(); + assert key != null; + assert cch > 0; + assert cch <= cchLeft(); + + int d = -1; + + if (cchLeft() > 0) { + Xobj x = getDenormal(); + int p = _posTemp - cch; + + for (Bookmark b = x._bookmarks; b != null; b = b._next) { + if (b._key == key && x.inChars(p, b._xobj, b._pos, cch, false)) { + d = (d == -1 || b._pos - p < d) ? b._pos - p : d; + } + } + } + + return d; + } + + String getCharsAsString() { + assert isNormal() && _xobj != null; + + return getCharsAsString(WS_PRESERVE); + } + + String getCharsAsString(int wsr) { + return _xobj.getCharsAsString(_pos, -1, wsr); + } + + String getValueAsString(int wsr) { + assert isNode(); + + return _xobj.getValueAsString(wsr); + } + + String getValueAsString() { + assert isNode(); + assert !hasChildren(); + + return _xobj.getValueAsString(); + } + + Object getChars(int cch) { + assert isPositioned(); + + return _xobj.getChars(_pos, cch, this); + } + + Object getFirstChars() { + assert isNode(); + + Object src = _xobj.getFirstChars(); + + _offSrc = _locale._offSrc; + _cchSrc = _locale._cchSrc; + + return src; + } + + void copyNode(Cur to) { + assert to != null; + assert isNode(); + + Xobj copy = _xobj.copyNode(to._locale); + + // TODO - in the moveNode case, I would not have to walk the tree for cursors ... optimize + + if (to.isPositioned()) { + Cur.moveNode(copy, to); + } else { + to.moveTo(copy); + } + } + + public Cur weakCur(Object o) { + Cur c = _locale.weakCur(o); + c.moveToCur(this); + return c; + } + + Cur tempCur() { + String id = null; + Cur c = _locale.tempCur(id); + c.moveToCur(this); + return c; + } + + private Cur tempCur(Xobj x, int p) { + assert (x == null || _locale == x._locale); + assert (x != null || p == NO_POS); + + Cur c = _locale.tempCur(); + + if (x != null) { + c.moveTo(getNormal(x, p), _posTemp); + } + + return c; + } + + // Is a cursor (c) in the chars defined by cch chars after where this Cur is positioned. + // Is inclusive on the left, and inclusive/exclusive on the right depending on the value + // of includeEnd. + + boolean inChars(Cur c, int cch, boolean includeEnd) { + assert isPositioned() && isText() && cchRight() >= cch; + assert c.isNormal(); + + return _xobj.inChars(_pos, c._xobj, c._pos, cch, includeEnd); + } + + boolean inChars(Bookmark b, int cch, boolean includeEnd) { + assert isPositioned() && isText() && cchRight() >= cch; + assert b._xobj.isNormal(b._pos); + + return _xobj.inChars(_pos, b._xobj, b._pos, cch, includeEnd); + } + + // Can't be static because I need to communicate pos in _posTemp :-( + // I wish I had multiple return vars ... + + private Xobj getNormal(Xobj x, int p) { + Xobj nx = x.getNormal(p); + _posTemp = x._locale._posTemp; + return nx; + } + + private Xobj getDenormal() { + assert isPositioned(); + + return getDenormal(_xobj, _pos); + } + + private Xobj getDenormal(Xobj x, int p) { + Xobj dx = x.getDenormal(p); + _posTemp = x._locale._posTemp; + return dx; + } + + // May throw IllegalArgumentException if can't change the type + + void setType(SchemaType type) { + setType(type, true); + } + + void setType(SchemaType type, boolean complain) { + assert type != null; + assert isUserNode(); + + TypeStoreUser user = peekUser(); + + if (user != null && user.get_schema_type() == type) { + return; + } + + if (isRoot()) { + _xobj.setStableType(type); + return; + } + + // Gotta get the parent user to make sure this type is ok here + + TypeStoreUser parentUser = _xobj.ensureParent().getUser(); + + // One may only set the type of an attribute to its 'natural' type because + // attributes cannot take advantage of the xsiType attribute. + + if (isAttr()) { + if (complain && parentUser.get_attribute_type(getName()) != type) { + throw new IllegalArgumentException("Can't set type of attribute to " + type.toString()); + } + + return; + } + + assert isElem(); + + // First check to see if this type can be here sans xsi:type. + // If so, make sure there is no xsi:type + + if (parentUser.get_element_type(getName(), null) == type) { + removeAttr(Locale._xsiType); + return; + } + + // If the desired type has no name, then it cannot be + // referenced via xsi:type + + QName typeName = type.getName(); + + if (typeName == null) { + if (complain) { + throw new IllegalArgumentException("Can't set type of element, type is un-named"); + } else { + return; + } + } + + // See if setting xsiType would result in the target type + + if (parentUser.get_element_type(getName(), typeName) != type) { + if (complain) { + throw new IllegalArgumentException("Can't set type of element, invalid type"); + } else { + return; + } + } + + setAttrValueAsQName(typeName); + } + + void setSubstitution(QName name, SchemaType type) { + assert name != null; + assert type != null; + assert isUserNode(); + + TypeStoreUser user = peekUser(); + + if (user != null && user.get_schema_type() == type && name.equals(getName())) { + return; + } + + if (isRoot()) { + // If this is the root node, we can't set its name, so the whole + // operation is aborted + return; + } + + // Gotta get the parent user to make sure this type is ok here + + TypeStoreUser parentUser = _xobj.ensureParent().getUser(); + + // One may only set the type of an attribute to its 'natural' type because + // attributes cannot take advantage of the xsiType attribute. + + if (isAttr()) { + // Can't use substitution with attributes + return; + } + + assert isElem(); + + // First check to see if this type can be here sans xsi:type. + // If so, make sure there is no xsi:type + + if (parentUser.get_element_type(name, null) == type) { + setName(name); + removeAttr(Locale._xsiType); + return; + } + + // If the desired type has no name, then it cannot be + // referenced via xsi:type + + QName typeName = type.getName(); + + if (typeName == null) { + // Can't set xsi:type on element, type is un-named + return; + } + + // See if setting xsiType would result in the target type + + if (parentUser.get_element_type(name, typeName) != type) { + // Can't set xsi:type on element, invalid type + return; + } + + setName(name); + setAttrValueAsQName(typeName); + } + + TypeStoreUser peekUser() { + assert isUserNode(); + + return _xobj._user; + } + + public XmlObject getObject() { + return isUserNode() ? (XmlObject) getUser() : null; + } + + TypeStoreUser getUser() { + assert isUserNode(); + + return _xobj.getUser(); + } + + public Dom getDom() { + assert isNormal(); + assert isPositioned(); + + if (isText()) { + int cch = cchLeft(); + + for (CharNode cn = getCharNodes(); ; cn = cn._next) { + if ((cch -= cn._cch) < 0) { + return cn; + } + } + } + + return _xobj.getDom(); + } + + public void release() { + if (_tempFrame >= 0) { + if (_nextTemp != null) { + _nextTemp._prevTemp = _prevTemp; + } + + if (_prevTemp == null) { + _locale._tempFrames[_tempFrame] = _nextTemp; + } else { + _prevTemp._nextTemp = _nextTemp; + } + + _prevTemp = _nextTemp = null; + _tempFrame = -1; + } + + if (_state != POOLED && _state != DISPOSED) { + // Clean up any state + + while (_stackTop != -1) { + popButStay(); + } + + clearSelection(); + + _id = null; + + // Unposition + + moveToCur(null); + + assert isNormal(); + + assert _xobj == null; + assert _pos == NO_POS; + + // Release weak reference and attacked value + + if (_ref != null) { + _ref.clear(); + _ref._cur = null; + } + + _ref = null; + + // Unregister and either diapose of cursor or add it back to pool + + assert _state == REGISTERED; + _locale._registered = listRemove(_locale._registered); + + if (_locale._curPoolCount < 16) { + _locale._curPool = listInsert(_locale._curPool); + _state = POOLED; + _locale._curPoolCount++; + } else { + _locale = null; + _state = DISPOSED; + } + } + } + + boolean isOnList(Cur head) { + for (; head != null; head = head._next) { + if (head == this) { + return true; + } + } + + return false; + } + + Cur listInsert(Cur head) { + assert _next == null && _prev == null; + + if (head == null) { + head = _prev = this; + } else { + _prev = head._prev; + head._prev = head._prev._next = this; + } + + return head; + } + + Cur listRemove(Cur head) { + assert _prev != null && isOnList(head); + + if (_prev == this) { + head = null; + } else { + if (head == this) { + head = _next; + } else { + _prev._next = _next; + } + + if (_next == null) { + if (head != null) { + head._prev = _prev; + } + } else { + _next._prev = _prev; + _next = null; + } + } + + _prev = null; + assert _next == null; + + return head; + } + +// boolean isNormal ( Cur that ) +// { +// return isNormal() && (that == null || (_locale == that._locale && that.isNormal())); +// } + + boolean isNormal() { + if (_state == POOLED || _state == DISPOSED) { + return false; + } + + if (_xobj == null) { + return _pos == NO_POS; + } + + if (!_xobj.isNormal(_pos)) { + return false; + } + + if (_state == EMBEDDED) { + return isOnList(_xobj._embedded); + } + + assert _state == REGISTERED; + + return isOnList(_locale._registered); + } + + public static final class CurLoadContext extends LoadContext { + public CurLoadContext(Locale l, XmlOptions options) { + options = XmlOptions.maskNull(options); + + _locale = l; + + _charUtil = + options.isLoadUseLocaleCharUtil() + ? _locale.getCharUtil() + : CharUtil.getThreadLocalCharUtil(); + + _frontier = createDomDocumentRootXobj(_locale); + _after = false; + + _lastXobj = _frontier; + _lastPos = 0; + + _replaceDocElem = options.getLoadReplaceDocumentElement(); + _discardDocElem = options.hasOption(XmlOptions.XmlOptionsKeys.LOAD_REPLACE_DOCUMENT_ELEMENT); + + _stripWhitespace = options.isSetLoadStripWhitespace(); + _stripComments = options.isLoadStripComments(); + _stripProcinsts = options.isLoadStripProcinsts(); + + _substituteNamespaces = options.getLoadSubstituteNamespaces(); + _additionalNamespaces = options.getLoadAdditionalNamespaces(); + + _locale._versionAll++; + _locale._versionSansText++; + } + + // + // Really primitive load context operations + // + + private void start(Xobj xo) { + assert _frontier != null; + assert !_after || _frontier._parent != null; + + flushText(); + + if (_after) { + _frontier = _frontier._parent; + _after = false; + } + + _frontier.appendXobj(xo); + _frontier = xo; + + _lastXobj = xo; + _lastPos = 0; + } + + private void end() { + assert _frontier != null; + assert !_after || _frontier._parent != null; + + flushText(); + + if (_after) { + _frontier = _frontier._parent; + } else { + _after = true; + } + + _lastXobj = _frontier; + _lastPos = END_POS; + } + + private void text(Object src, int off, int cch) { + if (cch <= 0) { + return; + } + + _lastXobj = _frontier; + _lastPos = _frontier._cchValue + 1; + + if (_after) { + _lastPos += _frontier._cchAfter + 1; + + _frontier._srcAfter = + _charUtil.saveChars( + src, off, cch, + _frontier._srcAfter, _frontier._offAfter, _frontier._cchAfter); + + _frontier._offAfter = _charUtil._offSrc; + _frontier._cchAfter = _charUtil._cchSrc; + + } else { + _frontier._srcValue = + _charUtil.saveChars( + src, off, cch, + _frontier._srcValue, _frontier._offValue, _frontier._cchValue); + + _frontier._offValue = _charUtil._offSrc; + _frontier._cchValue = _charUtil._cchSrc; + } + } + + private void flushText() { + if (_stripWhitespace) { + if (_after) { + _frontier._srcAfter = + _charUtil.stripRight( + _frontier._srcAfter, _frontier._offAfter, _frontier._cchAfter); + + _frontier._offAfter = _charUtil._offSrc; + _frontier._cchAfter = _charUtil._cchSrc; + } else { + _frontier._srcValue = + _charUtil.stripRight( + _frontier._srcValue, _frontier._offValue, _frontier._cchValue); + + _frontier._offValue = _charUtil._offSrc; + _frontier._cchValue = _charUtil._cchSrc; + } + } + } + + private Xobj parent() { + return _after ? _frontier._parent : _frontier; + } + + private QName checkName(QName name, boolean local) { + if (_substituteNamespaces != null && (!local || name.getNamespaceURI().length() > 0)) { + String substituteUri = _substituteNamespaces.get(name.getNamespaceURI()); + + if (substituteUri != null) { + name = _locale.makeQName(substituteUri, name.getLocalPart(), name.getPrefix()); + } + } + + return name; + } + + protected void startDTD(String name, String publicId, String systemId) { + _doctypeName = name; + _doctypePublicId = publicId; + _doctypeSystemId = systemId; + } + + protected void endDTD() { + } + + protected void startElement(QName name) { + start(createElementXobj(_locale, checkName(name, false), parent()._name)); + _stripLeft = true; + } + + protected void endElement() { + assert parent().isElem(); + + end(); + _stripLeft = true; + } + + protected void xmlns(String prefix, String uri) { + assert parent().isContainer(); + // BUGBUG - should assert there that there is no text before this attr + + // Namespace attrs are different than regular attrs -- I don't change their name, + // I change their value! + + if (_substituteNamespaces != null) { + String substituteUri = _substituteNamespaces.get(uri); + + if (substituteUri != null) { + uri = substituteUri; + } + } + + Xobj x = new AttrXobj(_locale, _locale.createXmlns(prefix)); + + start(x); + text(uri, 0, uri.length()); + end(); + + _lastXobj = x; + _lastPos = 0; + } + + public void attr(QName name, String value) { + assert parent().isContainer(); + // BUGBUG - should assert there that there is no text before this attr + + QName parentName = _after ? + _lastXobj._parent.getQName() : _lastXobj.getQName(); + boolean isId = isAttrOfTypeId(name, parentName); + + Xobj x = isId ? + new AttrIdXobj(_locale, checkName(name, true)) : + new AttrXobj(_locale, checkName(name, true)); + start(x); + text(value, 0, value.length()); + end(); + if (isId) { + Cur c1 = x.tempCur(); + c1.toRoot(); + Xobj doc = c1._xobj; + c1.release(); + if (doc instanceof DocumentXobj) { + ((DocumentXobj) doc).addIdElement(value, + x._parent.getDom()); + } + } + _lastXobj = x; + _lastPos = 0; + } + + protected void attr(String local, String uri, String prefix, String value) { + attr(_locale.makeQName(uri, local, prefix), value); + } + + protected void procInst(String target, String value) { + if (!_stripProcinsts) { + Xobj x = new ProcInstXobj(_locale, target); + + start(x); + text(value, 0, value.length()); + end(); + + _lastXobj = x; + _lastPos = 0; + } + _stripLeft = true; + } + + protected void comment(String comment) { + if (!_stripComments) { + comment(comment, 0, comment.length()); + } + _stripLeft = true; + } + + protected void comment(char[] chars, int off, int cch) { + if (!_stripComments) { + comment( + _charUtil.saveChars(chars, off, cch), + _charUtil._offSrc, _charUtil._cchSrc); + } + _stripLeft = true; + } + + private void comment(Object src, int off, int cch) { + Xobj x = new CommentXobj(_locale); + + start(x); + text(src, off, cch); + end(); + + _lastXobj = x; + _lastPos = 0; + } + + private boolean _stripLeft = true; + + private void stripText(Object src, int off, int cch) { + if (_stripWhitespace) { + // this is to avoid bug in cases like Procter & Gamble + if (_stripLeft) { + src = _charUtil.stripLeft(src, off, cch); + _stripLeft = false; + off = _charUtil._offSrc; + cch = _charUtil._cchSrc; + } + } + + text(src, off, cch); + } + + protected void text(String s) { + if (s == null) { + return; + } + + stripText(s, 0, s.length()); + } + + protected void text(char[] src, int off, int cch) { + stripText(src, off, cch); + } + + protected void bookmark(XmlBookmark bm) { + _lastXobj.setBookmark(_lastPos, bm.getKey(), bm); + } + + protected void bookmarkLastNonAttr(XmlBookmark bm) { + if (_lastPos > 0 || !_lastXobj.isAttr()) { + _lastXobj.setBookmark(_lastPos, bm.getKey(), bm); + } else { + assert _lastXobj._parent != null; + + _lastXobj._parent.setBookmark(0, bm.getKey(), bm); + } + } + + protected void bookmarkLastAttr(QName attrName, XmlBookmark bm) { + if (_lastPos == 0 && _lastXobj.isAttr()) { + assert _lastXobj._parent != null; + + Xobj a = _lastXobj._parent.getAttr(attrName); + + if (a != null) { + a.setBookmark(0, bm.getKey(), bm); + } + } + } + + protected void lineNumber(int line, int column, int offset) { + _lastXobj.setBookmark( + _lastPos, + XmlLineNumber.class, + new XmlLineNumber(line, column, offset)); + } + + protected void abort() { + _stripLeft = true; + while (!parent().isRoot()) { + end(); + } + + finish().release(); + } + + public Cur finish() { + flushText(); + + if (_after) { + _frontier = _frontier._parent; + } + + assert _frontier != null && _frontier._parent == null && _frontier.isRoot(); + + Cur c = _frontier.tempCur(); + + if (!Locale.toFirstChildElement(c)) { + return c; + } + + // See if the document element is a fragment + + boolean isFrag = Locale.isFragmentQName(c.getName()); + + if (_discardDocElem || isFrag) { + if (_replaceDocElem != null) { + c.setName(_replaceDocElem); + } else { + // Remove the content around the element to remove so that that content + // does not appear to have been the contents of the removed element. + + //noinspection StatementWithEmptyBody + while (c.toParent()) { + } + + c.next(); + + while (!c.isElem()) { + if (c.isText()) { + c.moveChars(null, -1); + } else { + c.moveNode(null); + } + } + + assert c.isElem(); + c.skip(); + + while (!c.isFinish()) { + if (c.isText()) { + c.moveChars(null, -1); + } else { + c.moveNode(null); + } + } + + c.toParent(); + + c.next(); + + assert c.isElem(); + + Cur c2 = c.tempCur(); + + c.moveNodeContents(c, true); + + c.moveToCur(c2); + + c2.release(); + + c.moveNode(null); + } + + // Remove the fragment namespace decl + + if (isFrag) { + c.moveTo(_frontier); + + if (c.toFirstAttr()) { + for (; ; ) { + if (c.isXmlns() && c.getXmlnsUri().equals(Locale._openFragUri)) { + c.moveNode(null); + + if (!c.isAttr()) { + break; + } + } else if (!c.toNextAttr()) { + break; + } + } + } + + c.moveTo(_frontier); + _frontier = createDomDocumentRootXobj(_locale, true); + + Cur c2 = _frontier.tempCur(); + c2.next(); + c.moveNodeContents(c2, true); + c.moveTo(_frontier); + c2.release(); + } + } + + + if (_additionalNamespaces != null) { + c.moveTo(_frontier); + Locale.toFirstChildElement(c); + Locale.applyNamespaces(c, _additionalNamespaces); + } + + if (_doctypeName != null && (_doctypePublicId != null || _doctypeSystemId != null)) { + XmlDocumentProperties props = Locale.getDocProps(c, true); + props.setDoctypeName(_doctypeName); + if (_doctypePublicId != null) { + props.setDoctypePublicId(_doctypePublicId); + } + if (_doctypeSystemId != null) { + props.setDoctypeSystemId(_doctypeSystemId); + } + } + + c.moveTo(_frontier); + + assert c.isRoot(); + + return c; + } + + public void dump() { + _frontier.dump(); + } + + private final Locale _locale; + private final CharUtil _charUtil; + + private Xobj _frontier; + private boolean _after; + + private Xobj _lastXobj; + private int _lastPos; + + private final boolean _discardDocElem; + private final QName _replaceDocElem; + private final boolean _stripWhitespace; + private final boolean _stripComments; + private final boolean _stripProcinsts; + private final Map _substituteNamespaces; + private final Map _additionalNamespaces; + + private String _doctypeName; + private String _doctypePublicId; + private String _doctypeSystemId; + } + + static String kindName(int kind) { + switch (kind) { + case ROOT: + return "ROOT"; + case ELEM: + return "ELEM"; + case ATTR: + return "ATTR"; + case COMMENT: + return "COMMENT"; + case PROCINST: + return "PROCINST"; + case TEXT: + return "TEXT"; + default: + return "<< Unknown Kind (" + kind + ") >>"; + } + } + + void dump() { + dump(System.out, _xobj, this); + } + + void dump(PrintStream o) { + if (_xobj == null) { + o.println("Unpositioned xptr"); + return; + } + + dump(o, _xobj, this); + } + + public static void dump(PrintStream o, Xobj xo, Object ref) { + if (ref == null) { + ref = xo; + } + + while (xo._parent != null) { + xo = xo._parent; + } + + dumpXobj(o, xo, 0, ref); + + o.println(); + } + + private static void dumpCur(PrintStream o, String prefix, Cur c, Object ref) { + o.print(" "); + + if (ref == c) { + o.print("*:"); + } + + o.print(prefix + (c._id == null ? "" : c._id) + "[" + c._pos + "]"); + } + + private static void dumpCurs(PrintStream o, Xobj xo, Object ref) { + for (Cur c = xo._embedded; c != null; c = c._next) { + dumpCur(o, "E:", c, ref); + } + + for (Cur c = xo._locale._registered; c != null; c = c._next) { + if (c._xobj == xo) { + dumpCur(o, "R:", c, ref); + } + } + } + + private static void dumpBookmarks(PrintStream o, Xobj xo, Object ref) { + for (Bookmark b = xo._bookmarks; b != null; b = b._next) { + o.print(" "); + + if (ref == b) { + o.print("*:"); + } + + if (b._value instanceof XmlLineNumber) { + XmlLineNumber l = (XmlLineNumber) b._value; + o.print("" + "[" + b._pos + "]"); + } else { + o.print("" + "[" + b._pos + "]"); + } + } + } + + private static void dumpCharNodes(PrintStream o, CharNode nodes, Object ref) { + for (CharNode n = nodes; n != null; n = n._next) { + o.print(" "); + + if (n == ref) { + o.print("*"); + } + + o.print((n instanceof TextNode ? "TEXT" : "CDATA") + "[" + n._cch + "]"); + } + } + + private static void dumpChars(PrintStream o, Object src, int off, int cch) { + + o.print("\""); + + String s = CharUtil.getString(src, off, cch); + + for (int i = 0; i < s.length(); ) { + if (i == 36) { + o.print("..."); + break; + } + + int codePoint = s.codePointAt(i); + char[] chars = Character.toChars(codePoint); + + if (chars.length == 1) { + char ch = chars[0]; + if (ch >= 32 && ch < 127 && ch != '\"') { + o.print(ch); + } else if (ch == '\n') { + o.print("\\n"); + } else if (ch == '\r') { + o.print("\\r"); + } else if (ch == '\t') { + o.print("\\t"); + } else if (ch == '\"') { + o.print("\\\""); + } else { + o.print("<#" + ((int) ch) + ">"); + } + } else { + o.print("<#" + codePoint + ">"); + } + + i += Character.charCount(codePoint); + } + + o.print("\""); + } + + private static void dumpXobj(PrintStream o, Xobj xo, int level, Object ref) { + if (xo == null) { + return; + } + + if (xo == ref) { + o.print("* "); + } else { + o.print(" "); + } + + for (int i = 0; i < level; i++) { + o.print(" "); + } + + o.print(kindName(xo.kind())); + + if (xo._name != null) { + o.print(" "); + + if (xo._name.getPrefix().length() > 0) { + o.print(xo._name.getPrefix() + ":"); + } + + o.print(xo._name.getLocalPart()); + + if (xo._name.getNamespaceURI().length() > 0) { + o.print("@" + xo._name.getNamespaceURI()); + } + } + + if (xo._srcValue != null || xo._charNodesValue != null) { + o.print(" Value( "); + dumpChars(o, xo._srcValue, xo._offValue, xo._cchValue); + dumpCharNodes(o, xo._charNodesValue, ref); + o.print(" )"); + } + + if (xo._user != null) { + o.print(" (USER)"); + } + + if (xo.isVacant()) { + o.print(" (VACANT)"); + } + + if (xo._srcAfter != null || xo._charNodesAfter != null) { + o.print(" After( "); + dumpChars(o, xo._srcAfter, xo._offAfter, xo._cchAfter); + dumpCharNodes(o, xo._charNodesAfter, ref); + o.print(" )"); + } + + dumpCurs(o, xo, ref); + dumpBookmarks(o, xo, ref); + + String className = xo.getClass().getName(); + + int i = className.lastIndexOf('.'); + + if (i > 0) { + className = className.substring(i + 1); + + i = className.lastIndexOf('$'); + + if (i > 0) { + className = className.substring(i + 1); + } + } + + o.print(" ("); + o.print(className); + o.print(")"); + + o.println(); + + for (xo = xo._firstChild; xo != null; xo = xo._nextSibling) { + dumpXobj(o, xo, level + 1, ref); + } + } + + void setId(String id) { + _id = id; + } + + public Locale getLocale() { + return _locale; + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java b/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java new file mode 100755 index 0000000..d96663f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java @@ -0,0 +1,2549 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlDocumentProperties; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.common.GlobalLock; +import org.apache.xmlbeans.impl.common.XMLChar; +import org.apache.xmlbeans.impl.store.Locale.ChangeListener; +import org.apache.xmlbeans.impl.store.Saver.TextSaver; +import org.apache.xmlbeans.impl.xpath.XPathEngine; +import org.apache.xmlbeans.impl.xpath.XPathFactory; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import java.io.*; +import java.util.Collection; +import java.util.Map; +import java.util.function.Supplier; + +import static org.apache.xmlbeans.impl.values.TypeStore.WS_PRESERVE; + +public final class Cursor implements XmlCursor, ChangeListener { + static final int ROOT = Cur.ROOT; + static final int ELEM = Cur.ELEM; + static final int ATTR = Cur.ATTR; + static final int COMMENT = Cur.COMMENT; + static final int PROCINST = Cur.PROCINST; + static final int TEXT = Cur.TEXT; + + private Cur _cur; + private XPathEngine _pathEngine; + private int _currentSelection; + + private ChangeListener _nextChangeListener; + + Cursor(Xobj x, int p) { + _cur = x._locale.weakCur(this); + _cur.moveTo(x, p); + _currentSelection = -1; + } + + public Cursor(Cur c) { + this(c._xobj, c._pos); + } + + private static boolean isValid(Cur c) { + if (c.kind() <= 0) { + c.push(); + + if (c.toParentRaw()) { + int pk = c.kind(); + + if (pk == COMMENT || pk == PROCINST || pk == ATTR) { + return false; + } + } + + c.pop(); + } + + return true; + } + + private boolean isValid() { + return isValid(_cur); + } + + Locale locale() { + return _cur._locale; + } + + Cur tempCur() { + return _cur.tempCur(); + } + + public void dump(PrintStream o) { + _cur.dump(o); + } + + static void validateLocalName(QName name) { + if (name == null) { + throw new IllegalArgumentException("QName is null"); + } + + validateLocalName(name.getLocalPart()); + } + + static void validateLocalName(String name) { + if (name == null) { + throw new IllegalArgumentException("Name is null"); + } + + if (name.length() == 0) { + throw new IllegalArgumentException("Name is empty"); + } + + if (!XMLChar.isValidNCName(name)) { + throw new IllegalArgumentException("Name is not valid"); + } + } + + static void validatePrefix(String name) { + if (name == null) { + throw new IllegalArgumentException("Prefix is null"); + } + + if (name.length() == 0) { + throw new IllegalArgumentException("Prefix is empty"); + } + + if (Locale.beginsWithXml(name)) { + throw new IllegalArgumentException("Prefix begins with 'xml'"); + } + + if (!XMLChar.isValidNCName(name)) { + throw new IllegalArgumentException("Prefix is not valid"); + } + } + + private static void complain(String msg) { + throw new IllegalArgumentException(msg); + } + + private void checkInsertionValidity(Cur that) { + int thatKind = that.kind(); + + if (thatKind < 0) { + complain("Can't move/copy/insert an end token."); + } + + if (thatKind == ROOT) { + complain("Can't move/copy/insert a whole document."); + } + + int thisKind = _cur.kind(); + + if (thisKind == ROOT) { + complain("Can't insert before the start of the document."); + } + + if (thatKind == ATTR) { + _cur.push(); + _cur.prevWithAttrs(); + int pk = _cur.kind(); + _cur.pop(); + + if (pk != ELEM && pk != ROOT && pk != -ATTR) { + complain("Can only insert attributes before other attributes or after containers."); + } + } + + if (thisKind == ATTR && thatKind != ATTR) { + complain("Can only insert attributes before other attributes or after containers."); + } + } + + private void insertNode(Cur that, String text) { + assert !that.isRoot(); + assert that.isNode(); + assert isValid(that); + assert isValid(); + + if (text != null && text.length() > 0) { + that.next(); + that.insertString(text); + that.toParent(); + } + + checkInsertionValidity(that); + + that.moveNode(_cur); + + _cur.toEnd(); + _cur.nextWithAttrs(); + } + + // + // + // + + // TODO - deal with cursors moving to other documents upon release? + // Can I move the ref from one q to another? If not I will have to + // change from a phantom ref to a soft/weak ref so I can know what + // to do when I dequeue from the old q. + + public void _dispose() { + _cur.release(); + _cur = null; + } + + public XmlCursor _newCursor() { + return new Cursor(_cur); + } + + public QName _getName() { + // TODO - consider taking this out of the gateway + + switch (_cur.kind()) { + case ATTR: + + if (_cur.isXmlns()) { + return + _cur._locale.makeQNameNoCheck(_cur.getXmlnsUri(), _cur.getXmlnsPrefix()); + } + + // Fall thru + + case ELEM: + case PROCINST: + return _cur.getName(); + } + + return null; + } + + public void _setName(QName name) { + if (name == null) { + throw new IllegalArgumentException("Name is null"); + } + + switch (_cur.kind()) { + case ELEM: + case ATTR: { + validateLocalName(name.getLocalPart()); + break; + } + + case PROCINST: { + validatePrefix(name.getLocalPart()); + + if (name.getNamespaceURI().length() > 0) { + throw new IllegalArgumentException("Procinst name must have no URI"); + } + + if (name.getPrefix().length() > 0) { + throw new IllegalArgumentException("Procinst name must have no prefix"); + } + + break; + } + + default: + throw + new IllegalStateException("Can set name on element, atrtribute and procinst only"); + } + + _cur.setName(name); + } + + public TokenType _currentTokenType() { + assert isValid(); + + switch (_cur.kind()) { + case ROOT: + return TokenType.STARTDOC; + case -ROOT: + return TokenType.ENDDOC; + case ELEM: + return TokenType.START; + case -ELEM: + return TokenType.END; + case TEXT: + return TokenType.TEXT; + case ATTR: + return _cur.isXmlns() ? TokenType.NAMESPACE : TokenType.ATTR; + case COMMENT: + return TokenType.COMMENT; + case PROCINST: + return TokenType.PROCINST; + + default: + throw new IllegalStateException(); + } + } + + public boolean _isStartdoc() { + //return _currentTokenType().isStartdoc(); + assert isValid(); + return _cur.isRoot(); + } + + public boolean _isEnddoc() { + //return _currentTokenType().isEnddoc(); + assert isValid(); + return _cur.isEndRoot(); + } + + public boolean _isStart() { + //return _currentTokenType().isStart(); + assert isValid(); + return _cur.isElem(); + } + + public boolean _isEnd() { + //return _currentTokenType().isEnd(); + assert isValid(); + return _cur.isEnd(); + } + + public boolean _isText() { + //return _currentTokenType().isText(); + assert isValid(); + return _cur.isText(); + } + + public boolean _isAttr() { + //return _currentTokenType().isAttr(); + assert isValid(); + return _cur.isNormalAttr(); + } + + public boolean _isNamespace() { + //return _currentTokenType().isNamespace(); + assert isValid(); + return _cur.isXmlns(); + } + + public boolean _isComment() { + //return _currentTokenType().isComment(); + assert isValid(); + return _cur.isComment(); + } + + public boolean _isProcinst() { + //return _currentTokenType().isProcinst(); + assert isValid(); + return _cur.isProcinst(); + } + + public boolean _isContainer() { + //return _currentTokenType().isContainer(); + assert isValid(); + return _cur.isContainer(); + } + + public boolean _isFinish() { + //return _currentTokenType().isFinish(); + assert isValid(); + return _cur.isFinish(); + } + + public boolean _isAnyAttr() { + //return _currentTokenType().isAnyAttr(); + assert isValid(); + return _cur.isAttr(); + } + + public TokenType _toNextToken() { + assert isValid(); + + switch (_cur.kind()) { + case ROOT: + case ELEM: { + if (!_cur.toFirstAttr()) { + _cur.next(); + } + + break; + } + + case ATTR: { + if (!_cur.toNextSibling()) { + _cur.toParent(); + _cur.next(); + } + + break; + } + + case COMMENT: + case PROCINST: { + _cur.skip(); + break; + } + + default: { + if (!_cur.next()) { + return TokenType.NONE; + } + + break; + } + } + + return _currentTokenType(); + } + + public TokenType _toPrevToken() { + assert isValid(); + + // This method is different than the Cur version of prev in a few ways. First, + // Cursor iterates over attrs inline with all the other content. Cur will skip attrs, or + // if the Cur in in attrs, it will not jump out of attrs. Also, if moving backwards and + // text is to the left and right, Cur will move to the beginning of that text, while + // Cursor will move further so that the token type to the right is not text. + + boolean wasText = _cur.isText(); + + if (!_cur.prev()) { + assert _cur.isRoot() || _cur.isAttr(); + + if (_cur.isRoot()) { + return TokenType.NONE; + } + + _cur.toParent(); + } else { + int k = _cur.kind(); + + if (k == -COMMENT || k == -PROCINST || k == -ATTR) { + _cur.toParent(); + } else if (_cur.isContainer()) { + _cur.toLastAttr(); + } else if (wasText && _cur.isText()) { + return _toPrevToken(); + } + } + + return _currentTokenType(); + } + + public Object _monitor() { + // TODO - some of these methods need not be protected by a + // gatway. This is one of them. Inline this. + + return _cur._locale; + } + + public boolean _toParent() { + Cur c = _cur.tempCur(); + + if (!c.toParent()) { + return false; + } + + _cur.moveToCur(c); + + c.release(); + + return true; + } + + private static final class ChangeStampImpl implements ChangeStamp { + ChangeStampImpl(Locale l) { + _locale = l; + _versionStamp = _locale.version(); + } + + public boolean hasChanged() { + return _versionStamp != _locale.version(); + } + + private final Locale _locale; + private final long _versionStamp; + } + + public ChangeStamp _getDocChangeStamp() { + return new ChangeStampImpl(_cur._locale); + } + + // + // These simply delegate to the version of the method which takes XmlOptions + // + + + public XMLStreamReader _newXMLStreamReader() { + return _newXMLStreamReader(null); + } + + public Node _newDomNode() { + return _newDomNode(null); + } + + public InputStream _newInputStream() { + return _newInputStream(null); + } + + public String _xmlText() { + return _xmlText(null); + } + + public Reader _newReader() { + return _newReader(null); + } + + public void _save(File file) throws IOException { + _save(file, null); + } + + public void _save(OutputStream os) throws IOException { + _save(os, null); + } + + public void _save(Writer w) throws IOException { + _save(w, null); + } + + public void _save(ContentHandler ch, LexicalHandler lh) throws SAXException { + _save(ch, lh, null); + } + + // + // + // + + public XmlDocumentProperties _documentProperties() { + return Locale.getDocProps(_cur, true); + } + + public XMLStreamReader _newXMLStreamReader(XmlOptions options) { + return Jsr173.newXmlStreamReader(_cur, options); + } + + public String _xmlText(XmlOptions options) { + assert isValid(); + + return new TextSaver(_cur, options, null).saveToString(); + } + + public InputStream _newInputStream(XmlOptions options) { + return new Saver.InputStreamSaver(_cur, options); + } + + public Reader _newReader(XmlOptions options) { + return new Saver.TextReader(_cur, options); + } + + public void _save(ContentHandler ch, LexicalHandler lh, XmlOptions options) + throws SAXException { + new Saver.SaxSaver(_cur, options, ch, lh); + } + + public void _save(File file, XmlOptions options) throws IOException { + if (file == null) { + throw new IllegalArgumentException("Null file specified"); + } + + try (OutputStream os = new FileOutputStream(file)) { + _save(os, options); + } + } + + public void _save(OutputStream os, XmlOptions options) throws IOException { + if (os == null) { + throw new IllegalArgumentException("Null OutputStream specified"); + } + + try (InputStream is = _newInputStream(options)) { + byte[] bytes = new byte[8192]; + + for (; ; ) { + int n = is.read(bytes); + + if (n < 0) { + break; + } + + os.write(bytes, 0, n); + } + } + } + + public void _save(Writer w, XmlOptions options) throws IOException { + if (w == null) { + throw new IllegalArgumentException("Null Writer specified"); + } + + if (options != null && options.isSaveOptimizeForSpeed()) { + Saver.OptimizedForSpeedSaver.save(_cur, w); //ignore all other options + return; + } + + try (Reader r = _newReader(options)) { + char[] chars = new char[8192]; + + for (; ; ) { + int n = r.read(chars); + + if (n < 0) { + break; + } + + w.write(chars, 0, n); + } + } + } + + public Node _getDomNode() { + return (Node) _cur.getDom(); + } + + private boolean isDomFragment() { + if (!isStartdoc()) { + return true; + } + + boolean seenElement = false; + + XmlCursor c = newCursor(); + int token = c.toNextToken().intValue(); + + try { + LOOP: + for (; ; ) { + switch (token) { + case TokenType.INT_START: + if (seenElement) { + return true; + } + seenElement = true; + token = c.toEndToken().intValue(); + break; + + case TokenType.INT_TEXT: + if (!Locale.isWhiteSpace(c.getChars())) { + return true; + } + token = c.toNextToken().intValue(); + break; + + case TokenType.INT_NONE: + case TokenType.INT_ENDDOC: + break LOOP; + + case TokenType.INT_ATTR: + case TokenType.INT_NAMESPACE: + return true; + + case TokenType.INT_END: + case TokenType.INT_COMMENT: + case TokenType.INT_PROCINST: + token = c.toNextToken().intValue(); + break; + + case TokenType.INT_STARTDOC: + assert false; + break LOOP; + } + } + } finally { + c.dispose(); + } + + return !seenElement; + } + + public Node _newDomNode(XmlOptions options) { + // Must ignore inner options for compat with v1. + + if (options != null && options.isSaveInner()) { + options = new XmlOptions(options); + options.setSaveInner(false); + } + + return new DomSaver(_cur, isDomFragment(), options).saveDom(); + } + + public boolean _toCursor(Cursor other) { + assert _cur._locale == other._cur._locale; + + _cur.moveToCur(other._cur); + + return true; + } + + public void _push() { + _cur.push(); + } + + public boolean _pop() { + return _cur.pop(); + } + + public void notifyChange() { + // Force any path to get exausted, cursor may be disposed, but still be on the notification + // list. + + if (_cur != null) { + _getSelectionCount(); + } + } + + public void setNextChangeListener(ChangeListener listener) { + _nextChangeListener = listener; + } + + public ChangeListener getNextChangeListener() { + return _nextChangeListener; + } + + public void _selectPath(String path) { + _selectPath(path, null); + } + + public void _selectPath(String pathExpr, XmlOptions options) { + _clearSelections(); + + assert _pathEngine == null; + + _pathEngine = XPathFactory.getCompiledPath(pathExpr, options).execute(_cur, options); + + _cur._locale.registerForChange(this); + } + + public boolean _hasNextSelection() { + int curr = _currentSelection; + push(); + + try { + return _toNextSelection(); + } finally { + _currentSelection = curr; + pop(); + } + } + + public boolean _toNextSelection() { + return _toSelection(_currentSelection + 1); + } + + public boolean _toSelection(int i) { + if (i < 0) { + return false; + } + + while (i >= _cur.selectionCount()) { + if (_pathEngine == null) { + return false; + } + + if (!_pathEngine.next(_cur)) { + _pathEngine.release(); + _pathEngine = null; + + return false; + } + } + + _cur.moveToSelection(_currentSelection = i); + + return true; + } + + public int _getSelectionCount() { + // Should never get to MAX_VALUE selection index, so, state should not change + _toSelection(Integer.MAX_VALUE); + + return _cur.selectionCount(); + } + + public void _addToSelection() { + _toSelection(Integer.MAX_VALUE); + + _cur.addToSelection(); + } + + public void _clearSelections() { + if (_pathEngine != null) { + _pathEngine.release(); + _pathEngine = null; + } + + _cur.clearSelection(); + + _currentSelection = -1; + } + + public String _namespaceForPrefix(String prefix) { + if (!_cur.isContainer()) { + throw new IllegalStateException("Not on a container"); + } + + return _cur.namespaceForPrefix(prefix, true); + } + + public String _prefixForNamespace(String ns) { + if (ns == null || ns.length() == 0) { + throw new IllegalArgumentException("Must specify a namespace"); + } + +// Note: I loosen this requirement in v2, can call this from anywhere +// if (!_cur.isContainer()) +// throw new IllegalStateException( "Not on a container" ); + + return _cur.prefixForNamespace(ns, null, true); + } + + public void _getAllNamespaces(Map addToThis) { + if (!_cur.isContainer()) { + throw new IllegalStateException("Not on a container"); + } + + if (addToThis != null) { + Locale.getAllNamespaces(_cur, addToThis); + } + } + + public XmlObject _getObject() { + return _cur.getObject(); + } + + public TokenType _prevTokenType() { + _cur.push(); + + TokenType tt = _toPrevToken(); + + _cur.pop(); + + return tt; + } + + public boolean _hasNextToken() { + //return _cur.kind() != -ROOT; + return _cur._pos != Cur.END_POS || _cur._xobj.kind() != ROOT; + } + + public boolean _hasPrevToken() { + return _cur.kind() != ROOT; + } + + public TokenType _toFirstContentToken() { + if (!_cur.isContainer()) { + return TokenType.NONE; + } + + _cur.next(); + + return currentTokenType(); + } + + public TokenType _toEndToken() { + if (!_cur.isContainer()) { + return TokenType.NONE; + } + + _cur.toEnd(); + + return currentTokenType(); + } + + public boolean _toChild(String local) { + return _toChild(null, local); + } + + public boolean _toChild(QName name) { + return _toChild(name, 0); + } + + public boolean _toChild(int index) { + return _toChild(null, index); + } + + public boolean _toChild(String uri, String local) { + validateLocalName(local); + + return _toChild(_cur._locale.makeQName(uri, local), 0); + } + + public boolean _toChild(QName name, int index) { + return Locale.toChild(_cur, name, index); + } + + public int _toNextChar(int maxCharacterCount) { + return _cur.nextChars(maxCharacterCount); + } + + public int _toPrevChar(int maxCharacterCount) { + return _cur.prevChars(maxCharacterCount); + } + + public boolean _toPrevSibling() { + return Locale.toPrevSiblingElement(_cur); + } + + public boolean _toLastChild() { + return Locale.toLastChildElement(_cur); + } + + public boolean _toFirstChild() { + return Locale.toFirstChildElement(_cur); + } + + public boolean _toNextSibling(String name) { + return _toNextSibling(new QName(name)); + } + + public boolean _toNextSibling(String uri, String local) { + validateLocalName(local); + + return _toNextSibling(_cur._locale._qnameFactory.getQName(uri, local)); + } + + public boolean _toNextSibling(QName name) { + _cur.push(); + + while (___toNextSibling()) { + if (_cur.getName().equals(name)) { + _cur.popButStay(); + return true; + } + } + + _cur.pop(); + + return false; + } + + public boolean _toFirstAttribute() { + return _cur.isContainer() && Locale.toFirstNormalAttr(_cur); + } + + public boolean _toLastAttribute() { + if (_cur.isContainer()) { + _cur.push(); + _cur.push(); + + boolean foundAttr = false; + + while (_cur.toNextAttr()) { + if (_cur.isNormalAttr()) { + _cur.popButStay(); + _cur.push(); + foundAttr = true; + } + } + + _cur.pop(); + + if (foundAttr) { + _cur.popButStay(); + return true; + } + + _cur.pop(); + } + + return false; + } + + public boolean _toNextAttribute() { + return _cur.isAttr() && Locale.toNextNormalAttr(_cur); + } + + public boolean _toPrevAttribute() { + return _cur.isAttr() && Locale.toPrevNormalAttr(_cur); + } + + public String _getAttributeText(QName attrName) { + if (attrName == null) { + throw new IllegalArgumentException("Attr name is null"); + } + + if (!_cur.isContainer()) { + return null; + } + + return _cur.getAttrValue(attrName); + } + + public boolean _setAttributeText(QName attrName, String value) { + if (attrName == null) { + throw new IllegalArgumentException("Attr name is null"); + } + + validateLocalName(attrName.getLocalPart()); + + if (!_cur.isContainer()) { + return false; + } + + _cur.setAttrValue(attrName, value); + + return true; + } + + public boolean _removeAttribute(QName attrName) { + if (attrName == null) { + throw new IllegalArgumentException("Attr name is null"); + } + + if (!_cur.isContainer()) { + return false; + } + + return _cur.removeAttr(attrName); + } + + public String _getTextValue() { + if (_cur.isText()) { + return _getChars(); + } + + if (!_cur.isNode()) { + throw new IllegalStateException("Can't get text value, current token can have no text value"); + } + + return _cur.hasChildren() ? Locale.getTextValue(_cur) : _cur.getValueAsString(); + } + + public int _getTextValue(char[] chars, int offset, int max) { + if (_cur.isText()) { + return _getChars(chars, offset, max); + } + + if (chars == null) { + throw new IllegalArgumentException("char buffer is null"); + } + + if (offset < 0) { + throw new IllegalArgumentException("offset < 0"); + } + + if (offset >= chars.length) { + throw new IllegalArgumentException("offset off end"); + } + + if (max < 0) { + max = Integer.MAX_VALUE; + } + + if (offset + max > chars.length) { + max = chars.length - offset; + } + + if (!_cur.isNode()) { + throw new IllegalStateException("Can't get text value, current token can have no text value"); + } + + // If there are no children (hopefully the common case), I can get the text faster. + + if (_cur.hasChildren()) { + return Locale.getTextValue(_cur, WS_PRESERVE, chars, offset, max); + } + + // Fast way + + Object src = _cur.getFirstChars(); + + if (_cur._cchSrc > max) { + _cur._cchSrc = max; + } + + if (_cur._cchSrc <= 0) { + return 0; + } + + CharUtil.getChars(chars, offset, src, _cur._offSrc, _cur._cchSrc); + + return _cur._cchSrc; + } + + private void setTextValue(Object src, int off, int cch) { + if (!_cur.isNode()) { + throw new IllegalStateException("Can't set text value, current token can have no text value"); + } + + _cur.moveNodeContents(null, false); + _cur.next(); + _cur.insertChars(src, off, cch); + _cur.toParent(); + } + + public void _setTextValue(String text) { + if (text == null) { + text = ""; + } + + setTextValue(text, 0, text.length()); + } + + public void _setTextValue(char[] sourceChars, int offset, int length) { + if (length < 0) { + throw new IndexOutOfBoundsException("setTextValue: length < 0"); + } + + if (sourceChars == null) { + if (length > 0) { + throw new IllegalArgumentException("setTextValue: sourceChars == null"); + } + + setTextValue(null, 0, 0); + + return; + } + + if (offset < 0 || offset >= sourceChars.length) { + throw new IndexOutOfBoundsException("setTextValue: offset out of bounds"); + } + + if (offset + length > sourceChars.length) { + length = sourceChars.length - offset; + } + + CharUtil cu = _cur._locale.getCharUtil(); + + setTextValue(cu.saveChars(sourceChars, offset, length), cu._offSrc, cu._cchSrc); + } + + public String _getChars() { + return _cur.getCharsAsString(); + } + + public int _getChars(char[] buf, int off, int cch) { + int cchRight = _cur.cchRight(); + + if (cch < 0 || cch > cchRight) { + cch = cchRight; + } + + if (buf == null || off >= buf.length) { + return 0; + } + + if (buf.length - off < cch) { + cch = buf.length - off; + } + + Object src = _cur.getChars(cch); + + CharUtil.getChars(buf, off, src, _cur._offSrc, _cur._cchSrc); + + return _cur._cchSrc; + } + + public void _toStartDoc() { + _cur.toRoot(); + } + + public void _toEndDoc() { + _toStartDoc(); + _cur.toEnd(); + } + + public int _comparePosition(Cursor other) { + int s = _cur.comparePosition(other._cur); + + if (s == 2) { + throw new IllegalArgumentException("Cursors not in same document"); + } + + assert s >= -1 && s <= 1; + + return s; + } + + public boolean _isLeftOf(Cursor other) { + return _comparePosition(other) < 0; + } + + public boolean _isAtSamePositionAs(Cursor other) { + return _cur.isSamePos(other._cur); + } + + public boolean _isRightOf(Cursor other) { + return _comparePosition(other) > 0; + } + + public XmlCursor _execQuery(String query) { + return _execQuery(query, null); + } + + public XmlCursor _execQuery(String query, XmlOptions options) { + checkThisCursor(); + return XPathFactory.cursorExecQuery(_cur, query, options); + } + + + public boolean _toBookmark(XmlBookmark bookmark) { + if (bookmark == null || !(bookmark._currentMark instanceof Bookmark)) { + return false; + } + + Bookmark m = (Bookmark) bookmark._currentMark; + + if (m._xobj == null || m._xobj._locale != _cur._locale) { + return false; + } + + _cur.moveTo(m._xobj, m._pos); + + return true; + } + + public XmlBookmark _toNextBookmark(Object key) { + if (key == null) { + return null; + } + + int cch; + + _cur.push(); + + for (; ; ) { + // Move a minimal amount. If at text, move to a potential bookmark in the text. + + if ((cch = _cur.cchRight()) > 1) { + _cur.nextChars(1); + _cur.nextChars((cch = _cur.firstBookmarkInChars(key, cch - 1)) >= 0 ? cch : -1); + } else if (_toNextToken().isNone()) { + _cur.pop(); + return null; + } + + XmlBookmark bm = getBookmark(key, _cur); + + if (bm != null) { + _cur.popButStay(); + return bm; + } + + if (_cur.kind() == -ROOT) { + _cur.pop(); + return null; + } + } + } + + public XmlBookmark _toPrevBookmark(Object key) { + if (key == null) { + return null; + } + + int cch; + + _cur.push(); + + for (; ; ) { + // Move a minimal amount. If at text, move to a potential bookmark in the text. + + if ((cch = _cur.cchLeft()) > 1) { + _cur.prevChars(1); + + _cur.prevChars((cch = _cur.firstBookmarkInCharsLeft(key, cch - 1)) >= 0 ? cch : -1); + } else if (cch == 1) { + // _toPrevToken will not skip to the beginning of the text, it will go further + // so that the token to the right is not text. I need to simply skip to + // the beginning of the text ... + + _cur.prevChars(1); + } else if (_toPrevToken().isNone()) { + _cur.pop(); + return null; + } + + XmlBookmark bm = getBookmark(key, _cur); + + if (bm != null) { + _cur.popButStay(); + return bm; + } + + if (_cur.kind() == ROOT) { + _cur.pop(); + return null; + } + } + } + + public void _setBookmark(XmlBookmark bookmark) { + if (bookmark != null) { + if (bookmark.getKey() == null) { + throw new IllegalArgumentException("Annotation key is null"); + } + + // TODO - I Don't do weak bookmarks yet ... perhaps I'll never do them .... + + bookmark._currentMark = _cur.setBookmark(bookmark.getKey(), bookmark); + } + } + + static XmlBookmark getBookmark(Object key, Cur c) { + // TODO - I Don't do weak bookmarks yet ... + + if (key == null) { + return null; + } + + Object bm = c.getBookmark(key); + + return bm instanceof XmlBookmark ? (XmlBookmark) bm : null; + } + + public XmlBookmark _getBookmark(Object key) { + return key == null ? null : getBookmark(key, _cur); + } + + public void _clearBookmark(Object key) { + if (key != null) { + _cur.setBookmark(key, null); + } + } + + public void _getAllBookmarkRefs(Collection listToFill) { + if (listToFill != null) { + for (Bookmark b = _cur._xobj._bookmarks; b != null; b = b._next) { + if (b._value instanceof XmlBookmark) { + listToFill.add(b._value); + } + } + } + } + + public boolean _removeXml() { + if (_cur.isRoot()) { + throw new IllegalStateException("Can't remove a whole document."); + } + + if (_cur.isFinish()) { + return false; + } + + assert _cur.isText() || _cur.isNode(); + + if (_cur.isText()) { + _cur.moveChars(null, -1); + } else { + _cur.moveNode(null); + } + + return true; + } + + public boolean _moveXml(Cursor to) { + to.checkInsertionValidity(_cur); + + // Check for a no-op + + if (_cur.isText()) { + int cchRight = _cur.cchRight(); + + assert cchRight > 0; + + if (_cur.inChars(to._cur, cchRight, true)) { + return false; + } + + _cur.moveChars(to._cur, cchRight); + + to._cur.nextChars(cchRight); + + return true; + } + + if (_cur.contains(to._cur)) { + return false; + } + + // Make a cur which will float to the right of the insertion + + Cur c = to.tempCur(); + + _cur.moveNode(to._cur); + + to._cur.moveToCur(c); + + c.release(); + + return true; + } + + public boolean _copyXml(Cursor to) { + to.checkInsertionValidity(_cur); + + assert _cur.isText() || _cur.isNode(); + + Cur c = to.tempCur(); + + if (_cur.isText()) { + to._cur.insertChars(_cur.getChars(-1), _cur._offSrc, _cur._cchSrc); + } else { + _cur.copyNode(to._cur); + } + + to._cur.moveToCur(c); + + c.release(); + + return true; + } + + public boolean _removeXmlContents() { + if (!_cur.isContainer()) { + return false; + } + + _cur.moveNodeContents(null, false); + + return true; + } + + private boolean checkContentInsertionValidity(Cursor to) { + _cur.push(); + + _cur.next(); + + if (_cur.isFinish()) { + _cur.pop(); + return false; + } + + try { + to.checkInsertionValidity(_cur); + } catch (IllegalArgumentException e) { + _cur.pop(); + throw e; + } + + _cur.pop(); + + return true; + } + + public boolean _moveXmlContents(Cursor to) { + if (!_cur.isContainer() || _cur.contains(to._cur)) { + return false; + } + + if (!checkContentInsertionValidity(to)) { + return false; + } + + Cur c = to.tempCur(); + + _cur.moveNodeContents(to._cur, false); + + to._cur.moveToCur(c); + + c.release(); + + return true; + } + + public boolean _copyXmlContents(Cursor to) { + if (!_cur.isContainer() || _cur.contains(to._cur)) { + return false; + } + + if (!checkContentInsertionValidity(to)) { + return false; + } + + // I don't have a primitive to copy contents, make a copy of the node and them move the + // contents + + Cur c = _cur._locale.tempCur(); + + _cur.copyNode(c); + + Cur c2 = to._cur.tempCur(); + + c.moveNodeContents(to._cur, false); + + c.release(); + + to._cur.moveToCur(c2); + + c2.release(); + + return true; + } + + public int _removeChars(int cch) { + int cchRight = _cur.cchRight(); + + if (cchRight == 0 || cch == 0) { + return 0; + } + + if (cch < 0 || cch > cchRight) { + cch = cchRight; + } + + _cur.moveChars(null, cch); + + return _cur._cchSrc; + } + + public int _moveChars(int cch, Cursor to) { + int cchRight = _cur.cchRight(); + + if (cchRight <= 0 || cch == 0) { + return 0; + } + + if (cch < 0 || cch > cchRight) { + cch = cchRight; + } + + to.checkInsertionValidity(_cur); + + _cur.moveChars(to._cur, cch); + + to._cur.nextChars(_cur._cchSrc); + + return _cur._cchSrc; + } + + public int _copyChars(int cch, Cursor to) { + int cchRight = _cur.cchRight(); + + if (cchRight <= 0 || cch == 0) { + return 0; + } + + if (cch < 0 || cch > cchRight) { + cch = cchRight; + } + + to.checkInsertionValidity(_cur); + + to._cur.insertChars(_cur.getChars(cch), _cur._offSrc, _cur._cchSrc); + + to._cur.nextChars(_cur._cchSrc); + + return _cur._cchSrc; + } + + public void _insertChars(String text) { + int l = text == null ? 0 : text.length(); + + if (l > 0) { + if (_cur.isRoot() || _cur.isAttr()) { + throw + new IllegalStateException("Can't insert before the document or an attribute."); + } + + _cur.insertChars(text, 0, l); + _cur.nextChars(l); + } + } + + // + // Inserting elements + // + + public void _beginElement(String localName) { + _insertElementWithText(localName, null, null); + _toPrevToken(); + } + + public void _beginElement(String localName, String uri) { + _insertElementWithText(localName, uri, null); + _toPrevToken(); + } + + public void _beginElement(QName name) { + _insertElementWithText(name, null); + _toPrevToken(); + } + + public void _insertElement(String localName) { + _insertElementWithText(localName, null, null); + } + + public void _insertElement(String localName, String uri) { + _insertElementWithText(localName, uri, null); + } + + public void _insertElement(QName name) { + _insertElementWithText(name, null); + } + + public void _insertElementWithText(String localName, String text) { + _insertElementWithText(localName, null, text); + } + + public void _insertElementWithText(String localName, String uri, String text) { + validateLocalName(localName); + + _insertElementWithText(_cur._locale.makeQName(uri, localName), text); + } + + public void _insertElementWithText(QName name, String text) { + validateLocalName(name.getLocalPart()); + + Cur c = _cur._locale.tempCur(); + + c.createElement(name); + + insertNode(c, text); + + c.release(); + } + + // + // + // + + public void _insertAttribute(String localName) { + _insertAttributeWithValue(localName, null); + } + + public void _insertAttribute(String localName, String uri) { + _insertAttributeWithValue(localName, uri, null); + } + + public void _insertAttribute(QName name) { + _insertAttributeWithValue(name, null); + } + + public void _insertAttributeWithValue(String localName, String value) { + _insertAttributeWithValue(localName, null, value); + } + + public void _insertAttributeWithValue(String localName, String uri, String value) { + validateLocalName(localName); + + _insertAttributeWithValue(_cur._locale.makeQName(uri, localName), value); + } + + public void _insertAttributeWithValue(QName name, String text) { + validateLocalName(name.getLocalPart()); + + Cur c = _cur._locale.tempCur(); + + c.createAttr(name); + + insertNode(c, text); + + c.release(); + } + + // + // + // + + public void _insertNamespace(String prefix, String namespace) { + _insertAttributeWithValue(_cur._locale.createXmlns(prefix), namespace); + } + + public void _insertComment(String text) { + Cur c = _cur._locale.tempCur(); + + c.createComment(); + + insertNode(c, text); + + c.release(); + } + + public void _insertProcInst(String target, String text) { + validateLocalName(target); + + if (Locale.beginsWithXml(target) && target.length() == 3) { + throw new IllegalArgumentException("Target is 'xml'"); + } + + Cur c = _cur._locale.tempCur(); + + c.createProcinst(target); + + insertNode(c, text); + + c.release(); + } + + public void _dump() { + _cur.dump(); + } + + // + // + // + // + // + // + // + + private void checkThisCursor() { + if (_cur == null) { + throw new IllegalStateException("This cursor has been disposed"); + } + } + + private Cursor checkCursors(XmlCursor xOther) { + checkThisCursor(); + + if (xOther == null) { + throw new IllegalArgumentException("Other cursor is "); + } + + if (!(xOther instanceof Cursor)) { + throw new IllegalArgumentException("Incompatible cursors: " + xOther); + } + + Cursor other = (Cursor) xOther; + + if (other._cur == null) { + throw new IllegalStateException("Other cursor has been disposed"); + } + + return other; + } + + // + // The following operations have two cursors, and can be in different documents + // + + private static final int MOVE_XML = 0; + private static final int COPY_XML = 1; + private static final int MOVE_XML_CONTENTS = 2; + private static final int COPY_XML_CONTENTS = 3; + private static final int MOVE_CHARS = 4; + private static final int COPY_CHARS = 5; + + private int twoLocaleOp(XmlCursor xOther, int op, int arg) { + Cursor other = checkCursors(xOther); + + Locale locale = _cur._locale; + Locale otherLocale = other._cur._locale; + + if (locale == otherLocale) { + return syncWrapNoEnter(() -> twoLocaleOp(other, op, arg)); + } + + if (locale.noSync()) { + if (otherLocale.noSync()) { + return twoLocaleOp(other, op, arg); + } else { + synchronized (otherLocale) { + return twoLocaleOp(other, op, arg); + } + } + } else if (otherLocale.noSync()) { + synchronized (locale) { + return twoLocaleOp(other, op, arg); + } + } + + boolean acquired = false; + + try { + GlobalLock.acquire(); + acquired = true; + + synchronized (locale) { + synchronized (otherLocale) { + GlobalLock.release(); + acquired = false; + + return twoLocaleOp(other, op, arg); + } + } + } catch (InterruptedException e) { + throw new RuntimeException(e.getMessage(), e); + } finally { + if (acquired) { + GlobalLock.release(); + } + } + } + + private int twoLocaleOp(Cursor other, int op, int arg) { + Locale locale = _cur._locale; + Locale otherLocale = other._cur._locale; + + locale.enter(otherLocale); + + try { + switch (op) { + case MOVE_XML: + return _moveXml(other) ? 1 : 0; + case COPY_XML: + return _copyXml(other) ? 1 : 0; + case MOVE_XML_CONTENTS: + return _moveXmlContents(other) ? 1 : 0; + case COPY_XML_CONTENTS: + return _copyXmlContents(other) ? 1 : 0; + case MOVE_CHARS: + return _moveChars(arg, other); + case COPY_CHARS: + return _copyChars(arg, other); + + default: + throw new RuntimeException("Unknown operation: " + op); + } + } finally { + locale.exit(otherLocale); + } + } + + public boolean moveXml(XmlCursor xTo) { + return twoLocaleOp(xTo, MOVE_XML, 0) == 1; + } + + public boolean copyXml(XmlCursor xTo) { + return twoLocaleOp(xTo, COPY_XML, 0) == 1; + } + + public boolean moveXmlContents(XmlCursor xTo) { + return twoLocaleOp(xTo, MOVE_XML_CONTENTS, 0) == 1; + } + + public boolean copyXmlContents(XmlCursor xTo) { + return twoLocaleOp(xTo, COPY_XML_CONTENTS, 0) == 1; + } + + public int moveChars(int cch, XmlCursor xTo) { + return twoLocaleOp(xTo, MOVE_CHARS, cch); + } + + public int copyChars(int cch, XmlCursor xTo) { + return twoLocaleOp(xTo, COPY_CHARS, cch); + } + + + // + // Special methods involving multiple cursors which can be in different locales, but do not + // require sync on both locales. + // + + public boolean toCursor(XmlCursor xOther) { + // One may only move cursors within the same locale + + Cursor other = checkCursors(xOther); + + return _cur._locale == other._cur._locale && + syncWrap(() -> _toCursor(other)); + } + + public boolean isInSameDocument(XmlCursor xOther) { + return xOther != null && _cur.isInSameTree(checkCursors(xOther)._cur); + } + + // + // The following operations have two cursors, but they must be in the same document + // + + private Cursor preCheck(XmlCursor xOther) { + Cursor other = checkCursors(xOther); + + if (_cur._locale != other._cur._locale) { + throw new IllegalArgumentException("Cursors not in same document"); + } + + return other; + } + + public int comparePosition(XmlCursor xOther) { + Cursor other = preCheck(xOther); + return syncWrap(() -> _comparePosition(other)); + } + + public boolean isLeftOf(XmlCursor xOther) { + Cursor other = preCheck(xOther); + return syncWrap(() -> _isLeftOf(other)); + } + + public boolean isAtSamePositionAs(XmlCursor xOther) { + Cursor other = preCheck(xOther); + return syncWrap(() -> _isAtSamePositionAs(other)); + } + + public boolean isRightOf(XmlCursor xOther) { + Cursor other = preCheck(xOther); + return syncWrap(() -> _isRightOf(other)); + } + + // + // Create a cursor from an Xobj -- used for XmlBookmark.createCursor + // + + public static XmlCursor newCursor(Xobj x, int p) { + Locale l = x._locale; + if (l.noSync()) { + l.enter(); + try { + return new Cursor(x, p); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return new Cursor(x, p); + } finally { + l.exit(); + } + } + } + } + + // + // The following operations involve only one cursor + // + + private boolean preCheck() { + checkThisCursor(); + return _cur._locale.noSync(); + } + + public void dispose() { + if (_cur != null) { + syncWrap(this::_dispose); + } + } + + public Object monitor() { + return syncWrap(this::_monitor); + } + + public XmlDocumentProperties documentProperties() { + return syncWrap(this::_documentProperties); + } + + public XmlCursor newCursor() { + return syncWrap(this::_newCursor); + } + + public XMLStreamReader newXMLStreamReader() { + return syncWrap((Supplier) this::_newXMLStreamReader); + } + + public XMLStreamReader newXMLStreamReader(XmlOptions options) { + return syncWrap(() -> _newXMLStreamReader(options)); + } + + public String xmlText() { + return syncWrap((Supplier) this::_xmlText); + } + + public InputStream newInputStream() { + return syncWrap((Supplier) this::_newInputStream); + } + + public Reader newReader() { + return syncWrap((Supplier) this::_newReader); + } + + public Node newDomNode() { + return syncWrap((Supplier) this::_newDomNode); + } + + public Node getDomNode() { + return syncWrap(this::_getDomNode); + } + + public void save(ContentHandler ch, LexicalHandler lh) throws SAXException { + syncWrapSAXEx(() -> _save(ch, lh)); + } + + public void save(File file) throws IOException { + syncWrapIOEx(() -> _save(file)); + } + + public void save(OutputStream os) throws IOException { + syncWrapIOEx(() -> _save(os)); + } + + public void save(Writer w) throws IOException { + syncWrapIOEx(() -> _save(w)); + } + + public String xmlText(XmlOptions options) { + return syncWrap(() -> _xmlText(options)); + } + + public InputStream newInputStream(XmlOptions options) { + return syncWrap(() -> _newInputStream(options)); + } + + public Reader newReader(XmlOptions options) { + return syncWrap(() -> _newReader(options)); + } + + public Node newDomNode(XmlOptions options) { + return syncWrap(() -> _newDomNode(options)); + } + + public void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException { + syncWrapSAXEx(() -> _save(ch, lh, options)); + } + + public void save(File file, XmlOptions options) throws IOException { + syncWrapIOEx(() -> _save(file, options)); + } + + public void save(OutputStream os, XmlOptions options) throws IOException { + syncWrapIOEx(() -> _save(os, options)); + } + + public void save(Writer w, XmlOptions options) throws IOException { + syncWrapIOEx(() -> _save(w, options)); + } + + public void push() { + syncWrap(this::_push); + } + + public boolean pop() { + return syncWrap(this::_pop); + } + + public void selectPath(String path) { + syncWrap(() -> _selectPath(path)); + } + + public void selectPath(String path, XmlOptions options) { + syncWrap(() -> _selectPath(path, options)); + } + + public boolean hasNextSelection() { + return syncWrap(this::_hasNextSelection); + } + + public boolean toNextSelection() { + return syncWrap(this::_toNextSelection); + } + + public boolean toSelection(int i) { + return syncWrap(() -> _toSelection(i)); + } + + public int getSelectionCount() { + return syncWrap(this::_getSelectionCount); + } + + public void addToSelection() { + syncWrap(this::_addToSelection); + } + + public void clearSelections() { + syncWrap(this::_clearSelections); + } + + public boolean toBookmark(XmlBookmark bookmark) { + return syncWrap(() -> _toBookmark(bookmark)); + } + + public XmlBookmark toNextBookmark(Object key) { + return syncWrap(() -> _toNextBookmark(key)); + } + + public XmlBookmark toPrevBookmark(Object key) { + return syncWrap(() -> _toPrevBookmark(key)); + } + + public QName getName() { + return syncWrap(this::_getName); + } + + public void setName(QName name) { + syncWrap(() -> _setName(name)); + } + + public String namespaceForPrefix(String prefix) { + return syncWrap(() -> _namespaceForPrefix(prefix)); + } + + public String prefixForNamespace(String namespaceURI) { + return syncWrap(() -> _prefixForNamespace(namespaceURI)); + } + + public void getAllNamespaces(Map addToThis) { + syncWrap(() -> _getAllNamespaces(addToThis)); + } + + public XmlObject getObject() { + return syncWrap(this::_getObject); + } + + public TokenType currentTokenType() { + return syncWrapNoEnter(this::_currentTokenType); + } + + public boolean isStartdoc() { + return syncWrapNoEnter(this::_isStartdoc); + } + + public boolean isEnddoc() { + return syncWrapNoEnter(this::_isEnddoc); + } + + public boolean isStart() { + return syncWrapNoEnter(this::_isStart); + } + + public boolean isEnd() { + return syncWrapNoEnter(this::_isEnd); + } + + public boolean isText() { + return syncWrapNoEnter(this::_isText); + } + + public boolean isAttr() { + return syncWrapNoEnter(this::_isAttr); + } + + public boolean isNamespace() { + return syncWrapNoEnter(this::_isNamespace); + } + + public boolean isComment() { + return syncWrapNoEnter(this::_isComment); + } + + public boolean isProcinst() { + return syncWrapNoEnter(this::_isProcinst); + } + + public boolean isContainer() { + return syncWrapNoEnter(this::_isContainer); + } + + public boolean isFinish() { + return syncWrapNoEnter(this::_isFinish); + } + + public boolean isAnyAttr() { + return syncWrapNoEnter(this::_isAnyAttr); + } + + public TokenType prevTokenType() { + return syncWrap(this::_prevTokenType); + } + + public boolean hasNextToken() { + return syncWrapNoEnter(this::_hasNextToken); + } + + public boolean hasPrevToken() { + return syncWrap(this::_hasPrevToken); + } + + public TokenType toNextToken() { + return syncWrap(this::_toNextToken); + } + + public TokenType toPrevToken() { + return syncWrap(this::_toPrevToken); + } + + public TokenType toFirstContentToken() { + return syncWrap(this::_toFirstContentToken); + } + + public TokenType toEndToken() { + return syncWrap(this::_toEndToken); + } + + public int toNextChar(int cch) { + return syncWrap(() -> _toNextChar(cch)); + } + + public int toPrevChar(int cch) { + return syncWrap(() -> _toPrevChar(cch)); + } + +// public boolean _toNextSibling() +// { +// return Locale.toNextSiblingElement(_cur); +// } + + public boolean ___toNextSibling() { + if (!_cur.hasParent()) { + return false; + } + + Xobj parent = _cur.getParentNoRoot(); + + if (parent == null) { + _cur._locale.enter(); + try { + parent = _cur.getParent(); + } finally { + _cur._locale.exit(); + } + } + + return Locale.toNextSiblingElement(_cur, parent); + } + + public boolean toNextSibling() { + return syncWrapNoEnter(this::___toNextSibling); + } + + public boolean toPrevSibling() { + return syncWrap(this::_toPrevSibling); + } + + public boolean toParent() { + return syncWrap(this::_toParent); + } + + public boolean toFirstChild() { + return syncWrapNoEnter(this::_toFirstChild); + } + + public boolean toLastChild() { + return syncWrap(this::_toLastChild); + } + + public boolean toChild(String name) { + return syncWrap(() -> _toChild(name)); + } + + public boolean toChild(String namespace, String name) { + return syncWrap(() -> _toChild(namespace, name)); + } + + public boolean toChild(QName name) { + return syncWrap(() -> _toChild(name)); + } + + public boolean toChild(int index) { + return syncWrap(() -> _toChild(index)); + } + + public boolean toChild(QName name, int index) { + return syncWrap(() -> _toChild(name, index)); + } + + public boolean toNextSibling(String name) { + return syncWrap(() -> _toNextSibling(name)); + } + + public boolean toNextSibling(String namespace, String name) { + return syncWrap(() -> _toNextSibling(namespace, name)); + } + + public boolean toNextSibling(QName name) { + return syncWrap(() -> _toNextSibling(name)); + } + + public boolean toFirstAttribute() { + return syncWrapNoEnter(this::_toFirstAttribute); + } + + public boolean toLastAttribute() { + return syncWrap(this::_toLastAttribute); + } + + public boolean toNextAttribute() { + return syncWrap(this::_toNextAttribute); + } + + public boolean toPrevAttribute() { + return syncWrap(this::_toPrevAttribute); + } + + public String getAttributeText(QName attrName) { + return syncWrap(() -> _getAttributeText(attrName)); + } + + public boolean setAttributeText(QName attrName, String value) { + return syncWrap(() -> _setAttributeText(attrName, value)); + } + + public boolean removeAttribute(QName attrName) { + return syncWrap(() -> _removeAttribute(attrName)); + } + + public String getTextValue() { + return syncWrap((Supplier) this::_getTextValue); + } + + public int getTextValue(char[] chars, int offset, int cch) { + return syncWrap(() -> _getTextValue(chars, offset, cch)); + } + + public void setTextValue(String text) { + syncWrap(() -> _setTextValue(text)); + } + + public void setTextValue(char[] sourceChars, int offset, int length) { + syncWrap(() -> _setTextValue(sourceChars, offset, length)); + } + + public String getChars() { + return syncWrap((Supplier) this::_getChars); + } + + public int getChars(char[] chars, int offset, int cch) { + return syncWrap(() -> _getChars(chars, offset, cch)); + } + + public void toStartDoc() { + syncWrapNoEnter(this::_toStartDoc); + } + + public void toEndDoc() { + syncWrapNoEnter(this::_toEndDoc); + } + + public XmlCursor execQuery(String query) { + return syncWrap(() -> _execQuery(query)); + } + + public XmlCursor execQuery(String query, XmlOptions options) { + return syncWrap(() -> _execQuery(query, options)); + } + + public ChangeStamp getDocChangeStamp() { + return syncWrap(this::_getDocChangeStamp); + } + + public void setBookmark(XmlBookmark bookmark) { + syncWrap(() -> _setBookmark(bookmark)); + } + + public XmlBookmark getBookmark(Object key) { + return syncWrap(() -> _getBookmark(key)); + } + + public void clearBookmark(Object key) { + syncWrap(() -> _clearBookmark(key)); + } + + public void getAllBookmarkRefs(Collection listToFill) { + syncWrap(() -> _getAllBookmarkRefs(listToFill)); + } + + public boolean removeXml() { + return syncWrap(this::_removeXml); + } + + public boolean removeXmlContents() { + return syncWrap(this::_removeXmlContents); + } + + public int removeChars(int cch) { + return syncWrap(() -> _removeChars(cch)); + } + + public void insertChars(String text) { + syncWrap(() -> _insertChars(text)); + } + + public void insertElement(QName name) { + syncWrap(() -> _insertElement(name)); + } + + public void insertElement(String localName) { + syncWrap(() -> _insertElement(localName)); + } + + public void insertElement(String localName, String uri) { + syncWrap(() -> _insertElement(localName, uri)); + } + + public void beginElement(QName name) { + syncWrap(() -> _beginElement(name)); + } + + public void beginElement(String localName) { + syncWrap(() -> _beginElement(localName)); + } + + public void beginElement(String localName, String uri) { + syncWrap(() -> _beginElement(localName, uri)); + } + + public void insertElementWithText(QName name, String text) { + syncWrap(() -> _insertElementWithText(name, text)); + } + + public void insertElementWithText(String localName, String text) { + syncWrap(() -> _insertElementWithText(localName, text)); + } + + public void insertElementWithText(String localName, String uri, String text) { + syncWrap(() -> _insertElementWithText(localName, uri, text)); + } + + public void insertAttribute(String localName) { + syncWrap(() -> _insertAttribute(localName)); + } + + public void insertAttribute(String localName, String uri) { + syncWrap(() -> _insertAttribute(localName, uri)); + } + + public void insertAttribute(QName name) { + syncWrap(() -> _insertAttribute(name)); + } + + public void insertAttributeWithValue(String name, String value) { + syncWrap(() -> _insertAttributeWithValue(name, value)); + } + + public void insertAttributeWithValue(String name, String uri, String value) { + syncWrap(() -> _insertAttributeWithValue(name, uri, value)); + } + + public void insertAttributeWithValue(QName name, String value) { + syncWrap(() -> _insertAttributeWithValue(name, value)); + } + + public void insertNamespace(String prefix, String namespace) { + syncWrap(() -> _insertNamespace(prefix, namespace)); + } + + public void insertComment(String text) { + syncWrap(() -> _insertComment(text)); + } + + public void insertProcInst(String target, String text) { + syncWrap(() -> _insertProcInst(target, text)); + } + + public void dump() { + syncWrap(this::_dump); + } + + private interface WrapSAXEx { + void run() throws SAXException; + } + + private interface WrapIOEx { + void run() throws IOException; + } + + + @SuppressWarnings("SynchronizeOnNonFinalField") + private void syncWrap(Runnable inner) { + if (preCheck()) { + syncWrapHelper(inner, true); + } else { + synchronized (_cur._locale) { + syncWrapHelper(inner, true); + } + } + } + + @SuppressWarnings("SynchronizeOnNonFinalField") + private T syncWrap(Supplier inner) { + if (preCheck()) { + return syncWrapHelper(inner, true); + } else { + synchronized (_cur._locale) { + return syncWrapHelper(inner, true); + } + } + } + + @SuppressWarnings("SynchronizeOnNonFinalField") + private T syncWrapNoEnter(Supplier inner) { + if (preCheck()) { + return syncWrapHelper(inner, false); + } else { + synchronized (_cur._locale) { + return syncWrapHelper(inner, false); + } + } + } + + @SuppressWarnings("SynchronizeOnNonFinalField") + private void syncWrapNoEnter(Runnable inner) { + if (preCheck()) { + syncWrapHelper(inner, false); + } else { + synchronized (_cur._locale) { + syncWrapHelper(inner, false); + } + } + } + + @SuppressWarnings("SynchronizeOnNonFinalField") + private void syncWrapSAXEx(WrapSAXEx inner) throws SAXException { + if (preCheck()) { + syncWrapHelper(inner); + } else { + synchronized (_cur._locale) { + syncWrapHelper(inner); + } + } + } + + @SuppressWarnings("SynchronizeOnNonFinalField") + private void syncWrapIOEx(WrapIOEx inner) throws IOException { + if (preCheck()) { + syncWrapHelper(inner); + } else { + synchronized (_cur._locale) { + syncWrapHelper(inner); + } + } + } + + private void syncWrapHelper(Runnable inner, final boolean enterLocale) { + final Locale l = _cur._locale; + if (enterLocale) { + l.enter(); + } + try { + inner.run(); + } finally { + if (enterLocale) { + l.exit(); + } + } + } + + private T syncWrapHelper(Supplier inner, final boolean enterLocale) { + final Locale l = _cur._locale; + if (enterLocale) { + l.enter(); + } + try { + return inner.get(); + } finally { + if (enterLocale) { + l.exit(); + } + } + } + + private void syncWrapHelper(WrapSAXEx inner) throws SAXException { + final Locale l = _cur._locale; + l.enter(); + try { + inner.run(); + } finally { + l.exit(); + } + } + + private void syncWrapHelper(WrapIOEx inner) throws IOException { + final Locale l = _cur._locale; + l.enter(); + try { + inner.run(); + } finally { + l.exit(); + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DetailEntryXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/DetailEntryXobj.java new file mode 100644 index 0000000..9aacf20 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/DetailEntryXobj.java @@ -0,0 +1,30 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.DetailEntry; + +import javax.xml.namespace.QName; + +class DetailEntryXobj extends SoapElementXobj implements DetailEntry { + Xobj newNode(Locale l) { + return new DetailEntryXobj(l, _name); + } + + DetailEntryXobj(Locale l, QName name) { + super(l, name); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DetailXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/DetailXobj.java new file mode 100644 index 0000000..4756a3b --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/DetailXobj.java @@ -0,0 +1,41 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.Detail; +import org.apache.xmlbeans.impl.soap.DetailEntry; +import org.apache.xmlbeans.impl.soap.Name; + +import javax.xml.namespace.QName; +import java.util.Iterator; + +class DetailXobj extends SoapFaultElementXobj implements Detail { + DetailXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new DetailXobj(l, _name); + } + + public DetailEntry addDetailEntry(Name name) { + return DomImpl.detail_addDetailEntry(this, name); + } + + public Iterator getDetailEntries() { + return DomImpl.detail_getDetailEntries(this); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DocumentFragXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/DocumentFragXobj.java new file mode 100644 index 0000000..6d5477e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/DocumentFragXobj.java @@ -0,0 +1,31 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.DocumentFragment; + +import static org.apache.xmlbeans.impl.store.Cur.ROOT; + +class DocumentFragXobj extends NodeXobj implements DocumentFragment { + DocumentFragXobj(Locale l) { + super(l, ROOT, DomImpl.DOCFRAG); + } + + Xobj newNode(Locale l) { + return new DocumentFragXobj(l); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DocumentXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/DocumentXobj.java new file mode 100644 index 0000000..60eb36e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/DocumentXobj.java @@ -0,0 +1,184 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.*; + +import static org.apache.xmlbeans.impl.store.Cur.ROOT; + +class DocumentXobj extends NodeXobj implements Document { + DocumentXobj(Locale l) { + super(l, ROOT, DomImpl.DOCUMENT); + } + + Xobj newNode(Locale l) { + return new DocumentXobj(l); + } + + // + // + // + + public Attr createAttribute(String name) { + return DomImpl._document_createAttribute(this, name); + } + + public Attr createAttributeNS(String namespaceURI, String qualifiedName) { + return DomImpl._document_createAttributeNS(this, namespaceURI, qualifiedName); + } + + public CDATASection createCDATASection(String data) { + return DomImpl._document_createCDATASection(this, data); + } + + public Comment createComment(String data) { + return DomImpl._document_createComment(this, data); + } + + public DocumentFragment createDocumentFragment() { + return DomImpl._document_createDocumentFragment(this); + } + + public Element createElement(String tagName) { + return DomImpl._document_createElement(this, tagName); + } + + public Element createElementNS(String namespaceURI, String qualifiedName) { + return DomImpl._document_createElementNS(this, namespaceURI, qualifiedName); + } + + public EntityReference createEntityReference(String name) { + return DomImpl._document_createEntityReference(this, name); + } + + public ProcessingInstruction createProcessingInstruction(String target, String data) { + return DomImpl._document_createProcessingInstruction(this, target, data); + } + + public Text createTextNode(String data) { + return DomImpl._document_createTextNode(this, data); + } + + public DocumentType getDoctype() { + return DomImpl._document_getDoctype(this); + } + + public Element getDocumentElement() { + return DomImpl._document_getDocumentElement(this); + } + + public Element getElementById(String elementId) { + if (_idToElement == null) { + return null; + } + Xobj o = (Xobj) _idToElement.get(elementId); + if (o == null) { + return null; + } + if (!isInSameTree(o)) { + _idToElement.remove(elementId); + } + return (Element) o; + } + + public NodeList getElementsByTagName(String tagname) { + return DomImpl._document_getElementsByTagName(this, tagname); + } + + public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { + return DomImpl._document_getElementsByTagNameNS(this, namespaceURI, localName); + } + + public DOMImplementation getImplementation() { + return DomImpl._document_getImplementation(this); + } + + public Node importNode(Node importedNode, boolean deep) { + return DomImpl._document_importNode(this, importedNode, deep); + } + + // DOM Level 3 + public Node adoptNode(Node source) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getDocumentURI() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public DOMConfiguration getDomConfig() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getInputEncoding() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public boolean getStrictErrorChecking() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getXmlEncoding() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public boolean getXmlStandalone() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getXmlVersion() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void normalizeDocument() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public Node renameNode(Node n, String namespaceURI, String qualifiedName) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setDocumentURI(String documentURI) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setStrictErrorChecking(boolean strictErrorChecking) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setXmlStandalone(boolean xmlStandalone) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setXmlVersion(String xmlVersion) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + protected void addIdElement(String idVal, DomImpl.Dom e) { + if (_idToElement == null) { + _idToElement = new java.util.Hashtable<>(); + } + _idToElement.put(idVal, e); + } + + void removeIdElement(String idVal) { + if (_idToElement != null) { + _idToElement.remove(idVal); + } + } + + private java.util.Hashtable _idToElement; +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DomImpl.java b/src/main/java/org/apache/xmlbeans/impl/store/DomImpl.java new file mode 100755 index 0000000..2b93134 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/DomImpl.java @@ -0,0 +1,3792 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlRuntimeException; +import org.apache.xmlbeans.impl.common.XMLChar; +import org.apache.xmlbeans.impl.soap.*; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import org.w3c.dom.*; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.Source; +import java.io.PrintStream; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +// DOM Level 3 + +public final class DomImpl { + static final int ELEMENT = Node.ELEMENT_NODE; + static final int ATTR = Node.ATTRIBUTE_NODE; + static final int TEXT = Node.TEXT_NODE; + static final int CDATA = Node.CDATA_SECTION_NODE; + static final int ENTITYREF = Node.ENTITY_REFERENCE_NODE; + static final int ENTITY = Node.ENTITY_NODE; + static final int PROCINST = Node.PROCESSING_INSTRUCTION_NODE; + static final int COMMENT = Node.COMMENT_NODE; + static final int DOCUMENT = Node.DOCUMENT_NODE; + static final int DOCTYPE = Node.DOCUMENT_TYPE_NODE; + static final int DOCFRAG = Node.DOCUMENT_FRAGMENT_NODE; + static final int NOTATION = Node.NOTATION_NODE; + + public interface Dom { + Locale locale(); + + int nodeType(); + + Cur tempCur(); + + QName getQName(); + + boolean nodeCanHavePrefixUri(); + + void dump(); + + void dump(PrintStream o); + + void dump(PrintStream o, Object ref); + } + + static Node parent(Dom d) { + return node_getParentNode(d); + } + + static Node firstChild(Dom d) { + return node_getFirstChild(d); + } + + static Node nextSibling(Dom d) { + return node_getNextSibling(d); + } + + static Node prevSibling(Dom d) { + return node_getPreviousSibling(d); + } + + public static Node append(Dom n, Dom p) { + return node_insertBefore(p, n, null); + } + + public static Node insert(Dom n, Dom b) { + assert b != null; + return node_insertBefore((Dom) parent(b), n, b); + } + + public static Node remove(Dom n) { + Node p = parent(n); + + if (p != null) { + node_removeChild((Dom) p, n); + } + + return (Node) n; + } + + // + // Handy dandy Dom exceptions + // + + static class HierarchyRequestErr extends DOMException { + HierarchyRequestErr(String message) { + super(HIERARCHY_REQUEST_ERR, message); + } + } + + static class WrongDocumentErr extends DOMException { + WrongDocumentErr(String message) { + super(WRONG_DOCUMENT_ERR, message); + } + } + + static class NotFoundErr extends DOMException { + NotFoundErr(String message) { + super(NOT_FOUND_ERR, message); + } + } + + static class NamespaceErr extends DOMException { + NamespaceErr(String message) { + super(NAMESPACE_ERR, message); + } + } + + static class NoModificationAllowedErr extends DOMException { + NoModificationAllowedErr(String message) { + super(NO_MODIFICATION_ALLOWED_ERR, message); + } + } + + static class InuseAttributeError extends DOMException { + InuseAttributeError() { + this("Attribute currently in use error"); + } + + InuseAttributeError(String message) { + super(INUSE_ATTRIBUTE_ERR, message); + } + } + + static class IndexSizeError extends DOMException { + IndexSizeError() { + this("Index Size Error"); + } + + IndexSizeError(String message) { + super(INDEX_SIZE_ERR, message); + } + } + + static class NotSupportedError extends DOMException { + NotSupportedError(String message) { + super(NOT_SUPPORTED_ERR, message); + } + } + + static class InvalidCharacterError extends DOMException { + InvalidCharacterError() { + this("The name contains an invalid character"); + } + + InvalidCharacterError(String message) { + super(INVALID_CHARACTER_ERR, message); + } + } + + // + // Helper fcns + // + + private static final class EmptyNodeList implements NodeList { + public int getLength() { + return 0; + } + + public Node item(int i) { + return null; + } + } + + public static final NodeList _emptyNodeList = new EmptyNodeList(); + + static String nodeKindName(int t) { + switch (t) { + case ATTR: + return "attribute"; + case CDATA: + return "cdata section"; + case COMMENT: + return "comment"; + case DOCFRAG: + return "document fragment"; + case DOCUMENT: + return "document"; + case DOCTYPE: + return "document type"; + case ELEMENT: + return "element"; + case ENTITY: + return "entity"; + case ENTITYREF: + return "entity reference"; + case NOTATION: + return "notation"; + case PROCINST: + return "processing instruction"; + case TEXT: + return "text"; + + default: + throw new RuntimeException("Unknown node type"); + } + } + + private static String isValidChild(Dom parent, Dom child) { + int pk = parent.nodeType(); + int ck = child.nodeType(); + + switch (pk) { + case DOCUMENT: { + switch (ck) { + case ELEMENT: { + if (document_getDocumentElement(parent) != null) { + return "Documents may only have a maximum of one document element"; + } + + return null; + } + case DOCTYPE: { + if (document_getDoctype(parent) != null) { + return "Documents may only have a maximum of one document type node"; + } + + return null; + } + case PROCINST: + case COMMENT: + return null; + } + + break; + } + + case ATTR: { + if (ck == TEXT || ck == ENTITYREF) { + return null; + } + + // TODO -- traverse the entity tree, making sure that there are + // only entity refs and text nodes in it. + + break; + } + + case DOCFRAG: + case ELEMENT: + case ENTITY: + case ENTITYREF: { + switch (ck) { + case ELEMENT: + case ENTITYREF: + case CDATA: + case TEXT: + case COMMENT: + case PROCINST: + return null; + } + + break; + } + + case CDATA: + case TEXT: + case COMMENT: + case PROCINST: + case DOCTYPE: + case NOTATION: + return nodeKindName(pk) + " nodes may not have any children"; + } + + return + nodeKindName(pk) + " nodes may not have " + + nodeKindName(ck) + " nodes as children"; + } + + private static void validateNewChild(final Dom parent, Dom child) { + String msg = isValidChild(parent, child); + + if (msg != null) { + throw new HierarchyRequestErr(msg); + } + + if (parent == child) { + throw new HierarchyRequestErr("New child and parent are the same node"); + } + + for (Node p = (Node) parent; (p = parent((Dom) p)) != null; ) { + // TODO - use read only state on a node to know if it is under an + // entity ref + + if (child.nodeType() == ENTITYREF) { + throw new NoModificationAllowedErr("Entity reference trees may not be modified"); + } + + if (child == p) { + throw new HierarchyRequestErr("New child is an ancestor node of the parent node"); + } + } + } + + private static String validatePrefix( + String prefix, String uri, String local, boolean isAttr) { + validateNcName(prefix); + + if (prefix == null) { + prefix = ""; + } + + if (uri == null) { + uri = ""; + } + + if (prefix.length() > 0 && uri.length() == 0) { + throw new NamespaceErr("Attempt to give a prefix for no namespace"); + } + + if (prefix.equals("xml") && !uri.equals(Locale._xml1998Uri)) { + throw new NamespaceErr("Invalid prefix - begins with 'xml'"); + } + + if (isAttr) { + if (prefix.length() > 0) { + if (local.equals("xmlns")) { + throw new NamespaceErr("Invalid namespace - attr is default namespace already"); + } + + if (Locale.beginsWithXml(local)) { + throw new NamespaceErr("Invalid namespace - attr prefix begins with 'xml'"); + } + + if (prefix.equals("xmlns") && !uri.equals(Locale._xmlnsUri)) { + throw new NamespaceErr("Invalid namespace - uri is not '" + Locale._xmlnsUri + ";"); + } + } else { + if (local.equals("xmlns") && !uri.equals(Locale._xmlnsUri)) { + throw new NamespaceErr("Invalid namespace - uri is not '" + Locale._xmlnsUri + ";"); + } + } + } else if (Locale.beginsWithXml(prefix)) { + throw new NamespaceErr("Invalid prefix - begins with 'xml'"); + } + + return prefix; + } + + private static void validateName(String name) { + if (name == null) { + throw new IllegalArgumentException("Name is null"); + } + + if (name.length() == 0) { + throw new IllegalArgumentException("Name is empty"); + } + + if (!XMLChar.isValidName(name)) { + throw new InvalidCharacterError("Name has an invalid character"); + } + } + + private static void validateNcName(String name) { + if (name != null && name.length() > 0 && !XMLChar.isValidNCName(name)) { + throw new InvalidCharacterError(); + } + } + + private static void validateQualifiedName(String name, String uri, boolean isAttr) { + assert name != null; + + if (uri == null) { + uri = ""; + } + + int i = name.indexOf(':'); + + String local; + + if (i < 0) { + validateNcName(local = name); + + if (isAttr && local.equals("xmlns") && !uri.equals(Locale._xmlnsUri)) { + throw + new NamespaceErr( + "Default xmlns attribute does not have namespace: " + Locale._xmlnsUri); + } + } else { + if (i == 0) { + throw new NamespaceErr("Invalid qualified name, no prefix specified"); + } + + String prefix = name.substring(0, i); + + validateNcName(prefix); + + if (uri.length() == 0) { + throw new NamespaceErr("Attempt to give a prefix for no namespace"); + } + + local = name.substring(i + 1); + + if (local.indexOf(':') >= 0) { + throw new NamespaceErr("Invalid qualified name, more than one colon"); + } + + validateNcName(local); + + if (prefix.equals("xml") && !uri.equals(Locale._xml1998Uri)) { + throw new NamespaceErr("Invalid prefix - begins with 'xml'"); + } + } + + if (local.length() == 0) { + throw new NamespaceErr("Invalid qualified name, no local part specified"); + } + } + + private static void removeNode(Dom n) { + assert n.nodeType() != TEXT && n.nodeType() != CDATA; + + Cur cFrom = n.tempCur(); + + cFrom.toEnd(); + + // Move any char nodes which ater after the node to remove to be before it. The call to + // Next here does two things, it tells me if I can get after the move to remove (all nodes + // but the root) and it positions me at the place where there are char nodes after. + + if (cFrom.next()) { + CharNode fromNodes = cFrom.getCharNodes(); + + if (fromNodes != null) { + cFrom.setCharNodes(null); + Cur cTo = n.tempCur(); + cTo.setCharNodes(CharNode.appendNodes(cTo.getCharNodes(), fromNodes)); + cTo.release(); + } + } + + cFrom.release(); + + Cur.moveNode((Xobj) n, null); + } + + private abstract static class ElementsNodeList implements NodeList { + ElementsNodeList(Dom root) { + assert root.nodeType() == DOCUMENT || root.nodeType() == ELEMENT; + + _root = root; + _locale = _root.locale(); + _version = 0; + } + + public int getLength() { + ensureElements(); + + return _elements.size(); + } + + public Node item(int i) { + ensureElements(); + return i < 0 || i >= _elements.size() ? null : (Node) _elements.get(i); + } + + private void ensureElements() { + if (_version == _locale.version()) { + return; + } + + _version = _locale.version(); + _elements = new ArrayList<>(); + + syncWrapHelper(_locale, true, () -> { + addElements(_root); + return null; + }); + } + + private void addElements(Dom node) { + for (Node c = firstChild(node); c != null; c = nextSibling((Dom) c)) { + if (((Dom) c).nodeType() == ELEMENT) { + if (match((Dom) c)) { + _elements.add((Dom) c); + } + + addElements((Dom) c); + } + } + } + + protected abstract boolean match(Dom element); + + private final Dom _root; + private final Locale _locale; + private long _version; + private ArrayList _elements; + } + + private static class ElementsByTagNameNodeList extends ElementsNodeList { + ElementsByTagNameNodeList(Dom root, String name) { + super(root); + _name = name; + assert (_name != null); + } + + protected boolean match(Dom element) { + return _name.equals("*") || _name.equals(_node_getNodeName(element)); + } + + private final String _name; + } + + private static class ElementsByTagNameNSNodeList extends ElementsNodeList { + ElementsByTagNameNSNodeList(Dom root, String uri, String local) { + super(root); + + _uri = uri == null ? "" : uri; + _local = local; + assert (local != null); + } + + protected boolean match(Dom element) { + if (!(_uri.equals("*") || _uri.equals(_node_getNamespaceURI(element)))) { + return false; + } + + return _local.equals("*") || _local.equals(_node_getLocalName(element)); + } + + private final String _uri; + private final String _local; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Document _domImplementation_createDocument(Locale l, String u, String n, DocumentType t) { + return syncWrapHelper(l, true, () -> domImplementation_createDocument(l, u, n, t)); + } + + public static Document domImplementation_createDocument( + Locale l, String namespaceURI, String qualifiedName, DocumentType doctype) { + validateQualifiedName(qualifiedName, namespaceURI, false); + + Cur c = l.tempCur(); + c.createDomDocumentRoot(); + Document doc = (Document) c.getDom(); + c.next(); + c.createElement(l.makeQualifiedQName(namespaceURI, qualifiedName)); + + if (doctype != null) { + throw new RuntimeException("Not impl"); + } + + c.toParent(); + + try { + Locale.autoTypeDocument(c, null, null); + } catch (XmlException e) { + throw new XmlRuntimeException(e); + } + + c.release(); + + return doc; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static boolean _domImplementation_hasFeature(Locale l, String feature, String version) { + if (feature == null) { + return false; + } + + if (version != null && version.length() > 0 && + !version.equals("1.0") && !version.equals("2.0")) { + return false; + } + + if (feature.equalsIgnoreCase("core")) { + return true; + } + + return feature.equalsIgnoreCase("xml"); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Element _document_getDocumentElement(Dom d) { + return syncWrap(d, DomImpl::document_getDocumentElement); + } + + public static Element document_getDocumentElement(final Dom d) { + for (Node n = firstChild(d); n != null; n = nextSibling((Dom) n)) { + if (((Dom) n).nodeType() == ELEMENT) { + return (Element) n; + } + } + + return null; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static DocumentFragment _document_createDocumentFragment(Dom d) { + return syncWrap(d, DomImpl::document_createDocumentFragment); + } + + public static DocumentFragment document_createDocumentFragment(Dom d) { + Cur c = d.locale().tempCur(); + c.createDomDocFragRoot(); + Dom f = c.getDom(); + c.release(); + return (DocumentFragment) f; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Element _document_createElement(Dom d, String name) { + return syncWrap(d, p -> document_createElement(p, name)); + } + + public static Element document_createElement(Dom d, String name) { + validateName(name); + Locale l = d.locale(); + Cur c = l.tempCur(); + c.createElement(l.makeQualifiedQName("", name)); + ElementXobj e = (ElementXobj) c.getDom(); + c.release(); + e._canHavePrefixUri = false; + return e; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Element _document_createElementNS(Dom d, String uri, String qname) { + return syncWrap(d, p -> document_createElementNS(p, uri, qname)); + } + + public static Element document_createElementNS(Dom d, String uri, String qname) { + validateQualifiedName(qname, uri, false); + Locale l = d.locale(); + Cur c = l.tempCur(); + c.createElement(l.makeQualifiedQName(uri, qname)); + Dom e = c.getDom(); + c.release(); + return (Element) e; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _document_createAttribute(Dom d, String name) { + return syncWrap(d, p -> document_createAttribute(p, name)); + } + + public static Attr document_createAttribute(Dom d, String name) { + validateName(name); + Locale l = d.locale(); + Cur c = l.tempCur(); + c.createAttr(l.makeQualifiedQName("", name)); + AttrXobj e = (AttrXobj) c.getDom(); + c.release(); + e._canHavePrefixUri = false; + return e; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _document_createAttributeNS(Dom d, String uri, String qname) { + return syncWrap(d, p -> document_createAttributeNS(p, uri, qname)); + } + + public static Attr document_createAttributeNS(Dom d, String uri, String qname) { + validateQualifiedName(qname, uri, true); + Locale l = d.locale(); + Cur c = l.tempCur(); + c.createAttr(l.makeQualifiedQName(uri, qname)); + Dom e = c.getDom(); + c.release(); + return (Attr) e; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Comment _document_createComment(Dom d, String data) { + return syncWrap(d, p -> document_createComment(p, data)); + } + + public static Comment document_createComment(Dom d, String data) { + Locale l = d.locale(); + Cur c = l.tempCur(); + c.createComment(); + Dom comment = c.getDom(); + if (data != null) { + c.next(); + c.insertString(data); + } + c.release(); + return (Comment) comment; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static ProcessingInstruction _document_createProcessingInstruction(Dom d, String target, String data) { + return syncWrap(d, p -> document_createProcessingInstruction(p, target, data)); + } + + public static ProcessingInstruction document_createProcessingInstruction(Dom d, String target, String data) { + if (target == null) { + throw new IllegalArgumentException("Target is null"); + } + + if (target.length() == 0) { + throw new IllegalArgumentException("Target is empty"); + } + + if (!XMLChar.isValidName(target)) { + throw new InvalidCharacterError("Target has an invalid character"); + } + + if (Locale.beginsWithXml(target) && target.length() == 3) { + throw new InvalidCharacterError("Invalid target - is 'xml'"); + } + + Locale l = d.locale(); + Cur c = l.tempCur(); + c.createProcinst(target); + Dom pi = c.getDom(); + if (data != null) { + c.next(); + c.insertString(data); + } + c.release(); + return (ProcessingInstruction) pi; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static CDATASection _document_createCDATASection(Dom d, String data) { + return document_createCDATASection(d, data); + } + + public static CDATASection document_createCDATASection(Dom d, String data) { + TextNode t = d.locale().createCdataNode(); + + if (data == null) { + data = ""; + } + + t.setChars(data, 0, data.length()); + + return (CDATASection) t; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Text _document_createTextNode(Dom d, String data) { + return document_createTextNode(d, data); + } + + public static Text document_createTextNode(Dom d, String data) { + TextNode t = d.locale().createTextNode(); + + if (data == null) { + data = ""; + } + + t.setChars(data, 0, data.length()); + + return t; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static EntityReference _document_createEntityReference(Dom d, String name) { + throw new RuntimeException("Not implemented"); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static Element _document_getElementById(Dom d, String elementId) { + throw new RuntimeException("Not implemented"); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static NodeList _document_getElementsByTagName(Dom d, String name) { + return syncWrap(d, p -> document_getElementsByTagName(p, name)); + } + + public static NodeList document_getElementsByTagName(Dom d, String name) { + return new ElementsByTagNameNodeList(d, name); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static NodeList _document_getElementsByTagNameNS(Dom d, String uri, String local) { + return syncWrap(d, p -> document_getElementsByTagNameNS(p, uri, local)); + } + + public static NodeList document_getElementsByTagNameNS(Dom d, String uri, String local) { + return new ElementsByTagNameNSNodeList(d, uri, local); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static DOMImplementation _document_getImplementation(Dom d) { + return d.locale(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _document_importNode(Dom d, Node n, boolean deep) { + // TODO -- I'm importing my own nodes through DOM methods! -- make this faster + return syncWrap(d, p -> document_importNode(p, n, deep)); + } + + public static Node document_importNode(Dom d, Node n, boolean deep) { + if (n == null) { + return null; + } + + Node i; + + boolean copyChildren = false; + + switch (n.getNodeType()) { + case DOCUMENT: + throw new NotSupportedError("Document nodes may not be imported"); + + case DOCTYPE: + throw new NotSupportedError("Document type nodes may not be imported"); + + case ELEMENT: { + String local = n.getLocalName(); + + if (local == null || local.length() == 0) { + i = document_createElement(d, n.getNodeName()); + } else { + String prefix = n.getPrefix(); + String name = prefix == null || prefix.length() == 0 ? local : prefix + ":" + local; + String uri = n.getNamespaceURI(); + + if (uri == null || uri.length() == 0) { + i = document_createElement(d, name); + } else { + i = document_createElementNS(d, uri, name); + } + } + + NamedNodeMap attrs = n.getAttributes(); + + for (int a = 0; a < attrs.getLength(); a++) { + attributes_setNamedItem((Dom) i, (Dom) document_importNode(d, attrs.item(a), true)); + } + + copyChildren = deep; + + break; + } + + case ATTR: { + String local = n.getLocalName(); + + if (local == null || local.length() == 0) { + i = document_createAttribute(d, n.getNodeName()); + } else { + String prefix = n.getPrefix(); + String name = prefix == null || prefix.length() == 0 ? local : prefix + ":" + local; + String uri = n.getNamespaceURI(); + + if (uri == null || uri.length() == 0) { + i = document_createAttribute(d, name); + } else { + i = document_createAttributeNS(d, uri, name); + } + } + + copyChildren = true; + + break; + } + + case DOCFRAG: { + i = document_createDocumentFragment(d); + + copyChildren = deep; + + break; + } + + case PROCINST: { + i = document_createProcessingInstruction(d, n.getNodeName(), n.getNodeValue()); + break; + } + + case COMMENT: { + i = document_createComment(d, n.getNodeValue()); + break; + } + + case TEXT: { + i = document_createTextNode(d, n.getNodeValue()); + break; + } + + case CDATA: { + i = document_createCDATASection(d, n.getNodeValue()); + break; + } + + case ENTITYREF: + case ENTITY: + case NOTATION: + throw new RuntimeException("Not impl"); + + default: + throw new RuntimeException("Unknown kind"); + } + + if (copyChildren) { + NodeList children = n.getChildNodes(); + + for (int c = 0; c < children.getLength(); c++) { + node_insertBefore((Dom) i, (Dom) document_importNode(d, children.item(c), true), null); + } + } + + return i; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static DocumentType _document_getDoctype(Dom d) { + return syncWrap(d, DomImpl::document_getDoctype); + } + + public static DocumentType document_getDoctype(Dom d) { + return null; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Document _node_getOwnerDocument(Dom d) { + return syncWrap(d, DomImpl::node_getOwnerDocument); + } + + public static Document node_getOwnerDocument(Dom n) { + if (n.nodeType() == DOCUMENT) { + return null; + } + + Locale l = n.locale(); + + if (l._ownerDoc == null) { + Cur c = l.tempCur(); + c.createDomDocumentRoot(); + l._ownerDoc = c.getDom(); + c.release(); + } + + return (Document) l._ownerDoc; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_getParentNode(Dom d) { + return syncWrap(d, DomImpl::node_getParentNode); + } + + public static Node node_getParentNode(Dom n) { + Cur c = null; + + switch (n.nodeType()) { + case DOCUMENT: + case DOCFRAG: + case ATTR: + break; + + case PROCINST: + case COMMENT: + case ELEMENT: { + if (!(c = n.tempCur()).toParentRaw()) { + c.release(); + c = null; + } + + break; + } + + case TEXT: + case CDATA: { + if ((c = n.tempCur()) != null) { + c.toParent(); + } + + break; + } + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + default: + throw new RuntimeException("Unknown kind"); + } + + if (c == null) { + return null; + } + + Dom d = c.getDom(); + + c.release(); + + return (Node) d; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_getFirstChild(Dom n) { + assert n instanceof Xobj; + Xobj node = (Xobj) n; + if (!node.isVacant()) { + if (node.isFirstChildPtrDomUsable()) { + return (Node) node._firstChild; + } + Xobj lastAttr = node.lastAttr(); + if (lastAttr != null && + lastAttr.isNextSiblingPtrDomUsable()) { + return (NodeXobj) lastAttr._nextSibling; + } + if (node.isExistingCharNodesValueUsable()) { + return node._charNodesValue; + } + } + + return syncWrapNoEnter(n, DomImpl::node_getFirstChild); + } + + public static Node node_getFirstChild(Dom n) { + Dom fc = null; + + switch (n.nodeType()) { + case TEXT: + case CDATA: + case PROCINST: + case COMMENT: + break; + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + case ELEMENT: + case DOCUMENT: + case DOCFRAG: + case ATTR: { + + Xobj node = (Xobj) n; + node.ensureOccupancy(); + if (node.isFirstChildPtrDomUsable()) { + return (NodeXobj) node._firstChild; + } + Xobj lastAttr = node.lastAttr(); + if (lastAttr != null) { + if (lastAttr.isNextSiblingPtrDomUsable()) { + return (NodeXobj) lastAttr._nextSibling; + } else if (lastAttr.isCharNodesAfterUsable()) { + return lastAttr._charNodesAfter; + } + } + if (node.isCharNodesValueUsable()) { + return node._charNodesValue; + } + + + break; + } + } + + // TODO - handle entity refs here ... + + return (Node) fc; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_getLastChild(Dom n) { + return syncWrap(n, DomImpl::node_getLastChild); + } + + public static Node node_getLastChild(Dom n) { + switch (n.nodeType()) { + case TEXT: + case CDATA: + case PROCINST: + case COMMENT: + return null; + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + case ELEMENT: + case DOCUMENT: + case DOCFRAG: + case ATTR: + break; + } + + Dom lc = null; + CharNode nodes; + + Cur c = n.tempCur(); + + if (c.toLastChild()) { + lc = c.getDom(); + + c.skip(); + + if ((nodes = c.getCharNodes()) != null) { + lc = null; + } + } else { + c.next(); + nodes = c.getCharNodes(); + } + + if (lc == null && nodes != null) { + while (nodes._next != null) { + nodes = nodes._next; + } + + lc = nodes; + } + + c.release(); + + // TODO - handle entity refs here ... + + return (Node) lc; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_getNextSibling(Dom n) { + return syncWrapNoEnter(n, DomImpl::node_getNextSibling); + } + + public static Node node_getNextSibling(Dom n) { + Dom ns = null; + + switch (n.nodeType()) { + case DOCUMENT: + case DOCFRAG: + case ATTR: + break; + + case TEXT: + case CDATA: { + CharNode cn = (CharNode) n; + //if src is attr & next is null , ret null; + //if src is container and + // a) this node is aftertext && src._nextSib = null; ret null + // b) this node is value && src._fc = null; ret null + + + if (!(cn.getObject() instanceof Xobj)) { + return null; + } + Xobj src = (Xobj) cn.getObject(); + //if src is attr this node is always value and + // next is always the next ptr of the attr + src._charNodesAfter = + Cur.updateCharNodes(src._locale, src, src._charNodesAfter, src._cchAfter); + + src._charNodesValue = + Cur.updateCharNodes(src._locale, src, src._charNodesValue, src._cchValue); + + if (cn._next != null) { + ns = cn._next; + break; + } + boolean isThisNodeAfterText = cn.isNodeAftertext(); + + if (isThisNodeAfterText) { + ns = (NodeXobj) src._nextSibling; + } else //srcValue or attribute source + { + ns = (NodeXobj) src._firstChild; + } + break; + + } + + case PROCINST: + case COMMENT: + case ELEMENT: { + assert n instanceof Xobj : "PI, Comments and Elements always backed up by Xobj"; + Xobj node = (Xobj) n; + node.ensureOccupancy(); + if (node.isNextSiblingPtrDomUsable()) { + return + (NodeXobj) node._nextSibling; + } + if (node.isCharNodesAfterUsable()) { + return node._charNodesAfter; + } + break; + } + + case ENTITY: + case NOTATION: + case ENTITYREF: + case DOCTYPE: + throw new RuntimeException("Not implemented"); + } + + // TODO - handle entity refs here ... + + return (Node) ns; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_getPreviousSibling(Dom n) { + return syncWrapNoEnter(n, DomImpl::node_getPreviousSibling); + } + + public static Node node_getPreviousSibling(Dom n) { + Node prev; + switch (n.nodeType()) { + case TEXT: + case CDATA: { + assert n instanceof CharNode : "Text/CData should be a CharNode"; + CharNode node = (CharNode) n; + if (!(node.getObject() instanceof Xobj)) { + return null; + } + NodeXobj src = (NodeXobj) node.getObject(); + src.ensureOccupancy(); + boolean isThisNodeAfterText = node.isNodeAftertext(); + prev = node._prev; + if (prev == null) { + prev = isThisNodeAfterText ? src : src._charNodesValue; + } + break; + } + default: { + assert n instanceof NodeXobj; + NodeXobj node = (NodeXobj) n; + prev = (NodeXobj) node._prevSibling; + if ((prev == null || !(node instanceof AttrXobj) && prev instanceof AttrXobj) && + node._parent != null) { + prev = node_getFirstChild((Dom) node._parent); + } + } + } + Node temp = prev; + while (temp != null && (temp = node_getNextSibling((Dom) temp)) != n) { + prev = temp; + } + return prev; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static boolean _node_hasAttributes(Dom n) { + return syncWrap(n, DomImpl::node_hasAttributes); + } + + public static boolean node_hasAttributes(Dom n) { + boolean hasAttrs = false; + + if (n.nodeType() == ELEMENT) { + Cur c = n.tempCur(); + hasAttrs = c.hasAttrs(); + c.release(); + } + + return hasAttrs; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static boolean _node_isSupported(Dom n, String feature, String version) { + return _domImplementation_hasFeature(n.locale(), feature, version); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _node_normalize(Dom n) { + syncWrapVoid(n, DomImpl::node_normalize); + } + + public static void node_normalize(Dom n) { + switch (n.nodeType()) { + case TEXT: + case CDATA: + case PROCINST: + case COMMENT: + return; + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + case ELEMENT: + case DOCUMENT: + case DOCFRAG: + case ATTR: + break; + } + + Cur c = n.tempCur(); + + c.push(); + + do { + c.nextWithAttrs(); + + CharNode cn = c.getCharNodes(); + + if (cn != null) { + if (!c.isText()) { + while (cn != null) { + cn.setChars(null, 0, 0); + cn = CharNode.remove(cn, cn); + } + } else if (cn._next != null) { + while (cn._next != null) { + cn.setChars(null, 0, 0); + cn = CharNode.remove(cn, cn._next); + } + + cn._cch = Integer.MAX_VALUE; + } + + c.setCharNodes(cn); + } + } + while (!c.isAtEndOfLastPush()); + + c.release(); + + n.locale().invalidateDomCaches(n); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static boolean _node_hasChildNodes(Dom n) { + // TODO - make this faster + return n instanceof Xobj && _node_getFirstChild(n) != null; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_appendChild(Dom p, Node newChild) { + return _node_insertBefore(p, newChild, null); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_replaceChild(Dom p, Node newChild, Node oldChild) { + Locale l = p.locale(); + + if (newChild == null) { + throw new IllegalArgumentException("Child to add is null"); + } + + if (oldChild == null) { + throw new NotFoundErr("Child to replace is null"); + } + + Dom nc; + + if (!(newChild instanceof Dom) || (nc = (Dom) newChild).locale() != l) { + throw new WrongDocumentErr("Child to add is from another document"); + } + + Dom oc; + + if (!(oldChild instanceof Dom) || (oc = (Dom) oldChild).locale() != l) { + throw new WrongDocumentErr("Child to replace is from another document"); + } + + Dom oc2 = oc; + return syncWrap(p, x -> node_replaceChild(x, nc, oc2)); + } + + public static Node node_replaceChild(Dom p, Dom newChild, Dom oldChild) { + // Remove the old child firest to avoid a dom exception raised + // when inserting two document elements + + Node nextNode = node_getNextSibling(oldChild); + + node_removeChild(p, oldChild); + + try { + node_insertBefore(p, newChild, (Dom) nextNode); + } catch (DOMException e) { + node_insertBefore(p, oldChild, (Dom) nextNode); + + throw e; + } + + return (Node) oldChild; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_insertBefore(Dom p, Node newChild, Node refChild) { + Locale l = p.locale(); + + if (newChild == null) { + throw new IllegalArgumentException("Child to add is null"); + } + + Dom nc; + + if (!(newChild instanceof Dom) || (nc = (Dom) newChild).locale() != l) { + throw new WrongDocumentErr("Child to add is from another document"); + } + + Dom rc = null; + + if (refChild != null) { + if (!(refChild instanceof Dom) || (rc = (Dom) refChild).locale() != l) { + throw new WrongDocumentErr("Reference child is from another document"); + } + } + Dom rc2 = rc; + + return syncWrap(p, x -> node_insertBefore(x, nc, rc2)); + } + + public static Node node_insertBefore(Dom p, Dom nc, final Dom rc) { + assert nc != null; + + // Inserting self before self is a no-op + + if (nc == rc) { + return (Node) nc; + } + + if (rc != null && parent(rc) != p) { + throw new NotFoundErr("RefChild is not a child of this node"); + } + + // TODO - obey readonly status of a substree + + int nck = nc.nodeType(); + + if (nck == DOCFRAG) { + for (Node c = firstChild(nc); c != null; c = nextSibling((Dom) c)) { + validateNewChild(p, (Dom) c); + } + + for (Node c = firstChild(nc); c != null; ) { + Node n = nextSibling((Dom) c); + + if (rc == null) { + append((Dom) c, p); + } else { + insert((Dom) c, rc); + } + + c = n; + } + + return (Node) nc; + } + + // + // Make sure the new child is allowed here + // + + validateNewChild(p, nc); + + // + // Orphan the child before establishing a new parent + // + + remove(nc); + + int pk = p.nodeType(); + + // Only these nodes can be modifiable parents + assert pk == ATTR || pk == DOCFRAG || pk == DOCUMENT || pk == ELEMENT; + + switch (nck) { + case ELEMENT: + case COMMENT: + case PROCINST: { + if (rc == null) { + Cur cTo = p.tempCur(); + cTo.toEnd(); + Cur.moveNode((Xobj) nc, cTo); + cTo.release(); + } else { + int rck = rc.nodeType(); + + if (rck == TEXT || rck == CDATA) { + // Quick and dirty impl.... + + List charNodes = new ArrayList<>(); + + Dom rc2 = rc; + + while (rc2 != null && (rc2.nodeType() == TEXT || rc2.nodeType() == CDATA)) { + Node next = nextSibling(rc2); + charNodes.add((Dom) remove(rc2)); + rc2 = (Dom) next; + } + + if (rc2 == null) { + append(nc, p); + } else { + insert(nc, rc2); + } + + rc2 = (Dom) nextSibling(nc); + + for (Object charNode : charNodes) { + Dom n = (Dom) charNode; + + if (rc2 == null) { + append(n, p); + } else { + insert(n, rc2); + } + } + } else if (rck == ENTITYREF) { + throw new RuntimeException("Not implemented"); + } else { + assert rck == ELEMENT || rck == PROCINST || rck == COMMENT; + Cur cTo = rc.tempCur(); + Cur.moveNode((Xobj) nc, cTo); + cTo.release(); + } + } + + break; + } + + case TEXT: + case CDATA: { + CharNode n = (CharNode) nc; + + assert n._prev == null && n._next == null; + + CharNode refCharNode = null; + Cur c = p.tempCur(); + + if (rc == null) { + c.toEnd(); + } else { + int rck = rc.nodeType(); + + if (rck == TEXT || rck == CDATA) { + c.moveToCharNode(refCharNode = (CharNode) rc); + } else if (rck == ENTITYREF) { + throw new RuntimeException("Not implemented"); + } else { + c.moveToDom(rc); + } + } + + CharNode nodes = c.getCharNodes(); + + nodes = CharNode.insertNode(nodes, n, refCharNode); + + c.insertChars(n.getObject(), n._off, n._cch); + + c.setCharNodes(nodes); + + c.release(); + + break; + } + + case ENTITYREF: { + throw new RuntimeException("Not implemented"); + } + + case DOCTYPE: { + // TODO - don't actually insert this here, associate it with the + // doc?? Hmm .. Perhaps I should disallow insertion into the tree + // at all. + + throw new RuntimeException("Not implemented"); + } + + default: + throw new RuntimeException("Unexpected child node type"); + } + + return (Node) nc; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_removeChild(Dom p, Node child) { + Locale l = p.locale(); + + if (child == null) { + throw new NotFoundErr("Child to remove is null"); + } + + Dom c; + + if (!(child instanceof Dom) || (c = (Dom) child).locale() != l) { + throw new WrongDocumentErr("Child to remove is from another document"); + } + + return syncWrap(p, x -> node_removeChild(x, c)); + } + + public static Node node_removeChild(Dom parent, Dom child) { + if (parent(child) != parent) { + throw new NotFoundErr("Child to remove is not a child of given parent"); + } + + switch (child.nodeType()) { + case DOCUMENT: + case DOCFRAG: + case ATTR: + throw new IllegalStateException(); + + case ELEMENT: + case PROCINST: + case COMMENT: + removeNode(child); + break; + + case TEXT: + case CDATA: { + Cur c = child.tempCur(); + CharNode nodes = c.getCharNodes(); + CharNode cn = (CharNode) child; + assert (cn.getDom() != null); + + cn.setChars(c.moveChars(null, cn._cch), c._offSrc, c._cchSrc); + c.setCharNodes(CharNode.remove(nodes, cn)); + c.release(); + break; + } + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + default: + throw new RuntimeException("Unknown kind"); + } + + return (Node) child; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _node_cloneNode(Dom n, boolean deep) { + return syncWrap(n, p -> node_cloneNode(p, deep)); + } + + public static Node node_cloneNode(Dom n, boolean deep) { + Locale l = n.locale(); + + Dom clone = null; + + if (!deep) { + Cur shallow = null; + + switch (n.nodeType()) { + case DOCUMENT: + shallow = l.tempCur(); + shallow.createDomDocumentRoot(); + break; + + case DOCFRAG: + shallow = l.tempCur(); + shallow.createDomDocFragRoot(); + break; + + case ELEMENT: { + shallow = l.tempCur(); + shallow.createElement(n.getQName()); + + Element elem = (Element) shallow.getDom(); + NamedNodeMap attrs = ((Element) n).getAttributes(); + + for (int i = 0; i < attrs.getLength(); i++) { + elem.setAttributeNodeNS((Attr) attrs.item(i).cloneNode(true)); + } + + break; + } + + case ATTR: + shallow = l.tempCur(); + shallow.createAttr(n.getQName()); + break; + + case PROCINST: + case COMMENT: + case TEXT: + case CDATA: + case ENTITYREF: + case ENTITY: + case DOCTYPE: + case NOTATION: + break; + } + + if (shallow != null) { + clone = shallow.getDom(); + shallow.release(); + } + } + + if (clone == null) { + switch (n.nodeType()) { + case DOCUMENT: + case DOCFRAG: + case ATTR: + case ELEMENT: + case PROCINST: + case COMMENT: { + Cur cClone = l.tempCur(); + Cur cSrc = n.tempCur(); + cSrc.copyNode(cClone); + clone = cClone.getDom(); + cClone.release(); + cSrc.release(); + + break; + } + + case TEXT: + case CDATA: { + Cur c = n.tempCur(); + CharNode cn = n.nodeType() == TEXT ? l.createTextNode() : l.createCdataNode(); + cn.setChars(c.getChars(((CharNode) n)._cch), c._offSrc, c._cchSrc); + clone = cn; + c.release(); + break; + } + + case ENTITYREF: + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + default: + throw new RuntimeException("Unknown kind"); + } + } + + return (Node) clone; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _node_getLocalName(Dom n) { + if (!n.nodeCanHavePrefixUri()) { + return null; + } + QName name = n.getQName(); + return name == null ? "" : name.getLocalPart(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _node_getNamespaceURI(Dom n) { + if (!n.nodeCanHavePrefixUri()) { + return null; + } + QName name = n.getQName(); + // TODO - should return the correct namespace for xmlns ... + //name.getNamespaceURI().equals("")? null: + return name == null ? "" : name.getNamespaceURI(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _node_setPrefix(Dom n, String prefix) { + syncWrapVoid(n, p -> node_setPrefix(p, prefix)); + } + + public static void node_setPrefix(Dom n, String prefix) { + // TODO - make it possible to set the prefix of an xmlns + // TODO - test to make use prefix: xml maps to the predefined namespace + // if set???? hmmm ... perhaps I should not allow the setting of any + // prefixes which start with xml unless the namespace is the predefined + // one and the prefix is 'xml' all other prefixes which start with + // 'xml' should fail. + + if (n.nodeType() == ELEMENT || n.nodeType() == ATTR) { + Cur c = n.tempCur(); + QName name = c.getName(); + String uri = name.getNamespaceURI(); + String local = name.getLocalPart(); + + prefix = validatePrefix(prefix, uri, local, n.nodeType() == ATTR); + + c.setName(n.locale().makeQName(uri, local, prefix)); + c.release(); + } else { + validatePrefix(prefix, "", "", false); + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _node_getPrefix(Dom n) { + if (!n.nodeCanHavePrefixUri()) { + return null; + } + QName name = n.getQName(); + return name == null ? "" : name.getPrefix(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _node_getNodeName(Dom n) { + switch (n.nodeType()) { + case CDATA: + return "#cdata-section"; + case COMMENT: + return "#comment"; + case DOCFRAG: + return "#document-fragment"; + case DOCUMENT: + return "#document"; + case PROCINST: + return n.getQName().getLocalPart(); + case TEXT: + return "#text"; + + case ATTR: + case ELEMENT: { + QName name = n.getQName(); + String prefix = name.getPrefix(); + return prefix.length() == 0 ? name.getLocalPart() : prefix + ":" + name.getLocalPart(); + } + + case DOCTYPE: + case ENTITY: + case ENTITYREF: + case NOTATION: + throw new RuntimeException("Not impl"); + + default: + throw new RuntimeException("Unknown node type"); + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static short _node_getNodeType(Dom n) { + return (short) n.nodeType(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _node_setNodeValue(Dom n, String nodeValue) { + syncWrapVoid(n, p -> node_setNodeValue(p, nodeValue)); + } + + public static void node_setNodeValue(Dom n, String nodeValue) { + if (nodeValue == null) { + nodeValue = ""; + } + + switch (n.nodeType()) { + case TEXT: + case CDATA: { + CharNode cn = (CharNode) n; + + Cur c; + + if ((c = cn.tempCur()) != null) { + c.moveChars(null, cn._cch); + cn._cch = nodeValue.length(); + c.insertString(nodeValue); + c.release(); + } else { + cn.setChars(nodeValue, 0, nodeValue.length()); + } + + break; + } + + case ATTR: { + // Try to set an exisiting text node to contain the new value + + NodeList children = ((Node) n).getChildNodes(); + + while (children.getLength() > 1) { + node_removeChild(n, (Dom) children.item(1)); + } + + if (children.getLength() == 0) { + TextNode tn = n.locale().createTextNode(); + tn.setChars(nodeValue, 0, nodeValue.length()); + node_insertBefore(n, tn, null); + } else { + assert children.getLength() == 1; + children.item(0).setNodeValue(nodeValue); + } + if (((AttrXobj) n).isId()) { + Document d = DomImpl.node_getOwnerDocument(n); + String val = node_getNodeValue(n); + if (d instanceof DocumentXobj) { + DocumentXobj dox = (DocumentXobj) d; + dox.removeIdElement(val); + dox.addIdElement(nodeValue, (Dom) attr_getOwnerElement(n)); + } + } + + break; + } + + case PROCINST: + case COMMENT: { + Cur c = n.tempCur(); + c.next(); + + c.getChars(-1); + c.moveChars(null, c._cchSrc); + c.insertString(nodeValue); + + c.release(); + + break; + } + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _node_getNodeValue(Dom n) { + return syncWrapNoEnter(n, DomImpl::node_getNodeValue); + } + + public static String node_getNodeValue(Dom n) { + String s = null; + + switch (n.nodeType()) { + case ATTR: + case PROCINST: + case COMMENT: { + s = ((Xobj) n).getValueAsString(); + break; + } + + case TEXT: + case CDATA: { + assert n instanceof CharNode : "Text/CData should be a CharNode"; + CharNode node = (CharNode) n; + if (!(node.getObject() instanceof Xobj)) { + s = CharUtil.getString(node.getObject(), node._off, node._cch); + } else { + Xobj src = (Xobj) node.getObject(); + src.ensureOccupancy(); + boolean isThisNodeAfterText = node.isNodeAftertext(); + if (isThisNodeAfterText) { + src._charNodesAfter = + Cur.updateCharNodes(src._locale, src, src._charNodesAfter, src._cchAfter); + s = src.getCharsAfterAsString(node._off, node._cch); + } else { + src._charNodesValue = + Cur.updateCharNodes(src._locale, src, src._charNodesValue, src._cchValue); + s = src.getCharsValueAsString(node._off, node._cch); + } + + } + break; + } + } + + return s; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static Object _node_getUserData(Dom n, String key) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static Object _node_setUserData(Dom n, String key, Object data, UserDataHandler handler) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static Object _node_getFeature(Dom n, String feature, String version) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static boolean _node_isEqualNode(Dom n, Node arg) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static boolean _node_isSameNode(Dom n, Node arg) { + // TODO: check if relying on object identity is ok + boolean ret; + if (n instanceof CharNode) { +// ret = ((CharNode)n).getDom().equals(arg); + ret = n.equals(arg); + } else if (n instanceof NodeXobj) { + ret = ((NodeXobj) n).getDom().equals(arg); + } else { + throw new DomLevel3NotImplemented(); + } + return ret; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static String _node_lookupNamespaceURI(Dom n, String prefix) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static boolean _node_isDefaultNamespace(Dom n, String namespaceURI) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static String _node_lookupPrefix(Dom n, String namespaceURI) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static void _node_setTextContent(Dom n, String textContent) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static String _node_getTextContent(Dom n) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static short _node_compareDocumentPosition(Dom n, Node other) { + // TODO: find a faster way to compare, may be based on the locale / cursor elements inside the nodes + if (!(n instanceof Node)) { + return Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC; + } + Iterator nAncIter = ancestorAndSelf((Node) n).iterator(); + Iterator oAncIter = ancestorAndSelf(other).iterator(); + + Node nAnc, oAnc; + boolean isFirst = true, isEqual; + do { + nAnc = nAncIter.next(); + oAnc = oAncIter.next(); + isEqual = Objects.equals(nAnc, oAnc); + if (isFirst && !isEqual) { + // if root node differ, the elements are from different documents + return Node.DOCUMENT_POSITION_DISCONNECTED; + } + isFirst = false; + } while (isEqual && nAncIter.hasNext() && oAncIter.hasNext()); + + if (isEqual) { + return nAncIter.hasNext() + ? Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING + : (oAncIter.hasNext() + ? Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING + : Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + ); + } else { + Node prevSib = nAnc; + while ((prevSib = prevSib.getPreviousSibling()) != null) { + if (Objects.equals(prevSib, oAnc)) { + return Node.DOCUMENT_POSITION_PRECEDING; + } + } + return Node.DOCUMENT_POSITION_FOLLOWING; + } + } + + private static List ancestorAndSelf(Node node) { + LinkedList nodes = new LinkedList<>(); + Node n = node; + do { + nodes.addFirst(n); + n = n.getParentNode(); + } while (n != null); + return nodes; + } + + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static String _node_getBaseURI(Dom n) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _childNodes_item(Dom n, int i) { + return i == 0 + ? _node_getFirstChild(n) + : syncWrapNoEnter(n, p -> childNodes_item(p, i)); + } + + public static Node childNodes_item(Dom n, int i) { + if (i < 0) { + return null; + } + + switch (n.nodeType()) { + case TEXT: + case CDATA: + case PROCINST: + case COMMENT: + return null; + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + case ELEMENT: + case DOCUMENT: + case DOCFRAG: + case ATTR: + break; + } + if (i == 0) { + return node_getFirstChild(n); + } + return (Node) n.locale().findDomNthChild(n, i); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static int _childNodes_getLength(Dom n) { + assert n instanceof Xobj; + int count; + Xobj node = (Xobj) n; + if (!node.isVacant() && + (count = node.getDomZeroOneChildren()) < 2) { + return count; + } + + return syncWrapNoEnter(n, DomImpl::childNodes_getLength); + } + + public static int childNodes_getLength(Dom n) { + switch (n.nodeType()) { + case TEXT: + case CDATA: + case PROCINST: + case COMMENT: + return 0; + + case ENTITYREF: + throw new RuntimeException("Not impl"); + + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + case ELEMENT: + case DOCUMENT: + case DOCFRAG: + case ATTR: + break; + } + + int count; + assert n instanceof Xobj; + Xobj node = (Xobj) n; + node.ensureOccupancy(); + if ((count = node.getDomZeroOneChildren()) < 2) { + return count; + } + return n.locale().domLength(n); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _element_getTagName(Dom e) { + return _node_getNodeName(e); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _element_getAttributeNode(Dom e, String name) { + return (Attr) _attributes_getNamedItem(e, name); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _element_getAttributeNodeNS(Dom e, String uri, String local) { + return (Attr) _attributes_getNamedItemNS(e, uri, local); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _element_setAttributeNode(Dom e, Attr newAttr) { + return (Attr) _attributes_setNamedItem(e, newAttr); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _element_setAttributeNodeNS(Dom e, Attr newAttr) { + return (Attr) _attributes_setNamedItemNS(e, newAttr); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _element_getAttribute(Dom e, String name) { + Node a = _attributes_getNamedItem(e, name); + return a == null ? "" : a.getNodeValue(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _element_getAttributeNS(Dom e, String uri, String local) { + Node a = _attributes_getNamedItemNS(e, uri, local); + return a == null ? "" : a.getNodeValue(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static boolean _element_hasAttribute(Dom e, String name) { + return _attributes_getNamedItem(e, name) != null; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static boolean _element_hasAttributeNS(Dom e, String uri, String local) { + return _attributes_getNamedItemNS(e, uri, local) != null; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _element_removeAttribute(Dom e, String name) { + try { + _attributes_removeNamedItem(e, name); + } catch (NotFoundErr ignored) { + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _element_removeAttributeNS(Dom e, String uri, String local) { + try { + _attributes_removeNamedItemNS(e, uri, local); + } catch (NotFoundErr ignored) { + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Attr _element_removeAttributeNode(Dom e, Attr oldAttr) { + if (oldAttr == null) { + throw new NotFoundErr("Attribute to remove is null"); + } + + if (oldAttr.getOwnerElement() != e) { + throw new NotFoundErr("Attribute to remove does not belong to this element"); + } + + return (Attr) _attributes_removeNamedItem(e, oldAttr.getNodeName()); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _element_setAttribute(Dom e, String name, String value) { + // TODO - validate all attr/element names in all appropriate methods + syncWrapVoid(e, p -> element_setAttribute(p, name, value)); + } + + public static void element_setAttribute(Dom e, String name, String value) { + Node a = attributes_getNamedItem(e, name); + + if (a == null) { + Dom e2 = (Dom) node_getOwnerDocument(e); + if (e2 == null) { + throw new NotFoundErr("Document element can't be determined."); + } + + a = document_createAttribute(e2, name); + attributes_setNamedItem(e, (Dom) a); + } + + node_setNodeValue((Dom) a, value); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _element_setAttributeNS(Dom e, String uri, String qname, String value) { + syncWrapVoid(e, p -> element_setAttributeNS(p, uri, qname, value)); + } + + public static void element_setAttributeNS(Dom e, String uri, String qname, String value) { + validateQualifiedName(qname, uri, true); + + QName name = e.locale().makeQualifiedQName(uri, qname); + String local = name.getLocalPart(); + String prefix = validatePrefix(name.getPrefix(), uri, local, true); + + Node a = attributes_getNamedItemNS(e, uri, local); + + if (a == null) { + a = document_createAttributeNS((Dom) node_getOwnerDocument(e), uri, local); + attributes_setNamedItemNS(e, (Dom) a); + } + + node_setPrefix((Dom) a, prefix); + node_setNodeValue((Dom) a, value); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static NodeList _element_getElementsByTagName(Dom e, String name) { + return syncWrap(e, p -> element_getElementsByTagName(p, name)); + } + + public static NodeList element_getElementsByTagName(Dom e, String name) { + return new ElementsByTagNameNodeList(e, name); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static NodeList _element_getElementsByTagNameNS(Dom e, String uri, String local) { + return syncWrap(e, p -> element_getElementsByTagNameNS(p, uri, local)); + } + + public static NodeList element_getElementsByTagNameNS(Dom e, String uri, String local) { + return new ElementsByTagNameNSNodeList(e, uri, local); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static int _attributes_getLength(Dom e) { + return syncWrap(e, DomImpl::attributes_getLength); + } + + public static int attributes_getLength(Dom e) { + int n = 0; + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + n++; + } + + c.release(); + return n; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_setNamedItem(Dom e, Node attr) { + Locale l = e.locale(); + + if (attr == null) { + throw new IllegalArgumentException("Attr to set is null"); + } + + Dom a; + + if (!(attr instanceof Dom) || (a = (Dom) attr).locale() != l) { + throw new WrongDocumentErr("Attr to set is from another document"); + } + + return syncWrap(e, p -> attributes_setNamedItem(p, a)); + } + + public static Node attributes_setNamedItem(Dom e, Dom a) { + if (attr_getOwnerElement(a) != null) { + throw new InuseAttributeError(); + } + + if (a.nodeType() != ATTR) { + throw new HierarchyRequestErr("Node is not an attribute"); + } + + String name = _node_getNodeName(a); + Dom oldAttr = null; + + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + Dom aa = c.getDom(); + + if (_node_getNodeName(aa).equals(name)) { + if (oldAttr == null) { + oldAttr = aa; + } else { + removeNode(aa); + c.toPrevAttr(); + } + } + } + + if (oldAttr == null) { + c.moveToDom(e); + c.next(); + Cur.moveNode((Xobj) a, c); + } else { + c.moveToDom(oldAttr); + Cur.moveNode((Xobj) a, c); + removeNode(oldAttr); + } + + c.release(); + + return (Node) oldAttr; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_getNamedItem(Dom e, String name) { + return syncWrap(e, p -> attributes_getNamedItem(e, name)); + } + + public static Node attributes_getNamedItem(Dom e, String name) { + Dom a = null; + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + Dom d = c.getDom(); + if (_node_getNodeName(d).equals(name)) { + a = d; + break; + } + } + + c.release(); + return (Node) a; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_getNamedItemNS(Dom e, String uri, String local) { + return syncWrap(e, p -> attributes_getNamedItemNS(p, uri, local)); + } + + public static Node attributes_getNamedItemNS(Dom e, String uri, String local) { + if (uri == null) { + uri = ""; + } + + Dom a = null; + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + Dom d = c.getDom(); + QName n = d.getQName(); + + if (n.getNamespaceURI().equals(uri) && n.getLocalPart().equals(local)) { + a = d; + break; + } + } + + c.release(); + return (Node) a; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_removeNamedItem(Dom e, String name) { + return syncWrap(e, p -> attributes_removeNamedItem(p, name)); + } + + public static Node attributes_removeNamedItem(Dom e, String name) { + Dom oldAttr = null; + + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + Dom aa = c.getDom(); + + if (_node_getNodeName(aa).equals(name)) { + if (oldAttr == null) { + oldAttr = aa; + } + + if (((AttrXobj) aa).isId()) { + Node d = DomImpl.node_getOwnerDocument(aa); + String val = node_getNodeValue(aa); + if (d instanceof DocumentXobj) { + ((DocumentXobj) d).removeIdElement(val); + } + } + removeNode(aa); + c.toPrevAttr(); + } + } + + c.release(); + + if (oldAttr == null) { + throw new NotFoundErr("Named item not found: " + name); + } + + return (Node) oldAttr; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_removeNamedItemNS(Dom e, String uri, String local) { + return syncWrap(e, p -> attributes_removeNamedItemNS(p, uri, local)); + } + + public static Node attributes_removeNamedItemNS(Dom e, String uri, String local) { + if (uri == null) { + uri = ""; + } + + Dom oldAttr = null; + + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + Dom aa = c.getDom(); + + QName qn = aa.getQName(); + + if (qn.getNamespaceURI().equals(uri) && qn.getLocalPart().equals(local)) { + if (oldAttr == null) { + oldAttr = aa; + } + if (((AttrXobj) aa).isId()) { + Node d = DomImpl.node_getOwnerDocument(aa); + String val = node_getNodeValue(aa); + if (d instanceof DocumentXobj) { + ((DocumentXobj) d).removeIdElement(val); + } + } + removeNode(aa); + + c.toPrevAttr(); + } + } + + c.release(); + + if (oldAttr == null) { + throw new NotFoundErr("Named item not found: uri=" + uri + ", local=" + local); + } + + return (Node) oldAttr; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_setNamedItemNS(Dom e, Node attr) { + Locale l = e.locale(); + + if (attr == null) { + throw new IllegalArgumentException("Attr to set is null"); + } + + Dom a; + + if (!(attr instanceof Dom) || (a = (Dom) attr).locale() != l) { + throw new WrongDocumentErr("Attr to set is from another document"); + } + + return syncWrap(e, p -> attributes_setNamedItemNS(p, a)); + } + + public static Node attributes_setNamedItemNS(Dom e, Dom a) { + Node owner = attr_getOwnerElement(a); + + if (owner == e) { + return (Node) a; + } + + if (owner != null) { + throw new InuseAttributeError(); + } + + if (a.nodeType() != ATTR) { + throw new HierarchyRequestErr("Node is not an attribute"); + } + + QName name = a.getQName(); + Dom oldAttr = null; + + Cur c = e.tempCur(); + + while (c.toNextAttr()) { + Dom aa = c.getDom(); + + if (aa.getQName().equals(name)) { + if (oldAttr == null) { + oldAttr = aa; + } else { + removeNode(aa); + c.toPrevAttr(); + } + } + } + + if (oldAttr == null) { + c.moveToDom(e); + c.next(); + Cur.moveNode((Xobj) a, c); + } else { + c.moveToDom(oldAttr); + Cur.moveNode((Xobj) a, c); + removeNode(oldAttr); + } + + c.release(); + + return (Node) oldAttr; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Node _attributes_item(Dom e, int index) { + return syncWrap(e, p -> attributes_item(p, index)); + } + + public static Node attributes_item(Dom e, int index) { + if (index < 0) { + return null; + } + + Cur c = e.tempCur(); + + Dom a = null; + + while (c.toNextAttr()) { + if (index-- == 0) { + a = c.getDom(); + break; + } + } + + c.release(); + + return (Node) a; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _processingInstruction_getData(Dom p) { + return _node_getNodeValue(p); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _processingInstruction_getTarget(Dom p) { + return _node_getNodeName(p); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _processingInstruction_setData(Dom p, String data) { + _node_setNodeValue(p, data); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static boolean _attr_getSpecified(Dom a) { + // Can't tell the difference + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Element _attr_getOwnerElement(Dom a) { + return syncWrap(a, DomImpl::attr_getOwnerElement); + } + + public static Element attr_getOwnerElement(Dom n) { + Cur c = n.tempCur(); + + if (!c.toParentRaw()) { + c.release(); + return null; + } + + Dom p = c.getDom(); + c.release(); + return (Element) p; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _characterData_appendData(Dom cd, String arg) { + // TODO - fix this *really* cheesy/bad/lousy perf impl + // also fix all the funcitons which follow + + if (arg != null && arg.length() != 0) { + _node_setNodeValue(cd, _node_getNodeValue(cd) + arg); + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _characterData_deleteData(Dom c, int offset, int count) { + String s = _characterData_getData(c); + + if (offset < 0 || offset > s.length() || count < 0) { + throw new IndexSizeError(); + } + + if (offset + count > s.length()) { + count = s.length() - offset; + } + + if (count > 0) { + _characterData_setData(c, s.substring(0, offset) + s.substring(offset + count)); + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _characterData_getData(Dom c) { + return _node_getNodeValue(c); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static int _characterData_getLength(Dom c) { + return _characterData_getData(c).length(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _characterData_insertData(Dom c, int offset, String arg) { + String s = _characterData_getData(c); + + if (offset < 0 || offset > s.length()) { + throw new IndexSizeError(); + } + + if (arg != null && arg.length() > 0) { + _characterData_setData(c, s.substring(0, offset) + arg + s.substring(offset)); + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _characterData_replaceData(Dom c, int offset, int count, String arg) { + String s = _characterData_getData(c); + + if (offset < 0 || offset > s.length() || count < 0) { + throw new IndexSizeError(); + } + + if (offset + count > s.length()) { + count = s.length() - offset; + } + + if (count > 0) { + _characterData_setData( + c, s.substring(0, offset) + (arg == null ? "" : arg) + + s.substring(offset + count)); + } + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static void _characterData_setData(Dom c, String data) { + _node_setNodeValue(c, data); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static String _characterData_substringData(Dom c, int offset, int count) { + String s = _characterData_getData(c); + + if (offset < 0 || offset > s.length() || count < 0) { + throw new IndexSizeError(); + } + + if (offset + count > s.length()) { + count = s.length() - offset; + } + + return s.substring(offset, offset + count); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static Text _text_splitText(Dom t, int offset) { + assert t.nodeType() == TEXT; + + String s = _characterData_getData(t); + + if (offset < 0 || offset > s.length()) { + throw new IndexSizeError(); + } + + _characterData_deleteData(t, offset, s.length() - offset); + + // Don't need to pass a doc here, any node will do.. + + Dom t2 = (Dom) _document_createTextNode(t, s.substring(offset)); + + Dom p = (Dom) _node_getParentNode(t); + + if (p != null) { + _node_insertBefore(p, (Text) t2, _node_getNextSibling(t)); + t.locale().invalidateDomCaches(p); + } + + return (Text) t2; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static String _text_getWholeText(Dom t) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static boolean _text_isElementContentWhitespace(Dom t) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + @SuppressWarnings("unused") + public static Text _text_replaceWholeText(Dom t, String content) { + throw new DomLevel3NotImplemented(); + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static XMLStreamReader _getXmlStreamReader(Dom n) { + return syncWrap(n, DomImpl::getXmlStreamReader); + } + + public static XMLStreamReader getXmlStreamReader(Dom n) { + XMLStreamReader xs; + + switch (n.nodeType()) { + case DOCUMENT: + case DOCFRAG: + case ATTR: + case ELEMENT: + case PROCINST: + case COMMENT: { + Cur c = n.tempCur(); + xs = Jsr173.newXmlStreamReader(c, null); + c.release(); + break; + } + + case TEXT: + case CDATA: { + CharNode cn = (CharNode) n; + + Cur c; + + if ((c = cn.tempCur()) == null) { + c = n.locale().tempCur(); + + xs = Jsr173.newXmlStreamReader(c, cn.getObject(), cn._off, cn._cch); + } else { + xs = + Jsr173.newXmlStreamReader( + c, c.getChars(cn._cch), c._offSrc, c._cchSrc); + + } + + c.release(); + + break; + } + + case ENTITYREF: + case ENTITY: + case DOCTYPE: + case NOTATION: + throw new RuntimeException("Not impl"); + + default: + throw new RuntimeException("Unknown kind"); + } + + return xs; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static XmlCursor _getXmlCursor(Dom n) { + return syncWrap(n, DomImpl::getXmlCursor); + } + + public static XmlCursor getXmlCursor(Dom n) { + Cur c = n.tempCur(); + Cursor xc = new Cursor(c); + c.release(); + return xc; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + public static XmlObject _getXmlObject(Dom n) { + return syncWrap(n, DomImpl::getXmlObject); + } + + public static XmlObject getXmlObject(Dom n) { + Cur c = n.tempCur(); + XmlObject x = c.getObject(); + c.release(); + return x; + } + + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////// + + + // + // Soap Text Node + // + + public static boolean _soapText_isComment(Dom n) { + org.apache.xmlbeans.impl.soap.Text text = (org.apache.xmlbeans.impl.soap.Text) n; + return syncWrap(n, p -> p.locale()._saaj.soapText_isComment(text)); + } + + // + // Soap Node + // + + public static void _soapNode_detachNode(Dom n) { + org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; + syncWrapVoid(n, p -> p.locale()._saaj.soapNode_detachNode(node)); + } + + public static void _soapNode_recycleNode(Dom n) { + org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; + syncWrapVoid(n, p -> p.locale()._saaj.soapNode_recycleNode(node)); + } + + public static String _soapNode_getValue(Dom n) { + org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; + return syncWrap(n, p -> p.locale()._saaj.soapNode_getValue(node)); + } + + public static void _soapNode_setValue(Dom n, String value) { + org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; + syncWrapVoid(n, p -> p.locale()._saaj.soapNode_setValue(node, value)); + } + + public static SOAPElement _soapNode_getParentElement(Dom n) { + org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; + return syncWrap(n, p -> p.locale()._saaj.soapNode_getParentElement(node)); + } + + public static void _soapNode_setParentElement(Dom n, SOAPElement p) { + org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; + syncWrapVoid(n, x -> x.locale()._saaj.soapNode_setParentElement(node, p)); + } + + // + // Soap Element + // + + public static void _soapElement_removeContents(Dom d) { + SOAPElement se = (SOAPElement) d; + syncWrapVoid(d, x -> x.locale()._saaj.soapElement_removeContents(se)); + } + + public static String _soapElement_getEncodingStyle(Dom d) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getEncodingStyle(se)); + } + + public static void _soapElement_setEncodingStyle(Dom d, String encodingStyle) { + SOAPElement se = (SOAPElement) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapElement_setEncodingStyle(se, encodingStyle)); + } + + public static boolean _soapElement_removeNamespaceDeclaration(Dom d, String prefix) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_removeNamespaceDeclaration(se, prefix)); + } + + public static Iterator _soapElement_getAllAttributes(Dom d) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getAllAttributes(se)); + } + + public static Iterator _soapElement_getChildElements(Dom d) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getChildElements(se)); + } + + public static Iterator _soapElement_getNamespacePrefixes(Dom d) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getNamespacePrefixes(se)); + } + + public static SOAPElement _soapElement_addAttribute(Dom d, Name name, String value) throws SOAPException { + SOAPElement se = (SOAPElement) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapElement_addAttribute(se, name, value)); + } + + public static SOAPElement _soapElement_addChildElement(Dom d, SOAPElement oldChild) throws SOAPException { + SOAPElement se = (SOAPElement) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapElement_addChildElement(se, oldChild)); + } + + public static SOAPElement _soapElement_addChildElement(Dom d, Name name) throws SOAPException { + SOAPElement se = (SOAPElement) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapElement_addChildElement(se, name)); + } + + public static SOAPElement _soapElement_addChildElement(Dom d, String localName) throws SOAPException { + SOAPElement se = (SOAPElement) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapElement_addChildElement(se, localName)); + } + + public static SOAPElement _soapElement_addChildElement(Dom d, String localName, String prefix) throws SOAPException { + SOAPElement se = (SOAPElement) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapElement_addChildElement(se, localName, prefix)); + } + + public static SOAPElement _soapElement_addChildElement(Dom d, String localName, String prefix, String uri) throws SOAPException { + SOAPElement se = (SOAPElement) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapElement_addChildElement(se, localName, prefix, uri)); + } + + public static SOAPElement _soapElement_addNamespaceDeclaration(Dom d, String prefix, String uri) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_addNamespaceDeclaration(se, prefix, uri)); + } + + public static SOAPElement _soapElement_addTextNode(Dom d, String data) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_addTextNode(se, data)); + } + + public static String _soapElement_getAttributeValue(Dom d, Name name) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getAttributeValue(se, name)); + } + + public static Iterator _soapElement_getChildElements(Dom d, Name name) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getChildElements(se, name)); + } + + public static Name _soapElement_getElementName(Dom d) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getElementName(se)); + } + + public static String _soapElement_getNamespaceURI(Dom d, String prefix) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getNamespaceURI(se, prefix)); + } + + public static Iterator _soapElement_getVisibleNamespacePrefixes(Dom d) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_getVisibleNamespacePrefixes(se)); + } + + public static boolean _soapElement_removeAttribute(Dom d, Name name) { + SOAPElement se = (SOAPElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapElement_removeAttribute(se, name)); + } + + // + // Soap Envelope + // + + public static SOAPBody _soapEnvelope_addBody(Dom d) throws SOAPException { + SOAPEnvelope se = (SOAPEnvelope) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapEnvelope_addBody(se)); + } + + public static SOAPBody _soapEnvelope_getBody(Dom d) throws SOAPException { + SOAPEnvelope se = (SOAPEnvelope) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapEnvelope_getBody(se)); + } + + public static SOAPHeader _soapEnvelope_getHeader(Dom d) throws SOAPException { + SOAPEnvelope se = (SOAPEnvelope) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapEnvelope_getHeader(se)); + } + + public static SOAPHeader _soapEnvelope_addHeader(Dom d) throws SOAPException { + SOAPEnvelope se = (SOAPEnvelope) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapEnvelope_addHeader(se)); + } + + public static Name _soapEnvelope_createName(Dom d, String localName) { + SOAPEnvelope se = (SOAPEnvelope) d; + return syncWrap(d, p -> p.locale()._saaj.soapEnvelope_createName(se, localName)); + } + + public static Name _soapEnvelope_createName(Dom d, String localName, String prefix, String namespaceURI) { + SOAPEnvelope se = (SOAPEnvelope) d; + return syncWrap(d, p -> p.locale()._saaj.soapEnvelope_createName(se, localName, prefix, namespaceURI)); + } + + // + // Soap Header + // + + public static Iterator soapHeader_examineAllHeaderElements(Dom d) { + SOAPHeader sh = (SOAPHeader) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeader_examineAllHeaderElements(sh)); + } + + public static Iterator soapHeader_extractAllHeaderElements(Dom d) { + SOAPHeader sh = (SOAPHeader) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeader_extractAllHeaderElements(sh)); + } + + public static Iterator soapHeader_examineHeaderElements(Dom d, String actor) { + SOAPHeader sh = (SOAPHeader) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeader_examineHeaderElements(sh, actor)); + } + + public static Iterator soapHeader_examineMustUnderstandHeaderElements(Dom d, String mustUnderstandString) { + SOAPHeader sh = (SOAPHeader) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeader_examineMustUnderstandHeaderElements(sh, mustUnderstandString)); + } + + public static Iterator soapHeader_extractHeaderElements(Dom d, String actor) { + SOAPHeader sh = (SOAPHeader) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeader_extractHeaderElements(sh, actor)); + } + + public static SOAPHeaderElement soapHeader_addHeaderElement(Dom d, Name name) { + SOAPHeader sh = (SOAPHeader) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeader_addHeaderElement(sh, name)); + } + + // + // Soap Body + // + + public static boolean soapBody_hasFault(Dom d) { + SOAPBody sb = (SOAPBody) d; + return syncWrap(d, p -> p.locale()._saaj.soapBody_hasFault(sb)); + } + + public static SOAPFault soapBody_addFault(Dom d) throws SOAPException { + SOAPBody sb = (SOAPBody) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapBody_addFault(sb)); + } + + public static SOAPFault soapBody_getFault(Dom d) { + SOAPBody sb = (SOAPBody) d; + return syncWrap(d, p -> p.locale()._saaj.soapBody_getFault(sb)); + } + + public static SOAPBodyElement soapBody_addBodyElement(Dom d, Name name) { + SOAPBody sb = (SOAPBody) d; + return syncWrap(d, p -> p.locale()._saaj.soapBody_addBodyElement(sb, name)); + } + + public static SOAPBodyElement soapBody_addDocument(Dom d, Document document) { + SOAPBody sb = (SOAPBody) d; + return syncWrap(d, p -> p.locale()._saaj.soapBody_addDocument(sb, document)); + } + + public static SOAPFault soapBody_addFault(Dom d, Name name, String s) throws SOAPException { + SOAPBody sb = (SOAPBody) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapBody_addFault(sb, name, s)); + } + + public static SOAPFault soapBody_addFault(Dom d, Name faultCode, String faultString, java.util.Locale locale) throws SOAPException { + SOAPBody sb = (SOAPBody) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapBody_addFault(sb, faultCode, faultString, locale)); + } + + // + // Soap Fault + // + + public static void soapFault_setFaultString(Dom d, String faultString) { + SOAPFault sf = (SOAPFault) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapFault_setFaultString(sf, faultString)); + } + + public static void soapFault_setFaultString(Dom d, String faultString, java.util.Locale locale) { + SOAPFault sf = (SOAPFault) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapFault_setFaultString(sf, faultString, locale)); + } + + public static void soapFault_setFaultCode(Dom d, Name faultCodeName) throws SOAPException { + SOAPFault sf = (SOAPFault) d; + syncWrapEx(d, () -> { + d.locale()._saaj.soapFault_setFaultCode(sf, faultCodeName); + return null; + }); + } + + public static void soapFault_setFaultActor(Dom d, String faultActorString) { + SOAPFault sf = (SOAPFault) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapFault_setFaultActor(sf, faultActorString)); + } + + public static String soapFault_getFaultActor(Dom d) { + SOAPFault sf = (SOAPFault) d; + return syncWrap(d, p -> p.locale()._saaj.soapFault_getFaultActor(sf)); + } + + public static String soapFault_getFaultCode(Dom d) { + SOAPFault sf = (SOAPFault) d; + return syncWrap(d, p -> p.locale()._saaj.soapFault_getFaultCode(sf)); + } + + public static void soapFault_setFaultCode(Dom d, String faultCode) throws SOAPException { + SOAPFault sf = (SOAPFault) d; + syncWrapEx(d, () -> { + d.locale()._saaj.soapFault_setFaultCode(sf, faultCode); + return null; + }); + } + + public static java.util.Locale soapFault_getFaultStringLocale(Dom d) { + SOAPFault sf = (SOAPFault) d; + return syncWrap(d, p -> p.locale()._saaj.soapFault_getFaultStringLocale(sf)); + } + + public static Name soapFault_getFaultCodeAsName(Dom d) { + SOAPFault sf = (SOAPFault) d; + return syncWrap(d, p -> p.locale()._saaj.soapFault_getFaultCodeAsName(sf)); + } + + public static String soapFault_getFaultString(Dom d) { + SOAPFault sf = (SOAPFault) d; + return syncWrap(d, p -> p.locale()._saaj.soapFault_getFaultString(sf)); + } + + public static Detail soapFault_addDetail(Dom d) throws SOAPException { + SOAPFault sf = (SOAPFault) d; + return syncWrapEx(d, () -> d.locale()._saaj.soapFault_addDetail(sf)); + } + + public static Detail soapFault_getDetail(Dom d) { + SOAPFault sf = (SOAPFault) d; + return syncWrap(d, p -> p.locale()._saaj.soapFault_getDetail(sf)); + } + + // + // Soap Header Element + // + + public static void soapHeaderElement_setMustUnderstand(Dom d, boolean mustUnderstand) { + SOAPHeaderElement she = (SOAPHeaderElement) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapHeaderElement_setMustUnderstand(she, mustUnderstand)); + } + + public static boolean soapHeaderElement_getMustUnderstand(Dom d) { + SOAPHeaderElement she = (SOAPHeaderElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeaderElement_getMustUnderstand(she)); + } + + public static void soapHeaderElement_setActor(Dom d, String actor) { + SOAPHeaderElement she = (SOAPHeaderElement) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapHeaderElement_setActor(she, actor)); + } + + public static String soapHeaderElement_getActor(Dom d) { + SOAPHeaderElement she = (SOAPHeaderElement) d; + return syncWrap(d, p -> p.locale()._saaj.soapHeaderElement_getActor(she)); + } + + // + // Soap Header Element + // + + public static DetailEntry detail_addDetailEntry(Dom d, Name name) { + Detail detail = (Detail) d; + return syncWrap(d, p -> p.locale()._saaj.detail_addDetailEntry(detail, name)); + } + + public static Iterator detail_getDetailEntries(Dom d) { + Detail detail = (Detail) d; + return syncWrap(d, p -> p.locale()._saaj.detail_getDetailEntries(detail)); + } + + // + // Soap Header Element + // + + public static void _soapPart_removeAllMimeHeaders(Dom d) { + SOAPPart sp = (SOAPPart) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapPart_removeAllMimeHeaders(sp)); + } + + public static void _soapPart_removeMimeHeader(Dom d, String name) { + SOAPPart sp = (SOAPPart) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapPart_removeMimeHeader(sp, name)); + } + + public static Iterator _soapPart_getAllMimeHeaders(Dom d) { + SOAPPart sp = (SOAPPart) d; + return syncWrap(d, p -> p.locale()._saaj.soapPart_getAllMimeHeaders(sp)); + } + + public static SOAPEnvelope _soapPart_getEnvelope(Dom d) { + SOAPPart sp = (SOAPPart) d; + return syncWrap(d, p -> p.locale()._saaj.soapPart_getEnvelope(sp)); + } + + public static Source _soapPart_getContent(Dom d) { + SOAPPart sp = (SOAPPart) d; + return syncWrap(d, p -> p.locale()._saaj.soapPart_getContent(sp)); + } + + public static void _soapPart_setContent(Dom d, Source source) { + SOAPPart sp = (SOAPPart) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapPart_setContent(sp, source)); + } + + public static String[] _soapPart_getMimeHeader(Dom d, String name) { + SOAPPart sp = (SOAPPart) d; + return syncWrap(d, p -> p.locale()._saaj.soapPart_getMimeHeader(sp, name)); + } + + public static void _soapPart_addMimeHeader(Dom d, String name, String value) { + SOAPPart sp = (SOAPPart) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapPart_addMimeHeader(sp, name, value)); + } + + public static void _soapPart_setMimeHeader(Dom d, String name, String value) { + SOAPPart sp = (SOAPPart) d; + syncWrapVoid(d, p -> p.locale()._saaj.soapPart_setMimeHeader(sp, name, value)); + } + + public static Iterator _soapPart_getMatchingMimeHeaders(Dom d, String[] names) { + SOAPPart sp = (SOAPPart) d; + return syncWrap(d, p -> p.locale()._saaj.soapPart_getMatchingMimeHeaders(sp, names)); + } + + public static Iterator _soapPart_getNonMatchingMimeHeaders(Dom d, String[] names) { + SOAPPart sp = (SOAPPart) d; + return syncWrap(d, p -> p.locale()._saaj.soapPart_getNonMatchingMimeHeaders(sp, names)); + } + + // + // Saaj callback + // + + private static class SaajData { + Object _obj; + } + + public static void saajCallback_setSaajData(Dom d, Object o) { + syncWrapVoid(d, p -> impl_saajCallback_setSaajData(p, o)); + } + + public static void impl_saajCallback_setSaajData(Dom d, Object o) { + Locale l = d.locale(); + + Cur c = l.tempCur(); + + c.moveToDom(d); + + SaajData sd = null; + + if (o != null) { + sd = (SaajData) c.getBookmark(SaajData.class); + + if (sd == null) { + sd = new SaajData(); + } + + sd._obj = o; + } + + c.setBookmark(SaajData.class, sd); + + c.release(); + } + + public static Object saajCallback_getSaajData(Dom d) { + return syncWrap(d, DomImpl::impl_saajCallback_getSaajData); + } + + public static Object impl_saajCallback_getSaajData(Dom d) { + Locale l = d.locale(); + + Cur c = l.tempCur(); + + c.moveToDom(d); + + SaajData sd = (SaajData) c.getBookmark(SaajData.class); + + Object o = sd == null ? null : sd._obj; + + c.release(); + + return o; + } + + public static Element saajCallback_createSoapElement(Dom d, QName name, QName parentName) { + return syncWrap(d, p -> impl_saajCallback_createSoapElement(p, name, parentName)); + } + + public static Element impl_saajCallback_createSoapElement(Dom d, QName name, QName parentName) { + Cur c = d.locale().tempCur(); + c.createElement(name, parentName); + Dom e = c.getDom(); + c.release(); + return (Element) e; + } + + public static Element saajCallback_importSoapElement(Dom d, Element elem, boolean deep, QName parentName) { + return syncWrap(d, p -> impl_saajCallback_importSoapElement(p, elem, deep, parentName)); + } + + @SuppressWarnings("unused") + public static Element impl_saajCallback_importSoapElement(Dom d, Element elem, boolean deep, QName parentName) { + // TODO -- need to rewrite DomImpl.document_importNode to use an Xcur + // to create the new tree. Then, I can pass the parentName to the new + // fcn and use it to create the correct root parent + + throw new RuntimeException("Not impl"); + } + + + public static Text saajCallback_ensureSoapTextNode(Dom d) { + return syncWrap(d, DomImpl::impl_saajCallback_ensureSoapTextNode); + } + + public static Text impl_saajCallback_ensureSoapTextNode(Dom d) { + // if (!(d instanceof Text)) { + // Xcur x = d.tempCur(); + // x.moveTo + // x.release(); + // } + // return (Text) d; + + return null; + } + + public static class DomLevel3NotImplemented extends RuntimeException { + DomLevel3NotImplemented() { + super("DOM Level 3 Not implemented"); + } + } + + + private interface WrapSoapEx { + T get() throws SOAPException; + } + + private static T syncWrap(Dom d, Function inner) { + return syncWrapHelper(d.locale(), true, () -> inner.apply(d)); + } + + private static T syncWrapNoEnter(Dom d, Function inner) { + return syncWrapHelper(d.locale(), false, () -> inner.apply(d)); + } + + private static void syncWrapVoid(Dom d, Consumer inner) { + syncWrapHelper(d.locale(), true, () -> { + inner.accept(d); + return null; + }); + } + + private static T syncWrapEx(Dom d, WrapSoapEx inner) throws SOAPException { + return syncWrapHelperEx(d.locale(), true, inner); + } + + private static T syncWrapHelper(Locale l, boolean enter, Supplier inner) { + if (l.noSync()) { + return syncWrapHelper2(l, enter, inner); + } else { + synchronized (l) { + return syncWrapHelper2(l, enter, inner); + } + } + } + + private static T syncWrapHelper2(Locale l, boolean enter, Supplier inner) { + if (enter) { + l.enter(); + } + try { + return inner.get(); + } finally { + if (enter) { + l.exit(); + } + } + } + + private static T syncWrapHelperEx(Locale l, boolean enter, WrapSoapEx inner) throws SOAPException { + if (l.noSync()) { + return syncWrapHelperEx2(l, enter, inner); + } else { + synchronized (l) { + return syncWrapHelperEx2(l, enter, inner); + } + } + } + + private static T syncWrapHelperEx2(Locale l, boolean enter, WrapSoapEx inner) throws SOAPException { + if (enter) { + l.enter(); + } + try { + return inner.get(); + } finally { + if (enter) { + l.exit(); + } + } + } + + +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java b/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java new file mode 100644 index 0000000..dcc2f89 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java @@ -0,0 +1,204 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SchemaTypeLoader; +import org.apache.xmlbeans.XmlDocumentProperties; +import org.apache.xmlbeans.XmlOptions; +import org.w3c.dom.Node; + +import javax.xml.namespace.QName; +import java.util.List; + +final class DomSaver extends Saver { + private Cur _nodeCur; + private SchemaType _type; + private final SchemaTypeLoader _stl; + private final XmlOptions _options; + private final boolean _isFrag; + + + DomSaver(Cur c, boolean isFrag, XmlOptions options) { + super(c, options); + + if (c.isUserNode()) { + _type = c.getUser().get_schema_type(); + } + + _stl = c._locale._schemaTypeLoader; + _options = options; + _isFrag = isFrag; + } + + Node saveDom() { + Locale l = Locale.getLocale(_stl, _options); + + l.enter(); + + try { + _nodeCur = l.getCur(); // Not weak or temp + + // Build the tree + + //noinspection StatementWithEmptyBody + while (process()); + + // Set the type + + while (!_nodeCur.isRoot()) { + _nodeCur.toParent(); + } + + if (_type != null) { + _nodeCur.setType(_type); + } + + Node node = (Node) _nodeCur.getDom(); + + _nodeCur.release(); + + _nodeCur = null; + + return node; + } finally { + l.exit(); + } + } + + @Override + protected boolean emitElement(SaveCur c, List attrNames, List attrValues) { + // If there was text or comments before the frag element, I will loose them -- oh well + // Also, I will lose any attributes and namesapces on the fragment -- DOM can + // have attrs in fragments + + if (Locale.isFragmentQName(c.getName())) { + _nodeCur.moveTo(null, Cur.NO_POS); + } + + ensureDoc(); + + _nodeCur.createElement(getQualifiedName(c, c.getName())); + _nodeCur.next(); + + for (iterateMappings(); hasMapping(); nextMapping()) { + _nodeCur.createAttr(_nodeCur._locale.createXmlns(mappingPrefix())); + _nodeCur.next(); + _nodeCur.insertString(mappingUri()); + _nodeCur.toParent(); + _nodeCur.skipWithAttrs(); + } + + for (int i = 0; i < attrNames.size(); i++) { + _nodeCur.createAttr(getQualifiedName(c, (QName) attrNames.get(i))); + _nodeCur.next(); + _nodeCur.insertString((String) attrValues.get(i)); + _nodeCur.toParent(); + _nodeCur.skipWithAttrs(); + } + + return false; + } + + protected void emitFinish(SaveCur c) { + if (!Locale.isFragmentQName(c.getName())) { + assert _nodeCur.isEnd(); + _nodeCur.next(); + } + } + + protected void emitText(SaveCur c) { + ensureDoc(); + + Object src = c.getChars(); + + if (c._cchSrc > 0) { + _nodeCur.insertChars(src, c._offSrc, c._cchSrc); + _nodeCur.next(); + } + } + + protected void emitComment(SaveCur c) { + ensureDoc(); + + _nodeCur.createComment(); + emitTextValue(c); + _nodeCur.skip(); + } + + protected void emitProcinst(SaveCur c) { + ensureDoc(); + + _nodeCur.createProcinst(c.getName().getLocalPart()); + emitTextValue(c); + _nodeCur.skip(); + } + + protected void emitDocType(String docTypeName, String publicId, String systemId) { + ensureDoc(); + + XmlDocumentProperties props = Locale.getDocProps(_nodeCur, true); + props.setDoctypeName(docTypeName); + props.setDoctypePublicId(publicId); + props.setDoctypeSystemId(systemId); + } + + protected void emitStartDoc(SaveCur c) { + ensureDoc(); + } + + protected void emitEndDoc(SaveCur c) { + } + + private QName getQualifiedName(SaveCur c, QName name) { + String uri = name.getNamespaceURI(); + + String prefix = uri.length() > 0 ? getUriMapping(uri) : ""; + + if (prefix.equals(name.getPrefix())) { + return name; + } + + return _nodeCur._locale.makeQName(uri, name.getLocalPart(), prefix); + } + + private void emitTextValue(SaveCur c) { + c.push(); + c.next(); + + if (c.isText()) { + _nodeCur.next(); + _nodeCur.insertChars(c.getChars(), c._offSrc, c._cchSrc); + _nodeCur.toParent(); + } + + c.pop(); + } + + private void ensureDoc() { + if (!_nodeCur.isPositioned()) { + if (_isFrag) { + _nodeCur.createDomDocFragRoot(); + } else { + _nodeCur.createDomDocumentRoot(); + } + + _nodeCur.next(); + } + } + +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/ElementAttributes.java b/src/main/java/org/apache/xmlbeans/impl/store/ElementAttributes.java new file mode 100644 index 0000000..f5ce35f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/ElementAttributes.java @@ -0,0 +1,60 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +final class ElementAttributes implements NamedNodeMap { + ElementAttributes(ElementXobj elementXobj) { + _elementXobj = elementXobj; + } + + public int getLength() { + return DomImpl._attributes_getLength(_elementXobj); + } + + public Node getNamedItem(String name) { + return DomImpl._attributes_getNamedItem(_elementXobj, name); + } + + public Node getNamedItemNS(String namespaceURI, String localName) { + return DomImpl._attributes_getNamedItemNS(_elementXobj, namespaceURI, localName); + } + + public Node item(int index) { + return DomImpl._attributes_item(_elementXobj, index); + } + + public Node removeNamedItem(String name) { + return DomImpl._attributes_removeNamedItem(_elementXobj, name); + } + + public Node removeNamedItemNS(String namespaceURI, String localName) { + return DomImpl._attributes_removeNamedItemNS(_elementXobj, namespaceURI, localName); + } + + public Node setNamedItem(Node arg) { + return DomImpl._attributes_setNamedItem(_elementXobj, arg); + } + + public Node setNamedItemNS(Node arg) { + return DomImpl._attributes_setNamedItemNS(_elementXobj, arg); + } + + private ElementXobj _elementXobj; +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/ElementXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/ElementXobj.java new file mode 100644 index 0000000..4c7cf66 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/ElementXobj.java @@ -0,0 +1,128 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.*; + +import javax.xml.namespace.QName; + +import static org.apache.xmlbeans.impl.store.Cur.ELEM; + +class ElementXobj extends NamedNodeXobj implements Element { + ElementXobj(Locale l, QName name) { + super(l, ELEM, DomImpl.ELEMENT); + _name = name; + } + + Xobj newNode(Locale l) { + return new ElementXobj(l, _name); + } + + // + // + // + + public NamedNodeMap getAttributes() { + if (_attributes == null) + _attributes = new ElementAttributes(this); + + return _attributes; + } + + public String getAttribute(String name) { + return DomImpl._element_getAttribute(this, name); + } + + public Attr getAttributeNode(String name) { + return DomImpl._element_getAttributeNode(this, name); + } + + public Attr getAttributeNodeNS(String namespaceURI, String localName) { + return DomImpl._element_getAttributeNodeNS(this, namespaceURI, localName); + } + + public String getAttributeNS(String namespaceURI, String localName) { + return DomImpl._element_getAttributeNS(this, namespaceURI, localName); + } + + public NodeList getElementsByTagName(String name) { + return DomImpl._element_getElementsByTagName(this, name); + } + + public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { + return DomImpl._element_getElementsByTagNameNS(this, namespaceURI, localName); + } + + public String getTagName() { + return DomImpl._element_getTagName(this); + } + + public boolean hasAttribute(String name) { + return DomImpl._element_hasAttribute(this, name); + } + + public boolean hasAttributeNS(String namespaceURI, String localName) { + return DomImpl._element_hasAttributeNS(this, namespaceURI, localName); + } + + public void removeAttribute(String name) { + DomImpl._element_removeAttribute(this, name); + } + + public Attr removeAttributeNode(Attr oldAttr) { + return DomImpl._element_removeAttributeNode(this, oldAttr); + } + + public void removeAttributeNS(String namespaceURI, String localName) { + DomImpl._element_removeAttributeNS(this, namespaceURI, localName); + } + + public void setAttribute(String name, String value) { + DomImpl._element_setAttribute(this, name, value); + } + + public Attr setAttributeNode(Attr newAttr) { + return DomImpl._element_setAttributeNode(this, newAttr); + } + + public Attr setAttributeNodeNS(Attr newAttr) { + return DomImpl._element_setAttributeNodeNS(this, newAttr); + } + + public void setAttributeNS(String namespaceURI, String qualifiedName, String value) { + DomImpl._element_setAttributeNS(this, namespaceURI, qualifiedName, value); + } + + // DOM Level 3 + public TypeInfo getSchemaTypeInfo() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setIdAttribute(String name, boolean isId) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setIdAttributeNode(Attr idAttr, boolean isId) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + private ElementAttributes _attributes; +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java b/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java new file mode 100755 index 0000000..6fec248 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java @@ -0,0 +1,2246 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.XmlDocumentProperties; +import org.apache.xmlbeans.XmlLineNumber; +import org.apache.xmlbeans.XmlOptions; +import org.w3c.dom.Node; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.Iterator; + +public class Jsr173 { + public static Node nodeFromStream(XMLStreamReader xs) { + if (!(xs instanceof Jsr173GateWay)) { + return null; + } + + Jsr173GateWay gw = (Jsr173GateWay) xs; + + Locale l = gw._l; + + if (l.noSync()) { + l.enter(); + try { + return nodeFromStreamImpl(gw); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return nodeFromStreamImpl(gw); + } finally { + l.exit(); + } + } + } + + } + + public static Node nodeFromStreamImpl(Jsr173GateWay gw) { + Cur c = gw._xs.getStreamCur(); + + return c.isNode() ? (Node) c.getDom() : (Node) null; + } + + public static XMLStreamReader newXmlStreamReader(Cur c, Object src, int off, int cch) { + XMLStreamReaderBase xs = new XMLStreamReaderForString(c, src, off, cch); + + if (c._locale.noSync()) { + return new UnsyncedJsr173(c._locale, xs); + } else { + return new SyncedJsr173(c._locale, xs); + } + } + + public static XMLStreamReader newXmlStreamReader(Cur c, XmlOptions options) { + options = XmlOptions.maskNull(options); + + boolean inner = options.isSaveInner() && !options.isSaveOuter(); + + XMLStreamReaderBase xs; + + int k = c.kind(); + + if (k == Cur.TEXT || k < 0) { + xs = new XMLStreamReaderForString(c, c.getChars(-1), c._offSrc, c._cchSrc); + } else if (inner) { + if (!c.hasAttrs() && !c.hasChildren()) { + xs = new XMLStreamReaderForString(c, c.getFirstChars(), c._offSrc, c._cchSrc); + } else { + assert c.isContainer(); + xs = new XMLStreamReaderForNode(c, true); + } + } else { + xs = new XMLStreamReaderForNode(c, false); + } + + if (c._locale.noSync()) { + return new UnsyncedJsr173(c._locale, xs); + } else { + return new SyncedJsr173(c._locale, xs); + } + } + + // + // + // + + private static final class XMLStreamReaderForNode extends XMLStreamReaderBase { + public XMLStreamReaderForNode(Cur c, boolean inner) { + super(c); + + assert c.isContainer() || c.isComment() || c.isProcinst() || c.isAttr(); + + // Iterate over everything *between* _cur and _end. Do + // not iterate the thing to the right of _end + + if (inner) { + assert c.isContainer(); + + _cur = c.weakCur(this); + + if (!_cur.toFirstAttr()) { + _cur.next(); + } + + _end = c.weakCur(this); + _end.toEnd(); + } else { + _cur = c.weakCur(this); + + if (c.isRoot()) { + _wholeDoc = true; + } else { + _end = c.weakCur(this); + + if (c.isAttr()) { + if (!_end.toNextAttr()) { + _end.toParent(); + _end.next(); + } + } else { + _end.skip(); + } + } + } + + if (!_wholeDoc) { + // Set the _done bit properly + + _cur.push(); + + try { + next(); + } catch (XMLStreamException e) { + throw new RuntimeException(e.getMessage(), e); + } + + _cur.pop(); + } + + assert _wholeDoc || !_cur.isSamePos(_end); + } + + protected Cur getStreamCur() { + return _cur; + } + + // + // + // + + public boolean hasNext() throws XMLStreamException { + checkChanged(); + + return !_done; + } + + public int getEventType() { + switch (_cur.kind()) { + case Cur.ROOT: + return START_DOCUMENT; + case -Cur.ROOT: + return END_DOCUMENT; + case Cur.ELEM: + return START_ELEMENT; + case -Cur.ELEM: + return END_ELEMENT; + case Cur.ATTR: + return _cur.isXmlns() ? NAMESPACE : ATTRIBUTE; + case Cur.TEXT: + return CHARACTERS; + case Cur.COMMENT: + return COMMENT; + case Cur.PROCINST: + return PROCESSING_INSTRUCTION; + default: + throw new IllegalStateException(); + } + } + + public int next() throws XMLStreamException { + checkChanged(); + + if (!hasNext()) { + throw new IllegalStateException("No next event in stream"); + } + + int kind = _cur.kind(); + + if (kind == -Cur.ROOT) { + assert _wholeDoc; + _done = true; + } else { + if (kind == Cur.ATTR) { + if (!_cur.toNextAttr()) { + _cur.toParent(); + _cur.next(); + } + } else if (kind == Cur.COMMENT || kind == Cur.PROCINST) { + _cur.skip(); + } else if (kind == Cur.ROOT) { + if (!_cur.toFirstAttr()) { + _cur.next(); + } + } else { + _cur.next(); + } + + assert _wholeDoc || _end != null; + + _done = _wholeDoc ? _cur.kind() == -Cur.ROOT : _cur.isSamePos(_end); + } + + _textFetched = false; + _srcFetched = false; + + return getEventType(); + } + + public String getText() { + checkChanged(); + + int k = _cur.kind(); + + if (k == Cur.COMMENT) { + return _cur.getValueAsString(); + } + + if (k == Cur.TEXT) { + return _cur.getCharsAsString(); + } + + throw new IllegalStateException(); + } + + public boolean isStartElement() { + return getEventType() == START_ELEMENT; + } + + public boolean isEndElement() { + return getEventType() == END_ELEMENT; + } + + public boolean isCharacters() { + return getEventType() == CHARACTERS; + } + + public String getElementText() throws XMLStreamException { + checkChanged(); + + if (!isStartElement()) { + throw new IllegalStateException(); + } + + StringBuilder sb = new StringBuilder(); + + for (; ; ) { + if (!hasNext()) { + throw new XMLStreamException(); + } + + int e = next(); + + if (e == END_ELEMENT) { + break; + } else if (e == START_ELEMENT) { + throw new XMLStreamException(); + } else if (e != COMMENT && e != PROCESSING_INSTRUCTION) { + sb.append(getText()); + } + } + + return sb.toString(); + } + + public int nextTag() throws XMLStreamException { + checkChanged(); + + for (; ; ) { + if (isStartElement() || isEndElement()) { + return getEventType(); + } + + if (!isWhiteSpace()) { + throw new XMLStreamException(); + } + + if (!hasNext()) { + throw new XMLStreamException(); + } + + next(); + } + } + + private static boolean matchAttr(Cur c, String uri, String local) { + assert c.isNormalAttr(); + + QName name = c.getName(); + + return + name.getLocalPart().equals(local) && + (uri == null || name.getNamespaceURI().equals(uri)); + } + + private static Cur toAttr(Cur c, String uri, String local) { + if (uri == null || local == null || local.length() == 0) { + throw new IllegalArgumentException(); + } + + Cur ca = c.tempCur(); + boolean match = false; + + if (c.isElem()) { + if (ca.toFirstAttr()) { + do { + if (ca.isNormalAttr() && matchAttr(ca, uri, local)) { + match = true; + break; + } + } + while (ca.toNextSibling()); + } + } else if (c.isNormalAttr()) { + match = matchAttr(c, uri, local); + } else { + throw new IllegalStateException(); + } + + if (!match) { + ca.release(); + ca = null; + } + + return ca; + } + + public String getAttributeValue(String uri, String local) { + Cur ca = toAttr(_cur, uri, local); + + String value = null; + + if (ca != null) { + value = ca.getValueAsString(); + ca.release(); + } + + return value; + } + + private static Cur toAttr(Cur c, int i) { + if (i < 0) { + throw new IndexOutOfBoundsException("Attribute index is negative"); + } + + Cur ca = c.tempCur(); + boolean match = false; + + if (c.isElem()) { + if (ca.toFirstAttr()) { + do { + if (ca.isNormalAttr() && i-- == 0) { + match = true; + break; + } + } + while (ca.toNextSibling()); + } + } else if (c.isNormalAttr()) { + match = i == 0; + } else { + throw new IllegalStateException(); + } + + if (!match) { + ca.release(); + throw new IndexOutOfBoundsException("Attribute index is too large"); + } + + return ca; + } + + public int getAttributeCount() { + int n = 0; + + if (_cur.isElem()) { + Cur ca = _cur.tempCur(); + + if (ca.toFirstAttr()) { + do { + if (ca.isNormalAttr()) { + n++; + } + } + while (ca.toNextSibling()); + } + + ca.release(); + } else if (_cur.isNormalAttr()) { + n++; + } else { + throw new IllegalStateException(); + } + + return n; + } + + public QName getAttributeName(int index) { + Cur ca = toAttr(_cur, index); + QName name = ca.getName(); + ca.release(); + return name; + } + + public String getAttributeNamespace(int index) { + return getAttributeName(index).getNamespaceURI(); + } + + public String getAttributeLocalName(int index) { + return getAttributeName(index).getLocalPart(); + } + + public String getAttributePrefix(int index) { + return getAttributeName(index).getPrefix(); + } + + public String getAttributeType(int index) { + toAttr(_cur, index).release(); + return "CDATA"; + } + + public String getAttributeValue(int index) { + Cur ca = toAttr(_cur, index); + + String value = null; + + if (ca != null) { + value = ca.getValueAsString(); + ca.release(); + } + + return value; + } + + public boolean isAttributeSpecified(int index) { + // Go to attr to force index check + Cur ca = toAttr(_cur, index); + ca.release(); + + return false; + } + + public int getNamespaceCount() { + int n = 0; + + if (_cur.isElem() || _cur.kind() == -Cur.ELEM) { + Cur ca = _cur.tempCur(); + + if (_cur.kind() == -Cur.ELEM) { + ca.toParent(); + } + + if (ca.toFirstAttr()) { + do { + if (ca.isXmlns()) { + n++; + } + } + while (ca.toNextSibling()); + } + + ca.release(); + } else if (_cur.isXmlns()) { + n++; + } else { + throw new IllegalStateException(); + } + + return n; + } + + private static Cur toXmlns(Cur c, int i) { + if (i < 0) { + throw new IndexOutOfBoundsException("Namespace index is negative"); + } + + Cur ca = c.tempCur(); + boolean match = false; + + if (c.isElem() || c.kind() == -Cur.ELEM) { + if (c.kind() == -Cur.ELEM) { + ca.toParent(); + } + + if (ca.toFirstAttr()) { + do { + if (ca.isXmlns() && i-- == 0) { + match = true; + break; + } + } + while (ca.toNextSibling()); + } + } else if (c.isXmlns()) { + match = i == 0; + } else { + throw new IllegalStateException(); + } + + if (!match) { + ca.release(); + throw new IndexOutOfBoundsException("Namespace index is too large"); + } + + return ca; + } + + public String getNamespacePrefix(int index) { + Cur ca = toXmlns(_cur, index); + String prefix = ca.getXmlnsPrefix(); + ca.release(); + return prefix; + } + + public String getNamespaceURI(int index) { + Cur ca = toXmlns(_cur, index); + String uri = ca.getXmlnsUri(); + ca.release(); + return uri; + } + + private void fetchChars() { + if (!_textFetched) { + int k = _cur.kind(); + + Cur cText = null; + + if (k == Cur.COMMENT) { + cText = _cur.tempCur(); + cText.next(); + } else if (k == Cur.TEXT) { + cText = _cur; + } else { + throw new IllegalStateException(); + } + + Object src = cText.getChars(-1); + + ensureCharBufLen(cText._cchSrc); + + CharUtil.getChars( + _chars, _offChars = 0, src, cText._offSrc, _cchChars = cText._cchSrc); + + if (cText != _cur) { + cText.release(); + } + + _textFetched = true; + } + } + + private void ensureCharBufLen(int cch) { + if (_chars == null || _chars.length < cch) { + int l = 256; + + while (l < cch) { + l *= 2; + } + + _chars = new char[l]; + } + } + + public char[] getTextCharacters() { + checkChanged(); + + fetchChars(); + + return _chars; + } + + public int getTextStart() { + checkChanged(); + + fetchChars(); + + return _offChars; + } + + public int getTextLength() { + checkChanged(); + + fetchChars(); + + return _cchChars; + } + + public int getTextCharacters( + int sourceStart, char[] target, int targetStart, int length) + throws XMLStreamException { + if (length < 0) { + throw new IndexOutOfBoundsException(); + } + + if (targetStart < 0 || targetStart >= target.length) { + throw new IndexOutOfBoundsException(); + } + + if (targetStart + length > target.length) { + throw new IndexOutOfBoundsException(); + } + + if (!_srcFetched) { + int k = _cur.kind(); + + Cur cText = null; + + if (k == Cur.COMMENT) { + cText = _cur.tempCur(); + cText.next(); + } else if (k == Cur.TEXT) { + cText = _cur; + } else { + throw new IllegalStateException(); + } + + _src = cText.getChars(-1); + _offSrc = cText._offSrc; + _cchSrc = cText._cchSrc; + + if (cText != _cur) { + cText.release(); + } + + _srcFetched = true; + } + + if (sourceStart > _cchSrc) { + throw new IndexOutOfBoundsException(); + } + + if (sourceStart + length > _cchSrc) { + length = _cchSrc - sourceStart; + } + + CharUtil.getChars(target, targetStart, _src, _offSrc, length); + + return length; + } + + public boolean hasText() { + int k = _cur.kind(); + + return k == Cur.COMMENT || k == Cur.TEXT; + } + + public boolean hasName() { + int k = _cur.kind(); + return k == Cur.ELEM || k == -Cur.ELEM; + } + + public QName getName() { + if (!hasName()) { + throw new IllegalStateException(); + } + + return _cur.getName(); + } + + public String getNamespaceURI() { + return getName().getNamespaceURI(); + } + + public String getLocalName() { + return getName().getLocalPart(); + } + + public String getPrefix() { + return getName().getPrefix(); + } + + public String getPITarget() { + return _cur.kind() == Cur.PROCINST ? _cur.getName().getLocalPart() : null; + } + + public String getPIData() { + return _cur.kind() == Cur.PROCINST ? _cur.getValueAsString() : null; + } + + // + // + // + + private boolean _wholeDoc; + private boolean _done; + + private Cur _cur; + private Cur _end; + + private boolean _srcFetched; + private Object _src; + private int _offSrc; + private int _cchSrc; + + private boolean _textFetched; + private char[] _chars; + private int _offChars; + private int _cchChars; + } + + // + // + // + + private static abstract class XMLStreamReaderBase + implements XMLStreamReader, NamespaceContext, Location { + XMLStreamReaderBase(Cur c) { + _locale = c._locale; + _version = _locale.version(); + } + + protected final void checkChanged() { + if (_version != _locale.version()) { + throw new ConcurrentModificationException("Document changed while streaming"); + } + } + + // + // XMLStreamReader methods + // + + public void close() throws XMLStreamException { + checkChanged(); + } + + public boolean isWhiteSpace() { + checkChanged(); + + // TODO - avoid creating a string here + String s = getText(); + + return _locale.getCharUtil().isWhiteSpace(s, 0, s.length()); + } + + public Location getLocation() { + checkChanged(); + + Cur c = getStreamCur(); + + XmlLineNumber ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); + + // BUGBUG - put source name here + _uri = null; + + if (ln != null) { + _line = ln.getLine(); + _column = ln.getColumn(); + _offset = ln.getOffset(); + } else { + _line = -1; + _column = -1; + _offset = -1; + } + + return this; + } + + + public Object getProperty(String name) { + checkChanged(); + + if (name == null) { + throw new IllegalArgumentException("Property name is null"); + } + + // BUGBUG - I should implement some perperties here + + return null; + } + + public String getCharacterEncodingScheme() { + checkChanged(); + + XmlDocumentProperties props = _locale.getDocProps(getStreamCur(), false); + + return props == null ? null : props.getEncoding(); + } + + public String getEncoding() { + // BUGBUG - this should probably return the actual decoding used on the document + return null; + } + + public String getVersion() { + checkChanged(); + + XmlDocumentProperties props = _locale.getDocProps(getStreamCur(), false); + + return props == null ? null : props.getVersion(); + } + + public boolean isStandalone() { + checkChanged(); + + XmlDocumentProperties props = _locale.getDocProps(getStreamCur(), false); + + return props == null ? false : props.getStandalone(); + } + + public boolean standaloneSet() { + checkChanged(); + + return false; + } + + public void require(int type, String namespaceURI, String localName) + throws XMLStreamException { + checkChanged(); + + if (type != getEventType()) { + throw new XMLStreamException(); + } + + if (namespaceURI != null && !getNamespaceURI().equals(namespaceURI)) { + throw new XMLStreamException(); + } + + if (localName != null && !getLocalName().equals(localName)) { + throw new XMLStreamException(); + } + } + + // + // Location methods do not need a gatway + // + + public int getCharacterOffset() { + return _offset; + } + + public int getColumnNumber() { + return _column; + } + + public int getLineNumber() { + return _line; + } + + public String getLocationURI() { + return _uri; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + + public NamespaceContext getNamespaceContext() { + throw new RuntimeException("This version of getNamespaceContext should not be called"); + } + + public String getNamespaceURI(String prefix) { + checkChanged(); + + Cur c = getStreamCur(); + + c.push(); + + if (!c.isContainer()) { + c.toParent(); + } + + String ns = c.namespaceForPrefix(prefix, true); + + c.pop(); + + return ns; + } + + public String getPrefix(String namespaceURI) { + checkChanged(); + + Cur c = getStreamCur(); + + c.push(); + + if (!c.isContainer()) { + c.toParent(); + } + + String prefix = c.prefixForNamespace(namespaceURI, null, false); + + c.pop(); + + return prefix; + } + + public Iterator getPrefixes(String namespaceURI) { + checkChanged(); + + // BUGBUG - get only one for now ... + + HashMap map = new HashMap(); + + map.put(namespaceURI, getPrefix(namespaceURI)); + + return map.values().iterator(); + } + + // + // + // + + protected abstract Cur getStreamCur(); + + // + // + // + + private Locale _locale; + private long _version; + + String _uri; + + int _line = -1; + int _column = -1; + int _offset = -1; + } + + // + // + // + + private static final class XMLStreamReaderForString extends XMLStreamReaderBase { + XMLStreamReaderForString(Cur c, Object src, int off, int cch) { + super(c); + + _src = src; + _off = off; + _cch = cch; + + _cur = c; + } + + protected Cur getStreamCur() { + return _cur; + } + + // + // Legal stream methods + // + + public String getText() { + checkChanged(); + + return CharUtil.getString(_src, _off, _cch); + } + + public char[] getTextCharacters() { + checkChanged(); + + char[] chars = new char[_cch]; + + CharUtil.getChars(chars, 0, _src, _off, _cch); + + return chars; + } + + public int getTextStart() { + checkChanged(); + + return _off; + } + + public int getTextLength() { + checkChanged(); + + return _cch; + } + + public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) { + checkChanged(); + + if (length < 0) { + throw new IndexOutOfBoundsException(); + } + + if (sourceStart > _cch) { + throw new IndexOutOfBoundsException(); + } + + if (sourceStart + length > _cch) { + length = _cch - sourceStart; + } + + CharUtil.getChars(target, targetStart, _src, _off + sourceStart, length); + + return length; + } + + public int getEventType() { + checkChanged(); + return CHARACTERS; + } + + public boolean hasName() { + checkChanged(); + return false; + } + + public boolean hasNext() { + checkChanged(); + return false; + } + + public boolean hasText() { + checkChanged(); + return true; + } + + public boolean isCharacters() { + checkChanged(); + return true; + } + + public boolean isEndElement() { + checkChanged(); + return false; + } + + public boolean isStartElement() { + checkChanged(); + return false; + } + + // + // Illegal stream methods + // + + public int getAttributeCount() { + throw new IllegalStateException(); + } + + public String getAttributeLocalName(int index) { + throw new IllegalStateException(); + } + + public QName getAttributeName(int index) { + throw new IllegalStateException(); + } + + public String getAttributeNamespace(int index) { + throw new IllegalStateException(); + } + + public String getAttributePrefix(int index) { + throw new IllegalStateException(); + } + + public String getAttributeType(int index) { + throw new IllegalStateException(); + } + + public String getAttributeValue(int index) { + throw new IllegalStateException(); + } + + public String getAttributeValue(String namespaceURI, String localName) { + throw new IllegalStateException(); + } + + public String getElementText() { + throw new IllegalStateException(); + } + + public String getLocalName() { + throw new IllegalStateException(); + } + + public QName getName() { + throw new IllegalStateException(); + } + + public int getNamespaceCount() { + throw new IllegalStateException(); + } + + public String getNamespacePrefix(int index) { + throw new IllegalStateException(); + } + + public String getNamespaceURI(int index) { + throw new IllegalStateException(); + } + + public String getNamespaceURI() { + throw new IllegalStateException(); + } + + public String getPIData() { + throw new IllegalStateException(); + } + + public String getPITarget() { + throw new IllegalStateException(); + } + + public String getPrefix() { + throw new IllegalStateException(); + } + + public boolean isAttributeSpecified(int index) { + throw new IllegalStateException(); + } + + public int next() { + throw new IllegalStateException(); + } + + public int nextTag() { + throw new IllegalStateException(); + } + + public String getPublicId() { + throw new IllegalStateException(); + } + + public String getSystemId() { + throw new IllegalStateException(); + } + + private Cur _cur; + private Object _src; + private int _off; + private int _cch; + } + + // + // + // + + private static abstract class Jsr173GateWay { + public Jsr173GateWay(Locale l, XMLStreamReaderBase xs) { + _l = l; + _xs = xs; + } + + Locale _l; + XMLStreamReaderBase _xs; + } + + private static final class SyncedJsr173 extends Jsr173GateWay implements XMLStreamReader, Location, NamespaceContext { + public SyncedJsr173(Locale l, XMLStreamReaderBase xs) { + super(l, xs); + } + + public Object getProperty(java.lang.String name) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getProperty(name); + } finally { + _l.exit(); + } + } + } + + public int next() throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + return _xs.next(); + } finally { + _l.exit(); + } + } + } + + public void require(int type, String namespaceURI, String localName) throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + _xs.require(type, namespaceURI, localName); + } finally { + _l.exit(); + } + } + } + + public String getElementText() throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + return _xs.getElementText(); + } finally { + _l.exit(); + } + } + } + + public int nextTag() throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + return _xs.nextTag(); + } finally { + _l.exit(); + } + } + } + + public boolean hasNext() throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + return _xs.hasNext(); + } finally { + _l.exit(); + } + } + } + + public void close() throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + _xs.close(); + } finally { + _l.exit(); + } + } + } + + public String getNamespaceURI(String prefix) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getNamespaceURI(prefix); + } finally { + _l.exit(); + } + } + } + + public boolean isStartElement() { + synchronized (_l) { + _l.enter(); + try { + return _xs.isStartElement(); + } finally { + _l.exit(); + } + } + } + + public boolean isEndElement() { + synchronized (_l) { + _l.enter(); + try { + return _xs.isEndElement(); + } finally { + _l.exit(); + } + } + } + + public boolean isCharacters() { + synchronized (_l) { + _l.enter(); + try { + return _xs.isCharacters(); + } finally { + _l.exit(); + } + } + } + + public boolean isWhiteSpace() { + synchronized (_l) { + _l.enter(); + try { + return _xs.isWhiteSpace(); + } finally { + _l.exit(); + } + } + } + + public String getAttributeValue(String namespaceURI, String localName) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeValue(namespaceURI, localName); + } finally { + _l.exit(); + } + } + } + + public int getAttributeCount() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeCount(); + } finally { + _l.exit(); + } + } + } + + public QName getAttributeName(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeName(index); + } finally { + _l.exit(); + } + } + } + + public String getAttributeNamespace(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeNamespace(index); + } finally { + _l.exit(); + } + } + } + + public String getAttributeLocalName(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeLocalName(index); + } finally { + _l.exit(); + } + } + } + + public String getAttributePrefix(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributePrefix(index); + } finally { + _l.exit(); + } + } + } + + public String getAttributeType(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeType(index); + } finally { + _l.exit(); + } + } + } + + public String getAttributeValue(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getAttributeValue(index); + } finally { + _l.exit(); + } + } + } + + public boolean isAttributeSpecified(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.isAttributeSpecified(index); + } finally { + _l.exit(); + } + } + } + + public int getNamespaceCount() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getNamespaceCount(); + } finally { + _l.exit(); + } + } + } + + public String getNamespacePrefix(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getNamespacePrefix(index); + } finally { + _l.exit(); + } + } + } + + public String getNamespaceURI(int index) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getNamespaceURI(index); + } finally { + _l.exit(); + } + } + } + + public NamespaceContext getNamespaceContext() { + return this; + } + + public int getEventType() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getEventType(); + } finally { + _l.exit(); + } + } + } + + public String getText() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getText(); + } finally { + _l.exit(); + } + } + } + + public char[] getTextCharacters() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getTextCharacters(); + } finally { + _l.exit(); + } + } + } + + public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) throws XMLStreamException { + synchronized (_l) { + _l.enter(); + try { + return _xs.getTextCharacters(sourceStart, target, targetStart, length); + } finally { + _l.exit(); + } + } + } + + public int getTextStart() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getTextStart(); + } finally { + _l.exit(); + } + } + } + + public int getTextLength() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getTextLength(); + } finally { + _l.exit(); + } + } + } + + public String getEncoding() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getEncoding(); + } finally { + _l.exit(); + } + } + } + + public boolean hasText() { + synchronized (_l) { + _l.enter(); + try { + return _xs.hasText(); + } finally { + _l.exit(); + } + } + } + + public Location getLocation() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getLocation(); + } finally { + _l.exit(); + } + } + } + + public QName getName() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getName(); + } finally { + _l.exit(); + } + } + } + + public String getLocalName() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getLocalName(); + } finally { + _l.exit(); + } + } + } + + public boolean hasName() { + synchronized (_l) { + _l.enter(); + try { + return _xs.hasName(); + } finally { + _l.exit(); + } + } + } + + public String getNamespaceURI() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getNamespaceURI(); + } finally { + _l.exit(); + } + } + } + + public String getPrefix() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPrefix(); + } finally { + _l.exit(); + } + } + } + + public String getVersion() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getVersion(); + } finally { + _l.exit(); + } + } + } + + public boolean isStandalone() { + synchronized (_l) { + _l.enter(); + try { + return _xs.isStandalone(); + } finally { + _l.exit(); + } + } + } + + public boolean standaloneSet() { + synchronized (_l) { + _l.enter(); + try { + return _xs.standaloneSet(); + } finally { + _l.exit(); + } + } + } + + public String getCharacterEncodingScheme() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getCharacterEncodingScheme(); + } finally { + _l.exit(); + } + } + } + + public String getPITarget() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPITarget(); + } finally { + _l.exit(); + } + } + } + + public String getPIData() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPIData(); + } finally { + _l.exit(); + } + } + } + + public String getPrefix(String namespaceURI) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPrefix(namespaceURI); + } finally { + _l.exit(); + } + } + } + + public Iterator getPrefixes(String namespaceURI) { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPrefixes(namespaceURI); + } finally { + _l.exit(); + } + } + } + + public int getCharacterOffset() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getCharacterOffset(); + } finally { + _l.exit(); + } + } + } + + public int getColumnNumber() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getColumnNumber(); + } finally { + _l.exit(); + } + } + } + + public int getLineNumber() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getLineNumber(); + } finally { + _l.exit(); + } + } + } + + public String getLocationURI() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getLocationURI(); + } finally { + _l.exit(); + } + } + } + + public String getPublicId() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPublicId(); + } finally { + _l.exit(); + } + } + } + + public String getSystemId() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getSystemId(); + } finally { + _l.exit(); + } + } + } + } + + private static final class UnsyncedJsr173 extends Jsr173GateWay implements XMLStreamReader, Location, NamespaceContext { + public UnsyncedJsr173(Locale l, XMLStreamReaderBase xs) { + super(l, xs); + } + + public Object getProperty(java.lang.String name) { + try { + _l.enter(); + return _xs.getProperty(name); + } finally { + _l.exit(); + } + } + + public int next() throws XMLStreamException { + try { + _l.enter(); + return _xs.next(); + } finally { + _l.exit(); + } + } + + public void require(int type, String namespaceURI, String localName) throws XMLStreamException { + try { + _l.enter(); + _xs.require(type, namespaceURI, localName); + } finally { + _l.exit(); + } + } + + public String getElementText() throws XMLStreamException { + try { + _l.enter(); + return _xs.getElementText(); + } finally { + _l.exit(); + } + } + + public int nextTag() throws XMLStreamException { + try { + _l.enter(); + return _xs.nextTag(); + } finally { + _l.exit(); + } + } + + public boolean hasNext() throws XMLStreamException { + try { + _l.enter(); + return _xs.hasNext(); + } finally { + _l.exit(); + } + } + + public void close() throws XMLStreamException { + try { + _l.enter(); + _xs.close(); + } finally { + _l.exit(); + } + } + + public String getNamespaceURI(String prefix) { + try { + _l.enter(); + return _xs.getNamespaceURI(prefix); + } finally { + _l.exit(); + } + } + + public boolean isStartElement() { + try { + _l.enter(); + return _xs.isStartElement(); + } finally { + _l.exit(); + } + } + + public boolean isEndElement() { + try { + _l.enter(); + return _xs.isEndElement(); + } finally { + _l.exit(); + } + } + + public boolean isCharacters() { + try { + _l.enter(); + return _xs.isCharacters(); + } finally { + _l.exit(); + } + } + + public boolean isWhiteSpace() { + try { + _l.enter(); + return _xs.isWhiteSpace(); + } finally { + _l.exit(); + } + } + + public String getAttributeValue(String namespaceURI, String localName) { + try { + _l.enter(); + return _xs.getAttributeValue(namespaceURI, localName); + } finally { + _l.exit(); + } + } + + public int getAttributeCount() { + try { + _l.enter(); + return _xs.getAttributeCount(); + } finally { + _l.exit(); + } + } + + public QName getAttributeName(int index) { + try { + _l.enter(); + return _xs.getAttributeName(index); + } finally { + _l.exit(); + } + } + + public String getAttributeNamespace(int index) { + try { + _l.enter(); + return _xs.getAttributeNamespace(index); + } finally { + _l.exit(); + } + } + + public String getAttributeLocalName(int index) { + try { + _l.enter(); + return _xs.getAttributeLocalName(index); + } finally { + _l.exit(); + } + } + + public String getAttributePrefix(int index) { + try { + _l.enter(); + return _xs.getAttributePrefix(index); + } finally { + _l.exit(); + } + } + + public String getAttributeType(int index) { + try { + _l.enter(); + return _xs.getAttributeType(index); + } finally { + _l.exit(); + } + } + + public String getAttributeValue(int index) { + try { + _l.enter(); + return _xs.getAttributeValue(index); + } finally { + _l.exit(); + } + } + + public boolean isAttributeSpecified(int index) { + try { + _l.enter(); + return _xs.isAttributeSpecified(index); + } finally { + _l.exit(); + } + } + + public int getNamespaceCount() { + try { + _l.enter(); + return _xs.getNamespaceCount(); + } finally { + _l.exit(); + } + } + + public String getNamespacePrefix(int index) { + try { + _l.enter(); + return _xs.getNamespacePrefix(index); + } finally { + _l.exit(); + } + } + + public String getNamespaceURI(int index) { + try { + _l.enter(); + return _xs.getNamespaceURI(index); + } finally { + _l.exit(); + } + } + + public NamespaceContext getNamespaceContext() { + return this; + } + + public int getEventType() { + try { + _l.enter(); + return _xs.getEventType(); + } finally { + _l.exit(); + } + } + + public String getText() { + try { + _l.enter(); + return _xs.getText(); + } finally { + _l.exit(); + } + } + + public char[] getTextCharacters() { + try { + _l.enter(); + return _xs.getTextCharacters(); + } finally { + _l.exit(); + } + } + + public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) throws XMLStreamException { + try { + _l.enter(); + return _xs.getTextCharacters(sourceStart, target, targetStart, length); + } finally { + _l.exit(); + } + } + + public int getTextStart() { + try { + _l.enter(); + return _xs.getTextStart(); + } finally { + _l.exit(); + } + } + + public int getTextLength() { + try { + _l.enter(); + return _xs.getTextLength(); + } finally { + _l.exit(); + } + } + + public String getEncoding() { + try { + _l.enter(); + return _xs.getEncoding(); + } finally { + _l.exit(); + } + } + + public boolean hasText() { + try { + _l.enter(); + return _xs.hasText(); + } finally { + _l.exit(); + } + } + + public Location getLocation() { + try { + _l.enter(); + return _xs.getLocation(); + } finally { + _l.exit(); + } + } + + public QName getName() { + try { + _l.enter(); + return _xs.getName(); + } finally { + _l.exit(); + } + } + + public String getLocalName() { + try { + _l.enter(); + return _xs.getLocalName(); + } finally { + _l.exit(); + } + } + + public boolean hasName() { + try { + _l.enter(); + return _xs.hasName(); + } finally { + _l.exit(); + } + } + + public String getNamespaceURI() { + try { + _l.enter(); + return _xs.getNamespaceURI(); + } finally { + _l.exit(); + } + } + + public String getPrefix() { + try { + _l.enter(); + return _xs.getPrefix(); + } finally { + _l.exit(); + } + } + + public String getVersion() { + try { + _l.enter(); + return _xs.getVersion(); + } finally { + _l.exit(); + } + } + + public boolean isStandalone() { + try { + _l.enter(); + return _xs.isStandalone(); + } finally { + _l.exit(); + } + } + + public boolean standaloneSet() { + try { + _l.enter(); + return _xs.standaloneSet(); + } finally { + _l.exit(); + } + } + + public String getCharacterEncodingScheme() { + try { + _l.enter(); + return _xs.getCharacterEncodingScheme(); + } finally { + _l.exit(); + } + } + + public String getPITarget() { + try { + _l.enter(); + return _xs.getPITarget(); + } finally { + _l.exit(); + } + } + + public String getPIData() { + try { + _l.enter(); + return _xs.getPIData(); + } finally { + _l.exit(); + } + } + + public String getPrefix(String namespaceURI) { + try { + _l.enter(); + return _xs.getPrefix(namespaceURI); + } finally { + _l.exit(); + } + } + + public Iterator getPrefixes(String namespaceURI) { + try { + _l.enter(); + return _xs.getPrefixes(namespaceURI); + } finally { + _l.exit(); + } + } + + public int getCharacterOffset() { + try { + _l.enter(); + return _xs.getCharacterOffset(); + } finally { + _l.exit(); + } + } + + public int getColumnNumber() { + try { + _l.enter(); + return _xs.getColumnNumber(); + } finally { + _l.exit(); + } + } + + public int getLineNumber() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getLineNumber(); + } finally { + _l.exit(); + } + } + } + + public String getLocationURI() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getLocationURI(); + } finally { + _l.exit(); + } + } + } + + public String getPublicId() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getPublicId(); + } finally { + _l.exit(); + } + } + } + + public String getSystemId() { + synchronized (_l) { + _l.enter(); + try { + return _xs.getSystemId(); + } finally { + _l.exit(); + } + } + } + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Locale.java b/src/main/java/org/apache/xmlbeans/impl/store/Locale.java new file mode 100755 index 0000000..8376ac0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Locale.java @@ -0,0 +1,3080 @@ +/* Copyright 2004-2018 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.XmlCursor.XmlBookmark; +import org.apache.xmlbeans.impl.common.*; +import org.apache.xmlbeans.impl.store.Cur.Locations; +import org.apache.xmlbeans.impl.store.DomImpl.Dom; +import org.apache.xmlbeans.impl.store.Saaj.SaajCallback; +import org.w3c.dom.*; +import org.xml.sax.*; +import org.xml.sax.ext.DeclHandler; +import org.xml.sax.ext.LexicalHandler; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.lang.ref.PhantomReference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import static org.apache.xmlbeans.impl.values.TypeStore.*; + +public final class Locale + implements DOMImplementation, SaajCallback, XmlLocale { + private static final XBLogger logger = XBLogFactory.getLogger(Locale.class); + + static final int ROOT = Cur.ROOT; + static final int ELEM = Cur.ELEM; + static final int ATTR = Cur.ATTR; + static final int COMMENT = Cur.COMMENT; + static final int PROCINST = Cur.PROCINST; + static final int TEXT = Cur.TEXT; + + static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance"; + static final String _schema = "http://www.w3.org/2001/XMLSchema"; + static final String _openFragUri = "http://www.openuri.org/fragment"; + static final String _xml1998Uri = "http://www.w3.org/XML/1998/namespace"; + static final String _xmlnsUri = "http://www.w3.org/2000/xmlns/"; + + static final QName _xsiNil = new QName(_xsi, "nil", "xsi"); + static final QName _xsiType = new QName(_xsi, "type", "xsi"); + static final QName _xsiLoc = new QName(_xsi, "schemaLocation", "xsi"); + static final QName _xsiNoLoc = new QName(_xsi, "noNamespaceSchemaLocation", + "xsi"); + static final QName _openuriFragment = new QName(_openFragUri, "fragment", + "frag"); + static final QName _xmlFragment = new QName("xml-fragment"); + + private Locale(SchemaTypeLoader stl, XmlOptions options) { + options = XmlOptions.maskNull(options); + + // + // + // + + // TODO - add option for no=sync, or make it all thread safe + // + // Also - have a thread local setting for thread safety? .. Perhaps something + // in the type loader which defines whether ot not sync is on???? + + _noSync = options.isUnsynchronized(); + + _tempFrames = new Cur[_numTempFramesLeft = 8]; + + // BUGBUG - this cannot be thread local .... + // BUGBUG - this cannot be thread local .... + // BUGBUG - this cannot be thread local .... uhh what, again? + // + // Lazy create this (loading up a locale should use the thread locale one) + // same goes for the qname factory .. use thread local for hte most part when loading + + _qnameFactory = new DefaultQNameFactory(); //new LocalDocumentQNameFactory(); + + _locations = new Locations(this); + + _schemaTypeLoader = stl; + + _validateOnSet = options.isValidateOnSet(); + + // + // Check for Saaj implementation request + // + + _saaj = options.getSaaj(); + + if (_saaj != null) { + _saaj.setCallback(this); + } + } + + // + // + // + + public static Locale getLocale(SchemaTypeLoader stl, XmlOptions options) { + if (stl == null) { + stl = XmlBeans.getContextTypeLoader(); + } + + options = XmlOptions.maskNull(options); + + if (options.getUseSameLocale() == null) { + return new Locale(stl, options); + } + + Object source = options.getUseSameLocale(); + + Locale l; + + if (source instanceof Locale) { + l = (Locale) source; + } else if (source instanceof XmlTokenSource) { + l = (Locale) ((XmlTokenSource) source).monitor(); + } else { + throw new IllegalArgumentException("Source locale not understood: " + source); + } + + if (l._schemaTypeLoader != stl) { + throw new IllegalArgumentException( + "Source locale does not support same schema type loader"); + } + + if (l._saaj != null && l._saaj != options.getSaaj()) { + throw new IllegalArgumentException( + "Source locale does not support same saaj"); + } + + if (l._validateOnSet && !options.isValidateOnSet()) { + throw new IllegalArgumentException( + "Source locale does not support same validate on set"); + } + + // TODO - other things to check? + + return l; + } + + // + // + // + + public static void associateSourceName(Cur c, XmlOptions options) { + String sourceName = options == null ? null : options.getDocumentSourceName(); + + if (sourceName != null) { + getDocProps(c, true).setSourceName(sourceName); + } + } + + // + // + // + + public static void autoTypeDocument(Cur c, SchemaType requestedType, + XmlOptions options) + throws XmlException { + assert c.isRoot(); + + // The type in the options overrides all sniffing + + options = XmlOptions.maskNull(options); + + SchemaType optionType = options.getDocumentType(); + + if (optionType != null) { + c.setType(optionType); + return; + } + + SchemaType type = null; + + // An xsi:type can be used to pick a type out of the loader, or used to refine + // a type with a name. + + if (requestedType == null || requestedType.getName() != null) { + QName xsiTypeName = c.getXsiTypeName(); + + SchemaType xsiSchemaType = + xsiTypeName == null ? + null : c._locale._schemaTypeLoader.findType(xsiTypeName); + + if (requestedType == null || + requestedType.isAssignableFrom(xsiSchemaType)) { + type = xsiSchemaType; + } + } + + // Look for a document element to establish type + + if (type == null && + (requestedType == null || requestedType.isDocumentType())) { + assert c.isRoot(); + + c.push(); + + QName docElemName = + !c.hasAttrs() && Locale.toFirstChildElement(c) && + !Locale.toNextSiblingElement(c) + ? c.getName() : null; + + c.pop(); + + if (docElemName != null) { + type = + c._locale._schemaTypeLoader.findDocumentType(docElemName); + + if (type != null && requestedType != null) { + QName requesteddocElemNameName = requestedType.getDocumentElementName(); + + if (!requesteddocElemNameName.equals(docElemName) && + !requestedType.isValidSubstitution(docElemName)) { + throw + new XmlException("Element " + + QNameHelper.pretty(docElemName) + + " is not a valid " + + QNameHelper.pretty(requesteddocElemNameName) + + " document or a valid substitution."); + } + } + } + } + + if (type == null && requestedType == null) { + c.push(); + + type = + Locale.toFirstNormalAttr(c) && !Locale.toNextNormalAttr(c) + ? + c._locale._schemaTypeLoader.findAttributeType(c.getName()) : + null; + + c.pop(); + } + + if (type == null) { + type = requestedType; + } + + if (type == null) { + type = XmlBeans.NO_TYPE; + } + + c.setType(type); + + if (requestedType != null) { + if (type.isDocumentType()) { + verifyDocumentType(c, type.getDocumentElementName()); + } else if (type.isAttributeType()) { + verifyAttributeType(c, type.getAttributeTypeAttributeName()); + } + } + } + + private static boolean namespacesSame(QName n1, QName n2) { + if (n1 == n2) { + return true; + } + + if (n1 == null || n2 == null) { + return false; + } + + return Objects.equals(n1.getNamespaceURI(), n2.getNamespaceURI()); + } + + private static void addNamespace(StringBuffer sb, QName name) { + if (name.getNamespaceURI() == null) { + sb.append(""); + } else { + sb.append("\""); + sb.append(name.getNamespaceURI()); + sb.append("\""); + } + } + + private static void verifyDocumentType(Cur c, QName docElemName) + throws XmlException { + assert c.isRoot(); + + c.push(); + + try { + StringBuffer sb = null; + + if (!Locale.toFirstChildElement(c) || + Locale.toNextSiblingElement(c)) { + sb = new StringBuffer(); + + sb.append("The document is not a "); + sb.append(QNameHelper.pretty(docElemName)); + sb.append( + c.isRoot() ? + ": no document element" : ": multiple document elements"); + } else { + QName name = c.getName(); + + if (!name.equals(docElemName)) { + sb = new StringBuffer(); + + sb.append("The document is not a "); + sb.append(QNameHelper.pretty(docElemName)); + + if (docElemName.getLocalPart().equals(name.getLocalPart())) { + sb.append(": document element namespace mismatch "); + sb.append("expected "); + addNamespace(sb, docElemName); + sb.append(" got "); + addNamespace(sb, name); + } else if (namespacesSame(docElemName, name)) { + sb.append(": document element local name mismatch expected ") + .append(docElemName.getLocalPart()) + .append(" got ") + .append(name.getLocalPart()); + } else { + sb.append(": document element mismatch got "); + sb.append(QNameHelper.pretty(name)); + } + } + } + + if (sb != null) { + XmlError err = XmlError.forCursor(sb.toString(), + new Cursor(c)); + throw new XmlException(err.toString(), null, err); + } + } finally { + c.pop(); + } + } + + private static void verifyAttributeType(Cur c, QName attrName) + throws XmlException { + assert c.isRoot(); + + c.push(); + + try { + StringBuffer sb = null; + + if (!Locale.toFirstNormalAttr(c) || Locale.toNextNormalAttr(c)) { + sb = new StringBuffer(); + + sb.append("The document is not a "); + sb.append(QNameHelper.pretty(attrName)); + sb.append( + c.isRoot() ? ": no attributes" : ": multiple attributes"); + } else { + QName name = c.getName(); + + if (!name.equals(attrName)) { + sb = new StringBuffer(); + + sb.append("The document is not a "); + sb.append(QNameHelper.pretty(attrName)); + + if (attrName.getLocalPart().equals(name.getLocalPart())) { + sb.append(": attribute namespace mismatch "); + sb.append("expected "); + addNamespace(sb, attrName); + sb.append(" got "); + addNamespace(sb, name); + } else if (namespacesSame(attrName, name)) { + sb.append(": attribute local name mismatch "); + sb.append("expected " + attrName.getLocalPart()); + sb.append(" got " + name.getLocalPart()); + } else { + sb.append(": attribute element mismatch "); + sb.append("got "); + sb.append(QNameHelper.pretty(name)); + } + } + } + + if (sb != null) { + XmlError err = XmlError.forCursor(sb.toString(), + new Cursor(c)); + throw new XmlException(err.toString(), null, err); + } + } finally { + c.pop(); + } + } + + static boolean isFragmentQName(QName name) { + return name.equals(Locale._openuriFragment) || + name.equals(Locale._xmlFragment); + } + + static boolean isFragment(Cur start, Cur end) { + assert !end.isAttr(); + + start.push(); + end.push(); + + int numDocElems = 0; + boolean isFrag = false; + + while (!start.isSamePos(end)) { + int k = start.kind(); + + if (k == ATTR) { + break; + } + + if (k == TEXT && !isWhiteSpace(start.getCharsAsString())) { + isFrag = true; + break; + } + + if (k == ELEM && ++numDocElems > 1) { + isFrag = true; + break; + } + + // Move to next token + + if (k != TEXT) { + start.toEnd(); + } + + start.next(); + } + + start.pop(); + end.pop(); + + return isFrag || numDocElems != 1; + } + + // + // + // + + public static XmlObject newInstance(SchemaTypeLoader stl, SchemaType type, + XmlOptions options) { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.newInstance(type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.newInstance(type, options); + } finally { + l.exit(); + } + } + } + } + + private XmlObject newInstance(SchemaType type, XmlOptions options) { + options = XmlOptions.maskNull(options); + + Cur c = tempCur(); + + + SchemaType sType = options.getDocumentType(); + + if (sType == null) { + sType = type == null ? XmlObject.type : type; + } + if (sType.isDocumentType()) { + c.createDomDocumentRoot(); + } else { + c.createRoot(); + } + c.setType(sType); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + return x; + } + + // + // + // + + public static DOMImplementation newDomImplementation(SchemaTypeLoader stl, + XmlOptions options) { + return getLocale(stl, options); + } + + // + // + // + + public static XmlObject parseToXmlObject(SchemaTypeLoader stl, + String xmlText, SchemaType type, XmlOptions options) + throws XmlException { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.parseToXmlObject(xmlText, type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.parseToXmlObject(xmlText, type, options); + } finally { + l.exit(); + } + } + } + } + + private XmlObject parseToXmlObject(String xmlText, SchemaType type, + XmlOptions options) + throws XmlException { + Cur c = parse(xmlText, type, options); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + return x; + } + + Cur parse(String s, SchemaType type, XmlOptions options) + throws XmlException { + + try (Reader r = new StringReader(s)) { + Cur c = getSaxLoader(options).load(this, new InputSource(r), + options); + + autoTypeDocument(c, type, options); + + return c; + } catch (IOException e) { + assert false : "StringReader should not throw IOException"; + + throw new XmlException(e.getMessage(), e); + } + } + + // + // + // + + + // + // + // + + public static XmlObject parseToXmlObject(SchemaTypeLoader stl, + XMLStreamReader xsr, SchemaType type, XmlOptions options) + throws XmlException { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.parseToXmlObject(xsr, type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.parseToXmlObject(xsr, type, options); + } finally { + l.exit(); + } + } + } + } + + public XmlObject parseToXmlObject(XMLStreamReader xsr, SchemaType type, + XmlOptions options) + throws XmlException { + Cur c; + + try { + c = loadXMLStreamReader(xsr, options); + } catch (XMLStreamException e) { + throw new XmlException(e.getMessage(), e); + } + + autoTypeDocument(c, type, options); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + return x; + } + + private static void lineNumber(XMLStreamReader xsr, LoadContext context) { + javax.xml.stream.Location loc = xsr.getLocation(); + + if (loc != null) { + context.lineNumber(loc.getLineNumber(), loc.getColumnNumber(), + loc.getCharacterOffset()); + } + } + + private void doAttributes(XMLStreamReader xsr, LoadContext context) { + int n = xsr.getAttributeCount(); + + for (int a = 0; a < n; a++) { + context.attr(xsr.getAttributeLocalName(a), + xsr.getAttributeNamespace(a), + xsr.getAttributePrefix(a), + xsr.getAttributeValue(a)); + } + } + + private void doNamespaces(XMLStreamReader xsr, LoadContext context) { + int n = xsr.getNamespaceCount(); + + for (int a = 0; a < n; a++) { + String prefix = xsr.getNamespacePrefix(a); + + if (prefix == null || prefix.length() == 0) { + context.attr("xmlns", _xmlnsUri, null, + xsr.getNamespaceURI(a)); + } else { + context.attr(prefix, _xmlnsUri, "xmlns", + xsr.getNamespaceURI(a)); + } + } + + } + + private Cur loadXMLStreamReader(XMLStreamReader xsr, XmlOptions options) + throws XMLStreamException { + options = XmlOptions.maskNull(options); + + boolean lineNums = options.isLoadLineNumbers(); + + String encoding = null, version = null; + boolean standAlone = false; + + LoadContext context = new Cur.CurLoadContext(this, options); + int depth = 0; + + events: + for (int eventType = xsr.getEventType(); ; eventType = xsr.next()) { + switch (eventType) { + case XMLStreamReader.START_DOCUMENT: { + depth++; + + encoding = xsr.getCharacterEncodingScheme(); + version = xsr.getVersion(); + standAlone = xsr.isStandalone(); + + if (lineNums) { + lineNumber(xsr, context); + } + + break; + } + + case XMLStreamReader.END_DOCUMENT: { + depth--; + + if (lineNums) { + lineNumber(xsr, context); + } + + break events; + } + + case XMLStreamReader.START_ELEMENT: { + depth++; + context.startElement(xsr.getName()); + + if (lineNums) { + lineNumber(xsr, context); + } + + doAttributes(xsr, context); + doNamespaces(xsr, context); + + break; + } + + case XMLStreamReader.END_ELEMENT: { + depth--; + context.endElement(); + + if (lineNums) { + lineNumber(xsr, context); + } + + break; + } + + case XMLStreamReader.CHARACTERS: + case XMLStreamReader.CDATA: { + context.text(xsr.getTextCharacters(), xsr.getTextStart(), + xsr.getTextLength()); + + if (lineNums) { + lineNumber(xsr, context); + } + + break; + } + + case XMLStreamReader.COMMENT: { + String comment = xsr.getText(); + + context.comment(comment); + + if (lineNums) { + lineNumber(xsr, context); + } + + break; + } + + case XMLStreamReader.PROCESSING_INSTRUCTION: { + context.procInst(xsr.getPITarget(), xsr.getPIData()); + + if (lineNums) { + lineNumber(xsr, context); + } + + break; + } + + case XMLStreamReader.ATTRIBUTE: { + doAttributes(xsr, context); + break; + } + + case XMLStreamReader.NAMESPACE: { + doNamespaces(xsr, context); + break; + } + + case XMLStreamReader.ENTITY_REFERENCE: { + context.text(xsr.getText()); + break; + } + + case XMLStreamReader.SPACE: + case XMLStreamReader.DTD: + break; + + default: + throw new RuntimeException( + "Unhandled xml event type: " + eventType); + } + + if (!xsr.hasNext() || depth <= 0) { + break; + } + } + + Cur c = context.finish(); + + associateSourceName(c, options); + + XmlDocumentProperties props = getDocProps(c, true); + + props.setEncoding(encoding); + props.setVersion(version); + props.setStandalone(standAlone); + + return c; + } + + // + // + // + + public static XmlObject parseToXmlObject(SchemaTypeLoader stl, + InputStream is, SchemaType type, XmlOptions options) + throws XmlException, IOException { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.parseToXmlObject(is, type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.parseToXmlObject(is, type, options); + } finally { + l.exit(); + } + } + } + } + + private XmlObject parseToXmlObject(InputStream is, SchemaType type, + XmlOptions options) + throws XmlException, IOException { + Cur c = getSaxLoader(options).load(this, new InputSource(is), + options); + + autoTypeDocument(c, type, options); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + return x; + } + + // + // + // + + public static XmlObject parseToXmlObject(SchemaTypeLoader stl, + Reader reader, SchemaType type, XmlOptions options) + throws XmlException, IOException { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.parseToXmlObject(reader, type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.parseToXmlObject(reader, type, options); + } finally { + l.exit(); + } + } + } + } + + private XmlObject parseToXmlObject(Reader reader, SchemaType type, + XmlOptions options) + throws XmlException, IOException { + Cur c = getSaxLoader(options).load(this, new InputSource(reader), + options); + + autoTypeDocument(c, type, options); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + return x; + } + + // + // + // + + public static XmlObject parseToXmlObject(SchemaTypeLoader stl, Node node, + SchemaType type, XmlOptions options) + throws XmlException { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.parseToXmlObject(node, type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.parseToXmlObject(node, type, options); + } finally { + l.exit(); + } + } + } + } + + public XmlObject parseToXmlObject(Node node, SchemaType type, + XmlOptions options) + throws XmlException { + LoadContext context = new Cur.CurLoadContext(this, options); + + loadNode(node, context); + + Cur c = context.finish(); + + associateSourceName(c, options); + + autoTypeDocument(c, type, options); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + return x; + } + + private void loadNodeChildren(Node n, LoadContext context) { + for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling()) { + loadNode(c, context); + } + } + + public void loadNode(Node n, LoadContext context) { + switch (n.getNodeType()) { + case Node.DOCUMENT_NODE: + case Node.DOCUMENT_FRAGMENT_NODE: + case Node.ENTITY_REFERENCE_NODE: { + loadNodeChildren(n, context); + + break; + } + case Node.ELEMENT_NODE: { + context.startElement( + makeQualifiedQName(n.getNamespaceURI(), n.getNodeName())); + + NamedNodeMap attrs = n.getAttributes(); + + for (int i = 0; i < attrs.getLength(); i++) { + Node a = attrs.item(i); + + String attrName = a.getNodeName(); + String attrValue = a.getNodeValue(); + + if (attrName.toLowerCase(java.util.Locale.ROOT).startsWith("xmlns")) { + if (attrName.length() == 5) { + context.xmlns(null, attrValue); + } else { + context.xmlns(attrName.substring(6), attrValue); + } + } else { + context.attr( + makeQualifiedQName(a.getNamespaceURI(), attrName), + attrValue); + } + } + + loadNodeChildren(n, context); + + context.endElement(); + + break; + } + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: { + context.text(n.getNodeValue()); + break; + } + case Node.COMMENT_NODE: { + context.comment(n.getNodeValue()); + break; + } + case Node.PROCESSING_INSTRUCTION_NODE: { + context.procInst(n.getNodeName(), n.getNodeValue()); + break; + } + case Node.DOCUMENT_TYPE_NODE: + case Node.ENTITY_NODE: + case Node.NOTATION_NODE: { + Node next = n.getNextSibling(); + if (next != null) { + loadNode(next, context); + } + break; + } + case Node.ATTRIBUTE_NODE: { + throw new RuntimeException("Unexpected node"); + } + } + } + + // + // + // + + private static class XmlSaxHandlerImpl + extends SaxHandler + implements XmlSaxHandler { + XmlSaxHandlerImpl(Locale l, SchemaType type, XmlOptions options) { + super(null); + + _options = options; + _type = type; + + // Because SAX loading is not atomic with respect to XmlBeans, I can't use the default + // thread local CharUtil. Instruct the SaxHandler (and the LoadContext, eventually) + // to use the Locale specific CharUtil. + + XmlOptions saxHandlerOptions = new XmlOptions(options); + saxHandlerOptions.setLoadUseLocaleCharUtil(true); + initSaxHandler(l, saxHandlerOptions); + } + + public ContentHandler getContentHandler() { + return _context == null ? null : this; + } + + public LexicalHandler getLexicalHandler() { + return _context == null ? null : this; + } + + public void bookmarkLastEvent(XmlBookmark mark) { + _context.bookmarkLastNonAttr(mark); + } + + public void bookmarkLastAttr(QName attrName, XmlBookmark mark) { + _context.bookmarkLastAttr(attrName, mark); + } + + public XmlObject getObject() + throws XmlException { + if (_context == null) { + return null; + } + + _locale.enter(); + + try { + Cur c = _context.finish(); + + autoTypeDocument(c, _type, _options); + + XmlObject x = (XmlObject) c.getUser(); + + c.release(); + + _context = null; + + return x; + } finally { + _locale.exit(); + } + } + + private final SchemaType _type; + private final XmlOptions _options; + } + + public static XmlSaxHandler newSaxHandler(SchemaTypeLoader stl, + SchemaType type, XmlOptions options) { + Locale l = getLocale(stl, options); + + if (l.noSync()) { + l.enter(); + try { + return l.newSaxHandler(type, options); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return l.newSaxHandler(type, options); + } finally { + l.exit(); + } + } + } + } + + public XmlSaxHandler newSaxHandler(SchemaType type, XmlOptions options) { + return new XmlSaxHandlerImpl(this, type, options); + } + + // TODO (ericvas ) - have a qname factory here so that the same factory may be + // used by the parser. This factory would probably come from my + // high speed parser. Otherwise, use a thread local on + + QName makeQName(String uri, String localPart) { + assert localPart != null && localPart.length() > 0; + // TODO - make sure name is a well formed name? + + return _qnameFactory.getQName(uri, localPart); + } + + QName makeQNameNoCheck(String uri, String localPart) { + return _qnameFactory.getQName(uri, localPart); + } + + QName makeQName(String uri, String local, String prefix) { + return _qnameFactory.getQName(uri, local, prefix == null ? "" : prefix); + } + + QName makeQualifiedQName(String uri, String qname) { + if (qname == null) { + qname = ""; + } + + int i = qname.indexOf(':'); + + return i < 0 + ? + _qnameFactory.getQName(uri, qname) + : + _qnameFactory.getQName(uri, qname.substring(i + 1), + qname.substring(0, i)); + } + + static private class DocProps + extends XmlDocumentProperties { + private final HashMap _map = new HashMap<>(); + + public Object put(Object key, Object value) { + return _map.put(key, value); + } + + public Object get(Object key) { + return _map.get(key); + } + + public Object remove(Object key) { + return _map.remove(key); + } + } + + static XmlDocumentProperties getDocProps(Cur c, boolean ensure) { + c.push(); + + while (c.toParent()) { + } + + DocProps props = (DocProps) c.getBookmark(DocProps.class); + + if (props == null && ensure) { + c.setBookmark(DocProps.class, props = new DocProps()); + } + + c.pop(); + + return props; + } + + interface ChangeListener { + void notifyChange(); + + void setNextChangeListener(ChangeListener listener); + + ChangeListener getNextChangeListener(); + } + + void registerForChange(ChangeListener listener) { + if (listener.getNextChangeListener() == null) { + if (_changeListeners == null) { + listener.setNextChangeListener(listener); + } else { + listener.setNextChangeListener(_changeListeners); + } + + _changeListeners = listener; + } + } + + void notifyChange() { + // First, notify the registered listeners ... + + while (_changeListeners != null) { + _changeListeners.notifyChange(); + + if (_changeListeners.getNextChangeListener() == _changeListeners) { + _changeListeners.setNextChangeListener(null); + } + + ChangeListener next = _changeListeners.getNextChangeListener(); + + _changeListeners.setNextChangeListener(null); + + _changeListeners = next; + } + + // Then, prepare for the change in a locale specific way. Need to create real Curs for + // 'virtual' Curs in Locations + + _locations.notifyChange(); + } + + // + // Cursor helpers + // + + static String getTextValue(Cur c) { + assert c.isNode(); + + if (!c.hasChildren()) { + return c.getValueAsString(); + } + + StringBuffer sb = new StringBuffer(); + + c.push(); + + for (c.next(); !c.isAtEndOfLastPush(); c.next()) { + if (c.isText()) { + if ((c._xobj.isComment() || c._xobj.isProcinst()) && c._pos < c._xobj._cchValue) { + continue; + } + CharUtil.getString(sb, c.getChars(-1), c._offSrc, c._cchSrc); + } + } + + c.pop(); + + return sb.toString(); + } + + static int getTextValue(Cur c, int wsr, char[] chars, int off, int maxCch) { + // TODO - hack impl for now ... improve + + assert c.isNode(); + + String s = c._xobj.getValueAsString(wsr); + + int n = s.length(); + + if (n > maxCch) { + n = maxCch; + } + + if (n <= 0) { + return 0; + } + + s.getChars(0, n, chars, off); + + return n; + } + + static String applyWhiteSpaceRule(String s, int wsr) { + int l = s == null ? 0 : s.length(); + + if (l == 0 || wsr == WS_PRESERVE) { + return s; + } + + char ch; + + if (wsr == WS_REPLACE) { + for (int i = 0; i < l; i++) { + if ((ch = s.charAt(i)) == '\n' || ch == '\r' || ch == '\t') { + return processWhiteSpaceRule(s, wsr); + } + } + } else if (wsr == WS_COLLAPSE) { + if (CharUtil.isWhiteSpace(s.charAt(0)) || + CharUtil.isWhiteSpace(s.charAt(l - 1))) { + return processWhiteSpaceRule(s, wsr); + } + + boolean lastWasWhite = false; + + for (int i = 1; i < l; i++) { + boolean isWhite = CharUtil.isWhiteSpace(s.charAt(i)); + + if (isWhite && lastWasWhite) { + return processWhiteSpaceRule(s, wsr); + } + + lastWasWhite = isWhite; + } + } + + return s; + } + + static String processWhiteSpaceRule(String s, int wsr) { + ScrubBuffer sb = getScrubBuffer(wsr); + + sb.scrub(s, 0, s.length()); + + return sb.getResultAsString(); + } + + static final class ScrubBuffer { + ScrubBuffer() { + _sb = new StringBuffer(); + } + + void init(int wsr) { + _sb.delete(0, _sb.length()); + + _wsr = wsr; + _state = START_STATE; + } + + void scrub(Object src, int off, int cch) { + if (cch == 0) { + return; + } + + if (_wsr == WS_PRESERVE) { + CharUtil.getString(_sb, src, off, cch); + return; + } + + char[] chars; + + if (src instanceof char[]) { + chars = (char[]) src; + } else { + if (cch <= _srcBuf.length) { + chars = _srcBuf; + } else if (cch <= 16384) { + chars = _srcBuf = new char[16384]; + } else { + chars = new char[cch]; + } + + CharUtil.getChars(chars, 0, src, off, cch); + off = 0; + } + + int start = 0; + + for (int i = 0; i < cch; i++) { + char ch = chars[off + i]; + + if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') { + _sb.append(chars, off + start, i - start); + + start = i + 1; + + if (_wsr == WS_REPLACE) { + _sb.append(' '); + } else if (_state == NOSPACE_STATE) { + _state = SPACE_SEEN_STATE; + } + } else { + if (_state == SPACE_SEEN_STATE) { + _sb.append(' '); + } + + _state = NOSPACE_STATE; + } + } + + _sb.append(chars, off + start, cch - start); + } + + String getResultAsString() { + return _sb.toString(); + } + + private static final int START_STATE = 0; + private static final int SPACE_SEEN_STATE = 1; + private static final int NOSPACE_STATE = 2; + + private int _state; + + private int _wsr; + + private char[] _srcBuf = new char[1024]; + private final StringBuffer _sb; + } + + private static final ThreadLocal> tl_scrubBuffer = + ThreadLocal.withInitial(() -> new SoftReference<>(new ScrubBuffer())); + + public static void clearThreadLocals() { + tl_scrubBuffer.remove(); + } + + static ScrubBuffer getScrubBuffer(int wsr) { + SoftReference softRef = tl_scrubBuffer.get(); + ScrubBuffer scrubBuffer = softRef.get(); + if (scrubBuffer == null) { + scrubBuffer = new ScrubBuffer(); + tl_scrubBuffer.set(new SoftReference<>(scrubBuffer)); + } + + scrubBuffer.init(wsr); + return scrubBuffer; + } + + static boolean pushToContainer(Cur c) { + c.push(); + + for (; ; ) { + switch (c.kind()) { + case ROOT: + case ELEM: + return true; + case -ROOT: + case -ELEM: + c.pop(); + return false; + case COMMENT: + case PROCINST: + c.skip(); + break; + default: + c.nextWithAttrs(); + break; + } + } + } + + static boolean toFirstNormalAttr(Cur c) { + c.push(); + + if (c.toFirstAttr()) { + do { + if (!c.isXmlns()) { + c.popButStay(); + return true; + } + } + while (c.toNextAttr()); + } + + c.pop(); + + return false; + } + + static boolean toPrevNormalAttr(Cur c) { + if (c.isAttr()) { + c.push(); + + for (; ; ) { + assert c.isAttr(); + + // See if I can move backward. If I'm at the first attr, prev must return + // false and not move. + + if (!c.prev()) { + break; + } + + // Skip past the text value or attr begin + + c.prev(); + + // I might have skipped over text above + + if (!c.isAttr()) { + c.prev(); + } + + if (c.isNormalAttr()) { + c.popButStay(); + return true; + } + } + + c.pop(); + } + + return false; + } + + static boolean toNextNormalAttr(Cur c) { + c.push(); + + while (c.toNextAttr()) { + if (!c.isXmlns()) { + c.popButStay(); + return true; + } + } + + c.pop(); + + return false; + } + + Xobj findNthChildElem(Xobj parent, QName name, QNameSet set, int n) { + // only one of (set or name) is not null + // or both are null for a wildcard + assert (name == null || set == null); + assert n >= 0; + + if (parent == null) { + return null; + } + + int da = _nthCache_A.distance(parent, name, set, n); + int db = _nthCache_B.distance(parent, name, set, n); + + Xobj x = + da <= db + ? _nthCache_A.fetch(parent, name, set, n) + : _nthCache_B.fetch(parent, name, set, n); + + if (da == db) { + nthCache temp = _nthCache_A; + _nthCache_A = _nthCache_B; + _nthCache_B = temp; + } + + return x; + } + + int count(Xobj parent, QName name, QNameSet set) { + int n = 0; + + for (Xobj x = findNthChildElem(parent, name, set, 0); + x != null; x = x._nextSibling) { + if (x.isElem()) { + if (set == null) { + if (x._name.equals(name)) { + n++; + } + } else if (set.contains(x._name)) { + n++; + } + } + } + + return n; + } + + static boolean toChild(Cur c, QName name, int n) { + if (n >= 0 && pushToContainer(c)) { + Xobj x = c._locale.findNthChildElem(c._xobj, name, null, n); + + c.pop(); + + if (x != null) { + c.moveTo(x); + return true; + } + } + + return false; + } + + public static boolean toFirstChildElement(Cur c) { +// if (!pushToContainer(c)) +// return false; +// +// if (!c.toFirstChild() || (!c.isElem() && !toNextSiblingElement(c))) +// { +// c.pop(); +// return false; +// } +// +// c.popButStay(); +// +// return true; + + Xobj originalXobj = c._xobj; + int originalPos = c._pos; + + loop: + for (; ; ) { + switch (c.kind()) { + case ROOT: + case ELEM: + break loop; + case -ROOT: + case -ELEM: + c.moveTo(originalXobj, originalPos); + return false; + case COMMENT: + case PROCINST: + c.skip(); + break; + default: + c.nextWithAttrs(); + break; + } + } + + if (!c.toFirstChild() || (!c.isElem() && !toNextSiblingElement(c))) { + c.moveTo(originalXobj, originalPos); + return false; + } + + return true; + } + + static boolean toLastChildElement(Cur c) { + if (!pushToContainer(c)) { + return false; + } + + if (!c.toLastChild() || (!c.isElem() && !toPrevSiblingElement(c))) { + c.pop(); + return false; + } + + c.popButStay(); + + return true; + } + + static boolean toPrevSiblingElement(Cur cur) { + if (!cur.hasParent()) { + return false; + } + + Cur c = cur.tempCur(); + + boolean moved = false; + + int k = c.kind(); + + if (k != ATTR) { + for (; ; ) { + if (!c.prev()) { + break; + } + + k = c.kind(); + + if (k == ROOT || k == ELEM) { + break; + } + + if (c.kind() == -ELEM) { + c.toParent(); + + cur.moveToCur(c); + moved = true; + + break; + } + } + } + + c.release(); + + return moved; + } + + static boolean toNextSiblingElement(Cur c) { + if (!c.hasParent()) { + return false; + } + + c.push(); + + int k = c.kind(); + + if (k == ATTR) { + c.toParent(); + c.next(); + } else if (k == ELEM) { + c.skip(); + } + + while ((k = c.kind()) >= 0) { + if (k == ELEM) { + c.popButStay(); + return true; + } + + if (k > 0) { + c.toEnd(); + } + + c.next(); + } + + c.pop(); + + return false; + } + + static boolean toNextSiblingElement(Cur c, Xobj parent) { + Xobj originalXobj = c._xobj; + int originalPos = c._pos; + + int k = c.kind(); + + if (k == ATTR) { + c.moveTo(parent); + c.next(); + } else if (k == ELEM) { + c.skip(); + } + + while ((k = c.kind()) >= 0) { + if (k == ELEM) { + return true; + } + + if (k > 0) { + c.toEnd(); + } + + c.next(); + } + + c.moveTo(originalXobj, originalPos); + + return false; + } + + static void applyNamespaces(Cur c, Map namespaces) { + assert c.isContainer(); + + for (String prefix : namespaces.keySet()) { + // Usually, this is the predefined xml namespace + if (!prefix.toLowerCase(java.util.Locale.ROOT).startsWith("xml")) { + if (c.namespaceForPrefix(prefix, false) == null) { + c.push(); + + c.next(); + c.createAttr(c._locale.createXmlns(prefix)); + c.next(); + + c.insertString(namespaces.get(prefix)); + + c.pop(); + } + } + } + } + + static Map getAllNamespaces(Cur c, Map filleMe) { + assert c.isNode(); + + c.push(); + + if (!c.isContainer()) { + c.toParent(); + } + + assert c.isContainer(); + + do { + QName cName = c.getName(); + + while (c.toNextAttr()) { + if (c.isXmlns()) { + String prefix = c.getXmlnsPrefix(); + String uri = c.getXmlnsUri(); + + if (filleMe == null) { + filleMe = new HashMap<>(); + } + + if (!filleMe.containsKey(prefix)) { + filleMe.put(prefix, uri); + } + } + } + + if (!c.isContainer()) { + c.toParentRaw(); + } + } + while (c.toParentRaw()); + + c.pop(); + + return filleMe; + } + + class nthCache { + private boolean namesSame(QName pattern, QName name) { + return pattern == null || pattern.equals(name); + } + + private boolean setsSame(QNameSet patternSet, QNameSet set) { + // value equality is probably too expensive. Since the use case + // involves QNameSets that are generated by the compiler, we + // can use identity comparison. + + return patternSet != null && patternSet == set; + } + + private boolean nameHit(QName namePattern, QNameSet setPattern, + QName name) { + return + setPattern == null + ? namesSame(namePattern, name) + : setPattern.contains(name); + } + + private boolean cacheSame(QName namePattern, QNameSet setPattern) { + return + setPattern == null + ? namesSame(namePattern, _name) + : setsSame(setPattern, _set); + } + + int distance(Xobj parent, QName name, QNameSet set, int n) { + assert n >= 0; + + if (_version != Locale.this.version()) { + return Integer.MAX_VALUE - 1; + } + + if (parent != _parent || !cacheSame(name, set)) { + return Integer.MAX_VALUE; + } + + return n > _n ? n - _n : _n - n; + } + + Xobj fetch(Xobj parent, QName name, QNameSet set, int n) { + assert n >= 0; + + if (_version != Locale.this.version() || _parent != parent || + !cacheSame(name, set) || n == 0) { + _version = Locale.this.version(); + _parent = parent; + _name = name; + _child = null; + _n = -1; + + loop: + for (Xobj x = parent._firstChild; + x != null; x = x._nextSibling) { + if (x.isElem() && nameHit(name, set, x._name)) { + _child = x; + _n = 0; + + break loop; + } + } + } + + if (_n < 0) { + return null; + } + + if (n > _n) { + while (n > _n) { + for (Xobj x = _child._nextSibling; ; x = x._nextSibling) { + if (x == null) { + return null; + } + + if (x.isElem() && nameHit(name, set, x._name)) { + _child = x; + _n++; + + break; + } + } + } + } else if (n < _n) { + while (n < _n) { + for (Xobj x = _child._prevSibling; ; x = x._prevSibling) { + if (x == null) { + return null; + } + + if (x.isElem() && nameHit(name, set, x._name)) { + _child = x; + _n--; + + break; + } + } + } + } + + return _child; + } + + private long _version; + private Xobj _parent; + private QName _name; + private QNameSet _set; + private Xobj _child; + private int _n; + } + + // + // + // + + Dom findDomNthChild(Dom parent, int n) { + assert n >= 0; + + if (parent == null) { + return null; + } + + int da = _domNthCache_A.distance(parent, n); + int db = _domNthCache_B.distance(parent, n); + + + // the "better" cache should never walk more than 1/2 len + Dom x = null; + boolean bInvalidate = (db - _domNthCache_B._len / 2 > 0) && + (db - _domNthCache_B._len / 2 - domNthCache.BLITZ_BOUNDARY > 0); + boolean aInvalidate = (da - _domNthCache_A._len / 2 > 0) && + (da - _domNthCache_A._len / 2 - domNthCache.BLITZ_BOUNDARY > 0); + if (da <= db) { + if (!aInvalidate) { + x = _domNthCache_A.fetch(parent, n); + } else { + _domNthCache_B._version = -1;//blitz the cache + x = _domNthCache_B.fetch(parent, n); + } + } else if (!bInvalidate) { + x = _domNthCache_B.fetch(parent, n); + } else { + _domNthCache_A._version = -1;//blitz the cache + x = _domNthCache_A.fetch(parent, n); + } + + if (da == db) { + domNthCache temp = _domNthCache_A; + _domNthCache_A = _domNthCache_B; + _domNthCache_B = temp; + } + + return x; + } + + int domLength(Dom parent) { + if (parent == null) { + return 0; + } + + int da = _domNthCache_A.distance(parent, 0); + int db = _domNthCache_B.distance(parent, 0); + + int len = + da <= db + ? _domNthCache_A.length(parent) + : _domNthCache_B.length(parent); + + if (da == db) { + domNthCache temp = _domNthCache_A; + _domNthCache_A = _domNthCache_B; + _domNthCache_B = temp; + } + + return len; + } + + void invalidateDomCaches(Dom d) { + if (_domNthCache_A._parent == d) { + _domNthCache_A._version = -1; + } + if (_domNthCache_B._parent == d) { + _domNthCache_B._version = -1; + } + } + + boolean isDomCached(Dom d) { + return _domNthCache_A._parent == d || _domNthCache_B._parent == d; + } + + class domNthCache { + + int distance(Dom parent, int n) { + assert n >= 0; + + if (_version != Locale.this.version()) { + return Integer.MAX_VALUE - 1; + } + + if (parent != _parent) { + return Integer.MAX_VALUE; + } + + return n > _n ? n - _n : _n - n; + } + + int length(Dom parent) { + if (_version != Locale.this.version() || _parent != parent) { + _parent = parent; + _version = Locale.this.version(); + _child = null; + _n = -1; + _len = -1; + } + + if (_len == -1) { + Dom x = null; + + if (_child != null && _n != -1) { + x = _child; + _len = _n; + } else { + x = (Dom) DomImpl.firstChild(_parent); + _len = 0; + + // cache the 0th child + _child = x; + _n = 0; + } + + for (; x != null; x = (Dom) DomImpl.nextSibling(x)) { + _len++; + } + } + + + return _len; + } + + Dom fetch(Dom parent, int n) { + assert n >= 0; + + if (_version != Locale.this.version() || _parent != parent) { + _parent = parent; + _version = Locale.this.version(); + _child = null; + _n = -1; + _len = -1; + + for (Dom x = (Dom) DomImpl.firstChild(_parent); x != null; x = (Dom) DomImpl.nextSibling(x)) { + _n++; + if (_child == null && n == _n) { + _child = x; + break; + } + } + + return _child; + } + + if (_n < 0) { + return null; + } + + if (n > _n) { + while (n > _n) { + for (Dom x = (Dom) DomImpl.nextSibling(_child); ; x = (Dom) DomImpl.nextSibling(x)) { + if (x == null) { + return null; + } + + _child = x; + _n++; + + break; + } + } + } else if (n < _n) { + while (n < _n) { + for (Dom x = (Dom) DomImpl.prevSibling(_child); ; x = (Dom) DomImpl.prevSibling(x)) { + if (x == null) { + return null; + } + + _child = x; + _n--; + + break; + } + } + } + + return _child; + } + + public static final int BLITZ_BOUNDARY = 40; //walk small lists + private long _version; + private Dom _parent; + private Dom _child; + private int _n; + private int _len; + } + + // + // + // + + CharUtil getCharUtil() { + if (_charUtil == null) { + _charUtil = new CharUtil(1024); + } + + return _charUtil; + } + + public long version() { + return _versionAll; + } + + Cur weakCur(Object o) { + assert o != null && !(o instanceof Ref); + + Cur c = getCur(); + + assert c._tempFrame == -1; + assert c._ref == null; + + c._ref = new Ref(c, o); + + return c; + } + + final ReferenceQueue refQueue() { + if (_refQueue == null) { + _refQueue = new ReferenceQueue(); + } + + return _refQueue; + } + + final static class Ref + extends PhantomReference { + Ref(Cur c, Object obj) { + super(obj, c._locale.refQueue()); + + _cur = c; + } + + Cur _cur; + } + + Cur tempCur() { + return tempCur(null); + } + + Cur tempCur(String id) { + Cur c = getCur(); + + assert c._tempFrame == -1; + + assert _numTempFramesLeft < _tempFrames.length : "Temp frame not pushed"; + + int frame = _tempFrames.length - _numTempFramesLeft - 1; + + assert frame >= 0 && frame < _tempFrames.length; + + Cur next = _tempFrames[frame]; + + c._nextTemp = next; + assert c._prevTemp == null; + + if (next != null) { + assert next._prevTemp == null; + next._prevTemp = c; + } + + _tempFrames[frame] = c; + c._tempFrame = frame; + + c._id = id; + + return c; + } + + Cur getCur() { + assert _curPool == null || _curPoolCount > 0; + + Cur c; + + if (_curPool == null) { + c = new Cur(this); + } else { + _curPool = _curPool.listRemove(c = _curPool); + _curPoolCount--; + } + + assert c._state == Cur.POOLED; + assert c._prev == null && c._next == null; + assert c._xobj == null && c._pos == Cur.NO_POS; + assert c._ref == null; + + _registered = c.listInsert(_registered); + c._state = Cur.REGISTERED; + + return c; + } + + void embedCurs() { + for (Cur c; (c = _registered) != null; ) { + assert c._xobj != null; + + _registered = c.listRemove(_registered); + c._xobj._embedded = c.listInsert(c._xobj._embedded); + c._state = Cur.EMBEDDED; + } + } + + TextNode createTextNode() { + return _saaj == null ? new TextNode(this) : new SaajTextNode(this); + } + + CdataNode createCdataNode() { + return _saaj == null ? + new CdataNode(this) : new SaajCdataNode(this); + } + + boolean entered() { + return _tempFrames.length - _numTempFramesLeft > 0; + } + + public void enter(Locale otherLocale) { + enter(); + + if (otherLocale != this) { + otherLocale.enter(); + } + } + + public void enter() { + assert _numTempFramesLeft >= 0; + + if (--_numTempFramesLeft <= 0) { + Cur[] newTempFrames = new Cur[_tempFrames.length * 2]; + //move this assignment down so if array allocation fails, error is not masked + _numTempFramesLeft = _tempFrames.length; + System.arraycopy(_tempFrames, 0, newTempFrames, 0, + _tempFrames.length); + _tempFrames = newTempFrames; + } + + if (++_entryCount > 1000) { + pollQueue(); + _entryCount = 0; + } + } + + private void pollQueue() { + if (_refQueue != null) { + for (; ; ) { + Ref ref = (Ref) _refQueue.poll(); + + if (ref == null) { + break; + } + + if (ref._cur != null) { + ref._cur.release(); + } + } + } + } + + public void exit(Locale otherLocale) { + exit(); + + if (otherLocale != this) { + otherLocale.exit(); + } + } + + public void exit() { + // assert _numTempFramesLeft >= 0; + //asserts computed frame fits between 0 and _tempFrames.length + assert _numTempFramesLeft >= 0 && + (_numTempFramesLeft <= _tempFrames.length - 1) : + " Temp frames mismanaged. Impossible stack frame. Unsynchronized: " + + noSync(); + + int frame = _tempFrames.length - ++_numTempFramesLeft; + + while (_tempFrames[frame] != null) { + _tempFrames[frame].release(); + } + } + + // + // + // + + public boolean noSync() { + return _noSync; + } + + public boolean sync() { + return !_noSync; + } + + static final boolean isWhiteSpace(String s) { + int l = s.length(); + + while (l-- > 0) { + if (!CharUtil.isWhiteSpace(s.charAt(l))) { + return false; + } + } + + return true; + } + + static final boolean isWhiteSpace(StringBuffer sb) { + int l = sb.length(); + + while (l-- > 0) { + if (!CharUtil.isWhiteSpace(sb.charAt(l))) { + return false; + } + } + + return true; + } + + static boolean beginsWithXml(String name) { + if (name.length() < 3) { + return false; + } + + char ch; + + if (((ch = name.charAt(0)) == 'x' || ch == 'X') && + ((ch = name.charAt(1)) == 'm' || ch == 'M') && + ((ch = name.charAt(2)) == 'l' || ch == 'L')) { + return true; + } + + return false; + } + + static boolean isXmlns(QName name) { + String prefix = name.getPrefix(); + + if (prefix.equals("xmlns")) { + return true; + } + + return prefix.length() == 0 && name.getLocalPart().equals("xmlns"); + } + + QName createXmlns(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return + prefix.length() == 0 + ? makeQName(_xmlnsUri, "xmlns", "") + : makeQName(_xmlnsUri, prefix, "xmlns"); + } + + static String xmlnsPrefix(QName name) { + return name.getPrefix().equals("xmlns") ? name.getLocalPart() : ""; + } + + // + // Loading/parsing + // + + public static abstract class LoadContext { + protected abstract void startDTD(String name, String publicId, + String systemId); + + protected abstract void endDTD(); + + protected abstract void startElement(QName name); + + protected abstract void endElement(); + + public abstract void attr(QName name, String value); + + protected abstract void attr(String local, String uri, String prefix, + String value); + + protected abstract void xmlns(String prefix, String uri); + + protected abstract void comment(char[] buff, int off, int cch); + + protected abstract void comment(String comment); + + protected abstract void procInst(String target, String value); + + protected abstract void text(char[] buff, int off, int cch); + + protected abstract void text(String s); + + public abstract Cur finish(); + + protected abstract void abort(); + + protected abstract void bookmark(XmlBookmark bm); + + protected abstract void bookmarkLastNonAttr(XmlBookmark bm); + + protected abstract void bookmarkLastAttr(QName attrName, + XmlBookmark bm); + + protected abstract void lineNumber(int line, int column, int offset); + + protected void addIdAttr(String eName, String aName) { + if (_idAttrs == null) { + _idAttrs = new java.util.Hashtable(); + } + _idAttrs.put(aName, eName); + } + + protected boolean isAttrOfTypeId(QName aqn, QName eqn) { + if (_idAttrs == null) { + return false; + } + String pre = aqn.getPrefix(); + String lName = aqn.getLocalPart(); + String urnName = "".equals(pre) ? lName : pre + ":" + lName; + String eName = (String) _idAttrs.get(urnName); + if (eName == null) { + return false; + } + //get the name of the parent elt + pre = eqn.getPrefix(); + lName = eqn.getLocalPart(); + lName = eqn.getLocalPart(); + urnName = "".equals(pre) ? lName : pre + ":" + lName; + return eName.equals(urnName); + } + + private java.util.Hashtable _idAttrs; + } + + private static class DefaultEntityResolver + implements EntityResolver { + public InputSource resolveEntity(String publicId, String systemId) { + return new InputSource(new StringReader("")); + } + } + + private static SaxLoader getSaxLoader(XmlOptions options) throws XmlException { + options = XmlOptions.maskNull(options); + + EntityResolver er = null; + + if (!options.isLoadUseDefaultResolver()) { + er = options.getEntityResolver(); + + if (er == null) { + er = ResolverUtil.getGlobalEntityResolver(); + } + + if (er == null) { + er = new DefaultEntityResolver(); + } + } + + XMLReader xr = options.getLoadUseXMLReader(); + + if (xr == null) { + try { + xr = SAXHelper.newXMLReader(new XmlOptionsBean(options)); + } catch (Exception e) { + throw new XmlException("Problem creating XMLReader", e); + } + } + + SaxLoader sl = new XmlReaderSaxLoader(xr); + + // I've noticed that most XMLReaders don't like a null EntityResolver... + + if (er != null) { + xr.setEntityResolver(er); + } + + return sl; + } + + private static class XmlReaderSaxLoader + extends SaxLoader { + XmlReaderSaxLoader(XMLReader xr) { + super(xr, null); + } + } + + private static abstract class SaxHandler + implements ContentHandler, LexicalHandler, DeclHandler, DTDHandler { + protected Locale _locale; + + protected LoadContext _context; + + private boolean _wantLineNumbers; + private boolean _wantLineNumbersAtEndElt; + private boolean _wantCdataBookmarks; + private Locator _startLocator; + private boolean _insideCDATA = false; + private int _entityBytesLimit = 10240; + private int _entityBytes = 0; + private int _insideEntity = 0; + + SaxHandler(Locator startLocator) { + _startLocator = startLocator; + } + + SaxHandler() { + this(null); + } + + void initSaxHandler(Locale l, final XmlOptions options) { + _locale = l; + + XmlOptions safeOptions = XmlOptions.maskNull(options); + + _context = new Cur.CurLoadContext(_locale, safeOptions); + + _wantLineNumbers = safeOptions.isLoadLineNumbers(); + _wantLineNumbersAtEndElt = safeOptions.isLoadLineNumbersEndElement(); + _wantCdataBookmarks = safeOptions.isUseCDataBookmarks(); + + Integer limit = safeOptions.getLoadEntityBytesLimit(); + if (limit != null) { + _entityBytesLimit = limit; + } + } + + public void startDocument() throws SAXException { + // Do nothing ... start of document is implicit + } + + public void endDocument() + throws SAXException { + // Do nothing ... end of document is implicit + } + + public void startElement(String uri, String local, String qName, + Attributes atts) + throws SAXException { + if (local.length() == 0) { + local = qName; + } + + // Out current parser does not error when a + // namespace is used and not defined. Check for these here + + if (qName.indexOf(':') >= 0 && uri.length() == 0) { + XmlError err = + XmlError.forMessage("Use of undefined namespace prefix: " + + qName.substring(0, qName.indexOf(':'))); + + throw new XmlRuntimeException(err.toString(), null, err); + } + + _context.startElement(_locale.makeQualifiedQName(uri, qName)); + + if (_wantLineNumbers && _startLocator != null) { + _context.bookmark( + new XmlLineNumber(_startLocator.getLineNumber(), + _startLocator.getColumnNumber() - 1, -1)); + } + + for (int i = 0, len = atts.getLength(); i < len; i++) { + String aqn = atts.getQName(i); + + if (aqn.equals("xmlns")) { + _context.xmlns("", atts.getValue(i)); + } else if (aqn.startsWith("xmlns:")) { + String prefix = aqn.substring(6); + + if (prefix.length() == 0) { + XmlError err = + XmlError.forMessage("Prefix not specified", + XmlError.SEVERITY_ERROR); + + throw new XmlRuntimeException(err.toString(), null, + err); + } + + String attrUri = atts.getValue(i); + + if (attrUri.length() == 0) { + XmlError err = + XmlError.forMessage( + "Prefix can't be mapped to no namespace: " + + prefix, + XmlError.SEVERITY_ERROR); + + throw new XmlRuntimeException(err.toString(), null, + err); + } + + _context.xmlns(prefix, attrUri); + } else { + int colon = aqn.indexOf(':'); + + if (colon < 0) { + _context.attr(aqn, atts.getURI(i), null, + atts.getValue(i)); + } else { + _context.attr(aqn.substring(colon + 1), atts.getURI(i), aqn.substring( + 0, colon), + atts.getValue(i)); + } + } + } + } + + public void endElement(String namespaceURI, String localName, + String qName) + throws SAXException { + _context.endElement(); + if (_wantLineNumbersAtEndElt && _startLocator != null) { + _context.bookmark( + new XmlLineNumber(_startLocator.getLineNumber(), + _startLocator.getColumnNumber() - 1, -1)); + } + } + + public void characters(char ch[], int start, int length) + throws SAXException { + _context.text(ch, start, length); + + if (_wantCdataBookmarks && _insideCDATA && _startLocator != null) { + _context.bookmarkLastNonAttr(CDataBookmark.CDATA_BOOKMARK); + } + + if (_insideEntity != 0) { + if ((_entityBytes += length) > _entityBytesLimit) { + XmlError err = XmlError.forMessage(XmlErrorCodes.EXCEPTION_EXCEEDED_ENTITY_BYTES, + new Integer[]{_entityBytesLimit}); + + throw new SAXException(err.getMessage()); + } + } + } + + public void ignorableWhitespace(char ch[], int start, int length) + throws SAXException { + } + + public void comment(char ch[], int start, int length) + throws SAXException { + _context.comment(ch, start, length); + } + + public void processingInstruction(String target, String data) + throws SAXException { + _context.procInst(target, data); + } + + public void startDTD(String name, String publicId, String systemId) + throws SAXException { + _context.startDTD(name, publicId, systemId); + } + + public void endDTD() + throws SAXException { + _context.endDTD(); + } + + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + if (beginsWithXml(prefix) && + !("xml".equals(prefix) && _xml1998Uri.equals(uri))) { + XmlError err = + XmlError.forMessage( + "Prefix can't begin with XML: " + prefix, + XmlError.SEVERITY_ERROR); + + throw new XmlRuntimeException(err.toString(), null, err); + } + } + + public void endPrefixMapping(String prefix) + throws SAXException { + } + + public void skippedEntity(String name) + throws SAXException { +// throw new RuntimeException( "Not impl: skippedEntity" ); + } + + public void startCDATA() + throws SAXException { + _insideCDATA = true; + } + + public void endCDATA() + throws SAXException { + _insideCDATA = false; + } + + public void startEntity(String name) + throws SAXException { + _insideEntity++; + } + + public void endEntity(String name) + throws SAXException { + _insideEntity--; + assert _insideEntity >= 0; + + if (_insideEntity == 0) { + _entityBytes = 0; + } + } + + public void setDocumentLocator(Locator locator) { + if (_startLocator == null) { + _startLocator = locator; + } + } + + //DeclHandler + public void attributeDecl(String eName, String aName, String type, String valueDefault, String value) { + if (type.equals("ID")) { + _context.addIdAttr(eName, aName); + } + } + + public void elementDecl(String name, String model) { + } + + public void externalEntityDecl(String name, String publicId, String systemId) { + } + + public void internalEntityDecl(String name, String value) { + } + + //DTDHandler + public void notationDecl(String name, String publicId, String systemId) { + } + + public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) { + } + } + + private static abstract class SaxLoader + extends SaxHandler + implements ErrorHandler { + SaxLoader(XMLReader xr, Locator startLocator) { + super(startLocator); + + _xr = xr; + + try { + _xr.setFeature( + "http://xml.org/sax/features/namespace-prefixes", true); + _xr.setFeature("http://xml.org/sax/features/namespaces", true); + _xr.setFeature("http://xml.org/sax/features/validation", false); + _xr.setProperty( + "http://xml.org/sax/properties/lexical-handler", this); + _xr.setContentHandler(this); + _xr.setDTDHandler(this); + _xr.setErrorHandler(this); + } catch (Throwable e) { + throw new RuntimeException(e.getMessage(), e); + } + try { + _xr.setProperty("http://xml.org/sax/properties/declaration-handler", this); + } catch (Throwable e) { + logger.log(XBLogger.WARN, "SAX Declaration Handler is not supported", e); + } + } + + void setEntityResolver(EntityResolver er) { + _xr.setEntityResolver(er); + } + + void postLoad(Cur c) { + // fix garbage collection of Locale -> Xobj -> STL + _locale = null; + _context = null; + } + + public Cur load(Locale l, InputSource is, XmlOptions options) + throws XmlException, IOException { + is.setSystemId("file://"); + + initSaxHandler(l, options); + + try { + _xr.parse(is); + + Cur c = _context.finish(); + + associateSourceName(c, options); + + postLoad(c); + + return c; + } catch (XmlRuntimeException e) { + _context.abort(); + + throw new XmlException(e); + } catch (SAXParseException e) { + _context.abort(); + + XmlError err = + XmlError.forLocation(e.getMessage(), + options == null ? null : options.getDocumentSourceName(), + e.getLineNumber(), e.getColumnNumber(), -1); + + throw new XmlException(err.toString(), e, err); + } catch (SAXException e) { + _context.abort(); + + XmlError err = XmlError.forMessage(e.getMessage()); + + throw new XmlException(err.toString(), e, err); + } catch (RuntimeException e) { + _context.abort(); + + throw e; + } + } + + public void fatalError(SAXParseException e) + throws SAXException { + throw e; + } + + public void error(SAXParseException e) + throws SAXException { + throw e; + } + + public void warning(SAXParseException e) + throws SAXException { + throw e; + } + + private XMLReader _xr; + } + + private Dom load(InputSource is, XmlOptions options) + throws XmlException, IOException { + return getSaxLoader(options).load(this, is, options).getDom(); + } + + public Dom load(Reader r) + throws XmlException, IOException { + return load(r, null); + } + + public Dom load(Reader r, XmlOptions options) + throws XmlException, IOException { + return load(new InputSource(r), options); + } + + public Dom load(InputStream in) + throws XmlException, IOException { + return load(in, null); + } + + public Dom load(InputStream in, XmlOptions options) + throws XmlException, IOException { + return load(new InputSource(in), options); + } + + public Dom load(String s) + throws XmlException { + return load(s, null); + } + + public Dom load(String s, XmlOptions options) + throws XmlException { + Reader r = new StringReader(s); + + try { + return load(r, options); + } catch (IOException e) { + assert false : "StringReader should not throw IOException"; + + throw new XmlException(e.getMessage(), e); + } finally { + try { + r.close(); + } catch (IOException e) { + } + } + } + + // + // DOMImplementation methods + // + + public Document createDocument(String uri, String qname, + DocumentType doctype) { + return DomImpl._domImplementation_createDocument(this, uri, qname, + doctype); + } + + public DocumentType createDocumentType(String qname, String publicId, + String systemId) { + throw new RuntimeException("Not implemented"); +// return DomImpl._domImplementation_createDocumentType( this, qname, publicId, systemId ); + } + + public boolean hasFeature(String feature, String version) { + return DomImpl._domImplementation_hasFeature(this, feature, version); + } + + public Object getFeature(String feature, String version) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + // + // Dom methods + // + + private static Dom checkNode(Node n) { + if (n == null) { + throw new IllegalArgumentException("Node is null"); + } + + if (!(n instanceof Dom)) { + throw new IllegalArgumentException("Node is not an XmlBeans node"); + } + + return (Dom) n; + } + + public static XmlCursor nodeToCursor(Node n) { + return DomImpl._getXmlCursor(checkNode(n)); + } + + public static XmlObject nodeToXmlObject(Node n) { + return DomImpl._getXmlObject(checkNode(n)); + } + + public static XMLStreamReader nodeToXmlStream(Node n) { + return DomImpl._getXmlStreamReader(checkNode(n)); + } + + public static Node streamToNode(XMLStreamReader xs) { + return Jsr173.nodeFromStream(xs); + } + + // + // SaajCallback methods + // + + public void setSaajData(Node n, Object o) { + assert n instanceof Dom; + + DomImpl.saajCallback_setSaajData((Dom) n, o); + } + + public Object getSaajData(Node n) { + assert n instanceof Dom; + + return DomImpl.saajCallback_getSaajData((Dom) n); + } + + public Element createSoapElement(QName name, QName parentName) { + assert _ownerDoc != null; + + return DomImpl.saajCallback_createSoapElement(_ownerDoc, name, + parentName); + } + + public Element importSoapElement(Document doc, Element elem, boolean deep, + QName parentName) { + assert doc instanceof Dom; + + return DomImpl.saajCallback_importSoapElement((Dom) doc, elem, deep, + parentName); + } + + public SchemaTypeLoader getSchemaTypeLoader() { + return _schemaTypeLoader; + } + + private static final class DefaultQNameFactory + implements QNameFactory { + private QNameCache _cache = XmlBeans.getQNameCache(); + + public QName getQName(String uri, String local) { + return _cache.getName(uri, local, ""); + } + + public QName getQName(String uri, String local, String prefix) { + return _cache.getName(uri, local, prefix); + } + + public QName getQName(char[] uriSrc, int uriPos, int uriCch, + char[] localSrc, int localPos, int localCch) { + return + _cache.getName(new String(uriSrc, uriPos, uriCch), + new String(localSrc, localPos, localCch), + ""); + } + + public QName getQName(char[] uriSrc, int uriPos, int uriCch, + char[] localSrc, int localPos, int localCch, + char[] prefixSrc, int prefixPos, int prefixCch) { + return + _cache.getName(new String(uriSrc, uriPos, uriCch), + new String(localSrc, localPos, localCch), + new String(prefixSrc, prefixPos, prefixCch)); + } + } + + + private static final class LocalDocumentQNameFactory + implements QNameFactory { + private QNameCache _cache = new QNameCache(32); + + public QName getQName(String uri, String local) { + return _cache.getName(uri, local, ""); + } + + public QName getQName(String uri, String local, String prefix) { + return _cache.getName(uri, local, prefix); + } + + public QName getQName(char[] uriSrc, int uriPos, int uriCch, + char[] localSrc, int localPos, int localCch) { + return + _cache.getName(new String(uriSrc, uriPos, uriCch), + new String(localSrc, localPos, localCch), + ""); + } + + public QName getQName(char[] uriSrc, int uriPos, int uriCch, + char[] localSrc, int localPos, int localCch, + char[] prefixSrc, int prefixPos, int prefixCch) { + return + _cache.getName(new String(uriSrc, uriPos, uriCch), + new String(localSrc, localPos, localCch), + new String(prefixSrc, prefixPos, prefixCch)); + } + } + + // + // + // + + boolean _noSync; + + SchemaTypeLoader _schemaTypeLoader; + + private ReferenceQueue _refQueue; + private int _entryCount; + + int _numTempFramesLeft; + Cur[] _tempFrames; + + Cur _curPool; + int _curPoolCount; + + Cur _registered; + + ChangeListener _changeListeners; + + long _versionAll; + long _versionSansText; + + Locations _locations; + + private CharUtil _charUtil; + + int _offSrc; + int _cchSrc; + + Saaj _saaj; + + Dom _ownerDoc; + + QNameFactory _qnameFactory; + + boolean _validateOnSet; + + int _posTemp; + + nthCache _nthCache_A = new nthCache(); + nthCache _nthCache_B = new nthCache(); + + domNthCache _domNthCache_A = new domNthCache(); + domNthCache _domNthCache_B = new domNthCache(); +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/NamedNodeXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/NamedNodeXobj.java new file mode 100644 index 0000000..01e2b99 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/NamedNodeXobj.java @@ -0,0 +1,30 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +abstract class NamedNodeXobj extends NodeXobj { + NamedNodeXobj(Locale l, int kind, int domType) { + super(l, kind, domType); + _canHavePrefixUri = true; + } + + public boolean nodeCanHavePrefixUri() { + return _canHavePrefixUri; + } + + boolean _canHavePrefixUri; +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/NodeXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/NodeXobj.java new file mode 100644 index 0000000..e24d38c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/NodeXobj.java @@ -0,0 +1,194 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.*; + +abstract class NodeXobj extends Xobj implements DomImpl.Dom, Node, NodeList { + NodeXobj(Locale l, int kind, int domType) { + super(l, kind, domType); + } + + DomImpl.Dom getDom() { + return this; + } + + // + // + // + + public int getLength() { + return DomImpl._childNodes_getLength(this); + } + + public Node item(int i) { + return DomImpl._childNodes_item(this, i); + } + + public Node appendChild(Node newChild) { + return DomImpl._node_appendChild(this, newChild); + } + + public Node cloneNode(boolean deep) { + return DomImpl._node_cloneNode(this, deep); + } + + public NamedNodeMap getAttributes() { + return null; + } + + public NodeList getChildNodes() { + return this; + } + + public Node getParentNode() { + return DomImpl._node_getParentNode(this); + } + + public Node removeChild(Node oldChild) { + return DomImpl._node_removeChild(this, oldChild); + } + + public Node getFirstChild() { + return DomImpl._node_getFirstChild(this); + } + + public Node getLastChild() { + return DomImpl._node_getLastChild(this); + } + + public String getLocalName() { + return DomImpl._node_getLocalName(this); + } + + public String getNamespaceURI() { + return DomImpl._node_getNamespaceURI(this); + } + + public Node getNextSibling() { + return DomImpl._node_getNextSibling(this); + } + + public String getNodeName() { + return DomImpl._node_getNodeName(this); + } + + public short getNodeType() { + return DomImpl._node_getNodeType(this); + } + + public String getNodeValue() { + return DomImpl._node_getNodeValue(this); + } + + public Document getOwnerDocument() { + return DomImpl._node_getOwnerDocument(this); + } + + public String getPrefix() { + return DomImpl._node_getPrefix(this); + } + + public Node getPreviousSibling() { + return DomImpl._node_getPreviousSibling(this); + } + + public boolean hasAttributes() { + return DomImpl._node_hasAttributes(this); + } + + public boolean hasChildNodes() { + return DomImpl._node_hasChildNodes(this); + } + + public Node insertBefore(Node newChild, Node refChild) { + return DomImpl._node_insertBefore(this, newChild, refChild); + } + + public boolean isSupported(String feature, String version) { + return DomImpl._node_isSupported(this, feature, version); + } + + public void normalize() { + DomImpl._node_normalize(this); + } + + public Node replaceChild(Node newChild, Node oldChild) { + return DomImpl._node_replaceChild(this, newChild, oldChild); + } + + public void setNodeValue(String nodeValue) { + DomImpl._node_setNodeValue(this, nodeValue); + } + + public void setPrefix(String prefix) { + DomImpl._node_setPrefix(this, prefix); + } + + public boolean nodeCanHavePrefixUri() { + return false; + } + + // DOM Level 3 + public Object getUserData(String key) { + return DomImpl._node_getUserData(this, key); + } + + public Object setUserData(String key, Object data, UserDataHandler handler) { + return DomImpl._node_setUserData(this, key, data, handler); + } + + public Object getFeature(String feature, String version) { + return DomImpl._node_getFeature(this, feature, version); + } + + public boolean isEqualNode(Node arg) { + return DomImpl._node_isEqualNode(this, arg); + } + + public boolean isSameNode(Node arg) { + return DomImpl._node_isSameNode(this, arg); + } + + public String lookupNamespaceURI(String prefix) { + return DomImpl._node_lookupNamespaceURI(this, prefix); + } + + public String lookupPrefix(String namespaceURI) { + return DomImpl._node_lookupPrefix(this, namespaceURI); + } + + public boolean isDefaultNamespace(String namespaceURI) { + return DomImpl._node_isDefaultNamespace(this, namespaceURI); + } + + public void setTextContent(String textContent) { + DomImpl._node_setTextContent(this, textContent); + } + + public String getTextContent() { + return DomImpl._node_getTextContent(this); + } + + public short compareDocumentPosition(Node other) { + return DomImpl._node_compareDocumentPosition(this, other); + } + + public String getBaseURI() { + return DomImpl._node_getBaseURI(this); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/ProcInstXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/ProcInstXobj.java new file mode 100644 index 0000000..a0b799b --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/ProcInstXobj.java @@ -0,0 +1,53 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; + +import static org.apache.xmlbeans.impl.store.Cur.PROCINST; + +class ProcInstXobj extends NodeXobj implements ProcessingInstruction { + ProcInstXobj(Locale l, String target) { + super(l, PROCINST, DomImpl.PROCINST); + _name = _locale.makeQName(null, target); + } + + Xobj newNode(Locale l) { + return new ProcInstXobj(l, _name.getLocalPart()); + } + + public int getLength() { + return 0; + } + + public Node getFirstChild() { + return null; + } + + public String getData() { + return DomImpl._processingInstruction_getData(this); + } + + public String getTarget() { + return DomImpl._processingInstruction_getTarget(this); + } + + public void setData(String data) { + DomImpl._processingInstruction_setData(this, data); + } +} + diff --git a/src/store/org/apache/xmlbeans/impl/store/Public2.java b/src/main/java/org/apache/xmlbeans/impl/store/Public2.java similarity index 94% rename from src/store/org/apache/xmlbeans/impl/store/Public2.java rename to src/main/java/org/apache/xmlbeans/impl/store/Public2.java index 93f20ae..6984028 100755 --- a/src/store/org/apache/xmlbeans/impl/store/Public2.java +++ b/src/main/java/org/apache/xmlbeans/impl/store/Public2.java @@ -15,42 +15,24 @@ package org.apache.xmlbeans.impl.store; -import javax.xml.stream.XMLStreamReader; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.IOException; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Node; -import org.w3c.dom.Document; - -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; - -import java.io.PrintStream; - +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.store.DomImpl.Dom; - import org.apache.xmlbeans.impl.store.Saver.TextSaver; - +import org.apache.xmlbeans.impl.values.NamespaceManager; import org.apache.xmlbeans.impl.values.TypeStore; import org.apache.xmlbeans.impl.values.TypeStoreUser; import org.apache.xmlbeans.impl.values.TypeStoreVisitor; -import org.apache.xmlbeans.impl.values.TypeStoreUserFactory; - -import org.apache.xmlbeans.SchemaType; - -import org.apache.xmlbeans.impl.values.NamespaceManager; +import org.apache.xmlbeans.impl.xpath.XPathFactory; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Node; import javax.xml.namespace.QName; - -import org.apache.xmlbeans.SchemaField; - -import org.apache.xmlbeans.QNameSet; +import javax.xml.stream.XMLStreamReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; public final class Public2 { @@ -61,7 +43,7 @@ private static Locale newLocale ( Saaj saaj ) if (saaj != null) { options = new XmlOptions(); - options.put( org.apache.xmlbeans.impl.store.Saaj.SAAJ_IMPL, saaj ); + options.setSaaj(saaj); } return Locale.getLocale( null, options ); @@ -83,7 +65,7 @@ public static void setSync ( Document doc, boolean sync ) public static String compilePath ( String path, XmlOptions options ) { - return Path.compilePath( path, options ); + return XPathFactory.compilePath( path, options ); } public static DOMImplementation getDomImplementation ( ) @@ -300,7 +282,7 @@ public static void dump ( PrintStream o, XmlObject x ) Node n = xc.getDomNode(); Dom d = (Dom) n; xc.dispose(); - + dump( o, d ); } @@ -342,7 +324,7 @@ public void invalidate_value() { } public static void test ( ) throws Exception { Xobj x = (Xobj) Public2.parse( "XY" ); - + Locale l = x._locale; l.enter(); @@ -352,20 +334,20 @@ public static void test ( ) throws Exception Cur c = x.tempCur(); c.next(); - + Cur c2 = c.tempCur(); c2.next(); - + Cur c3 = c2.tempCur(); c3.nextChars( 1 ); - + Cur c4 = c3.tempCur(); c4.nextChars( 1 ); c.dump(); - + c.moveNodeContents( c, true ); - + c.dump(); } catch ( Throwable e ) diff --git a/src/store/org/apache/xmlbeans/impl/store/QNameFactory.java b/src/main/java/org/apache/xmlbeans/impl/store/QNameFactory.java similarity index 100% rename from src/store/org/apache/xmlbeans/impl/store/QNameFactory.java rename to src/main/java/org/apache/xmlbeans/impl/store/QNameFactory.java diff --git a/src/store/org/apache/xmlbeans/impl/store/Saaj.java b/src/main/java/org/apache/xmlbeans/impl/store/Saaj.java similarity index 98% rename from src/store/org/apache/xmlbeans/impl/store/Saaj.java rename to src/main/java/org/apache/xmlbeans/impl/store/Saaj.java index a879567..7ff79aa 100755 --- a/src/store/org/apache/xmlbeans/impl/store/Saaj.java +++ b/src/main/java/org/apache/xmlbeans/impl/store/Saaj.java @@ -44,10 +44,7 @@ public interface Saaj { - // Use in XmlOptions to enable SAAJ support in store - - public static final String SAAJ_IMPL = "SAAJ_IMPL"; - + public interface SaajCallback { void setSaajData ( Node n, Object o ); @@ -61,7 +58,7 @@ public interface SaajCallback void setCallback ( SaajCallback callback ); Class identifyElement ( QName name, QName parentName ); - + void soapNode_detachNode ( org.apache.xmlbeans.impl.soap.Node soapNode ); void soapNode_recycleNode ( org.apache.xmlbeans.impl.soap.Node node ); String soapNode_getValue ( org.apache.xmlbeans.impl.soap.Node node ); @@ -147,4 +144,4 @@ public interface SaajCallback DetailEntry detail_addDetailEntry ( Detail detail, Name name ); Iterator detail_getDetailEntries ( Detail detail ); -} \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SaajCdataNode.java b/src/main/java/org/apache/xmlbeans/impl/store/SaajCdataNode.java new file mode 100644 index 0000000..e0067fa --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SaajCdataNode.java @@ -0,0 +1,53 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.SOAPElement; + +class SaajCdataNode extends CdataNode implements org.apache.xmlbeans.impl.soap.Text { + public SaajCdataNode(Locale l) { + super(l); + } + + public boolean isComment() { + return DomImpl._soapText_isComment(this); + } + + public void detachNode() { + DomImpl._soapNode_detachNode(this); + } + + public void recycleNode() { + DomImpl._soapNode_recycleNode(this); + } + + public String getValue() { + return DomImpl._soapNode_getValue(this); + } + + public void setValue(String value) { + DomImpl._soapNode_setValue(this, value); + } + + public SOAPElement getParentElement() { + return DomImpl._soapNode_getParentElement(this); + } + + public void setParentElement(SOAPElement p) { + DomImpl._soapNode_setParentElement(this, p); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SaajTextNode.java b/src/main/java/org/apache/xmlbeans/impl/store/SaajTextNode.java new file mode 100644 index 0000000..4dcece7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SaajTextNode.java @@ -0,0 +1,53 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.SOAPElement; + +class SaajTextNode extends TextNode implements org.apache.xmlbeans.impl.soap.Text { + SaajTextNode(Locale l) { + super(l); + } + + public boolean isComment() { + return DomImpl._soapText_isComment(this); + } + + public void detachNode() { + DomImpl._soapNode_detachNode(this); + } + + public void recycleNode() { + DomImpl._soapNode_recycleNode(this); + } + + public String getValue() { + return DomImpl._soapNode_getValue(this); + } + + public void setValue(String value) { + DomImpl._soapNode_setValue(this, value); + } + + public SOAPElement getParentElement() { + return DomImpl._soapNode_getParentElement(this); + } + + public void setParentElement(SOAPElement p) { + DomImpl._soapNode_setParentElement(this, p); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Saver.java b/src/main/java/org/apache/xmlbeans/impl/store/Saver.java new file mode 100755 index 0000000..4f5fc12 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Saver.java @@ -0,0 +1,4220 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.SystemProperties; +import org.apache.xmlbeans.XmlDocumentProperties; +import org.apache.xmlbeans.XmlOptionCharEscapeMap; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.common.EncodingMap; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.XmlEventBase; +import org.apache.xmlbeans.impl.common.XmlNameImpl; +import org.apache.xmlbeans.xml.stream.CharacterData; +import org.apache.xmlbeans.xml.stream.*; +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.namespace.QName; +import java.io.*; +import java.util.*; + +abstract class Saver { + static final int ROOT = Cur.ROOT; + static final int ELEM = Cur.ELEM; + static final int ATTR = Cur.ATTR; + static final int COMMENT = Cur.COMMENT; + static final int PROCINST = Cur.PROCINST; + static final int TEXT = Cur.TEXT; + + + private final Locale _locale; + private final long _version; + + private SaveCur _cur; + + private List _ancestorNamespaces; + private final Map _suggestedPrefixes; + protected XmlOptionCharEscapeMap _replaceChar; + private final boolean _useDefaultNamespace; + private Map _preComputedNamespaces; + private final boolean _saveNamespacesFirst; + + private final ArrayList _attrNames = new ArrayList<>(); + private final ArrayList _attrValues = new ArrayList<>(); + + private final ArrayList _namespaceStack = new ArrayList<>(); + private int _currentMapping; + private final HashMap _uriMap = new HashMap<>(); + private final HashMap _prefixMap = new HashMap<>(); + private String _initialDefaultUri; + + static final String _newLine = SystemProperties.getProperty("line.separator", "\n"); + + + protected abstract boolean emitElement(SaveCur c, List attrNames, List attrValues); + + protected abstract void emitFinish(SaveCur c); + + protected abstract void emitText(SaveCur c); + + protected abstract void emitComment(SaveCur c); + + protected abstract void emitProcinst(SaveCur c); + + protected abstract void emitDocType(String docTypeName, String publicId, String systemId); + + protected abstract void emitStartDoc(SaveCur c); + + protected abstract void emitEndDoc(SaveCur c); + + protected void syntheticNamespace(String prefix, String uri, boolean considerDefault) { + } + + Saver(Cur c, XmlOptions options) { + assert c._locale.entered(); + + options = XmlOptions.maskNull(options); + + _cur = createSaveCur(c, options); + + _locale = c._locale; + _version = _locale.version(); + + // Define implicit xml prefixed namespace + + addMapping("xml", Locale._xml1998Uri); + + Map m = options.getSaveImplicitNamespaces(); + if (m != null) { + for (String prefix : m.keySet()) { + addMapping(prefix, m.get(prefix)); + } + } + + // define character map for escaped replacements + _replaceChar = options.getSaveSubstituteCharacters(); + + // If the default prefix has not been mapped, do so now + + if (getNamespaceForPrefix("") == null) { + _initialDefaultUri = ""; + addMapping("", _initialDefaultUri); + } + + if (options.isSaveAggressiveNamespaces() && !(this instanceof SynthNamespaceSaver)) { + SynthNamespaceSaver saver = new SynthNamespaceSaver(c, options); + + //noinspection StatementWithEmptyBody + while (saver.process()) { + } + + if (!saver._synthNamespaces.isEmpty()) { + _preComputedNamespaces = saver._synthNamespaces; + } + } + + _useDefaultNamespace = options.isUseDefaultNamespace(); + + _saveNamespacesFirst = options.isSaveNamespacesFirst(); + + + _suggestedPrefixes = options.getSaveSuggestedPrefixes(); + + _ancestorNamespaces = _cur.getAncestorNamespaces(); + } + + private static SaveCur createSaveCur(Cur c, XmlOptions options) { + QName synthName = options.getSaveSyntheticDocumentElement(); + + QName fragName = synthName; + + if (fragName == null) { + fragName = options.isSaveUseOpenFrag() + ? Locale._openuriFragment + : Locale._xmlFragment; + } + + boolean saveInner = options.isSaveInner() && !options.isSaveOuter(); + + Cur start = c.tempCur(); + Cur end = c.tempCur(); + + SaveCur cur = null; + + int k = c.kind(); + + switch (k) { + case ROOT: { + positionToInner(c, start, end); + + if (Locale.isFragment(start, end)) { + cur = new FragSaveCur(start, end, fragName); + } else if (synthName != null) { + cur = new FragSaveCur(start, end, synthName); + } else { + cur = new DocSaveCur(c); + } + + break; + } + + case ELEM: { + if (saveInner) { + positionToInner(c, start, end); + + cur = + new FragSaveCur( + start, end, Locale.isFragment(start, end) ? fragName : synthName); + } else if (synthName != null) { + positionToInner(c, start, end); + + cur = new FragSaveCur(start, end, synthName); + } else { + start.moveToCur(c); + end.moveToCur(c); + end.skip(); + + cur = new FragSaveCur(start, end, null); + } + + break; + } + } + + if (cur == null) { + assert k < 0 || k == ATTR || k == COMMENT || k == PROCINST || k == TEXT; + + if (k < 0) { + // Save out "" + start.moveToCur(c); + end.moveToCur(c); + } else if (k == TEXT) { + start.moveToCur(c); + end.moveToCur(c); + end.next(); + } else if (saveInner) { + start.moveToCur(c); + start.next(); + + end.moveToCur(c); + end.toEnd(); + } else if (k == ATTR) { + start.moveToCur(c); + end.moveToCur(c); + } else { + start.moveToCur(c); + end.moveToCur(c); + end.skip(); + } + + cur = new FragSaveCur(start, end, fragName); + } + + String filterPI = options.getSaveFilterProcinst(); + + if (filterPI != null) { + cur = new FilterPiSaveCur(cur, filterPI); + } + + if (options.isSavePrettyPrint()) { + cur = new PrettySaveCur(cur, options); + } + + start.release(); + end.release(); + + return cur; + } + + private static void positionToInner(Cur c, Cur start, Cur end) { + assert c.isContainer(); + + start.moveToCur(c); + + if (!start.toFirstAttr()) { + start.next(); + } + + end.moveToCur(c); + end.toEnd(); + } + + /** + * Test if a character is valid in xml character content. See + * http://www.w3.org/TR/REC-xml#NT-Char + */ + static boolean isBadChar(char ch) { + return !( + Character.isHighSurrogate(ch) || + Character.isLowSurrogate(ch) || + (ch >= 0x20 && ch <= 0xD7FF) || + (ch >= 0xE000 && ch <= 0xFFFD) || + // TODO: ch >= 0x10000 && ch <= 0x10FFFF is always false for a char, use codepoints/ints + // (ch >= 0x10000 && ch <= 0x10FFFF) || + (ch == 0x9) || (ch == 0xA) || (ch == 0xD) + ); + } + + protected boolean saveNamespacesFirst() { + return _saveNamespacesFirst; + } + + protected void enterLocale() { + _locale.enter(); + } + + protected void exitLocale() { + _locale.exit(); + } + + protected final boolean process() { + assert _locale.entered(); + + if (_cur == null) { + return false; + } + + if (_version != _locale.version()) { + throw new ConcurrentModificationException("Document changed during save"); + } + + switch (_cur.kind()) { + case ROOT: { + processRoot(); + break; + } + case ELEM: { + processElement(); + break; + } + case -ELEM: { + processFinish(); + break; + } + case TEXT: { + emitText(_cur); + break; + } + + case COMMENT: { + emitComment(_cur); + _cur.toEnd(); + break; + } + case PROCINST: { + emitProcinst(_cur); + _cur.toEnd(); + break; + } + + case -ROOT: { + emitEndDoc(_cur); + _cur.release(); + _cur = null; + + return true; + } + + default: + throw new RuntimeException("Unexpected kind"); + } + + _cur.next(); + + return true; + } + + private void processFinish() { + emitFinish(_cur); + popMappings(); + } + + private void processRoot() { + assert _cur.isRoot(); + + XmlDocumentProperties props = _cur.getDocProps(); + String systemId = null; + String docTypeName = null; + if (props != null) { + systemId = props.getDoctypeSystemId(); + docTypeName = props.getDoctypeName(); + } + + if (systemId != null || docTypeName != null) { + if (docTypeName == null) { + _cur.push(); + //noinspection StatementWithEmptyBody + while (!_cur.isElem() && _cur.next()) { + } + if (_cur.isElem()) { + docTypeName = _cur.getName().getLocalPart(); + } + _cur.pop(); + } + + String publicId = props.getDoctypePublicId(); + + if (docTypeName != null) { + QName rootElemName = _cur.getName(); + + if (rootElemName == null) { + _cur.push(); + while (!_cur.isFinish()) { + if (_cur.isElem()) { + rootElemName = _cur.getName(); + break; + } + _cur.next(); + } + _cur.pop(); + } + + if (rootElemName != null && docTypeName.equals(rootElemName.getLocalPart())) { + emitDocType(docTypeName, publicId, systemId); + return; + } + } + } + + emitStartDoc(_cur); + } + + private void processElement() { + assert _cur.isElem() && _cur.getName() != null; + + QName name = _cur.getName(); + + // Add a new entry to the frontier. If this element has a name + // which has no namespace, then we must make sure that pushing + // the mappings causes the default namespace to be empty + + boolean ensureDefaultEmpty = name.getNamespaceURI().length() == 0; + + pushMappings(_cur, ensureDefaultEmpty); + + // + // There are four things which use mappings: + // + // 1) The element name + // 2) The element value (qname based) + // 3) Attribute names + // 4) The attribute values (qname based) + // + + // 1) The element name (not for starts) + + ensureMapping(name.getNamespaceURI(), name.getPrefix(), !ensureDefaultEmpty, false); + + // + // + // + + _attrNames.clear(); + _attrValues.clear(); + + _cur.push(); + + attrs: + for (boolean A = _cur.toFirstAttr(); A; A = _cur.toNextAttr()) { + if (_cur.isNormalAttr()) { + QName attrName = _cur.getName(); + + _attrNames.add(attrName); + + for (int i = _attrNames.size() - 2; i >= 0; i--) { + if (_attrNames.get(i).equals(attrName)) { + _attrNames.remove(_attrNames.size() - 1); + continue attrs; + } + } + + _attrValues.add(_cur.getAttrValue()); + + ensureMapping(attrName.getNamespaceURI(), attrName.getPrefix(), false, true); + } + } + + _cur.pop(); + + // If I am doing aggressive namespaces and we're emitting a + // container which can contain content, add the namespaces + // we've computed. Basically, I'm making sure the pre-computed + // namespaces are mapped on the first container which has a name. + + if (_preComputedNamespaces != null) { + for (Map.Entry entry : _preComputedNamespaces.entrySet()) { + String uri = entry.getKey(); + String prefix = entry.getValue(); + boolean considerDefault = prefix.length() == 0 && !ensureDefaultEmpty; + + ensureMapping(uri, prefix, considerDefault, false); + } + + // Set to null so we do this once at the top + _preComputedNamespaces = null; + } + + if (emitElement(_cur, _attrNames, _attrValues)) { + popMappings(); + _cur.toEnd(); + } + } + + // + // Layout of namespace stack: + // + // URI Undo + // URI Rename + // Prefix Undo + // Mapping + // + + void iterateMappings() { + _currentMapping = _namespaceStack.size(); + + while (_currentMapping > 0 && _namespaceStack.get(_currentMapping - 1) != null) { + _currentMapping -= 8; + } + } + + boolean hasMapping() { + return _currentMapping < _namespaceStack.size(); + } + + void nextMapping() { + _currentMapping += 8; + } + + String mappingPrefix() { + assert hasMapping(); + return _namespaceStack.get(_currentMapping + 6); + } + + String mappingUri() { + assert hasMapping(); + return _namespaceStack.get(_currentMapping + 7); + } + + private void pushMappings(SaveCur c, boolean ensureDefaultEmpty) { + assert c.isContainer(); + + _namespaceStack.add(null); + + c.push(); + + for (boolean A = c.toFirstAttr(); A; A = c.toNextAttr()) { + if (c.isXmlns()) { + addNewFrameMapping(c.getXmlnsPrefix(), c.getXmlnsUri(), ensureDefaultEmpty); + } + } + + c.pop(); + + if (_ancestorNamespaces != null) { + for (int i = 0; i < _ancestorNamespaces.size(); i += 2) { + String prefix = _ancestorNamespaces.get(i); + String uri = _ancestorNamespaces.get(i + 1); + + addNewFrameMapping(prefix, uri, ensureDefaultEmpty); + } + + _ancestorNamespaces = null; + } + + if (ensureDefaultEmpty) { + String defaultUri = _prefixMap.get(""); + + // I map the default to "" at the very beginning + assert defaultUri != null; + + if (defaultUri.length() > 0) { + addMapping("", ""); + } + } + } + + private void addNewFrameMapping(String prefix, String uri, boolean ensureDefaultEmpty) { + // If the prefix maps to "", this don't include this mapping 'cause it's not well formed. + // Also, if we want to make sure that the default namespace is always "", then check that + // here as well. + + if ((prefix.length() == 0 || uri.length() > 0) && + (!ensureDefaultEmpty || prefix.length() > 0 || uri.length() == 0)) { + // Make sure the prefix is not already mapped in this frame + + for (iterateMappings(); hasMapping(); nextMapping()) { + if (mappingPrefix().equals(prefix)) { + return; + } + } + + // Also make sure that the prefix declaration is not redundant + // This has the side-effect of making it impossible to set a + // redundant prefix declaration, but seems that it's better + // to just never issue a duplicate prefix declaration. + if (uri.equals(getNamespaceForPrefix(prefix))) { + return; + } + + addMapping(prefix, uri); + } + } + + private void addMapping(String prefix, String uri) { + assert uri != null; + assert prefix != null; + + // If the prefix being mapped here is already mapped to a uri, + // that uri will either go out of scope or be mapped to another + // prefix. + + String renameUri = _prefixMap.get(prefix); + String renamePrefix = null; + + if (renameUri != null) { + // See if this prefix is already mapped to this uri. If + // so, then add to the stack, but there is nothing to rename + + if (renameUri.equals(uri)) { + renameUri = null; + } else { + int i = _namespaceStack.size(); + + while (i > 0) { + if (_namespaceStack.get(i - 1) == null) { + i--; + continue; + } + + if (_namespaceStack.get(i - 7).equals(renameUri)) { + renamePrefix = _namespaceStack.get(i - 8); + + if (renamePrefix == null || !renamePrefix.equals(prefix)) { + break; + } + } + + i -= 8; + } + + assert i > 0; + } + } + + _namespaceStack.add(_uriMap.get(uri)); + _namespaceStack.add(uri); + + if (renameUri != null) { + _namespaceStack.add(_uriMap.get(renameUri)); + _namespaceStack.add(renameUri); + } else { + _namespaceStack.add(null); + _namespaceStack.add(null); + } + + _namespaceStack.add(prefix); + _namespaceStack.add(_prefixMap.get(prefix)); + + _namespaceStack.add(prefix); + _namespaceStack.add(uri); + + _uriMap.put(uri, prefix); + _prefixMap.put(prefix, uri); + + if (renameUri != null) { + _uriMap.put(renameUri, renamePrefix); + } + } + + private void popMappings() { + for (; ; ) { + int i = _namespaceStack.size(); + + if (i == 0) { + break; + } + + if (_namespaceStack.get(i - 1) == null) { + _namespaceStack.remove(i - 1); + break; + } + + String oldUri = _namespaceStack.get(i - 7); + String oldPrefix = _namespaceStack.get(i - 8); + + if (oldPrefix == null) { + _uriMap.remove(oldUri); + } else { + _uriMap.put(oldUri, oldPrefix); + } + + oldPrefix = _namespaceStack.get(i - 4); + oldUri = _namespaceStack.get(i - 3); + + if (oldUri == null) { + _prefixMap.remove(oldPrefix); + } else { + _prefixMap.put(oldPrefix, oldUri); + } + + String uri = _namespaceStack.get(i - 5); + + if (uri != null) { + _uriMap.put(uri, _namespaceStack.get(i - 6)); + } + + // Hahahahahaha -- :-( + _namespaceStack.remove(i - 1); + _namespaceStack.remove(i - 2); + _namespaceStack.remove(i - 3); + _namespaceStack.remove(i - 4); + _namespaceStack.remove(i - 5); + _namespaceStack.remove(i - 6); + _namespaceStack.remove(i - 7); + _namespaceStack.remove(i - 8); + } + } + + private void ensureMapping( + String uri, String candidatePrefix, + boolean considerCreatingDefault, boolean mustHavePrefix) { + assert uri != null; + + // Can be called for no-namespaced things + + if (uri.length() == 0) { + return; + } + + String prefix = _uriMap.get(uri); + + if (prefix != null && (prefix.length() > 0 || !mustHavePrefix)) { + return; + } + + // + // I try prefixes from a number of places, in order: + // + // 1) What was passed in + // 2) The optional suggestions (for uri's) + // 3) The default mapping is allowed + // 4) ns#++ + // + + if (candidatePrefix != null && candidatePrefix.length() == 0) { + candidatePrefix = null; + } + + if (!tryPrefix(candidatePrefix)) { + if (_suggestedPrefixes != null && + _suggestedPrefixes.containsKey(uri) && + tryPrefix(_suggestedPrefixes.get(uri))) { + candidatePrefix = _suggestedPrefixes.get(uri); + } else if (considerCreatingDefault && _useDefaultNamespace && tryPrefix("")) { + candidatePrefix = ""; + } else { + String basePrefix = QNameHelper.suggestPrefix(uri); + candidatePrefix = basePrefix; + + for (int i = 1; ; i++) { + if (tryPrefix(candidatePrefix)) { + break; + } + + candidatePrefix = basePrefix + i; + } + } + } + + assert candidatePrefix != null; + + syntheticNamespace(candidatePrefix, uri, considerCreatingDefault); + + addMapping(candidatePrefix, uri); + } + + protected final String getUriMapping(String uri) { + assert _uriMap.containsKey(uri); + return _uriMap.get(uri); + } + + String getNonDefaultUriMapping(String uri) { + String prefix = _uriMap.get(uri); + + if (prefix != null && prefix.length() > 0) { + return prefix; + } + + for (String s : _prefixMap.keySet()) { + prefix = s; + + if (prefix.length() > 0 && _prefixMap.get(prefix).equals(uri)) { + return prefix; + } + } + + assert false : "Could not find non-default mapping"; + + return null; + } + + private boolean tryPrefix(String prefix) { + if (prefix == null || Locale.beginsWithXml(prefix)) { + return false; + } + + String existingUri = _prefixMap.get(prefix); + + // If the prefix is currently mapped, then try another prefix. A + // special case is that of trying to map the default prefix (""). + // Here, there always exists a default mapping. If this is the + // mapping we found, then remap it anyways. I use != to compare + // strings because I want to test for the specific initial default + // uri I added when I initialized the saver. + + return existingUri == null || (prefix.length() <= 0 && Objects.equals(existingUri, _initialDefaultUri)); + } + + public final String getNamespaceForPrefix(String prefix) { + assert !prefix.equals("xml") || _prefixMap.get(prefix).equals(Locale._xml1998Uri); + + return _prefixMap.get(prefix); + } + + protected Map getPrefixMap() { + return _prefixMap; + } + + // + // + // + + static final class SynthNamespaceSaver extends Saver { + LinkedHashMap _synthNamespaces = new LinkedHashMap<>(); + + SynthNamespaceSaver(Cur c, XmlOptions options) { + super(c, options); + } + + protected void syntheticNamespace( + String prefix, String uri, boolean considerCreatingDefault) { + _synthNamespaces.put(uri, considerCreatingDefault ? "" : prefix); + } + + protected boolean emitElement( + SaveCur c, List attrNames, List attrValues) { + return false; + } + + protected void emitFinish(SaveCur c) { + } + + protected void emitText(SaveCur c) { + } + + protected void emitComment(SaveCur c) { + } + + protected void emitProcinst(SaveCur c) { + } + + protected void emitDocType(String docTypeName, String publicId, String systemId) { + } + + protected void emitStartDoc(SaveCur c) { + } + + protected void emitEndDoc(SaveCur c) { + } + } + + // + // + // + + static final class TextSaver extends Saver { + TextSaver(Cur c, XmlOptions options, String encoding) { + super(c, options); + + boolean noSaveDecl = options != null && options.isSaveNoXmlDecl(); + + if (options != null && options.getSaveCDataLengthThreshold() != null) { + _cdataLengthThreshold = options.getSaveCDataLengthThreshold(); + } + + if (options != null && options.getSaveCDataEntityCountThreshold() != null) { + _cdataEntityCountThreshold = options.getSaveCDataEntityCountThreshold(); + } + + if (options != null && options.isUseCDataBookmarks()) { + _useCDataBookmarks = true; + } + + if (options != null && options.isSavePrettyPrint()) { + _isPrettyPrint = true; + } + + _in = _out = 0; + _free = 0; + + //noinspection ConstantConditions + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + if (encoding != null && !noSaveDecl) { + XmlDocumentProperties props = Locale.getDocProps(c, false); + + String version = props == null ? null : props.getVersion(); + + if (version == null) { + version = "1.0"; + } + + Boolean standalone = null; + if (props != null && props.get(XmlDocumentProperties.STANDALONE) != null) { + standalone = props.getStandalone(); + } + + emit("" + _newLine); + } + } + + @Override + protected boolean emitElement(SaveCur c, List attrNames, List attrValues) { + assert c.isElem(); + + emit('<'); + emitName(c.getName(), false); + + if (saveNamespacesFirst()) { + emitNamespacesHelper(); + } + + for (int i = 0; i < attrNames.size(); i++) { + emitAttrHelper(attrNames.get(i), attrValues.get(i)); + } + + if (!saveNamespacesFirst()) { + emitNamespacesHelper(); + } + + if (!c.hasChildren() && !c.hasText()) { + emit('/', '>'); + return true; + } else { + emit('>'); + return false; + } + } + + protected void emitFinish(SaveCur c) { + emit('<', '/'); + emitName(c.getName(), false); + emit('>'); + } + + protected void emitXmlns(String prefix, String uri) { + assert prefix != null; + assert uri != null; + + emit("xmlns"); + + if (prefix.length() > 0) { + emit(':'); + emit(prefix); + } + + emit('=', '\"'); + + // TODO - must encode uri properly + + emit(uri); + entitizeAttrValue(false); + + emit('"'); + } + + private void emitNamespacesHelper() { + for (iterateMappings(); hasMapping(); nextMapping()) { + emit(' '); + emitXmlns(mappingPrefix(), mappingUri()); + } + } + + private void emitAttrHelper(QName attrName, String attrValue) { + emit(' '); + emitName(attrName, true); + emit('=', '\"'); + emit(attrValue); + entitizeAttrValue(true); + emit('"'); + } + + protected void emitText(SaveCur c) { + assert c.isText(); + + // c.isTextCData() is expensive do it only if useCDataBookmarks option is enabled + boolean forceCData = _useCDataBookmarks && c.isTextCData(); + + emit(c); + + entitizeContent(forceCData); + } + + protected void emitComment(SaveCur c) { + assert c.isComment(); + + emit(""); + } + + protected void emitProcinst(SaveCur c) { + assert c.isProcinst(); + + emit(""); + } + + private void emitLiteral(String literal) { + // TODO: systemId production http://www.w3.org/TR/REC-xml/#NT-SystemLiteral + // TODO: publicId production http://www.w3.org/TR/REC-xml/#NT-PubidLiteral + if (!literal.contains("\"")) { + emit('\"'); + emit(literal); + emit('\"'); + } else { + emit('\''); + emit(literal); + emit('\''); + } + } + + protected void emitDocType(String docTypeName, String publicId, String systemId) { + assert docTypeName != null; + + emit(""); + emit(_newLine); + } + + protected void emitStartDoc(SaveCur c) { + } + + protected void emitEndDoc(SaveCur c) { + } + + // + // + // + + private void emitName(QName name, boolean needsPrefix) { + assert name != null; + + String uri = name.getNamespaceURI(); + + assert uri != null; + + if (uri.length() != 0) { + String prefix = name.getPrefix(); + String mappedUri = getNamespaceForPrefix(prefix); + + if (mappedUri == null || !mappedUri.equals(uri)) { + prefix = getUriMapping(uri); + } + + // Attrs need a prefix. If I have not found one, then there must be a default + // prefix obscuring the prefix needed for this attr. Find it manually. + + // NOTE - Consider keeping the currently mapped default URI separate fromn the + // _urpMap and _prefixMap. This way, I would not have to look it up manually + // here + + if (needsPrefix && prefix.length() == 0) { + prefix = getNonDefaultUriMapping(uri); + } + + if (prefix.length() > 0) { + emit(prefix); + emit(':'); + } + } + + assert name.getLocalPart().length() > 0; + + emit(name.getLocalPart()); + } + + private void emit(char ch) { + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + preEmit(1); + + _buf[_in] = ch; + + _in = (_in + 1) % _buf.length; + + assert (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + } + + private void emit(char ch1, char ch2) { + if (preEmit(2)) { + return; + } + + _buf[_in] = ch1; + _in = (_in + 1) % _buf.length; + + _buf[_in] = ch2; + _in = (_in + 1) % _buf.length; + + assert (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + } + + private void emit(String s) { + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + int cch = s == null ? 0 : s.length(); + + if (preEmit(cch) || s == null) { + return; + } + + int chunk; + + if (_in <= _out || cch < (chunk = _buf.length - _in)) { + s.getChars(0, cch, _buf, _in); + _in += cch; + } else { + s.getChars(0, chunk, _buf, _in); + s.getChars(chunk, cch, _buf, 0); + _in = (_in + cch) % _buf.length; + } + + assert (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + } + + private void emit(SaveCur c) { + if (c.isText()) { + Object src = c.getChars(); + int cch = c._cchSrc; + + if (preEmit(cch)) { + return; + } + + int chunk; + + if (_in <= _out || cch < (chunk = _buf.length - _in)) { + CharUtil.getChars(_buf, _in, src, c._offSrc, cch); + _in += cch; + } else { + CharUtil.getChars(_buf, _in, src, c._offSrc, chunk); + CharUtil.getChars(_buf, 0, src, c._offSrc + chunk, cch - chunk); + _in = (_in + cch) % _buf.length; + } + } else { + preEmit(0); + } + } + + private boolean preEmit(int cch) { + assert cch >= 0; + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + _lastEmitCch = cch; + + if (cch == 0) { + return true; + } + + if (_free <= cch) { + resize(cch, -1); + } + + assert cch <= _free; + + int used = getAvailable(); + + // if we are about to emit and there is noting in the buffer, reset + // the buffer to be at the beginning so as to not grow it anymore + // than needed. + + if (used == 0) { + assert _in == _out; + assert _buf == null || _free == _buf.length; + _in = _out = 0; + } + + _lastEmitIn = _in; + + _free -= cch; + + assert _buf == null || _free == (_in >= _out ? _buf.length - (_in - _out) : _out - _in) - cch : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out) - cch) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in - cch) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length - cch) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + return false; + } + + private void entitizeContent(boolean forceCData) { + assert _free >= 0; + + if (_lastEmitCch == 0) { + return; + } + + int i = _lastEmitIn; + final int n = _buf.length; + + boolean hasCharToBeReplaced = false; + + int count = 0; + char prevChar = 0; + char prevPrevChar = 0; + for (int cch = _lastEmitCch; cch > 0; cch--) { + char ch = _buf[i]; + + if (ch == '<' || ch == '&') { + count++; + } else if (prevPrevChar == ']' && prevChar == ']' && ch == '>') { + hasCharToBeReplaced = true; + } else if (isBadChar(ch) || isEscapedChar(ch) || (!_isPrettyPrint && ch == '\r')) { + hasCharToBeReplaced = true; + } + + if (++i == n) { + i = 0; + } + + prevPrevChar = prevChar; + prevChar = ch; + } + + if (!forceCData && count == 0 && !hasCharToBeReplaced && count < _cdataEntityCountThreshold) { + return; + } + + i = _lastEmitIn; + + // + // Heuristic for knowing when to save out stuff as a CDATA. + // + if (forceCData || (_lastEmitCch > _cdataLengthThreshold && count > _cdataEntityCountThreshold)) { + boolean lastWasBracket = _buf[i] == ']'; + + i = replace(i, " 0; cch--) { + char ch = _buf[i]; + + if (ch == '>' && secondToLastWasBracket && lastWasBracket) { + i = replace(i, "]]>>"); + } else { + char ch = 0, ch_1 = 0, ch_2; + for (int cch = _lastEmitCch; cch > 0; cch--) { + ch_2 = ch_1; + ch_1 = ch; + ch = _buf[i]; + + if (ch == '<') { + i = replace(i, "<"); + } else if (ch == '&') { + i = replace(i, "&"); + } else if (ch == '>' && ch_1 == ']' && ch_2 == ']') { + i = replace(i, ">"); + } else if (isBadChar(ch)) { + i = replace(i, "?"); + } else if (!_isPrettyPrint && ch == '\r') { + i = replace(i, " "); + } else if (isEscapedChar(ch)) { + i = replace(i, _replaceChar.getEscapedString(ch)); + } else { + i++; + } + + if (i == _buf.length) { + i = 0; + } + } + } + } + + private void entitizeAttrValue(boolean replaceEscapedChar) { + if (_lastEmitCch == 0) { + return; + } + + int i = _lastEmitIn; + + for (int cch = _lastEmitCch; cch > 0; cch--) { + char ch = _buf[i]; + + if (ch == '<') { + i = replace(i, "<"); + } else if (ch == '&') { + i = replace(i, "&"); + } else if (ch == '"') { + i = replace(i, """); + } else if (isEscapedChar(ch)) { + if (replaceEscapedChar) { + i = replace(i, _replaceChar.getEscapedString(ch)); + } + } else { + i++; + } + + if (i == _buf.length) { + i = 0; + } + } + } + + private void entitizeComment() { + if (_lastEmitCch == 0) { + return; + } + + int i = _lastEmitIn; + + boolean lastWasDash = false; + + for (int cch = _lastEmitCch; cch > 0; cch--) { + char ch = _buf[i]; + + if (isBadChar(ch)) { + i = replace(i, "?"); + } else if (ch == '-') { + if (lastWasDash) { + // Replace "--" with "- " to make well formed + i = replace(i, " "); + lastWasDash = false; + } else { + lastWasDash = true; + i++; + } + } else { + lastWasDash = false; + i++; + } + + if (i == _buf.length) { + i = 0; + } + } + + // Because I have only replaced chars with single chars, + // _lastEmitIn will still be ok + + int offset = (_lastEmitIn + _lastEmitCch - 1) % _buf.length; + if (_buf[offset] == '-') { + replace(offset, " "); + } + } + + private void entitizeProcinst() { + if (_lastEmitCch == 0) { + return; + } + + int i = _lastEmitIn; + + boolean lastWasQuestion = false; + + for (int cch = _lastEmitCch; cch > 0; cch--) { + char ch = _buf[i]; + + if (isBadChar(ch)) { + i = replace(i, "?"); + } + + if (ch == '>') { + // TODO - Had to convert to a space here ... imples not well formed XML + if (lastWasQuestion) { + i = replace(i, " "); + } else { + i++; + } + + lastWasQuestion = false; + } else { + lastWasQuestion = ch == '?'; + i++; + } + + if (i == _buf.length) { + i = 0; + } + } + } + + /** + * Test if a character is to be replaced with an escaped value + */ + private boolean isEscapedChar(char ch) { + return (null != _replaceChar && _replaceChar.containsChar(ch)); + } + + private int replace(int i, String replacement) { + assert replacement.length() > 0; + + int dCch = replacement.length() - 1; + + if (dCch == 0) { + _buf[i] = replacement.charAt(0); + return i + 1; + } + + assert _free >= 0; + + if (dCch > _free) { + i = resize(dCch, i); + } + + assert _free >= 0; + + assert _free >= dCch; + assert getAvailable() > 0; + + int charsToCopy = dCch + 1; + + if (_out > _in && i >= _out) { + System.arraycopy(_buf, _out, _buf, _out - dCch, i - _out); + _out -= dCch; + i -= dCch; + } else { + assert i < _in; + int availableEndChunk = _buf.length - _in; + if (dCch <= availableEndChunk) { + System.arraycopy(_buf, i, _buf, i + dCch, _in - i); + _in = (_in + dCch) % _buf.length; + } else if (dCch <= availableEndChunk + _in - i - 1) { + int numToCopyToStart = dCch - availableEndChunk; + System.arraycopy(_buf, _in - numToCopyToStart, _buf, 0, numToCopyToStart); + System.arraycopy(_buf, i + 1, _buf, i + 1 + dCch, _in - i - 1 - numToCopyToStart); + + _in = numToCopyToStart; + } else { + int numToCopyToStart = _in - i - 1; + charsToCopy = availableEndChunk + _in - i; + + System.arraycopy(_buf, _in - numToCopyToStart, _buf, dCch - charsToCopy + 1, numToCopyToStart); + replacement.getChars(charsToCopy, dCch + 1, _buf, 0); + + _in = numToCopyToStart + dCch - charsToCopy + 1; + } + } + + replacement.getChars(0, charsToCopy, _buf, i); + + _free -= dCch; + + assert _free >= 0; + assert (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + return (i + dCch + 1) % _buf.length; + } + // + // + // + + private int ensure(int cch) { + // Even if we're asked to ensure nothing, still try to ensure + // atleast one character so we can determine if we're at the + // end of the stream. + + if (cch <= 0) { + cch = 1; + } + + int available = getAvailable(); + + for (; available < cch; available = getAvailable()) { + if (!process()) { + break; + } + } + + assert available == getAvailable(); + +// if (available == 0) +// return 0; + + return available; + } + + int getAvailable() { + return _buf == null ? 0 : _buf.length - _free; + } + + private int resize(int cch, int i) { + assert _free >= 0; + assert cch > 0; + assert cch >= _free; + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + int newLen = _buf == null ? _initialBufSize : _buf.length * 2; + int used = getAvailable(); + + while (newLen - used < cch) { + newLen *= 2; + } + + char[] newBuf = new char[newLen]; + + if (used > 0) { + if (_in > _out) { + assert i == -1 || (i >= _out && i < _in); + System.arraycopy(_buf, _out, newBuf, 0, used); + i -= _out; + } else { + assert i == -1 || (i >= _out || i < _in); + System.arraycopy(_buf, _out, newBuf, 0, used - _in); + System.arraycopy(_buf, 0, newBuf, used - _in, _in); + i = i >= _out ? i - _out : i + _out; + } + + _out = 0; + _in = used; + _free += newBuf.length - _buf.length; + } else { + _free = newBuf.length; + assert _in == 0 && _out == 0; + assert i == -1; + } + + _buf = newBuf; + + assert _free >= 0; + //noinspection ConstantConditions + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + return i; + } + + public int read() { + if (ensure(1) == 0) { + return -1; + } + + assert getAvailable() > 0; + + int ch = _buf[_out]; + + _out = (_out + 1) % _buf.length; + _free++; + + assert (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + return ch; + } + + public int read(char[] cbuf, int off, int len) { + // Check for end of stream even if there is no way to return + // characters because the Reader doc says to return -1 at end of + // stream. + + int n; + + if ((n = ensure(len)) == 0) { + return -1; + } + + if (cbuf == null || len <= 0) { + return 0; + } + + if (n < len) { + len = n; + } + + if (_out < _in) { + System.arraycopy(_buf, _out, cbuf, off, len); + } else { + int chunk = _buf.length - _out; + + if (chunk >= len) { + System.arraycopy(_buf, _out, cbuf, off, len); + } else { + System.arraycopy(_buf, _out, cbuf, off, chunk); + System.arraycopy(_buf, 0, cbuf, off + chunk, len - chunk); + } + } + + _out = (_out + len) % _buf.length; + _free += len; + + assert (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + assert _free >= 0; + + return len; + } + + public int write(Writer writer, int cchMin) { + while (getAvailable() < cchMin) { + if (!process()) { + break; + } + } + + int charsAvailable = getAvailable(); + + if (charsAvailable > 0) { + // I don't want to deal with the circular cases + + assert _out == 0; + assert _in >= _out : "_in:" + _in + " < _out:" + _out; + assert _free == _buf.length - _in; + + try { +//System.out.println("-------------\nWriting in corverter: TextSaver.write():1703 " + charsAvailable + " chars\n" + new String(_buf, 0, charsAvailable)); + writer.write(_buf, 0, charsAvailable); + writer.flush(); + } catch (IOException e) { + throw new RuntimeException(e); + } + + _free += charsAvailable; + + assert _free >= 0; + + _in = 0; + } + assert _buf == null || + (_out < _in && _free == _buf.length - (_in - _out)) || // data in the middle, free on the edges + (_out > _in && _free == _out - _in) || // data on the edges, free in the middle + (_out == _in && _free == _buf.length) || // no data, all buffer free + (_out == _in && _free == 0) // buffer full + : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; + + return charsAvailable; + } + + public String saveToString() { + // We're gonna build a string. Instead of using StringBuffer, may + // as well use my buffer here. Fill the whole sucker up and + // create a String! + + //noinspection StatementWithEmptyBody + while (process()) { + } + + assert _out == 0; + + int available = getAvailable(); + + return available == 0 ? "" : new String(_buf, _out, available); + } + + // + // + // + + private static final int _initialBufSize = 4096; + private int _cdataLengthThreshold = 32; + private int _cdataEntityCountThreshold = 5; + private boolean _useCDataBookmarks = false; + private boolean _isPrettyPrint = false; + + private int _lastEmitIn; + private int _lastEmitCch; + + private int _free; + private int _in; + private int _out; + private char[] _buf; + /* + _buf is a circular buffer, useful data is before _in up to _out, there are 2 posible configurations: + 1: _in<=_out |data|_in empty _out|data| + 2: _out<_in |empty _out|data|_in empty| + _free is used to keep around the remaining empty space in the bufer so assert _buf==null || _free == (_in>=_out ? _buf.length - (_in - _out) : _out - _in ) ; + */ + } + + static final class OptimizedForSpeedSaver + extends Saver { + Writer _w; + private final char[] _buf = new char[1024]; + + + static private class SaverIOException + extends RuntimeException { + SaverIOException(IOException e) { + super(e); + } + } + + + OptimizedForSpeedSaver(Cur cur, Writer writer) { + super(cur, XmlOptions.maskNull(null)); + _w = writer; + } + + static void save(Cur cur, Writer writer) + throws IOException { + try { + Saver saver = new OptimizedForSpeedSaver(cur, writer); + //noinspection StatementWithEmptyBody + while (saver.process()) { + } + } catch (SaverIOException e) { + throw (IOException) e.getCause(); + } + } + + private void emit(String s) { + try { + _w.write(s); + } catch (IOException e) { + throw new SaverIOException(e); + } + } + + private void emit(char c) { + try { + _buf[0] = c; + _w.write(_buf, 0, 1); + } catch (IOException e) { + throw new SaverIOException(e); + } + } + + private void emit(char c1, char c2) { + try { + _buf[0] = c1; + _buf[1] = c2; + _w.write(_buf, 0, 2); + } catch (IOException e) { + throw new SaverIOException(e); + } + } + + private void emit(char[] buf, int start, int len) { + try { + _w.write(buf, start, len); + } catch (IOException e) { + throw new SaverIOException(e); + } + } + + protected boolean emitElement(SaveCur c, List attrNames, List attrValues) { + assert c.isElem(); + + emit('<'); + emitName(c.getName(), false); + + for (int i = 0; i < attrNames.size(); i++) { + emitAttrHelper(attrNames.get(i), attrValues.get(i)); + } + + if (!saveNamespacesFirst()) { + emitNamespacesHelper(); + } + + if (!c.hasChildren() && !c.hasText()) { + emit('/', '>'); + return true; + } else { + emit('>'); + return false; + } + } + + protected void emitFinish(SaveCur c) { + emit('<', '/'); + emitName(c.getName(), false); + emit('>'); + } + + protected void emitXmlns(String prefix, String uri) { + assert prefix != null; + assert uri != null; + + emit("xmlns"); + + if (prefix.length() > 0) { + emit(':'); + emit(prefix); + } + + emit('=', '\"'); + + // TODO - must encode uri properly + emitAttrValue(uri); + + emit('"'); + } + + private void emitNamespacesHelper() { + for (iterateMappings(); hasMapping(); nextMapping()) { + emit(' '); + emitXmlns(mappingPrefix(), mappingUri()); + } + } + + private void emitAttrHelper(QName attrName, String attrValue) { + emit(' '); + emitName(attrName, true); + emit('=', '\"'); + emitAttrValue(attrValue); + + emit('"'); + } + + protected void emitComment(SaveCur c) { + assert c.isComment(); + + emit(""); + } + + protected void emitProcinst(SaveCur c) { + assert c.isProcinst(); + + emit(""); + } + + protected void emitDocType(String docTypeName, String publicId, String systemId) { + assert docTypeName != null; + + emit("'); + emit(_newLine); + } + + protected void emitStartDoc(SaveCur c) { + } + + protected void emitEndDoc(SaveCur c) { + } + + // + // + // + + private void emitName(QName name, boolean needsPrefix) { + assert name != null; + + String uri = name.getNamespaceURI(); + + assert uri != null; + + if (uri.length() != 0) { + String prefix = name.getPrefix(); + String mappedUri = getNamespaceForPrefix(prefix); + + if (mappedUri == null || !mappedUri.equals(uri)) { + prefix = getUriMapping(uri); + } + + // Attrs need a prefix. If I have not found one, then there must be a default + // prefix obscuring the prefix needed for this attr. Find it manually. + + // NOTE - Consider keeping the currently mapped default URI separate fromn the + // _urpMap and _prefixMap. This way, I would not have to look it up manually + // here + + if (needsPrefix && prefix.length() == 0) { + prefix = getNonDefaultUriMapping(uri); + } + + if (prefix.length() > 0) { + emit(prefix); + emit(':'); + } + } + + assert name.getLocalPart().length() > 0; + + emit(name.getLocalPart()); + } + + private void emitAttrValue(CharSequence attVal) { + int len = attVal.length(); + + for (int i = 0; i < len; i++) { + char ch = attVal.charAt(i); + + if (ch == '<') { + emit("<"); + } else if (ch == '&') { + emit("&"); + } else if (ch == '"') { + emit("""); + } else { + emit(ch); + } + } + } + + private void emitLiteral(String literal) { + // TODO: systemId production http://www.w3.org/TR/REC-xml/#NT-SystemLiteral + // TODO: publicId production http://www.w3.org/TR/REC-xml/#NT-PubidLiteral + if (!literal.contains("\"")) { + emit('\"'); + emit(literal); + emit('\"'); + } else { + emit('\''); + emit(literal); + emit('\''); + } + } + + protected void emitText(SaveCur c) { + assert c.isText(); + + Object src = c.getChars(); + int cch = c._cchSrc; + int off = c._offSrc; + int index = 0; + while (index < cch) { + int indexLimit = Math.min(index + 512, cch); + CharUtil.getChars(_buf, 0, src, off + index, indexLimit - index); + entitizeAndWriteText(indexLimit - index); + index = indexLimit; + } + } + + protected void emitPiText(SaveCur c) { + assert c.isText(); + + Object src = c.getChars(); + int cch = c._cchSrc; + int off = c._offSrc; + int index = 0; + while (index < cch) { + int indexLimit = index + 512 > cch ? cch : 512; + CharUtil.getChars(_buf, 0, src, off + index, indexLimit); + entitizeAndWritePIText(indexLimit - index); + index = indexLimit; + } + } + + protected void emitCommentText(SaveCur c) { + assert c.isText(); + + Object src = c.getChars(); + int cch = c._cchSrc; + int off = c._offSrc; + int index = 0; + while (index < cch) { + int indexLimit = index + 512 > cch ? cch : 512; + CharUtil.getChars(_buf, 0, src, off + index, indexLimit); + entitizeAndWriteCommentText(indexLimit - index); + index = indexLimit; + } + } + + private void entitizeAndWriteText(int bufLimit) { + int index = 0; + for (int i = 0; i < bufLimit; i++) { + char c = _buf[i]; + switch (c) { + case '<': + emit(_buf, index, i - index); + emit("<"); + index = i + 1; + break; + case '&': + emit(_buf, index, i - index); + emit("&"); + index = i + 1; + break; + } + } + emit(_buf, index, bufLimit - index); + } + + private void entitizeAndWriteCommentText(int bufLimit) { + boolean lastWasDash = false; + + for (int i = 0; i < bufLimit; i++) { + char ch = _buf[i]; + + if (isBadChar(ch)) { + _buf[i] = '?'; + } else if (ch == '-') { + if (lastWasDash) { + // Replace "--" with "- " to make well formed + _buf[i] = ' '; + lastWasDash = false; + } else { + lastWasDash = true; + } + } else { + lastWasDash = false; + } + + if (i == _buf.length) { + i = 0; + } + } + + if (_buf[bufLimit - 1] == '-') { + _buf[bufLimit - 1] = ' '; + } + + emit(_buf, 0, bufLimit); + } + + private void entitizeAndWritePIText(int bufLimit) { + boolean lastWasQuestion = false; + + for (int i = 0; i < bufLimit; i++) { + char ch = _buf[i]; + + if (isBadChar(ch)) { + _buf[i] = '?'; + ch = '?'; + } + + if (ch == '>') { + // Had to convert to a space here ... imples not well formed XML + if (lastWasQuestion) { + _buf[i] = ' '; + } + + lastWasQuestion = false; + } else { + lastWasQuestion = ch == '?'; + } + } + emit(_buf, 0, bufLimit); + } + } + + static final class TextReader extends Reader { + TextReader(Cur c, XmlOptions options) { + _textSaver = new TextSaver(c, options, null); + _locale = c._locale; + _closed = false; + } + + public void close() { + _closed = true; + } + + public boolean ready() { + return !_closed; + } + + public int read() throws IOException { + checkClosed(); + + if (_locale.noSync()) { + _locale.enter(); + try { + return _textSaver.read(); + } finally { + _locale.exit(); + } + } else { + synchronized (_locale) { + _locale.enter(); + try { + return _textSaver.read(); + } finally { + _locale.exit(); + } + } + } + } + + public int read(char[] cbuf) throws IOException { + checkClosed(); + + if (_locale.noSync()) { + _locale.enter(); + try { + return _textSaver.read(cbuf, 0, cbuf == null ? 0 : cbuf.length); + } finally { + _locale.exit(); + } + } else { + synchronized (_locale) { + _locale.enter(); + try { + return _textSaver.read(cbuf, 0, cbuf == null ? 0 : cbuf.length); + } finally { + _locale.exit(); + } + } + } + } + + public int read(char[] cbuf, int off, int len) throws IOException { + checkClosed(); + + if (_locale.noSync()) { + _locale.enter(); + try { + return _textSaver.read(cbuf, off, len); + } finally { + _locale.exit(); + } + } else { + synchronized (_locale) { + _locale.enter(); + try { + return _textSaver.read(cbuf, off, len); + } finally { + _locale.exit(); + } + } + } + } + + private void checkClosed() throws IOException { + if (_closed) { + throw new IOException("Reader has been closed"); + } + } + + private final Locale _locale; + private final TextSaver _textSaver; + private boolean _closed; + } + + static final class InputStreamSaver extends InputStream { + InputStreamSaver(Cur c, XmlOptions options) { + _locale = c._locale; + + _closed = false; + + assert _locale.entered(); + + options = XmlOptions.maskNull(options); + + _outStreamImpl = new OutputStreamImpl(); + + String encoding = null; + + XmlDocumentProperties props = Locale.getDocProps(c, false); + + if (props != null && props.getEncoding() != null) { + encoding = EncodingMap.getIANA2JavaMapping(props.getEncoding()); + } + + String enc = options.getCharacterEncoding(); + if (enc != null) { + encoding = enc; + } + + if (encoding != null) { + String ianaEncoding = EncodingMap.getJava2IANAMapping(encoding); + + if (ianaEncoding != null) { + encoding = ianaEncoding; + } + } + + if (encoding == null) { + encoding = EncodingMap.getJava2IANAMapping("UTF8"); + } + + String javaEncoding = (encoding == null) ? null : EncodingMap.getIANA2JavaMapping(encoding); + + if (javaEncoding == null) { + throw new IllegalStateException("Unknown encoding: " + encoding); + } + + try { + _converter = new OutputStreamWriter(_outStreamImpl, javaEncoding); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + + _textSaver = new TextSaver(c, options, encoding); + } + + public void close() { + _closed = true; + } + + private void checkClosed() throws IOException { + if (_closed) { + throw new IOException("Stream closed"); + } + } + + // Having the gateway here is kinda slow for the single character case. It may be possible + // to only enter the gate when there are no chars in the buffer. + + public int read() throws IOException { + checkClosed(); + + if (_locale.noSync()) { + _locale.enter(); + try { + return _outStreamImpl.read(); + } finally { + _locale.exit(); + } + } else { + synchronized (_locale) { + _locale.enter(); + try { + return _outStreamImpl.read(); + } finally { + _locale.exit(); + } + } + } + } + + public int read(byte[] bbuf, int off, int len) throws IOException { + checkClosed(); + + if (bbuf == null) { + throw new NullPointerException("buf to read into is null"); + } + + if (off < 0 || off > bbuf.length) { + throw new IndexOutOfBoundsException("Offset is not within buf"); + } + + if (_locale.noSync()) { + _locale.enter(); + try { + return _outStreamImpl.read(bbuf, off, len); + } finally { + _locale.exit(); + } + } else { + synchronized (_locale) { + _locale.enter(); + try { + return _outStreamImpl.read(bbuf, off, len); + } finally { + _locale.exit(); + } + } + } + } + + private int ensure(int cbyte) { + // Even if we're asked to ensure nothing, still try to ensure + // atleast one byte so we can determine if we're at the + // end of the stream. + + if (cbyte <= 0) { + cbyte = 1; + } + + int bytesAvailable = _outStreamImpl.getAvailable(); + + for (; bytesAvailable < cbyte; + bytesAvailable = _outStreamImpl.getAvailable()) { + if (_textSaver.write(_converter, 2048) < 2048) { + break; + } + } + + bytesAvailable = _outStreamImpl.getAvailable(); + +// if (bytesAvailable == 0) +// return 0; + + return bytesAvailable; + } + + public int available() { + if (_locale.noSync()) { + _locale.enter(); + try { + return ensure(1024); + } finally { + _locale.exit(); + } + } else { + synchronized (_locale) { + _locale.enter(); + try { + return ensure(1024); + } finally { + _locale.exit(); + } + } + } + } + + private final class OutputStreamImpl extends OutputStream { + int read() { + if (InputStreamSaver.this.ensure(1) == 0) { + return -1; + } + + assert getAvailable() > 0; + + int bite = _buf[_out]; + + _out = (_out + 1) % _buf.length; + _free++; + + return bite; + } + + int read(byte[] bbuf, int off, int len) { + // Check for end of stream even if there is no way to return + // characters because the Reader doc says to return -1 at end of + // stream. + + int n; + + if ((n = ensure(len)) == 0) { + return -1; + } + + if (bbuf == null || len <= 0) { + return 0; + } + + if (n < len) { + len = n; + } + + if (_out < _in) { + System.arraycopy(_buf, _out, bbuf, off, len); + } else { + int chunk = _buf.length - _out; + + if (chunk >= len) { + System.arraycopy(_buf, _out, bbuf, off, len); + } else { + System.arraycopy(_buf, _out, bbuf, off, chunk); + + System.arraycopy( + _buf, 0, bbuf, off + chunk, len - chunk); + } + } + _out = (_out + len) % _buf.length; + _free += len; + +//System.out.println("------------------------\nRead out of queue: Saver:2440 InputStreamSaver.read() bbuf " + len + " bytes :\n" + new String(bbuf, off, len)); + return len; + } + + int getAvailable() { + return _buf == null ? 0 : _buf.length - _free; + } + + public void write(int bite) { + if (_free == 0) { + resize(1); + } + + assert _free > 0; + + _buf[_in] = (byte) bite; + + _in = (_in + 1) % _buf.length; + _free--; + } + + public void write(byte[] buf, int off, int cbyte) { + assert cbyte >= 0; + if (cbyte == 0) { + return; + } + + if (_free < cbyte) { + resize(cbyte); + } + + if (_in == _out) { + assert getAvailable() == 0; + assert _free == _buf.length - getAvailable(); + _in = _out = 0; + } + + int chunk = _buf.length - _in; + + if (_in <= _out || cbyte < chunk) { + System.arraycopy(buf, off, _buf, _in, cbyte); + _in += cbyte; + } else { + System.arraycopy(buf, off, _buf, _in, chunk); + + System.arraycopy( + buf, off + chunk, _buf, 0, cbyte - chunk); + + _in = (_in + cbyte) % _buf.length; + } + + _free -= cbyte; + } + + void resize(int cbyte) { + assert cbyte > _free : cbyte + " !> " + _free; + + int newLen = _buf == null ? _initialBufSize : _buf.length * 2; + int used = getAvailable(); + + while (newLen - used < cbyte) { + newLen *= 2; + } + + byte[] newBuf = new byte[newLen]; + + if (used > 0) { + if (_in > _out) { + System.arraycopy(_buf, _out, newBuf, 0, used); + } else { + System.arraycopy( + _buf, _out, newBuf, 0, used - _in); + + System.arraycopy( + _buf, 0, newBuf, used - _in, _in); + } + + _out = 0; + _in = used; + _free += newBuf.length - _buf.length; + } else { + _free = newBuf.length; + assert _in == _out; + } + + _buf = newBuf; + } + + private static final int _initialBufSize = 4096; + + private int _free; + private int _in; + private int _out; + private byte[] _buf; + } + + private final Locale _locale; + private boolean _closed; + private final OutputStreamImpl _outStreamImpl; + private final TextSaver _textSaver; + private final OutputStreamWriter _converter; + } + + static final class XmlInputStreamSaver extends Saver { + XmlInputStreamSaver(Cur c, XmlOptions options) { + super(c, options); + } + + @Override + protected boolean emitElement(SaveCur c, List attrNames, List attrValues) { + assert c.isElem(); + + for (iterateMappings(); hasMapping(); nextMapping()) { + enqueue(new StartPrefixMappingImpl(mappingPrefix(), mappingUri())); + } + + StartElementImpl.AttributeImpl lastAttr = null; + StartElementImpl.AttributeImpl attributes = null; + StartElementImpl.AttributeImpl namespaces = null; + + for (int i = 0; i < attrNames.size(); i++) { + XMLName attXMLName = computeName(attrNames.get(i), this, true); + StartElementImpl.AttributeImpl attr = + new StartElementImpl.NormalAttributeImpl(attXMLName, attrValues.get(i)); + + if (attributes == null) { + attributes = attr; + } else { + lastAttr._next = attr; + } + + lastAttr = attr; + } + + lastAttr = null; + + for (iterateMappings(); hasMapping(); nextMapping()) { + String prefix = mappingPrefix(); + String uri = mappingUri(); + + StartElementImpl.AttributeImpl attr = + new StartElementImpl.XmlnsAttributeImpl(prefix, uri); + + if (namespaces == null) { + namespaces = attr; + } else { + lastAttr._next = attr; + } + + lastAttr = attr; + } + + + QName name = c.getName(); + enqueue(new StartElementImpl(computeName(name, this, false), attributes, namespaces, getPrefixMap())); + + return false; // still need to be called on end element + } + + protected void emitFinish(SaveCur c) { + if (c.isRoot()) { + enqueue(new EndDocumentImpl()); + } else { + XMLName xmlName = computeName(c.getName(), this, false); + enqueue(new EndElementImpl(xmlName)); + } + + emitEndPrefixMappings(); + } + + protected void emitText(SaveCur c) { + assert c.isText(); + Object src = c.getChars(); + int cch = c._cchSrc; + int off = c._offSrc; + + enqueue(new CharacterDataImpl(src, cch, off)); + } + + protected void emitComment(SaveCur c) { + enqueue(new CommentImpl(c.getChars(), c._cchSrc, c._offSrc)); + } + + protected void emitProcinst(SaveCur c) { + String target = null; + QName name = c.getName(); + + if (name != null) { + target = name.getLocalPart(); + } + + enqueue(new ProcessingInstructionImpl(target, c.getChars(), c._cchSrc, c._offSrc)); + } + + protected void emitDocType(String doctypeName, String publicID, String systemID) { + enqueue(new StartDocumentImpl(systemID, null, true, null)); //todo + } + + protected void emitStartDoc(SaveCur c) { + emitDocType(null, null, null); + } + + protected void emitEndDoc(SaveCur c) { + enqueue(new EndDocumentImpl()); + } + + XMLEvent dequeue() { + if (_out == null) { + enterLocale(); + try { + if (!process()) { + return null; + } + } finally { + exitLocale(); + } + } + + if (_out == null) { + return null; + } + + XmlEventImpl e = _out; + + if ((_out = _out._next) == null) { + _in = null; + } + + return e; + } + + private void enqueue(XmlEventImpl e) { + assert e._next == null; + + if (_in == null) { + assert _out == null; + _out = _in = e; + } else { + _in._next = e; + _in = e; + } + } + + // + // + // + + protected void emitEndPrefixMappings() { + for (iterateMappings(); hasMapping(); nextMapping()) { + String prevPrefixUri = null; // todo mappingPrevPrefixUri(); + String prefix = mappingPrefix(); + String uri = mappingUri(); + + if (prevPrefixUri == null) { + enqueue(new EndPrefixMappingImpl(prefix)); + } else { + enqueue(new ChangePrefixMappingImpl(prefix, uri, prevPrefixUri)); + } + } + } + + // + // + // + + private static XMLName computeName(QName name, Saver saver, boolean needsPrefix) { + String uri = name.getNamespaceURI(); + String local = name.getLocalPart(); + + assert uri != null; + assert local.length() > 0; + + String prefix = null; + + if (!uri.isEmpty()) { + prefix = name.getPrefix(); + String mappedUri = saver.getNamespaceForPrefix(prefix); + + if (mappedUri == null || !mappedUri.equals(uri)) { + prefix = saver.getUriMapping(uri); + } + + // Attrs need a prefix. If I have not found one, then there must be a default + // prefix obscuring the prefix needed for this attr. Find it manually. + + // NOTE - Consider keeping the currently mapped default URI separate fromn the + // _urpMap and _prefixMap. This way, I would not have to look it up manually + // here + + if (needsPrefix && prefix.length() == 0) { + prefix = saver.getNonDefaultUriMapping(uri); + } + + } + + return new XmlNameImpl(uri, local, prefix); + } + + private static abstract class XmlEventImpl extends XmlEventBase { + XmlEventImpl(int type) { + super(type); + } + + public XMLName getName() { + return null; + } + + public XMLName getSchemaType() { + throw new RuntimeException("NYI"); + } + + public boolean hasName() { + return false; + } + + public final Location getLocation() { + // (orig v1 comment)TODO - perhaps I can save a location goober sometimes? + return null; + } + + XmlEventImpl _next; + } + + private static class StartDocumentImpl + extends XmlEventImpl implements StartDocument { + StartDocumentImpl(String systemID, String encoding, boolean isStandAlone, String version) { + super(XMLEvent.START_DOCUMENT); + _systemID = systemID; + _encoding = encoding; + _standAlone = isStandAlone; + _version = version; + } + + public String getSystemId() { + return _systemID; + } + + public String getCharacterEncodingScheme() { + return _encoding; + } + + public boolean isStandalone() { + return _standAlone; + } + + public String getVersion() { + return _version; + } + + String _systemID; + String _encoding; + boolean _standAlone; + String _version; + } + + private static class StartElementImpl + extends XmlEventImpl implements StartElement { + StartElementImpl(XMLName name, AttributeImpl attributes, AttributeImpl namespaces, Map prefixMap) { + super(XMLEvent.START_ELEMENT); + + _name = name; + _attributes = attributes; + _namespaces = namespaces; + _prefixMap = prefixMap; + } + + public boolean hasName() { + return true; + } + + public XMLName getName() { + return _name; + } + + public AttributeIterator getAttributes() { + return new AttributeIteratorImpl(_attributes, null); + } + + public AttributeIterator getNamespaces() { + return new AttributeIteratorImpl(null, _namespaces); + } + + public AttributeIterator getAttributesAndNamespaces() { + return new AttributeIteratorImpl(_attributes, _namespaces); + } + + public Attribute getAttributeByName(XMLName xmlName) { + for (AttributeImpl a = _attributes; a != null; a = a._next) { + if (xmlName.equals(a.getName())) { + return a; + } + } + + return null; + } + + public String getNamespaceUri(String prefix) { + return _prefixMap.get(prefix == null ? "" : prefix); + } + + public Map getNamespaceMap() { + return _prefixMap; + } + + private static class AttributeIteratorImpl + implements AttributeIterator { + AttributeIteratorImpl(AttributeImpl attributes, AttributeImpl namespaces) { + _attributes = attributes; + _namespaces = namespaces; + } + + public Object monitor() { + return this; + } + + public Attribute next() { + synchronized (monitor()) { + checkVersion(); + + AttributeImpl attr = null; + + if (_attributes != null) { + attr = _attributes; + _attributes = attr._next; + } else if (_namespaces != null) { + attr = _namespaces; + _namespaces = attr._next; + } + + return attr; + } + } + + public boolean hasNext() { + synchronized (monitor()) { + checkVersion(); + + return _attributes != null || _namespaces != null; + } + } + + public Attribute peek() { + synchronized (monitor()) { + checkVersion(); + + if (_attributes != null) { + return _attributes; + } else if (_namespaces != null) { + return _namespaces; + } + + return null; + } + } + + public void skip() { + synchronized (monitor()) { + checkVersion(); + + if (_attributes != null) { + _attributes = _attributes._next; + } else if (_namespaces != null) { + _namespaces = _namespaces._next; + } + } + } + + private void checkVersion() { +// if (_version != _root.getVersion()) +// throw new IllegalStateException( "Document changed" ); + } + + // private long _version; + private AttributeImpl _attributes; + private AttributeImpl _namespaces; + } + + private static abstract class AttributeImpl implements Attribute { + /** + * Don't forget to set _name + */ + AttributeImpl() { + } + + public XMLName getName() { + return _name; + } + + public String getType() { + // (from v1 impl) TODO - Make sure throwing away this DTD info is ok. + // (from v1 impl) Is there schema info which can return more useful info? + return "CDATA"; + } + + public XMLName getSchemaType() { + // (from v1 impl) TODO - Can I return something reasonable here? + return null; + } + + AttributeImpl _next; + + protected XMLName _name; + } + + private static class XmlnsAttributeImpl extends AttributeImpl { + XmlnsAttributeImpl(String prefix, String uri) { + super(); + _uri = uri; + + String local; + + if (prefix.length() == 0) { + prefix = null; + local = "xmlns"; + } else { + local = prefix; + prefix = "xmlns"; + } + + _name = new XmlNameImpl(null, local, prefix); + } + + public String getValue() { + return _uri; + } + + private final String _uri; + } + + private static class NormalAttributeImpl extends AttributeImpl { + NormalAttributeImpl(XMLName name, String value) { + _name = name; + _value = value; + } + + public String getValue() { + return _value; + } + + private final String _value; // If invalid in the store + } + + private final XMLName _name; + private final Map _prefixMap; + + private final AttributeImpl _attributes; + private final AttributeImpl _namespaces; + } + + private static class StartPrefixMappingImpl + extends XmlEventImpl implements StartPrefixMapping { + StartPrefixMappingImpl(String prefix, String uri) { + super(XMLEvent.START_PREFIX_MAPPING); + + _prefix = prefix; + _uri = uri; + } + + public String getNamespaceUri() { + return _uri; + } + + public String getPrefix() { + return _prefix; + } + + private final String _prefix; + private final String _uri; + } + + private static class ChangePrefixMappingImpl + extends XmlEventImpl implements ChangePrefixMapping { + ChangePrefixMappingImpl(String prefix, String oldUri, String newUri) { + super(XMLEvent.CHANGE_PREFIX_MAPPING); + + _oldUri = oldUri; + _newUri = newUri; + _prefix = prefix; + } + + public String getOldNamespaceUri() { + return _oldUri; + } + + public String getNewNamespaceUri() { + return _newUri; + } + + public String getPrefix() { + return _prefix; + } + + private final String _oldUri; + private final String _newUri; + private final String _prefix; + } + + private static class EndPrefixMappingImpl + extends XmlEventImpl implements EndPrefixMapping { + EndPrefixMappingImpl(String prefix) { + super(XMLEvent.END_PREFIX_MAPPING); + _prefix = prefix; + } + + public String getPrefix() { + return _prefix; + } + + private final String _prefix; + } + + private static class EndElementImpl + extends XmlEventImpl implements EndElement { + EndElementImpl(XMLName name) { + super(XMLEvent.END_ELEMENT); + + _name = name; + } + + public boolean hasName() { + return true; + } + + public XMLName getName() { + return _name; + } + + private final XMLName _name; + } + + private static class EndDocumentImpl + extends XmlEventImpl implements EndDocument { + EndDocumentImpl() { + super(XMLEvent.END_DOCUMENT); + } + } + + private static class TripletEventImpl + extends XmlEventImpl implements CharacterData { + TripletEventImpl(int eventType, Object obj, int cch, int off) { + super(eventType); + _obj = obj; + _cch = cch; + _off = off; + } + + public String getContent() { + return CharUtil.getString(_obj, _off, _cch); + } + + public boolean hasContent() { + return _cch > 0; + } + + private final Object _obj; + private final int _cch; + private final int _off; + } + + private static class CharacterDataImpl + extends TripletEventImpl implements CharacterData { + CharacterDataImpl(Object obj, int cch, int off) { + super(XMLEvent.CHARACTER_DATA, obj, cch, off); + } + } + + private static class CommentImpl + extends TripletEventImpl implements Comment { + CommentImpl(Object obj, int cch, int off) { + super(XMLEvent.COMMENT, obj, cch, off); + } + } + + private static class ProcessingInstructionImpl + extends TripletEventImpl implements ProcessingInstruction { + ProcessingInstructionImpl(String target, Object obj, int cch, int off) { + super(XMLEvent.PROCESSING_INSTRUCTION, obj, cch, off); + _target = target; + } + + public String getTarget() { + return _target; + } + + public String getData() { + return getContent(); + } + + private final String _target; + } + + private XmlEventImpl _in, _out; + } + + static final class SaxSaver extends Saver { + SaxSaver(Cur c, XmlOptions options, ContentHandler ch, LexicalHandler lh) + throws SAXException { + super(c, options); + + _contentHandler = ch; + _lexicalHandler = lh; + + _attributes = new AttributesImpl(); + _nsAsAttrs = !options.isSaveSaxNoNSDeclsInAttributes(); + + _contentHandler.startDocument(); + + try { + //noinspection StatementWithEmptyBody + while (process()) { + } + } catch (SaverSAXException e) { + throw e._saxException; + } + + _contentHandler.endDocument(); + } + + private static class SaverSAXException extends RuntimeException { + SaverSAXException(SAXException e) { + _saxException = e; + } + + SAXException _saxException; + } + + private String getPrefixedName(QName name) { + String uri = name.getNamespaceURI(); + String local = name.getLocalPart(); + + if (uri.length() == 0) { + return local; + } + + String prefix = getUriMapping(uri); + + if (prefix.length() == 0) { + return local; + } + + return prefix + ":" + local; + } + + private void emitNamespacesHelper() { + for (iterateMappings(); hasMapping(); nextMapping()) { + String prefix = mappingPrefix(); + String uri = mappingUri(); + + try { + _contentHandler.startPrefixMapping(prefix, uri); + } catch (SAXException e) { + throw new SaverSAXException(e); + } + + if (_nsAsAttrs) { + if (prefix == null || prefix.length() == 0) { + _attributes.addAttribute("http://www.w3.org/2000/xmlns/", "xmlns", "xmlns", "CDATA", uri); + } else { + _attributes.addAttribute("http://www.w3.org/2000/xmlns/", prefix, "xmlns:" + prefix, "CDATA", uri); + } + } + } + } + + @Override + protected boolean emitElement(SaveCur c, List attrNames, List attrValues) { + _attributes.clear(); + + if (saveNamespacesFirst()) { + emitNamespacesHelper(); + } + + for (int i = 0; i < attrNames.size(); i++) { + QName name = attrNames.get(i); + + _attributes.addAttribute( + name.getNamespaceURI(), name.getLocalPart(), getPrefixedName(name), + "CDATA", attrValues.get(i)); + } + + if (!saveNamespacesFirst()) { + emitNamespacesHelper(); + } + + QName elemName = c.getName(); + + try { + _contentHandler.startElement( + elemName.getNamespaceURI(), elemName.getLocalPart(), + getPrefixedName(elemName), _attributes); + } catch (SAXException e) { + throw new SaverSAXException(e); + } + + return false; + } + + protected void emitFinish(SaveCur c) { + QName name = c.getName(); + + try { + _contentHandler.endElement( + name.getNamespaceURI(), name.getLocalPart(), getPrefixedName(name)); + + for (iterateMappings(); hasMapping(); nextMapping()) { + _contentHandler.endPrefixMapping(mappingPrefix()); + } + } catch (SAXException e) { + throw new SaverSAXException(e); + } + } + + protected void emitText(SaveCur c) { + assert c.isText(); + + Object src = c.getChars(); + + try { + if (src instanceof char[]) { + // Pray the user does not modify the buffer .... + _contentHandler.characters((char[]) src, c._offSrc, c._cchSrc); + } else { + if (_buf == null) { + _buf = new char[1024]; + } + + while (c._cchSrc > 0) { + int cch = java.lang.Math.min(_buf.length, c._cchSrc); + + CharUtil.getChars(_buf, 0, src, c._offSrc, cch); + + _contentHandler.characters(_buf, 0, cch); + + c._offSrc += cch; + c._cchSrc -= cch; + } + } + } catch (SAXException e) { + throw new SaverSAXException(e); + } + } + + protected void emitComment(SaveCur c) { + if (_lexicalHandler != null) { + c.push(); + + c.next(); + + try { + if (!c.isText()) { + _lexicalHandler.comment(null, 0, 0); + } else { + Object src = c.getChars(); + + if (src instanceof char[]) { + // Pray the user does not modify the buffer .... + _lexicalHandler.comment((char[]) src, c._offSrc, c._cchSrc); + } else { + if (_buf == null || _buf.length < c._cchSrc) { + _buf = new char[java.lang.Math.max(1024, c._cchSrc)]; + } + + CharUtil.getChars(_buf, 0, src, c._offSrc, c._cchSrc); + + _lexicalHandler.comment(_buf, 0, c._cchSrc); + } + } + } catch (SAXException e) { + throw new SaverSAXException(e); + } + + c.pop(); + } + } + + protected void emitProcinst(SaveCur c) { + c.push(); + + c.next(); + + String value = CharUtil.getString(c.getChars(), c._offSrc, c._cchSrc); + + c.pop(); + + try { + _contentHandler.processingInstruction(c.getName().getLocalPart(), value); + } catch (SAXException e) { + throw new SaverSAXException(e); + } + } + + protected void emitDocType(String docTypeName, String publicId, String systemId) { + if (_lexicalHandler != null) { + try { + _lexicalHandler.startDTD(docTypeName, publicId, systemId); + _lexicalHandler.endDTD(); + } catch (SAXException e) { + throw new SaverSAXException(e); + } + } + } + + protected void emitStartDoc(SaveCur c) { + } + + protected void emitEndDoc(SaveCur c) { + } + + private final ContentHandler _contentHandler; + private final LexicalHandler _lexicalHandler; + + private final AttributesImpl _attributes; + + private char[] _buf; + private final boolean _nsAsAttrs; + } + + // + // + // + + static abstract class SaveCur { + final boolean isRoot() { + return kind() == ROOT; + } + + final boolean isElem() { + return kind() == ELEM; + } + + final boolean isAttr() { + return kind() == ATTR; + } + + final boolean isText() { + return kind() == TEXT; + } + + final boolean isComment() { + return kind() == COMMENT; + } + + final boolean isProcinst() { + return kind() == PROCINST; + } + + final boolean isFinish() { + return Cur.kindIsFinish(kind()); + } + + final boolean isContainer() { + return Cur.kindIsContainer(kind()); + } + + final boolean isNormalAttr() { + return kind() == ATTR && !isXmlns(); + } + + @SuppressWarnings("unused") + final boolean skip() { + toEnd(); + return next(); + } + + abstract void release(); + + abstract int kind(); + + abstract QName getName(); + + abstract String getXmlnsPrefix(); + + abstract String getXmlnsUri(); + + abstract boolean isXmlns(); + + abstract boolean hasChildren(); + + abstract boolean hasText(); + + abstract boolean isTextCData(); + + abstract boolean toFirstAttr(); + + abstract boolean toNextAttr(); + + abstract String getAttrValue(); + + abstract boolean next(); + + abstract void toEnd(); + + abstract void push(); + + abstract void pop(); + + abstract Object getChars(); + + abstract List getAncestorNamespaces(); + + abstract XmlDocumentProperties getDocProps(); + + int _offSrc; + int _cchSrc; + } + + // TODO - saving a fragment need to take namesapces from root and + // reflect them on the document element + + private static final class DocSaveCur extends SaveCur { + DocSaveCur(Cur c) { + assert c.isRoot(); + _cur = c.weakCur(this); + } + + void release() { + _cur.release(); + _cur = null; + } + + int kind() { + return _cur.kind(); + } + + QName getName() { + return _cur.getName(); + } + + String getXmlnsPrefix() { + return _cur.getXmlnsPrefix(); + } + + String getXmlnsUri() { + return _cur.getXmlnsUri(); + } + + boolean isXmlns() { + return _cur.isXmlns(); + } + + boolean hasChildren() { + return _cur.hasChildren(); + } + + boolean hasText() { + return _cur.hasText(); + } + + boolean isTextCData() { + return _cur.isTextCData(); + } + + boolean toFirstAttr() { + return _cur.toFirstAttr(); + } + + boolean toNextAttr() { + return _cur.toNextAttr(); + } + + String getAttrValue() { + assert _cur.isAttr(); + return _cur.getValueAsString(); + } + + void toEnd() { + _cur.toEnd(); + } + + boolean next() { + return _cur.next(); + } + + void push() { + _cur.push(); + } + + void pop() { + _cur.pop(); + } + + List getAncestorNamespaces() { + return null; + } + + Object getChars() { + Object o = _cur.getChars(-1); + + _offSrc = _cur._offSrc; + _cchSrc = _cur._cchSrc; + + return o; + } + + XmlDocumentProperties getDocProps() { + return Locale.getDocProps(_cur, false); + } + + private Cur _cur; + } + + private static abstract class FilterSaveCur extends SaveCur { + FilterSaveCur(SaveCur c) { + assert c.isRoot(); + _cur = c; + } + + // Can filter anything by root and attributes and text + protected abstract boolean filter(); + + void release() { + _cur.release(); + _cur = null; + } + + int kind() { + return _cur.kind(); + } + + QName getName() { + return _cur.getName(); + } + + String getXmlnsPrefix() { + return _cur.getXmlnsPrefix(); + } + + String getXmlnsUri() { + return _cur.getXmlnsUri(); + } + + boolean isXmlns() { + return _cur.isXmlns(); + } + + boolean hasChildren() { + return _cur.hasChildren(); + } + + boolean hasText() { + return _cur.hasText(); + } + + boolean isTextCData() { + return _cur.isTextCData(); + } + + boolean toFirstAttr() { + return _cur.toFirstAttr(); + } + + boolean toNextAttr() { + return _cur.toNextAttr(); + } + + String getAttrValue() { + return _cur.getAttrValue(); + } + + void toEnd() { + _cur.toEnd(); + } + + boolean next() { + if (!_cur.next()) { + return false; + } + + if (!filter()) { + return true; + } + + assert !isRoot() && !isText() && !isAttr(); + + toEnd(); + + return next(); + } + + void push() { + _cur.push(); + } + + void pop() { + _cur.pop(); + } + + List getAncestorNamespaces() { + return _cur.getAncestorNamespaces(); + } + + Object getChars() { + Object o = _cur.getChars(); + + _offSrc = _cur._offSrc; + _cchSrc = _cur._cchSrc; + + return o; + } + + XmlDocumentProperties getDocProps() { + return _cur.getDocProps(); + } + + private SaveCur _cur; + } + + private static final class FilterPiSaveCur extends FilterSaveCur { + FilterPiSaveCur(SaveCur c, String target) { + super(c); + + _piTarget = target; + } + + protected boolean filter() { + return kind() == PROCINST && getName().getLocalPart().equals(_piTarget); + } + + private final String _piTarget; + } + + private static final class FragSaveCur extends SaveCur { + FragSaveCur(Cur start, Cur end, QName synthElem) { + _saveAttr = start.isAttr() && start.isSamePos(end); + + _cur = start.weakCur(this); + _end = end.weakCur(this); + + _elem = synthElem; + + _state = ROOT_START; + + _stateStack = new int[8]; + + start.push(); + computeAncestorNamespaces(start); + start.pop(); + } + + List getAncestorNamespaces() { + return _ancestorNamespaces; + } + + private void computeAncestorNamespaces(Cur c) { + _ancestorNamespaces = new ArrayList<>(); + + while (c.toParentRaw()) { + if (c.toFirstAttr()) { + do { + if (c.isXmlns()) { + String prefix = c.getXmlnsPrefix(); + String uri = c.getXmlnsUri(); + + // Don't let xmlns:foo="" get used + + if (uri.length() > 0 || prefix.length() == 0) { + _ancestorNamespaces.add(c.getXmlnsPrefix()); + _ancestorNamespaces.add(c.getXmlnsUri()); + } + } + } + while (c.toNextAttr()); + + c.toParent(); + } + } + } + + // + // + // + + void release() { + _cur.release(); + _cur = null; + + _end.release(); + _end = null; + } + + int kind() { + switch (_state) { + case ROOT_START: + return ROOT; + case ELEM_START: + return ELEM; + case ELEM_END: + return -ELEM; + case ROOT_END: + return -ROOT; + } + + assert _state == CUR; + + return _cur.kind(); + } + + QName getName() { + switch (_state) { + case ROOT_START: + case ROOT_END: + return null; + case ELEM_START: + case ELEM_END: + return _elem; + } + + assert _state == CUR; + + return _cur.getName(); + } + + String getXmlnsPrefix() { + assert _state == CUR && _cur.isAttr(); + return _cur.getXmlnsPrefix(); + } + + String getXmlnsUri() { + assert _state == CUR && _cur.isAttr(); + return _cur.getXmlnsUri(); + } + + boolean isXmlns() { + assert _state == CUR && _cur.isAttr(); + return _cur.isXmlns(); + } + + boolean hasChildren() { + boolean hasChildren = false; + + if (isContainer()) { // is there a faster way to do this? + push(); + next(); + + if (!isText() && !isFinish()) { + hasChildren = true; + } + + pop(); + } + + return hasChildren; + } + + boolean hasText() { + boolean hasText = false; + + if (isContainer()) { + push(); + next(); + + if (isText()) { + hasText = true; + } + + pop(); + } + + return hasText; + } + + boolean isTextCData() { + return _cur.isTextCData(); + } + + Object getChars() { + assert _state == CUR && _cur.isText(); + + Object src = _cur.getChars(-1); + + _offSrc = _cur._offSrc; + _cchSrc = _cur._cchSrc; + + return src; + } + + boolean next() { + switch (_state) { + case ROOT_START: { + _state = _elem == null ? CUR : ELEM_START; + break; + } + + case ELEM_START: { + if (_saveAttr) { + _state = ELEM_END; + } else { + if (_cur.isAttr()) { + _cur.toParent(); + _cur.next(); + } + + if (_cur.isSamePos(_end)) { + _state = ELEM_END; + } else { + _state = CUR; + } + } + + break; + } + + case CUR: { + assert !_cur.isAttr(); + + _cur.next(); + + if (_cur.isSamePos(_end)) { + _state = _elem == null ? ROOT_END : ELEM_END; + } + + break; + } + + case ELEM_END: { + _state = ROOT_END; + break; + } + case ROOT_END: + return false; + } + + return true; + } + + void toEnd() { + switch (_state) { + case ROOT_START: + _state = ROOT_END; + return; + case ELEM_START: + _state = ELEM_END; + return; + case ROOT_END: + case ELEM_END: + return; + } + + assert _state == CUR && !_cur.isAttr() && !_cur.isText(); + + _cur.toEnd(); + } + + boolean toFirstAttr() { + switch (_state) { + case ROOT_END: + case ELEM_END: + case ROOT_START: + return false; + case CUR: + return _cur.toFirstAttr(); + } + + assert _state == ELEM_START; + + if (!_cur.isAttr()) { + return false; + } + + _state = CUR; + + return true; + } + + boolean toNextAttr() { + assert _state == CUR; + return !_saveAttr && _cur.toNextAttr(); + } + + String getAttrValue() { + assert _state == CUR && _cur.isAttr(); + return _cur.getValueAsString(); + } + + void push() { + if (_stateStackSize == _stateStack.length) { + int[] newStateStack = new int[_stateStackSize * 2]; + System.arraycopy(_stateStack, 0, newStateStack, 0, _stateStackSize); + _stateStack = newStateStack; + } + + _stateStack[_stateStackSize++] = _state; + _cur.push(); + } + + void pop() { + _cur.pop(); + _state = _stateStack[--_stateStackSize]; + } + + XmlDocumentProperties getDocProps() { + return Locale.getDocProps(_cur, false); + } + + // + // + // + + private Cur _cur; + private Cur _end; + + private ArrayList _ancestorNamespaces; + + private final QName _elem; + + private final boolean _saveAttr; + + private static final int ROOT_START = 1; + private static final int ELEM_START = 2; + private static final int ROOT_END = 3; + private static final int ELEM_END = 4; + private static final int CUR = 5; + + private int _state; + + private int[] _stateStack; + private int _stateStackSize; + } + + private static final class PrettySaveCur extends SaveCur { + PrettySaveCur(SaveCur c, XmlOptions options) { + _sb = new StringBuffer(); + _stack = new ArrayList<>(); + + _cur = c; + + assert options != null; + + _prettyIndent = 2; + + if (options.getSavePrettyPrintIndent() != null) { + _prettyIndent = options.getSavePrettyPrintIndent(); + } + + if (options.getSavePrettyPrintOffset() != null) { + _prettyOffset = options.getSavePrettyPrintOffset(); + } + + _useCDataBookmarks = options.isUseCDataBookmarks(); + } + + List getAncestorNamespaces() { + return _cur.getAncestorNamespaces(); + } + + void release() { + _cur.release(); + } + + int kind() { + return _txt == null ? _cur.kind() : TEXT; + } + + QName getName() { + assert _txt == null; + return _cur.getName(); + } + + String getXmlnsPrefix() { + assert _txt == null; + return _cur.getXmlnsPrefix(); + } + + String getXmlnsUri() { + assert _txt == null; + return _cur.getXmlnsUri(); + } + + boolean isXmlns() { + return _txt == null && _cur.isXmlns(); + } + + boolean hasChildren() { + return _txt == null && _cur.hasChildren(); + } + + boolean hasText() { + return _txt == null && _cur.hasText(); + } + + // _cur.isTextCData() is expensive do it only if useCDataBookmarks option is enabled + boolean isTextCData() { + return _txt == null ? (_useCDataBookmarks && _cur.isTextCData()) + : _isTextCData; + } + + boolean toFirstAttr() { + assert _txt == null; + return _cur.toFirstAttr(); + } + + boolean toNextAttr() { + assert _txt == null; + return _cur.toNextAttr(); + } + + String getAttrValue() { + assert _txt == null; + return _cur.getAttrValue(); + } + + void toEnd() { + assert _txt == null; + _cur.toEnd(); + + if (_cur.kind() == -ELEM) { + _depth--; + } + } + + boolean next() { + int k; + + if (_txt != null) { + assert _txt.length() > 0; + assert !_cur.isText(); + _txt = null; + _isTextCData = false; + k = _cur.kind(); + } else { + int prevKind = _cur.kind(); + + if (!_cur.next()) { + return false; + } + + _sb.delete(0, _sb.length()); + + assert _txt == null; + + // place any text encountered in the buffer + if (_cur.isText()) { + // _cur.isTextCData() is expensive do it only if useCDataBookmarks option is enabled + _isTextCData = _useCDataBookmarks && _cur.isTextCData(); + CharUtil.getString(_sb, _cur.getChars(), _cur._offSrc, _cur._cchSrc); + _cur.next(); + k = _cur.kind(); + if (prevKind != ELEM || k != -ELEM) { + trim(_sb); + } + } + + k = _cur.kind(); + + // Check for non leaf, _prettyIndent < 0 means that the save is all on one line + + if (_prettyIndent >= 0 && + prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM)) { + if (_sb.length() > 0) { + _sb.insert(0, _newLine); + spaces(_sb, _newLine.length(), _prettyOffset + _prettyIndent * _depth); + } + + if (k != -ROOT) { + if (prevKind != ROOT) { + _sb.append(_newLine); + } + + int d = k < 0 ? _depth - 1 : _depth; + spaces(_sb, _sb.length(), _prettyOffset + _prettyIndent * d); + } + } + + if (_sb.length() > 0) { + _txt = _sb.toString(); + k = TEXT; + } + } + + if (k == ELEM) { + _depth++; + } else if (k == -ELEM) { + _depth--; + } + + return true; + } + + void push() { + _cur.push(); + _stack.add(_txt); + _stack.add(_depth); + _isTextCData = false; + } + + void pop() { + _cur.pop(); + _depth = (Integer) _stack.remove(_stack.size() - 1); + _txt = (String) _stack.remove(_stack.size() - 1); + _isTextCData = false; + } + + Object getChars() { + if (_txt != null) { + _offSrc = 0; + _cchSrc = _txt.length(); + return _txt; + } + + Object o = _cur.getChars(); + + _offSrc = _cur._offSrc; + _cchSrc = _cur._cchSrc; + + return o; + } + + XmlDocumentProperties getDocProps() { + return _cur.getDocProps(); + } + + static void spaces(StringBuffer sb, int offset, int count) { + while (count-- > 0) { + sb.insert(offset, ' '); + } + } + + static void trim(StringBuffer sb) { + int i; + + for (i = 0; i < sb.length(); i++) { + if (!CharUtil.isWhiteSpace(sb.charAt(i))) { + break; + } + } + + sb.delete(0, i); + + for (i = sb.length(); i > 0; i--) { + if (!CharUtil.isWhiteSpace(sb.charAt(i - 1))) { + break; + } + } + + sb.delete(i, sb.length()); + } + + private final SaveCur _cur; + + private int _prettyIndent; + private int _prettyOffset; + + private String _txt; + private final StringBuffer _sb; + + private int _depth; + + private final ArrayList _stack; + private boolean _isTextCData = false; + private final boolean _useCDataBookmarks; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapBodyElementXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapBodyElementXobj.java new file mode 100644 index 0000000..98f0627 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapBodyElementXobj.java @@ -0,0 +1,30 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.SOAPBodyElement; + +import javax.xml.namespace.QName; + +class SoapBodyElementXobj extends SoapElementXobj implements SOAPBodyElement { + SoapBodyElementXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapBodyElementXobj(l, _name); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapBodyXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapBodyXobj.java new file mode 100644 index 0000000..8eea3b5 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapBodyXobj.java @@ -0,0 +1,59 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.*; +import org.w3c.dom.Document; + +import javax.xml.namespace.QName; + +class SoapBodyXobj extends SoapElementXobj implements SOAPBody { + SoapBodyXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapBodyXobj(l, _name); + } + + public boolean hasFault() { + return DomImpl.soapBody_hasFault(this); + } + + public SOAPFault addFault() throws SOAPException { + return DomImpl.soapBody_addFault(this); + } + + public SOAPFault getFault() { + return DomImpl.soapBody_getFault(this); + } + + public SOAPBodyElement addBodyElement(Name name) { + return DomImpl.soapBody_addBodyElement(this, name); + } + + public SOAPBodyElement addDocument(Document document) { + return DomImpl.soapBody_addDocument(this, document); + } + + public SOAPFault addFault(Name name, String s) throws SOAPException { + return DomImpl.soapBody_addFault(this, name, s); + } + + public SOAPFault addFault(Name faultCode, String faultString, java.util.Locale locale) throws SOAPException { + return DomImpl.soapBody_addFault(this, faultCode, faultString, locale); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapElementXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapElementXobj.java new file mode 100644 index 0000000..e20a579 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapElementXobj.java @@ -0,0 +1,142 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.Name; +import org.apache.xmlbeans.impl.soap.SOAPElement; +import org.apache.xmlbeans.impl.soap.SOAPException; + +import javax.xml.namespace.QName; +import java.util.Iterator; + +class SoapElementXobj extends ElementXobj implements SOAPElement, org.apache.xmlbeans.impl.soap.Node { + SoapElementXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapElementXobj(l, _name); + } + + public void detachNode() { + DomImpl._soapNode_detachNode(this); + } + + public void recycleNode() { + DomImpl._soapNode_recycleNode(this); + } + + public String getValue() { + return DomImpl._soapNode_getValue(this); + } + + public void setValue(String value) { + DomImpl._soapNode_setValue(this, value); + } + + public SOAPElement getParentElement() { + return DomImpl._soapNode_getParentElement(this); + } + + public void setParentElement(SOAPElement p) { + DomImpl._soapNode_setParentElement(this, p); + } + + public void removeContents() { + DomImpl._soapElement_removeContents(this); + } + + public String getEncodingStyle() { + return DomImpl._soapElement_getEncodingStyle(this); + } + + public void setEncodingStyle(String encodingStyle) { + DomImpl._soapElement_setEncodingStyle(this, encodingStyle); + } + + public boolean removeNamespaceDeclaration(String prefix) { + return DomImpl._soapElement_removeNamespaceDeclaration(this, prefix); + } + + public Iterator getAllAttributes() { + return DomImpl._soapElement_getAllAttributes(this); + } + + public Iterator getChildElements() { + return DomImpl._soapElement_getChildElements(this); + } + + public Iterator getNamespacePrefixes() { + return DomImpl._soapElement_getNamespacePrefixes(this); + } + + public SOAPElement addAttribute(Name name, String value) throws SOAPException { + return DomImpl._soapElement_addAttribute(this, name, value); + } + + public SOAPElement addChildElement(SOAPElement oldChild) throws SOAPException { + return DomImpl._soapElement_addChildElement(this, oldChild); + } + + public SOAPElement addChildElement(Name name) throws SOAPException { + return DomImpl._soapElement_addChildElement(this, name); + } + + public SOAPElement addChildElement(String localName) throws SOAPException { + return DomImpl._soapElement_addChildElement(this, localName); + } + + public SOAPElement addChildElement(String localName, String prefix) throws SOAPException { + return DomImpl._soapElement_addChildElement(this, localName, prefix); + } + + public SOAPElement addChildElement(String localName, String prefix, String uri) throws SOAPException { + return DomImpl._soapElement_addChildElement(this, localName, prefix, uri); + } + + public SOAPElement addNamespaceDeclaration(String prefix, String uri) { + return DomImpl._soapElement_addNamespaceDeclaration(this, prefix, uri); + } + + public SOAPElement addTextNode(String data) { + return DomImpl._soapElement_addTextNode(this, data); + } + + public String getAttributeValue(Name name) { + return DomImpl._soapElement_getAttributeValue(this, name); + } + + public Iterator getChildElements(Name name) { + return DomImpl._soapElement_getChildElements(this, name); + } + + public Name getElementName() { + return DomImpl._soapElement_getElementName(this); + } + + public String getNamespaceURI(String prefix) { + return DomImpl._soapElement_getNamespaceURI(this, prefix); + } + + public Iterator getVisibleNamespacePrefixes() { + return DomImpl._soapElement_getVisibleNamespacePrefixes(this); + } + + public boolean removeAttribute(Name name) { + return DomImpl._soapElement_removeAttribute(this, name); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapEnvelopeXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapEnvelopeXobj.java new file mode 100644 index 0000000..bacb2c0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapEnvelopeXobj.java @@ -0,0 +1,54 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.*; + +import javax.xml.namespace.QName; + +class SoapEnvelopeXobj extends SoapElementXobj implements SOAPEnvelope { + SoapEnvelopeXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapEnvelopeXobj(l, _name); + } + + public SOAPBody addBody() throws SOAPException { + return DomImpl._soapEnvelope_addBody(this); + } + + public SOAPBody getBody() throws SOAPException { + return DomImpl._soapEnvelope_getBody(this); + } + + public SOAPHeader getHeader() throws SOAPException { + return DomImpl._soapEnvelope_getHeader(this); + } + + public SOAPHeader addHeader() throws SOAPException { + return DomImpl._soapEnvelope_addHeader(this); + } + + public Name createName(String localName) { + return DomImpl._soapEnvelope_createName(this, localName); + } + + public Name createName(String localName, String prefix, String namespaceURI) { + return DomImpl._soapEnvelope_createName(this, localName, prefix, namespaceURI); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapFaultElementXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapFaultElementXobj.java new file mode 100644 index 0000000..c4244e3 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapFaultElementXobj.java @@ -0,0 +1,30 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.SOAPFaultElement; + +import javax.xml.namespace.QName; + +class SoapFaultElementXobj extends SoapElementXobj implements SOAPFaultElement { + SoapFaultElementXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapFaultElementXobj(l, _name); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapFaultXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapFaultXobj.java new file mode 100644 index 0000000..787b997 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapFaultXobj.java @@ -0,0 +1,81 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.Detail; +import org.apache.xmlbeans.impl.soap.Name; +import org.apache.xmlbeans.impl.soap.SOAPException; +import org.apache.xmlbeans.impl.soap.SOAPFault; + +import javax.xml.namespace.QName; + +class SoapFaultXobj extends SoapBodyElementXobj implements SOAPFault { + SoapFaultXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapFaultXobj(l, _name); + } + + public void setFaultString(String faultString) { + DomImpl.soapFault_setFaultString(this, faultString); + } + + public void setFaultString(String faultString, java.util.Locale locale) { + DomImpl.soapFault_setFaultString(this, faultString, locale); + } + + public void setFaultCode(Name faultCodeName) throws SOAPException { + DomImpl.soapFault_setFaultCode(this, faultCodeName); + } + + public void setFaultActor(String faultActorString) { + DomImpl.soapFault_setFaultActor(this, faultActorString); + } + + public String getFaultActor() { + return DomImpl.soapFault_getFaultActor(this); + } + + public String getFaultCode() { + return DomImpl.soapFault_getFaultCode(this); + } + + public void setFaultCode(String faultCode) throws SOAPException { + DomImpl.soapFault_setFaultCode(this, faultCode); + } + + public java.util.Locale getFaultStringLocale() { + return DomImpl.soapFault_getFaultStringLocale(this); + } + + public Name getFaultCodeAsName() { + return DomImpl.soapFault_getFaultCodeAsName(this); + } + + public String getFaultString() { + return DomImpl.soapFault_getFaultString(this); + } + + public Detail addDetail() throws SOAPException { + return DomImpl.soapFault_addDetail(this); + } + + public Detail getDetail() { + return DomImpl.soapFault_getDetail(this); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapHeaderElementXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapHeaderElementXobj.java new file mode 100644 index 0000000..7bbac9c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapHeaderElementXobj.java @@ -0,0 +1,46 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.SOAPHeaderElement; + +import javax.xml.namespace.QName; + +class SoapHeaderElementXobj extends SoapElementXobj implements SOAPHeaderElement { + SoapHeaderElementXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapHeaderElementXobj(l, _name); + } + + public void setMustUnderstand(boolean mustUnderstand) { + DomImpl.soapHeaderElement_setMustUnderstand(this, mustUnderstand); + } + + public boolean getMustUnderstand() { + return DomImpl.soapHeaderElement_getMustUnderstand(this); + } + + public void setActor(String actor) { + DomImpl.soapHeaderElement_setActor(this, actor); + } + + public String getActor() { + return DomImpl.soapHeaderElement_getActor(this); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapHeaderXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapHeaderXobj.java new file mode 100644 index 0000000..0048ce3 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapHeaderXobj.java @@ -0,0 +1,57 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.Name; +import org.apache.xmlbeans.impl.soap.SOAPHeader; +import org.apache.xmlbeans.impl.soap.SOAPHeaderElement; + +import javax.xml.namespace.QName; +import java.util.Iterator; + +class SoapHeaderXobj extends SoapElementXobj implements SOAPHeader { + SoapHeaderXobj(Locale l, QName name) { + super(l, name); + } + + Xobj newNode(Locale l) { + return new SoapHeaderXobj(l, _name); + } + + public Iterator examineAllHeaderElements() { + return DomImpl.soapHeader_examineAllHeaderElements(this); + } + + public Iterator extractAllHeaderElements() { + return DomImpl.soapHeader_extractAllHeaderElements(this); + } + + public Iterator examineHeaderElements(String actor) { + return DomImpl.soapHeader_examineHeaderElements(this, actor); + } + + public Iterator examineMustUnderstandHeaderElements(String mustUnderstandString) { + return DomImpl.soapHeader_examineMustUnderstandHeaderElements(this, mustUnderstandString); + } + + public Iterator extractHeaderElements(String actor) { + return DomImpl.soapHeader_extractHeaderElements(this, actor); + } + + public SOAPHeaderElement addHeaderElement(Name name) { + return DomImpl.soapHeader_addHeaderElement(this, name); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapPartDocXobj.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapPartDocXobj.java new file mode 100644 index 0000000..06facdf --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapPartDocXobj.java @@ -0,0 +1,35 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +class SoapPartDocXobj extends DocumentXobj { + SoapPartDocXobj(Locale l) { + super(l); + //super( l, ROOT, DomImpl.DOCUMENT ); + _soapPartDom = new SoapPartDom(this); + } + + DomImpl.Dom getDom() { + return _soapPartDom; + } + + Xobj newNode(Locale l) { + return new SoapPartDocXobj(l); + } + + SoapPartDom _soapPartDom; +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/SoapPartDom.java b/src/main/java/org/apache/xmlbeans/impl/store/SoapPartDom.java new file mode 100644 index 0000000..f773e81 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/SoapPartDom.java @@ -0,0 +1,395 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.impl.soap.SOAPEnvelope; +import org.apache.xmlbeans.impl.soap.SOAPPart; +import org.w3c.dom.*; + +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import java.io.PrintStream; +import java.util.Iterator; + +class SoapPartDom extends SOAPPart implements DomImpl.Dom, Document, NodeList { + SoapPartDom(SoapPartDocXobj docXobj) { + _docXobj = docXobj; + } + + public int nodeType() { + return DomImpl.DOCUMENT; + } + + public Locale locale() { + return _docXobj._locale; + } + + public Cur tempCur() { + return _docXobj.tempCur(); + } + + public QName getQName() { + return _docXobj._name; + } + + public void dump() { + dump(System.out); + } + + public void dump(PrintStream o) { + _docXobj.dump(o); + } + + public void dump(PrintStream o, Object ref) { + _docXobj.dump(o, ref); + } + + public String name() { + return "#document"; + } + + public Node appendChild(Node newChild) { + return DomImpl._node_appendChild(this, newChild); + } + + public Node cloneNode(boolean deep) { + return DomImpl._node_cloneNode(this, deep); + } + + public NamedNodeMap getAttributes() { + return null; + } + + public NodeList getChildNodes() { + return this; + } + + public Node getParentNode() { + return DomImpl._node_getParentNode(this); + } + + public Node removeChild(Node oldChild) { + return DomImpl._node_removeChild(this, oldChild); + } + + public Node getFirstChild() { + return DomImpl._node_getFirstChild(this); + } + + public Node getLastChild() { + return DomImpl._node_getLastChild(this); + } + + public String getLocalName() { + return DomImpl._node_getLocalName(this); + } + + public String getNamespaceURI() { + return DomImpl._node_getNamespaceURI(this); + } + + public Node getNextSibling() { + return DomImpl._node_getNextSibling(this); + } + + public String getNodeName() { + return DomImpl._node_getNodeName(this); + } + + public short getNodeType() { + return DomImpl._node_getNodeType(this); + } + + public String getNodeValue() { + return DomImpl._node_getNodeValue(this); + } + + public Document getOwnerDocument() { + return DomImpl._node_getOwnerDocument(this); + } + + public String getPrefix() { + return DomImpl._node_getPrefix(this); + } + + public Node getPreviousSibling() { + return DomImpl._node_getPreviousSibling(this); + } + + public boolean hasAttributes() { + return DomImpl._node_hasAttributes(this); + } + + public boolean hasChildNodes() { + return DomImpl._node_hasChildNodes(this); + } + + public Node insertBefore(Node newChild, Node refChild) { + return DomImpl._node_insertBefore(this, newChild, refChild); + } + + public boolean isSupported(String feature, String version) { + return DomImpl._node_isSupported(this, feature, version); + } + + public void normalize() { + DomImpl._node_normalize(this); + } + + public Node replaceChild(Node newChild, Node oldChild) { + return DomImpl._node_replaceChild(this, newChild, oldChild); + } + + public void setNodeValue(String nodeValue) { + DomImpl._node_setNodeValue(this, nodeValue); + } + + public void setPrefix(String prefix) { + DomImpl._node_setPrefix(this, prefix); + } + + // DOM Level 3 + public Object getUserData(String key) { + return DomImpl._node_getUserData(this, key); + } + + public Object setUserData(String key, Object data, UserDataHandler handler) { + return DomImpl._node_setUserData(this, key, data, handler); + } + + public Object getFeature(String feature, String version) { + return DomImpl._node_getFeature(this, feature, version); + } + + public boolean isEqualNode(Node arg) { + return DomImpl._node_isEqualNode(this, arg); + } + + public boolean isSameNode(Node arg) { + return DomImpl._node_isSameNode(this, arg); + } + + public String lookupNamespaceURI(String prefix) { + return DomImpl._node_lookupNamespaceURI(this, prefix); + } + + public String lookupPrefix(String namespaceURI) { + return DomImpl._node_lookupPrefix(this, namespaceURI); + } + + public boolean isDefaultNamespace(String namespaceURI) { + return DomImpl._node_isDefaultNamespace(this, namespaceURI); + } + + public void setTextContent(String textContent) { + DomImpl._node_setTextContent(this, textContent); + } + + public String getTextContent() { + return DomImpl._node_getTextContent(this); + } + + public short compareDocumentPosition(Node other) { + return DomImpl._node_compareDocumentPosition(this, other); + } + + public String getBaseURI() { + return DomImpl._node_getBaseURI(this); + } + + public Node adoptNode(Node source) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getDocumentURI() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public DOMConfiguration getDomConfig() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getInputEncoding() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public boolean getStrictErrorChecking() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getXmlEncoding() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public boolean getXmlStandalone() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public String getXmlVersion() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void normalizeDocument() { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public Node renameNode(Node n, String namespaceURI, String qualifiedName) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setDocumentURI(String documentURI) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setStrictErrorChecking(boolean strictErrorChecking) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setXmlStandalone(boolean xmlStandalone) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public void setXmlVersion(String xmlVersion) { + throw new RuntimeException("DOM Level 3 Not implemented"); + } + + public Attr createAttribute(String name) { + return DomImpl._document_createAttribute(this, name); + } + + public Attr createAttributeNS(String namespaceURI, String qualifiedName) { + return DomImpl._document_createAttributeNS(this, namespaceURI, qualifiedName); + } + + public CDATASection createCDATASection(String data) { + return DomImpl._document_createCDATASection(this, data); + } + + public Comment createComment(String data) { + return DomImpl._document_createComment(this, data); + } + + public DocumentFragment createDocumentFragment() { + return DomImpl._document_createDocumentFragment(this); + } + + public Element createElement(String tagName) { + return DomImpl._document_createElement(this, tagName); + } + + public Element createElementNS(String namespaceURI, String qualifiedName) { + return DomImpl._document_createElementNS(this, namespaceURI, qualifiedName); + } + + public EntityReference createEntityReference(String name) { + return DomImpl._document_createEntityReference(this, name); + } + + public ProcessingInstruction createProcessingInstruction(String target, String data) { + return DomImpl._document_createProcessingInstruction(this, target, data); + } + + public Text createTextNode(String data) { + return DomImpl._document_createTextNode(this, data); + } + + public DocumentType getDoctype() { + return DomImpl._document_getDoctype(this); + } + + public Element getDocumentElement() { + return DomImpl._document_getDocumentElement(this); + } + + public Element getElementById(String elementId) { + return DomImpl._document_getElementById(this, elementId); + } + + public NodeList getElementsByTagName(String tagname) { + return DomImpl._document_getElementsByTagName(this, tagname); + } + + public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { + return DomImpl._document_getElementsByTagNameNS(this, namespaceURI, localName); + } + + public DOMImplementation getImplementation() { + return DomImpl._document_getImplementation(this); + } + + public Node importNode(Node importedNode, boolean deep) { + return DomImpl._document_importNode(this, importedNode, deep); + } + + public int getLength() { + return DomImpl._childNodes_getLength(this); + } + + public Node item(int i) { + return DomImpl._childNodes_item(this, i); + } + + public void removeAllMimeHeaders() { + DomImpl._soapPart_removeAllMimeHeaders(this); + } + + public void removeMimeHeader(String name) { + DomImpl._soapPart_removeMimeHeader(this, name); + } + + public Iterator getAllMimeHeaders() { + return DomImpl._soapPart_getAllMimeHeaders(this); + } + + public SOAPEnvelope getEnvelope() { + return DomImpl._soapPart_getEnvelope(this); + } + + public Source getContent() { + return DomImpl._soapPart_getContent(this); + } + + public void setContent(Source source) { + DomImpl._soapPart_setContent(this, source); + } + + public String[] getMimeHeader(String name) { + return DomImpl._soapPart_getMimeHeader(this, name); + } + + public void addMimeHeader(String name, String value) { + DomImpl._soapPart_addMimeHeader(this, name, value); + } + + public void setMimeHeader(String name, String value) { + DomImpl._soapPart_setMimeHeader(this, name, value); + } + + public Iterator getMatchingMimeHeaders(String[] names) { + return DomImpl._soapPart_getMatchingMimeHeaders(this, names); + } + + public Iterator getNonMatchingMimeHeaders(String[] names) { + return DomImpl._soapPart_getNonMatchingMimeHeaders(this, names); + } + + public boolean nodeCanHavePrefixUri() { + return true; + } + + SoapPartDocXobj _docXobj; +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/store/TextNode.java b/src/main/java/org/apache/xmlbeans/impl/store/TextNode.java new file mode 100644 index 0000000..c7f33ec --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/TextNode.java @@ -0,0 +1,48 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.w3c.dom.Text; + +class TextNode extends CharNode implements Text { + TextNode(Locale l) { + super(l); + } + + public int nodeType() { + return DomImpl.TEXT; + } + + public String name() { + return "#text"; + } + + public Text splitText(int offset) { + return DomImpl._text_splitText(this, offset); + } + + public String getWholeText() { + return DomImpl._text_getWholeText(this); + } + + public boolean isElementContentWhitespace() { + return DomImpl._text_isElementContentWhitespace(this); + } + + public Text replaceWholeText(String content) { + return DomImpl._text_replaceWholeText(this, content); + } +} diff --git a/src/store/org/apache/xmlbeans/impl/store/Validate.java b/src/main/java/org/apache/xmlbeans/impl/store/Validate.java similarity index 95% rename from src/store/org/apache/xmlbeans/impl/store/Validate.java rename to src/main/java/org/apache/xmlbeans/impl/store/Validate.java index fadfa2b..e866448 100644 --- a/src/store/org/apache/xmlbeans/impl/store/Validate.java +++ b/src/main/java/org/apache/xmlbeans/impl/store/Validate.java @@ -42,9 +42,9 @@ final class Validate implements ValidatorListener.Event { _cur.pop(); _cur = null; - + _sink = null; - + _textCur.release(); } } @@ -57,7 +57,7 @@ private void process ( ) { // If validating an attr, I'm really validating the contents of that attr. So, go to // any text value and shove it thru the validator. - + _cur.next(); if (_cur.isText()) @@ -68,7 +68,7 @@ private void process ( ) assert _cur.isContainer(); // Do the attrs of the top container - + doAttrs(); for ( _cur.next() ; ! _cur.isAtEndOfLastPush() ; _cur.next() ) @@ -79,15 +79,15 @@ private void process ( ) emitEvent( ValidatorListener.BEGIN ); doAttrs(); break; - + case - Cur.ELEM : emitEvent( ValidatorListener.END ); break; - + case Cur.TEXT : emitText(); break; - + case Cur.COMMENT : case Cur.PROCINST : _cur.toEnd(); @@ -98,7 +98,7 @@ private void process ( ) } } } - + emitEvent( ValidatorListener.END ); } @@ -106,9 +106,9 @@ private void doAttrs ( ) { // When processing attrs, there can be no accumulated text because there would have been // a preceeding event which would have flushged the text. - + assert !_hasText; - + if (_cur.toFirstAttr()) { do @@ -120,7 +120,7 @@ private void doAttrs ( ) _cur.toParent(); } - + _sink.nextEvent( ValidatorListener.ENDATTRS, this ); } @@ -144,9 +144,9 @@ private void emitText ( ) _oneChunk = false; } - + assert _textSb != null && _textSb.length() > 0; - + CharUtil.getString( _textSb, _cur.getChars( -1 ), _cur._offSrc, _cur._cchSrc ); } else @@ -181,7 +181,7 @@ public String getText ( ) assert _oneChunk || (_textSb != null && _textSb.length() > 0); assert !_oneChunk || _textCur.isText(); - return _oneChunk ? _textCur.getCharsAsString( -1 ) : _textSb.toString(); + return _oneChunk ? _textCur.getCharsAsString() : _textSb.toString(); } public String getText ( int wsr ) @@ -194,7 +194,7 @@ public String getText ( int wsr ) assert !_oneChunk || _textCur.isText(); if (_oneChunk) - return _textCur.getCharsAsString( -1, wsr ); + return _textCur.getCharsAsString( wsr ); return Locale.applyWhiteSpaceRule( _textSb.toString(), wsr ); } @@ -207,7 +207,7 @@ public boolean textIsWhitespace ( ) _cur._locale.getCharUtil().isWhiteSpace( _cur.getFirstChars(), _cur._offSrc, _cur._cchSrc ); } - + assert _hasText; if (_oneChunk) @@ -218,7 +218,7 @@ public boolean textIsWhitespace ( ) } String s = _textSb.toString(); - + return _cur._locale.getCharUtil().isWhiteSpace( s, 0, s.length() ); } @@ -275,7 +275,7 @@ public QName getName ( ) // This way, when I turn the text into a String, I can cache the string. If multiple chunks // of text exists for one event, then I accumulate all the text into a string buffer and I, // then, don't care about caching Strings. - + private boolean _hasText; private boolean _oneChunk; diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java b/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java new file mode 100644 index 0000000..082eb62 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java @@ -0,0 +1,2437 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.store; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidatorListener; +import org.apache.xmlbeans.impl.common.XmlLocale; +import org.apache.xmlbeans.impl.store.DomImpl.Dom; +import org.apache.xmlbeans.impl.values.TypeStore; +import org.apache.xmlbeans.impl.values.TypeStoreUser; +import org.apache.xmlbeans.impl.values.TypeStoreUserFactory; +import org.apache.xmlbeans.impl.values.TypeStoreVisitor; +import org.apache.xmlbeans.impl.xpath.XPathFactory; + +import javax.xml.namespace.QName; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.apache.xmlbeans.impl.store.Cur.*; + +// DOM Level 3 + +abstract class Xobj implements TypeStore { + + Xobj(Locale l, int kind, int domType) { + assert kind == ROOT || kind == ELEM || kind == ATTR || kind == COMMENT || kind == PROCINST; + + _locale = l; + _bits = (domType << 4) + kind; + } + + final int kind() { + return _bits & 0xF; + } + + final int domType() { + return (_bits & 0xF0) >> 4; + } + + final boolean isRoot() { + return kind() == ROOT; + } + + final boolean isAttr() { + return kind() == ATTR; + } + + final boolean isElem() { + return kind() == ELEM; + } + + final boolean isProcinst() { + return kind() == PROCINST; + } + + final boolean isComment() { + return kind() == COMMENT; + } + + final boolean isContainer() { + return Cur.kindIsContainer(kind()); + } + + final boolean isUserNode() { + int k = kind(); + return k == ELEM || k == ROOT || (k == ATTR && !isXmlns()); + } + + final boolean isNormalAttr() { + return isAttr() && !Locale.isXmlns(_name); + } + + final boolean isXmlns() { + return isAttr() && Locale.isXmlns(_name); + } + + final int cchAfter() { + return _cchAfter; + } + + final int posAfter() { + return 2 + _cchValue; + } + + final int posMax() { + return 2 + _cchValue + _cchAfter; + } + + final String getXmlnsPrefix() { + return Locale.xmlnsPrefix(_name); + } + + final String getXmlnsUri() { + return getValueAsString(); + } + + final boolean hasTextEnsureOccupancy() { + ensureOccupancy(); + return hasTextNoEnsureOccupancy(); + } + + final boolean hasTextNoEnsureOccupancy() { + if (_cchValue > 0) { + return true; + } + + Xobj lastAttr = lastAttr(); + + return lastAttr != null && lastAttr._cchAfter > 0; + } + + final boolean hasAttrs() { + return _firstChild != null && _firstChild.isAttr(); + } + + final boolean hasChildren() { + return _lastChild != null && !_lastChild.isAttr(); + } + + + /** + * this method is to speed up DomImpl + * when underlying obj is an Xobj + * + * @return 0 or 1 dom children; val 2 indicates that DomImpl needs to + * compute the result itself + */ + final protected int getDomZeroOneChildren() { + if (_firstChild == null && + _srcValue == null && + _charNodesValue == null) { + return 0; + } + + if (_lastChild != null && + _lastChild.isAttr() && + _lastChild._charNodesAfter == null && + _lastChild._srcAfter == null && + _srcValue == null && + _charNodesValue == null + ) { + return 0; + } + + if (_firstChild == _lastChild && + _firstChild != null && + !_firstChild.isAttr() && + _srcValue == null && + _charNodesValue == null && + _firstChild._srcAfter == null + ) { + return 1; + } + + if (_firstChild == null && + _srcValue != null && + (_charNodesValue == null || + (_charNodesValue._next == null && + _charNodesValue._cch == _cchValue)) + ) { + return 1; + } + //single elem after an attr + Xobj lastAttr = lastAttr(); + Xobj node = lastAttr == null ? + null : lastAttr._nextSibling; + if (lastAttr != null && + lastAttr._srcAfter == null && + node != null && + node._srcAfter == null && + node._nextSibling == null) { + return 1; + } + + return 2; + } + + /** + * can one use the _firstChild pointer to retrieve + * the first DOM child + */ + final protected boolean isFirstChildPtrDomUsable() { + if (_firstChild == null && + _srcValue == null && + _charNodesValue == null) { + return true; + } + + if (_firstChild != null && + !_firstChild.isAttr() && + _srcValue == null && + _charNodesValue == null) { + assert (_firstChild instanceof NodeXobj) : + "wrong node type"; + return true; + } + return false; + } + + /** + * can one use the _nextSibling pointer to retrieve + * the next DOM sibling + */ + final protected boolean isNextSiblingPtrDomUsable() { + if (_charNodesAfter == null && + _srcAfter == null) { + assert (_nextSibling == null || + _nextSibling instanceof NodeXobj) : + "wrong node type"; + return true; + } + return false; + } + + /** + * can one use the _charNodesValue pointer to retrieve + * the next DOM sibling + */ + final protected boolean isExistingCharNodesValueUsable() { + if (_srcValue == null) { + return false; + } + return _charNodesValue != null && _charNodesValue._next == null + && _charNodesValue._cch == _cchValue; + } + + final protected boolean isCharNodesValueUsable() { + return isExistingCharNodesValueUsable() || + (_charNodesValue = + Cur.updateCharNodes(_locale, this, + _charNodesValue, _cchValue)) != null; + } + + /** + * can one use the _charNodesAfter pointer to retrieve + * the next DOM sibling + */ + final protected boolean isCharNodesAfterUsable() { + if (_srcAfter == null) { + return false; + } + if (_charNodesAfter != null && _charNodesAfter._next == null + && _charNodesAfter._cch == this._cchAfter) { + return true; + } + return (_charNodesAfter = + Cur.updateCharNodes(_locale, this, + _charNodesAfter, _cchAfter)) != null; + } + + + final Xobj lastAttr() { + if (_firstChild == null || !_firstChild.isAttr()) { + return null; + } + + Xobj lastAttr = _firstChild; + + while (lastAttr._nextSibling != null && lastAttr._nextSibling.isAttr()) { + lastAttr = lastAttr._nextSibling; + } + + return lastAttr; + } + + abstract Dom getDom(); + + abstract Xobj newNode(Locale l); + + final int cchLeft(int p) { + if (isRoot() && p == 0) { + return 0; + } + + Xobj x = getDenormal(p); + + p = posTemp(); + int pa = x.posAfter(); + + return p - (p < pa ? 1 : pa); + } + + final int cchRight(int p) { + assert p < posMax(); + + if (p <= 0) { + return 0; + } + + int pa = posAfter(); + + return p < pa ? pa - p - 1 : posMax() - p; + } + + // + // Dom interface + // + + public final Locale locale() { + return _locale; + } + + public final int nodeType() { + return domType(); + } + + public final QName getQName() { + return _name; + } + + public final Cur tempCur() { + Cur c = _locale.tempCur(); + c.moveTo(this); + return c; + } + + public void dump(PrintStream o, Object ref) { + Cur.dump(o, this, ref); + } + + public void dump(PrintStream o) { + Cur.dump(o, this, this); + } + + public void dump() { + dump(System.out); + } + + // + // + // + + final Cur getEmbedded() { + _locale.embedCurs(); + + return _embedded; + } + + // Incoming p must be at text (implicitly denormalized) + + final boolean inChars(int p, Xobj xIn, int pIn, int cch, boolean includeEnd) { + assert p > 0 && p < posMax() && p != posAfter() - 1 && cch > 0; + assert xIn.isNormal(pIn); + + // No need to denormalize "in" if the right hand side is excluded. Denormalizing deals + // with the case where p is END_POS. + + int offset; + + if (includeEnd) { + // Can't denormalize at the beginning of the document + + if (xIn.isRoot() && pIn == 0) { + return false; + } + + xIn = xIn.getDenormal(pIn); + pIn = xIn.posTemp(); + + offset = 1; + } else { + offset = 0; + } + + return xIn == this && pIn >= p && pIn < p + cch + offset; + } + + // Is x/p just after the end of this + + final boolean isJustAfterEnd(Xobj x, int p) { + assert x.isNormal(p); + + // Get denormalize at the beginning of the doc + + if (x.isRoot() && p == 0) { + return false; + } + + return + x == this + ? p == posAfter() + : x.getDenormal(p) == this && x.posTemp() == posAfter(); + } + + final boolean isInSameTree(Xobj x) { + if (_locale != x._locale) { + return false; + } + + for (Xobj y = this; ; y = y._parent) { + if (y == x) { + return true; + } + + if (y._parent == null) { + for (; ; x = x._parent) { + if (x == this) { + return true; + } + + if (x._parent == null) { + return x == y; + } + } + } + } + } + + final boolean contains(Cur c) { + assert c.isNormal(); + + return contains(c._xobj, c._pos); + } + + final boolean contains(Xobj x, int p) { + assert x.isNormal(p); + + if (this == x) { + return p == END_POS || (p > 0 && p < posAfter()); + } + + if (_firstChild == null) { + return false; + } + + for (; x != null; x = x._parent) { + if (x == this) { + return true; + } + } + + return false; + } + + final Bookmark setBookmark(int p, Object key, Object value) { + assert isNormal(p); + + for (Bookmark b = _bookmarks; b != null; b = b._next) { + if (p == b._pos && key == b._key) { + if (value == null) { + _bookmarks = b.listRemove(_bookmarks); + return null; + } + + b._value = value; + + return b; + } + } + + if (value == null) { + return null; + } + + Bookmark b = new Bookmark(); + + b._xobj = this; + b._pos = p; + b._key = key; + b._value = value; + + _bookmarks = b.listInsert(_bookmarks); + + return b; + } + + final boolean hasBookmark(Object key, int pos) { + for (Bookmark b = _bookmarks; b != null; b = b._next) { + if (b._pos == pos && key == b._key) { + //System.out.println("hasCDataBookmark pos: " + pos + " xobj: " + getQName() + " b._pos: " + _bookmarks._pos); + return true; + } + } + + return false; + } + + final Xobj findXmlnsForPrefix(String prefix) { + assert isContainer() && prefix != null; + + for (Xobj c = this; c != null; c = c._parent) { + for (Xobj a = c.firstAttr(); a != null; a = a.nextAttr()) { + if (a.isXmlns() && a.getXmlnsPrefix().equals(prefix)) { + return a; + } + } + } + + return null; + } + + final boolean removeAttr(QName name) { + assert isContainer(); + + Xobj a = getAttr(name); + + if (a == null) { + return false; + } + + Cur c = a.tempCur(); + + for (; ; ) { + c.moveNode(null); + + a = getAttr(name); + + if (a == null) { + break; + } + + c.moveTo(a); + } + + c.release(); + + return true; + } + + final Xobj setAttr(QName name, String value) { + assert isContainer(); + + Cur c = tempCur(); + + if (c.toAttr(name)) { + c.removeFollowingAttrs(); + } else { + c.next(); + c.createAttr(name); + } + + c.setValue(value); + + Xobj a = c._xobj; + + c.release(); + + return a; + } + + final void setName(QName newName) { + assert isAttr() || isElem() || isProcinst(); + assert newName != null; + + if (!_name.equals(newName) || !_name.getPrefix().equals(newName.getPrefix())) { +// TODO - this is not a structural change .... perhaps should not issue a change here? + _locale.notifyChange(); + + QName oldName = _name; + + _name = newName; + if (this instanceof NamedNodeXobj) { + NamedNodeXobj me = (NamedNodeXobj) this; + me._canHavePrefixUri = true; + } + + if (!isProcinst()) { + Xobj disconnectFromHere = this; + + if (isAttr() && _parent != null) { + if (oldName.equals(Locale._xsiType) || newName.equals(Locale._xsiType)) { + disconnectFromHere = _parent; + } + + if (oldName.equals(Locale._xsiNil) || newName.equals(Locale._xsiNil)) { + _parent.invalidateNil(); + } + } + + disconnectFromHere.disconnectNonRootUsers(); + } + + _locale._versionAll++; + _locale._versionSansText++; + } + } + + final Xobj ensureParent() { + assert _parent != null || (!isRoot() && cchAfter() == 0); + return _parent == null ? new DocumentFragXobj(_locale).appendXobj(this) : _parent; + } + + final Xobj firstAttr() { + return _firstChild == null || !_firstChild.isAttr() ? null : _firstChild; + } + + final Xobj nextAttr() { + if (_firstChild != null && _firstChild.isAttr()) { + return _firstChild; + } + + if (_nextSibling != null && _nextSibling.isAttr()) { + return _nextSibling; + } + + return null; + } + + final boolean isValid() { + return !isVacant() || (_cchValue == 0 && _user != null); + } + + final int posTemp() { + return _locale._posTemp; + } + + final Xobj getNormal(int p) { + assert p == END_POS || (p >= 0 && p <= posMax()); + + Xobj x = this; + + if (p == x.posMax()) { + if (x._nextSibling != null) { + x = x._nextSibling; + p = 0; + } else { + x = x.ensureParent(); + p = END_POS; + } + } else if (p == x.posAfter() - 1) { + p = END_POS; + } + + _locale._posTemp = p; + + return x; + } + + // Can't denormalize a position at the very beginning of the document. No where to go to the + // left! + + final Xobj getDenormal(int p) { + assert !isRoot() || p == END_POS || p > 0; + + Xobj x = this; + + if (p == 0) { + if (x._prevSibling == null) { + x = x.ensureParent(); + p = x.posAfter() - 1; + } else { + x = x._prevSibling; + p = x.posMax(); + } + } else if (p == END_POS) { + if (x._lastChild == null) { + p = x.posAfter() - 1; + } else { + x = x._lastChild; + p = x.posMax(); + } + } + + _locale._posTemp = p; + + return x; + } + + final boolean isNormal(int p) { + if (!isValid()) { + return false; + } + + if (p == END_POS || p == 0) { + return true; + } + + if (p < 0 || p >= posMax()) { + return false; + } + + if (p >= posAfter()) { + if (isRoot()) { + return false; + } + + if (_nextSibling != null && _nextSibling.isAttr()) { + return false; + } + + if (_parent == null || !_parent.isContainer()) { + return false; + } + } + + return p != posAfter() - 1; + } + + final Xobj walk(Xobj root, boolean walkChildren) { + if (_firstChild != null && walkChildren) { + return _firstChild; + } + + for (Xobj x = this; x != root; x = x._parent) { + if (x._nextSibling != null) { + return x._nextSibling; + } + } + + return null; + } + + final void removeXobj() { + if (_parent != null) { + if (_parent._firstChild == this) { + _parent._firstChild = _nextSibling; + } + + if (_parent._lastChild == this) { + _parent._lastChild = _prevSibling; + } + + if (_prevSibling != null) { + _prevSibling._nextSibling = _nextSibling; + } + + if (_nextSibling != null) { + _nextSibling._prevSibling = _prevSibling; + } + + _parent = null; + _prevSibling = null; + _nextSibling = null; + } + + } + + final void insertXobj(Xobj s) { + assert _locale == s._locale; + assert !s.isRoot() && !isRoot(); + assert s._parent == null; + assert s._prevSibling == null; + assert s._nextSibling == null; + + ensureParent(); + + s._parent = _parent; + s._prevSibling = _prevSibling; + s._nextSibling = this; + + if (_prevSibling != null) { + _prevSibling._nextSibling = s; + } else { + _parent._firstChild = s; + } + + _prevSibling = s; + + } + + final Xobj appendXobj(Xobj c) { + assert _locale == c._locale; + assert !c.isRoot(); + assert c._parent == null; + assert c._prevSibling == null; + assert c._nextSibling == null; + assert _lastChild == null || _firstChild != null; + + c._parent = this; + c._prevSibling = _lastChild; + + if (_lastChild == null) { + _firstChild = c; + } else { + _lastChild._nextSibling = c; + } + + _lastChild = c; + + return this; + } + + final void removeXobjs(Xobj first, Xobj last) { + assert last._locale == first._locale; + assert first._parent == this; + assert last._parent == this; + + if (_firstChild == first) { + _firstChild = last._nextSibling; + } + + if (_lastChild == last) { + _lastChild = first._prevSibling; + } + + if (first._prevSibling != null) { + first._prevSibling._nextSibling = last._nextSibling; + } + + if (last._nextSibling != null) { + last._nextSibling._prevSibling = first._prevSibling; + } + + // Leave the children linked together + + first._prevSibling = null; + last._nextSibling = null; + + for (; first != null; first = first._nextSibling) { + first._parent = null; + } + } + + final void insertXobjs(Xobj first, Xobj last) { + assert _locale == first._locale; + assert last._locale == first._locale; + assert first._parent == null && last._parent == null; + assert first._prevSibling == null; + assert last._nextSibling == null; + + first._prevSibling = _prevSibling; + last._nextSibling = this; + + if (_prevSibling != null) { + _prevSibling._nextSibling = first; + } else { + _parent._firstChild = first; + } + + _prevSibling = last; + + for (; first != this; first = first._nextSibling) { + first._parent = _parent; + } + } + + final void appendXobjs(Xobj first, Xobj last) { + assert _locale == first._locale; + assert last._locale == first._locale; + assert first._parent == null && last._parent == null; + assert first._prevSibling == null; + assert last._nextSibling == null; + assert !first.isRoot(); + + first._prevSibling = _lastChild; + + if (_lastChild == null) { + _firstChild = first; + } else { + _lastChild._nextSibling = first; + } + + _lastChild = last; + + for (; first != null; first = first._nextSibling) { + first._parent = this; + } + } + + // Potential attr is going to be moved/removed, invalidate parent if it is a special attr + + final void invalidateSpecialAttr(Xobj newParent) { + if (isAttr()) { + if (_name.equals(Locale._xsiType)) { + if (_parent != null) { + _parent.disconnectNonRootUsers(); + } + + if (newParent != null) { + newParent.disconnectNonRootUsers(); + } + } + + if (_name.equals(Locale._xsiNil)) { + if (_parent != null) { + _parent.invalidateNil(); + } + + if (newParent != null) { + newParent.invalidateNil(); + } + } + } + } + + // Move or remove chars. Incoming p is denormalized. Incoming xTo and pTo are denormalized. + // Option to move curs with text. Option to perform invalidations. + // + // Important note: this fcn must operate under the assumption that the tree may be in an + // invalid state. Most likely, there may be text on two different nodes which should belong + // on the same node. Assertion of cursor normalization usually detects this problem. Any of + // the fcns it calls must also deal with these invalid conditions. Try not to call so many + // fcns from here. + + final void removeCharsHelper( + int p, int cchRemove, Xobj xTo, int pTo, boolean moveCurs, boolean invalidate) { + assert p > 0 && p < posMax() && p != posAfter() - 1; + assert cchRemove > 0; + assert cchRight(p) >= cchRemove; + assert !moveCurs || xTo != null; + + // Here I check the span of text to be removed for cursors. If xTo/pTo is not specified, + // then the caller wants these cursors to collapse to be after the text being removed. If + // the caller specifies moveCurs, then the caller has arranged for the text being removed + // to have been copied to xTp/pTo and wants the cursors to be moved there as well. + // Note that I call nextChars here. I do this because trying to shift the cursor to the + // end of the text to be removed with a moveTo could cause the improper placement of the + // cursor just before an end tag, instead of placing it just before the first child. Also, + // I adjust all positions of curs after the text to be removed to account for the removal. + + for (Cur c = getEmbedded(); c != null; ) { + Cur next = c._next; + + // Here I test to see if the Cur c is in the range of chars to be removed. Normally + // I would call inChars, but it can't handle the invalidity of the tree, so I heve + // inlined the inChars logic here (includeEnd is false, makes it much simpler). + // Note that I also call moveToNoCheck because the destination may have afterText + // and no parent which will cause normaliztion checks in MoveTo to fail. I don't think + // that nextChars will be called under such circumstnaces. + + assert c._xobj == this; + + if (c._pos >= p && c._pos < p + cchRemove) { + if (moveCurs) { + c.moveToNoCheck(xTo, pTo + c._pos - p); + } else { + c.nextChars(cchRemove - c._pos + p); + } + } + + // If c is still on this Xobj and it's to the right of the chars to remove, adjust + // it to adapt to the removal of the cars. I don't have to worry about END_POS + // here, just curs in text. + + if (c._xobj == this && c._pos >= p + cchRemove) { + c._pos -= cchRemove; + } + + c = next; + } + + // Here I move bookmarks in this text to the span of text at xTo/pTo. The text at this/p + // is going away, but a caller of this fcn who specifies xTo/pTo has copied the text to + // xTo/pTo. The caller has to make sure that if xTo/pTo is not specified, then there are + // no bookmarks in the span of text to be removed. + + for (Bookmark b = _bookmarks; b != null; ) { + // Similarly, as above, I can't call inChars here + + assert b._xobj == this; + + if (b._pos >= p && b._pos < p + cchRemove) { + assert xTo != null; + b.moveTo(xTo, pTo + b._pos - p); + } + + if (b._xobj == this && b._pos >= p + cchRemove) { + b._pos -= cchRemove; + } + + b = b._next; + } + + // Now, remove the actual chars + + int pa = posAfter(); + CharUtil cu = _locale.getCharUtil(); + + if (p < pa) { + _srcValue = cu.removeChars(p - 1, cchRemove, _srcValue, _offValue, _cchValue); + _offValue = cu._offSrc; + _cchValue = cu._cchSrc; + + if (invalidate) { + invalidateUser(); + invalidateSpecialAttr(null); + } + } else { + _srcAfter = cu.removeChars(p - pa, cchRemove, _srcAfter, _offAfter, _cchAfter); + _offAfter = cu._offSrc; + _cchAfter = cu._cchSrc; + + if (invalidate && _parent != null) { + _parent.invalidateUser(); + } + } + } + + // Insert chars into this xobj. Incoming p is denormalized. Update bookmarks and cursors. + // This fcn does not deal with occupation of the value, this needs to be handled by the + // caller. + + final void insertCharsHelper(int p, Object src, int off, int cch, boolean invalidate) { + assert p > 0; + assert p >= posAfter() || isOccupied(); + + int pa = posAfter(); + + // Here I shuffle bookmarks and cursors affected by the insertion of the new text. Because + // getting the embedded cursors is non-trivial, I avoid getting them if I don't need to. + // Basically, I need to know if p is before any text in the node as a whole. If it is, + // then there may be cursors/marks I need to shift right. + + if (p - (p < pa ? 1 : 2) < _cchValue + _cchAfter) { + for (Cur c = getEmbedded(); c != null; c = c._next) { + if (c._pos >= p) { + c._pos += cch; + } + } + + for (Bookmark b = _bookmarks; b != null; b = b._next) { + if (b._pos >= p) { + b._pos += cch; + } + } + } + + // Now, stuff the new characters in! Also invalidate the proper container and if the + // value of an attribute is changing, check for special attr invalidation. Note that + // I do not assume that inserting after text will have a parent. There are use cases + // from moveNodesContents which excersize this. + + CharUtil cu = _locale.getCharUtil(); + + if (p < pa) { + _srcValue = cu.insertChars(p - 1, _srcValue, _offValue, _cchValue, src, off, cch); + _offValue = cu._offSrc; + _cchValue = cu._cchSrc; + + if (invalidate) { + invalidateUser(); + invalidateSpecialAttr(null); + } + } else { + _srcAfter = cu.insertChars(p - pa, _srcAfter, _offAfter, _cchAfter, src, off, cch); + _offAfter = cu._offSrc; + _cchAfter = cu._cchSrc; + + if (invalidate && _parent != null) { + _parent.invalidateUser(); + } + } + } + + Xobj copyNode(Locale toLocale) { + Xobj newParent = null; + Xobj copy = null; + + for (Xobj x = this; ; ) { + x.ensureOccupancy(); + + Xobj newX = x.newNode(toLocale); + + newX._srcValue = x._srcValue; + newX._offValue = x._offValue; + newX._cchValue = x._cchValue; + + newX._srcAfter = x._srcAfter; + newX._offAfter = x._offAfter; + newX._cchAfter = x._cchAfter; + + for (Bookmark b = x._bookmarks; b != null; b = b._next) { + if (x.hasBookmark(CDataBookmark.CDATA_BOOKMARK.getKey(), b._pos)) { + newX.setBookmark(b._pos, CDataBookmark.CDATA_BOOKMARK.getKey(), CDataBookmark.CDATA_BOOKMARK); + } + } + // TODO - strange to have charNode stuff inside here ..... + // newX._charNodesValue = CharNode.copyNodes( x._charNodesValue, newX._srcValue ); + // newX._charNodesAfter = CharNode.copyNodes( x._charNodesAfter, newX._srcAfter ); + + if (newParent == null) { + copy = newX; + } else { + newParent.appendXobj(newX); + } + + // Walk to the next in-order xobj. Record the current (y) to compute newParent + + Xobj y = x; + + if ((x = x.walk(this, true)) == null) { + break; + } + + if (y == x._parent) { + newParent = newX; + } else { + for (; y._parent != x._parent; y = y._parent) { + newParent = newParent._parent; + } + } + } + + copy._srcAfter = null; + copy._offAfter = 0; + copy._cchAfter = 0; + + return copy; + } + + // Rturns all the chars, even if there is text intermixed with children + + String getCharsAsString(int p, int cch, int wsr) { + if (cchRight(p) == 0) { + return ""; + } + + Object src = getChars(p, cch); + + if (wsr == WS_PRESERVE) { + return CharUtil.getString(src, _locale._offSrc, _locale._cchSrc); + } + + Locale.ScrubBuffer scrub = Locale.getScrubBuffer(wsr); + + scrub.scrub(src, _locale._offSrc, _locale._cchSrc); + + return scrub.getResultAsString(); + } + + String getCharsAfterAsString(int off, int cch) { + int offset = off + _cchValue + 2; + if (offset == posMax()) { + offset = -1; + } + return getCharsAsString(offset, cch, WS_PRESERVE); + } + + String getCharsValueAsString(int off, int cch) { + return getCharsAsString(off + 1, cch, WS_PRESERVE); + } + + String getValueAsString(int wsr) { + if (!hasChildren()) { + Object src = getFirstChars(); + + if (wsr == WS_PRESERVE) { + String s = CharUtil.getString(src, _locale._offSrc, _locale._cchSrc); + + // Cache string to be able to use it later again + + int cch = s.length(); + + if (cch > 0) { + Xobj lastAttr = lastAttr(); + + assert (lastAttr == null ? _cchValue : lastAttr._cchAfter) == cch; + + if (lastAttr != null) { + lastAttr._srcAfter = s; + lastAttr._offAfter = 0; + } else { + _srcValue = s; + _offValue = 0; + } + } + + return s; + } + + Locale.ScrubBuffer scrub = Locale.getScrubBuffer(wsr); + + scrub.scrub(src, _locale._offSrc, _locale._cchSrc); + + return scrub.getResultAsString(); + } + + Locale.ScrubBuffer scrub = Locale.getScrubBuffer(wsr); + + Cur c = tempCur(); + + c.push(); + + for (c.next(); !c.isAtEndOfLastPush(); ) { + if (c.isText()) { + scrub.scrub(c.getChars(-1), c._offSrc, c._cchSrc); + } + + if (c.isComment() || c.isProcinst()) { + c.skip(); + } else { + c.next(); + } + } + + String s = scrub.getResultAsString(); + + c.release(); + + return s; + } + + String getValueAsString() { + return getValueAsString(WS_PRESERVE); + } + + // Returns just chars just after the begin tag ... does not get all the text if there are + // children + + Object getFirstChars() { + ensureOccupancy(); + + if (_cchValue > 0) { + return getChars(1, -1); + } + + Xobj lastAttr = lastAttr(); + + if (lastAttr == null || lastAttr._cchAfter <= 0) { + _locale._offSrc = 0; + _locale._cchSrc = 0; + + return null; + } + + return lastAttr.getChars(lastAttr.posAfter(), -1); + } + + Object getChars(int pos, int cch, Cur c) { + Object src = getChars(pos, cch); + + c._offSrc = _locale._offSrc; + c._cchSrc = _locale._cchSrc; + + return src; + } + + // These return the remainder of the char triple that getChars starts + + Object getChars(int pos, int cch) { + assert isNormal(pos); + + int cchRight = cchRight(pos); + + if (cch < 0 || cch > cchRight) { + cch = cchRight; + } + + if (cch == 0) { + _locale._offSrc = 0; + _locale._cchSrc = 0; + + return null; + } + + return getCharsHelper(pos, cch); + } + + // Assumes that there are chars to return, does not assume normal x/p + + Object getCharsHelper(int pos, int cch) { + assert cch > 0 && cchRight(pos) >= cch; + + int pa = posAfter(); + + Object src; + + if (pos >= pa) { + src = _srcAfter; + _locale._offSrc = _offAfter + pos - pa; + } else { + src = _srcValue; + _locale._offSrc = _offValue + pos - 1; + } + + _locale._cchSrc = cch; + + return src; + } + + // + // + // + + final void setBit(int mask) { + _bits |= mask; + } + + final void clearBit(int mask) { + _bits &= ~mask; + } + + final boolean bitIsSet(int mask) { + return (_bits & mask) != 0; + } + + final boolean bitIsClear(int mask) { + return (_bits & mask) == 0; + } + + static final int VACANT = 0x100; + static final int STABLE_USER = 0x200; + static final int INHIBIT_DISCONNECT = 0x400; + + final boolean isVacant() { + return bitIsSet(VACANT); + } + + final boolean isOccupied() { + return bitIsClear(VACANT); + } + + final boolean inhibitDisconnect() { + return bitIsSet(INHIBIT_DISCONNECT); + } + + final boolean isStableUser() { + return bitIsSet(STABLE_USER); + } + + void invalidateNil() { + if (_user != null) { + _user.invalidate_nilvalue(); + } + } + + void setStableType(SchemaType type) { + setStableUser(((TypeStoreUserFactory) type).createTypeStoreUser()); + } + + void setStableUser(TypeStoreUser user) { + disconnectNonRootUsers(); + disconnectUser(); + + assert _user == null; + + _user = user; + + _user.attach_store(this); + + setBit(STABLE_USER); + } + + void disconnectUser() { + if (_user != null && !inhibitDisconnect()) { + ensureOccupancy(); + _user.disconnect_store(); + _user = null; + } + } + + // If a node does not have a user, then I don't need to walk its descendents. NOte that + // the doconnect happens in document order. This may be a problem ... not sure ... May want + // to disconnect in a bottom up manner. + + void disconnectNonRootUsers() { + Xobj next; + + for (Xobj x = this; x != null; x = next) { + next = x.walk(this, x._user != null); + + if (!x.isRoot()) { + x.disconnectUser(); + } + } + } + + void disconnectChildrenUsers() { + Xobj next; + + for (Xobj x = walk(this, _user == null); x != null; x = next) { + next = x.walk(this, x._user != null); + + x.disconnectUser(); + } + } + + /** + * Given a prefix, returns the namespace corresponding to + * the prefix at this location, or null if there is no mapping + * for this prefix. + *

      + * prefix="" indicates the absence of a prefix. A return value + * of "" indicates the no-namespace, and should not be confused + * with a return value of null, which indicates an illegal + * state, where there is no mapping for the given prefix. + *

      + * If the the default namespace is not explicitly mapped in the xml, + * the xml spec says that it should be mapped to the no-namespace. + * When the 'defaultAlwaysMapped' parameter is true, the default namepsace + * will return the no-namespace even if it is not explicity + * mapped, otherwise the default namespace will return null. + *

      + * This function intercepts the built-in prefixes "xml" and + * "xmlns" and returns their well-known namespace URIs. + * + * @param prefix The prefix to look up. + * @param defaultAlwaysMapped If true, return the no-namespace for the default namespace if not set. + * @return The mapped namespace URI ("" if no-namespace), or null if no mapping. + */ + + final String namespaceForPrefix(String prefix, boolean defaultAlwaysMapped) { + if (prefix == null) { + prefix = ""; + } + + // handle built-in prefixes + + if (prefix.equals("xml")) { + return Locale._xml1998Uri; + } + + if (prefix.equals("xmlns")) { + return Locale._xmlnsUri; + } + + for (Xobj x = this; x != null; x = x._parent) { + for (Xobj a = x._firstChild; a != null && a.isAttr(); a = a._nextSibling) { + if (a.isXmlns() && a.getXmlnsPrefix().equals(prefix)) { + return a.getXmlnsUri(); + } + } + } + + return defaultAlwaysMapped && prefix.length() == 0 ? "" : null; + } + + final String prefixForNamespace(String ns, String suggestion, boolean createIfMissing) { + if (ns == null) { + ns = ""; + } + + // special cases + + if (ns.equals(Locale._xml1998Uri)) { + return "xml"; + } + + if (ns.equals(Locale._xmlnsUri)) { + return "xmlns"; + } + + // Get the closest container for the spot we're on + + Xobj base = this; + + while (!base.isContainer()) { + base = base.ensureParent(); + } + + // Special handling for the no-namespace case + + if (ns.length() == 0) { + // Search for a namespace decl which defines the default namespace + + Xobj a = base.findXmlnsForPrefix(""); + + // If I did not find a default decl or the decl maps to the no namespace, then + // the default namespace is mapped to "" + + if (a == null || a.getXmlnsUri().length() == 0) { + return ""; + } + + // At this point, I've found a default namespace which is *not* the no-namespace. + // If I can't modify the document to mape the desired no-namespace, I must fail. + + if (!createIfMissing) { + return null; + } + + // Ok, I need to make the default namespace on the nearest container map to "" + + base.setAttr(_locale.createXmlns(null), ""); + + return ""; + } + + // Look for an exisiting mapping for the desired uri which has a visible prefix + + for (Xobj c = base; c != null; c = c._parent) { + for (Xobj a = c.firstAttr(); a != null; a = a.nextAttr()) { + if (a.isXmlns() && a.getXmlnsUri().equals(ns)) { + if (base.findXmlnsForPrefix(a.getXmlnsPrefix()) == a) { + return a.getXmlnsPrefix(); + } + } + } + } + + // No exisiting xmlns I can use, need to create one. See if I can first + + if (!createIfMissing) { + return null; + } + + // Sanitize the suggestion. + + if (suggestion != null && + (suggestion.length() == 0 || suggestion.toLowerCase(java.util.Locale.ROOT).startsWith("xml") || + base.findXmlnsForPrefix(suggestion) != null)) { + suggestion = null; + } + + // If no suggestion, make one up + + if (suggestion == null) { + String prefixBase = QNameHelper.suggestPrefix(ns); + + suggestion = prefixBase; + + for (int i = 1; ; suggestion = prefixBase + i++) { + if (base.findXmlnsForPrefix(suggestion) == null) { + break; + } + } + } + + // Add a new namespace decl at the top elem if one exists, otherwise at root + + Xobj c = base; + + while (!c.isRoot() && !c.ensureParent().isRoot()) { + c = c._parent; + } + + base.setAttr(_locale.createXmlns(suggestion), ns); + + return suggestion; + } + + final QName getValueAsQName() { + assert !hasChildren(); + + // TODO - + // caching the QName value in this object would prevent one from having + // to repeat all this string arithmatic over and over again. Perhaps + // when I make the store capable of handling strong simple types this + // can be done ... + + String value = getValueAsString(WS_COLLAPSE); + + String prefix, localname; + + int firstcolon = value.indexOf(':'); + + if (firstcolon >= 0) { + prefix = value.substring(0, firstcolon); + localname = value.substring(firstcolon + 1); + } else { + prefix = ""; + localname = value; + } + + String uri = namespaceForPrefix(prefix, true); + + if (uri == null) { + return null; // no prefix definition found - that's illegal + } + + return new QName(uri, localname); + } + + final Xobj getAttr(QName name) { + for (Xobj x = _firstChild; x != null && x.isAttr(); x = x._nextSibling) { + if (x._name.equals(name)) { + return x; + } + } + + return null; + } + + final QName getXsiTypeName() { + assert isContainer(); + + Xobj a = getAttr(Locale._xsiType); + + return a == null ? null : a.getValueAsQName(); + } + + final XmlObject getObject() { + return isUserNode() ? (XmlObject) getUser() : null; + } + + final TypeStoreUser getUser() { + assert isUserNode(); + assert _user != null || (!isRoot() && !isStableUser()); + + if (_user == null) { + // BUGBUG - this is recursive + + TypeStoreUser parentUser = + _parent == null + ? ((TypeStoreUserFactory) XmlBeans.NO_TYPE).createTypeStoreUser() + : _parent.getUser(); + + _user = + isElem() + ? parentUser.create_element_user(_name, getXsiTypeName()) + : parentUser.create_attribute_user(_name); + + _user.attach_store(this); + } + + return _user; + } + + final void invalidateUser() { + assert isValid(); + assert _user == null || isUserNode(); + + if (_user != null) { + _user.invalidate_value(); + } + } + + final void ensureOccupancy() { + assert isValid(); + + if (isVacant()) { + assert isUserNode(); + + // In order to use Cur to set the value, I mark the + // value as occupied and remove the user to prohibit + // further user invalidations + + clearBit(VACANT); + + TypeStoreUser user = _user; + _user = null; + + String value = user.build_text(this); + + + long saveVersion = _locale._versionAll; + long saveVersionSansText = _locale._versionSansText; + + + setValue(value); + assert saveVersionSansText == _locale._versionSansText; + + _locale._versionAll = saveVersion; + + + assert _user == null; + _user = user; + } + } + + private void setValue(String val) { + assert CharUtil.isValid(val, 0, val.length()); + + // Check for nothing to insert + + if (val.length() <= 0) { + return; + } + + _locale.notifyChange(); + Xobj lastAttr = lastAttr(); + int startPos = 1; + Xobj charOwner = this; + if (lastAttr != null) { + charOwner = lastAttr; + startPos = charOwner.posAfter(); + } + charOwner.insertCharsHelper(startPos, val, 0, val.length(), true); + } + // + // TypeStore + // + + public SchemaTypeLoader get_schematypeloader() { + return _locale._schemaTypeLoader; + } + + public XmlLocale get_locale() { + return _locale; + } + + // TODO - remove this when I've replaced the old store + public Object get_root_object() { + return _locale; + } + + public boolean is_attribute() { + assert isValid(); + return isAttr(); + } + + public boolean validate_on_set() { + assert isValid(); + return _locale._validateOnSet; + } + + public void invalidate_text() { + _locale.enter(); + + try { + assert isValid(); + + if (isOccupied()) { + if (hasTextNoEnsureOccupancy() || hasChildren()) { + TypeStoreUser user = _user; + _user = null; + + Cur c = tempCur(); + c.moveNodeContents(null, false); + c.release(); + + assert _user == null; + _user = user; + } + + setBit(VACANT); + } + + assert isValid(); + } finally { + _locale.exit(); + } + } + + public String fetch_text(int wsr) { + _locale.enter(); + + try { + assert isValid() && isOccupied(); + + return getValueAsString(wsr); + } finally { + _locale.exit(); + } + } + + public XmlCursor new_cursor() { + _locale.enter(); + + try { + Cur c = tempCur(); + XmlCursor xc = new Cursor(c); + c.release(); + return xc; + + } finally { + _locale.exit(); + } + } + + public SchemaField get_schema_field() { + assert isValid(); + + if (isRoot()) { + return null; + } + + TypeStoreUser parentUser = ensureParent().getUser(); + + if (isAttr()) { + return parentUser.get_attribute_field(_name); + } + + assert isElem(); + + TypeStoreVisitor visitor = parentUser.new_visitor(); + + if (visitor == null) { + return null; + } + + for (Xobj x = _parent._firstChild; ; x = x._nextSibling) { + if (x.isElem()) { + visitor.visit(x._name); + + if (x == this) { + return visitor.get_schema_field(); + } + } + } + } + + public void validate(ValidatorListener eventSink) { + _locale.enter(); + + try { + Cur c = tempCur(); + new Validate(c, eventSink); + c.release(); + } finally { + _locale.exit(); + } + } + + public TypeStoreUser change_type(SchemaType type) { + _locale.enter(); + + try { + Cur c = tempCur(); + c.setType(type, false); + c.release(); + } finally { + _locale.exit(); + } + + return getUser(); + } + + public TypeStoreUser substitute(QName name, SchemaType type) { + _locale.enter(); + + try { + Cur c = tempCur(); + c.setSubstitution(name, type); + c.release(); + } finally { + _locale.exit(); + } + + return getUser(); + } + + public QName get_xsi_type() { + return getXsiTypeName(); + } + + public void store_text(String text) { + _locale.enter(); + + TypeStoreUser user = _user; + _user = null; + + try { + Cur c = tempCur(); + + c.moveNodeContents(null, false); + + if (text != null && text.length() > 0) { + c.next(); + c.insertString(text); + } + + c.release(); + } finally { + assert _user == null; + _user = user; + + _locale.exit(); + } + } + + public int compute_flags() { + if (isRoot()) { + return 0; + } + + TypeStoreUser parentUser = ensureParent().getUser(); + + if (isAttr()) { + return parentUser.get_attributeflags(_name); + } + + int f = parentUser.get_elementflags(_name); + + if (f != -1) { + return f; + } + + TypeStoreVisitor visitor = parentUser.new_visitor(); + + if (visitor == null) { + return 0; + } + + for (Xobj x = _parent._firstChild; ; x = x._nextSibling) { + if (x.isElem()) { + visitor.visit(x._name); + + if (x == this) { + return visitor.get_elementflags(); + } + } + } + } + + public String compute_default_text() { + if (isRoot()) { + return null; + } + + TypeStoreUser parentUser = ensureParent().getUser(); + + if (isAttr()) { + return parentUser.get_default_attribute_text(_name); + } + + String result = parentUser.get_default_element_text(_name); + + if (result != null) { + return result; + } + + TypeStoreVisitor visitor = parentUser.new_visitor(); + + if (visitor == null) { + return null; + } + + for (Xobj x = _parent._firstChild; ; x = x._nextSibling) { + if (x.isElem()) { + visitor.visit(x._name); + + if (x == this) { + return visitor.get_default_text(); + } + } + } + } + + public boolean find_nil() { + if (isAttr()) { + return false; + } + + _locale.enter(); + + try { + Xobj a = getAttr(Locale._xsiNil); + + if (a == null) { + return false; + } + + String value = a.getValueAsString(WS_COLLAPSE); + + return value.equals("true") || value.equals("1"); + } finally { + _locale.exit(); + } + } + + public void invalidate_nil() { + if (isAttr()) { + return; + } + + _locale.enter(); + + try { + if (!_user.build_nil()) { + removeAttr(Locale._xsiNil); + } else { + setAttr(Locale._xsiNil, "true"); + } + } finally { + _locale.exit(); + } + } + + public int count_elements(QName name) { + return _locale.count(this, name, null); + } + + public int count_elements(QNameSet names) { + return _locale.count(this, null, names); + } + + public TypeStoreUser find_element_user(QName name, int i) { + for (Xobj x = _firstChild; x != null; x = x._nextSibling) { + if (x.isElem() && x._name.equals(name) && --i < 0) { + return x.getUser(); + } + } + + return null; + } + + public TypeStoreUser find_element_user(QNameSet names, int i) { + for (Xobj x = _firstChild; x != null; x = x._nextSibling) { + if (x.isElem() && names.contains(x._name) && --i < 0) { + return x.getUser(); + } + } + + return null; + } + + @SuppressWarnings("unchecked") + @Override + public void find_all_element_users(QName name, List fillMeUp) { + for (Xobj x = _firstChild; x != null; x = x._nextSibling) { + if (x.isElem() && x._name.equals(name)) { + fillMeUp.add((T) x.getUser()); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public void find_all_element_users(QNameSet names, List fillMeUp) { + for (Xobj x = _firstChild; x != null; x = x._nextSibling) { + if (x.isElem() && names.contains(x._name)) { + fillMeUp.add((T) x.getUser()); + } + } + } + + private static TypeStoreUser insertElement(QName name, Xobj x, int pos) { + x._locale.enter(); + + try { + Cur c = x._locale.tempCur(); + c.moveTo(x, pos); + c.createElement(name); + TypeStoreUser user = c.getUser(); + c.release(); + return user; + } finally { + x._locale.exit(); + } + } + + public TypeStoreUser insert_element_user(QName name, int i) { + if (i < 0) { + throw new IndexOutOfBoundsException(); + } + + if (!isContainer()) { + throw new IllegalStateException(); + } + + Xobj x = _locale.findNthChildElem(this, name, null, i); + + if (x == null) { + if (i > _locale.count(this, name, null) + 1) { + throw new IndexOutOfBoundsException(); + } + + return add_element_user(name); + } + + return insertElement(name, x, 0); + } + + public TypeStoreUser insert_element_user(QNameSet names, QName name, int i) { + if (i < 0) { + throw new IndexOutOfBoundsException(); + } + + if (!isContainer()) { + throw new IllegalStateException(); + } + + Xobj x = _locale.findNthChildElem(this, null, names, i); + + if (x == null) { + if (i > _locale.count(this, null, names) + 1) { + throw new IndexOutOfBoundsException(); + } + + return add_element_user(name); + } + + return insertElement(name, x, 0); + } + + public TypeStoreUser add_element_user(QName name) { + if (!isContainer()) { + throw new IllegalStateException(); + } + + QNameSet endSet = null; + boolean gotEndSet = false; + + Xobj candidate = null; + + for (Xobj x = _lastChild; x != null; x = x._prevSibling) { + if (x.isContainer()) { + if (x._name.equals(name)) { + break; + } + + if (!gotEndSet) { + endSet = _user.get_element_ending_delimiters(name); + gotEndSet = true; + } + + if (endSet == null || endSet.contains(x._name)) { + candidate = x; + } + } + } + + return + candidate == null + ? insertElement(name, this, END_POS) + : insertElement(name, candidate, 0); + } + + private static void removeElement(Xobj x) { + if (x == null) { + throw new IndexOutOfBoundsException(); + } + + x._locale.enter(); + + try { + Cur c = x.tempCur(); + c.moveNode(null); + c.release(); + } finally { + x._locale.exit(); + } + } + + public void remove_element(QName name, int i) { + if (i < 0) { + throw new IndexOutOfBoundsException(); + } + + if (!isContainer()) { + throw new IllegalStateException(); + } + + Xobj x; + + for (x = _firstChild; x != null; x = x._nextSibling) { + if (x.isElem() && x._name.equals(name) && --i < 0) { + break; + } + } + + removeElement(x); + } + + public void remove_element(QNameSet names, int i) { + if (i < 0) { + throw new IndexOutOfBoundsException(); + } + + if (!isContainer()) { + throw new IllegalStateException(); + } + + Xobj x; + + for (x = _firstChild; x != null; x = x._nextSibling) { + if (x.isElem() && names.contains(x._name) && --i < 0) { + break; + } + } + + removeElement(x); + } + + public TypeStoreUser find_attribute_user(QName name) { + Xobj a = getAttr(name); + + return a == null ? null : a.getUser(); + } + + public TypeStoreUser add_attribute_user(QName name) { + if (getAttr(name) != null) { + throw new IndexOutOfBoundsException(); + } + + _locale.enter(); + + try { + return setAttr(name, "").getUser(); + } finally { + _locale.exit(); + } + } + + public void remove_attribute(QName name) { + _locale.enter(); + + try { + if (!removeAttr(name)) { + throw new IndexOutOfBoundsException(); + } + } finally { + _locale.exit(); + } + } + + public TypeStoreUser copy_contents_from(TypeStore source) { + Xobj xSrc = (Xobj) source; + + if (xSrc == this) { + return getUser(); + } + + _locale.enter(); + + try { + xSrc._locale.enter(); + + Cur c = tempCur(); + + try { + Cur cSrc1 = xSrc.tempCur(); + Map sourceNamespaces = Locale.getAllNamespaces(cSrc1, null); + cSrc1.release(); + + if (isAttr()) { + Cur cSrc = xSrc.tempCur(); + String value = Locale.getTextValue(cSrc); + cSrc.release(); + + c.setValue(value); + } else { + // Here I save away the user of this node so that it does not get whacked + // in the following operations. + + disconnectChildrenUsers(); + + assert !inhibitDisconnect(); + + setBit(INHIBIT_DISCONNECT); + + QName xsiType = isContainer() ? getXsiTypeName() : null; + + Xobj copy = xSrc.copyNode(_locale); + + Cur.moveNodeContents(this, null, true); + + c.next(); + + Cur.moveNodeContents(copy, c, true); + + c.moveTo(this); + + if (xsiType != null) { + c.setXsiType(xsiType); + } + + assert inhibitDisconnect(); + clearBit(INHIBIT_DISCONNECT); + } + + if (sourceNamespaces != null) { + if (!c.isContainer()) { + c.toParent(); + } + + Locale.applyNamespaces(c, sourceNamespaces); + } + + } finally { + c.release(); + + xSrc._locale.exit(); + } + } finally { + _locale.exit(); + } + + return getUser(); + } + + public TypeStoreUser copy(SchemaTypeLoader stl, SchemaType type, XmlOptions options) { + //do not use a user's Factory method for copying. + //XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); + options = XmlOptions.maskNull(options); + SchemaType sType = options.getDocumentType(); + + if (sType == null) { + sType = type == null ? XmlObject.type : type; + } + + Locale locale = this.locale(); + if (options.isCopyUseNewSynchronizationDomain()) { + locale = Locale.getLocale(stl, options); + } + + boolean isFragment = !sType.isDocumentType() && !(sType.isNoType() && (this instanceof DocumentXobj)); + Xobj destination = Cur.createDomDocumentRootXobj(locale, isFragment); + + + locale.enter(); + try { + Cur c = destination.tempCur(); + c.setType(type); + c.release(); + } finally { + locale.exit(); + } + + return destination.copy_contents_from(this); + } + + public void array_setter(XmlObject[] sources, QName elementName) { + _locale.enter(); + + try { + // TODO - this is the quick and dirty implementation, make this faster + + int m = sources.length; + + List copies = new ArrayList<>(); + List types = new ArrayList<>(); + + for (XmlObject source : sources) { + // TODO - deal with null sources[ i ] here -- what to do? + + if (source == null) { + throw new IllegalArgumentException("Array element null"); + } else if (source.isImmutable()) { + copies.add(null); + types.add(null); + } else { + Xobj x = ((Xobj) ((TypeStoreUser) source).get_store()); + + if (x._locale == _locale) { + copies.add(x.copyNode(_locale)); + } else { + x._locale.enter(); + + try { + copies.add(x.copyNode(_locale)); + } finally { + x._locale.exit(); + } + } + + types.add(source.schemaType()); + } + } + + int n = count_elements(elementName); + + for (; n > m; n--) { + remove_element(elementName, m); + } + + for (; m > n; n++) { + add_element_user(elementName); + } + + assert m == n; + + List elementsUser = new ArrayList<>(); + + find_all_element_users(elementName, elementsUser); + + List elements = elementsUser.stream() + .map(x -> (TypeStoreUser) x) + .map(TypeStoreUser::get_store) + .map(x -> (Xobj) x) + .collect(Collectors.toList()); + + assert elements.size() == n; + + Cur c = tempCur(); + + for (int i = 0; i < n; i++) { + Xobj x = elements.get(i); + + if (sources[i].isImmutable()) { + x.getObject().set(sources[i]); + } else { + Cur.moveNodeContents(x, null, true); + + c.moveTo(x); + c.next(); + + Cur.moveNodeContents(copies.get(i), c, true); + + x.change_type(types.get(i)); + } + } + + c.release(); + } finally { + _locale.exit(); + } + } + + public void visit_elements(TypeStoreVisitor visitor) { + throw new RuntimeException("Not implemeneted"); + } + + public XmlObject[] exec_query(String queryExpr, XmlOptions options) { + _locale.enter(); + + try { + Cur c = tempCur(); + + XmlObject[] result = XPathFactory.objectExecQuery(c, queryExpr, options); + + c.release(); + + return result; + } finally { + _locale.exit(); + } + } + + public String find_prefix_for_nsuri(String nsuri, String suggested_prefix) { + _locale.enter(); + + try { + return prefixForNamespace(nsuri, suggested_prefix, true); + } finally { + _locale.exit(); + } + } + + public String getNamespaceForPrefix(String prefix) { + return namespaceForPrefix(prefix, true); + } + + Locale _locale; + QName _name; + + Cur _embedded; + + Bookmark _bookmarks; + + int _bits; + + Xobj _parent; + Xobj _nextSibling; + Xobj _prevSibling; + Xobj _firstChild; + Xobj _lastChild; + + Object _srcValue, _srcAfter; + int _offValue, _offAfter; + int _cchValue, _cchAfter; + + // TODO - put this in a ptr off this node + CharNode _charNodesValue; + CharNode _charNodesAfter; + + // TODO - put this in a ptr off this node + TypeStoreUser _user; +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java b/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java new file mode 100644 index 0000000..4cdbcf1 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java @@ -0,0 +1,654 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.common.IOUtil; +import org.apache.xmlbeans.impl.util.HexBin; +import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemaEntry; +import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument; +import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument.DownloadedSchemas; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public abstract class BaseSchemaResourceManager extends SchemaImportResolver { + private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")"; + + private String _defaultCopyDirectory; + private DownloadedSchemasDocument _importsDoc; + private final Map _resourceForFilename = new HashMap<>(); + private final Map _resourceForURL = new HashMap<>(); + private final Map _resourceForNamespace = new HashMap<>(); + private final Map _resourceForDigest = new HashMap<>(); + private final Map _resourceForCacheEntry = new HashMap<>(); + private Set _redownloadSet = new HashSet<>(); + + protected BaseSchemaResourceManager() { + // concrete subclasses should call init in their constructors + } + + protected final void init() { + if (fileExists(getIndexFilename())) { + try { + _importsDoc = DownloadedSchemasDocument.Factory.parse(inputStreamForFile(getIndexFilename())); + } catch (IOException e) { + _importsDoc = null; + } catch (Exception e) { + throw new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file", e); + } + } + if (_importsDoc == null) { + try { + _importsDoc = DownloadedSchemasDocument.Factory.parse( + "" + ); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + String defaultDir = _importsDoc.getDownloadedSchemas().getDefaultDirectory(); + if (defaultDir == null) { + defaultDir = getDefaultSchemaDir(); + } + _defaultCopyDirectory = defaultDir; + + // now initialize data structures + DownloadedSchemaEntry[] entries = _importsDoc.getDownloadedSchemas().getEntryArray(); + for (DownloadedSchemaEntry entry : entries) { + updateResource(entry); + } + } + + public final void writeCache() throws IOException { + InputStream input = _importsDoc.newInputStream(new XmlOptions().setSavePrettyPrint()); + writeInputStreamToFile(input, getIndexFilename()); + } + + public final void processAll(boolean sync, boolean refresh, boolean imports) { + _redownloadSet = refresh ? new HashSet<>() : null; + + String[] allFilenames = getAllXSDFilenames(); + + if (sync) { + syncCacheWithLocalXsdFiles(allFilenames, false); + } + + SchemaResource[] starters = _resourceForFilename.values().toArray(new SchemaResource[0]); + + if (refresh) { + redownloadEntries(starters); + } + + if (imports) { + resolveImports(starters); + } + + _redownloadSet = null; + } + + public final void process(String[] uris, String[] filenames, boolean sync, boolean refresh, boolean imports) { + _redownloadSet = refresh ? new HashSet<>() : null; + + if (filenames.length > 0) { + syncCacheWithLocalXsdFiles(filenames, true); + } else if (sync) { + syncCacheWithLocalXsdFiles(getAllXSDFilenames(), false); + } + + Set starterset = new HashSet<>(); + + for (String s : uris) { + SchemaResource resource = (SchemaResource) lookupResource(null, s); + if (resource != null) { + starterset.add(resource); + } + } + + for (String filename : filenames) { + SchemaResource resource = _resourceForFilename.get(filename); + if (resource != null) { + starterset.add(resource); + } + } + + SchemaResource[] starters = starterset.toArray(new SchemaResource[0]); + + if (refresh) { + redownloadEntries(starters); + } + + if (imports) { + resolveImports(starters); + } + + _redownloadSet = null; + } + + /** + * Adds items to the cache that point to new files that aren't + * described in the cache, and optionally deletes old entries. + *

      + * If an old file is gone and a new file is + * found with exactly the same contents, the cache entry is moved + * to point to the new file. + */ + public final void syncCacheWithLocalXsdFiles(String[] filenames, boolean deleteOnlyMentioned) { + Set seenResources = new HashSet<>(); + Set vanishedResources = new HashSet<>(); + + for (String filename : filenames) { + // first, if the filename matches exactly, trust the filename + SchemaResource resource = _resourceForFilename.get(filename); + if (resource != null) { + if (fileExists(filename)) { + seenResources.add(resource); + } else { + vanishedResources.add(resource); + } + continue; + } + + // new file that is not in the index? + // not if the digest is known to the index and the original file is gone - that's a rename! + String digest = null; + try { + digest = shaDigestForFile(filename); + resource = _resourceForDigest.get(digest); + if (resource != null) { + String oldFilename = resource.getFilename(); + if (!fileExists(oldFilename)) { + warning("File " + filename + " is a rename of " + oldFilename); + resource.setFilename(filename); + seenResources.add(resource); + if (_resourceForFilename.get(oldFilename) == resource) { + _resourceForFilename.remove(oldFilename); + } + if (_resourceForFilename.containsKey(filename)) { + _resourceForFilename.put(filename, resource); + } + continue; + } + } + } catch (IOException e) { + // unable to read digest... no problem, ignore then + } + + // ok, this really is a new XSD file then, of unknown URL origin + DownloadedSchemaEntry newEntry = addNewEntry(); + newEntry.setFilename(filename); + warning("Caching information on new local file " + filename); + if (digest != null) { + newEntry.setSha1(digest); + } + + seenResources.add(updateResource(newEntry)); + } + + if (deleteOnlyMentioned) { + deleteResourcesInSet(vanishedResources, true); + } else { + deleteResourcesInSet(seenResources, false); + } + } + + /** + * Iterates through every entry and refetches it from its primary URL, + * if known. Replaces the contents of the file if the data is different. + */ + private void redownloadEntries(SchemaResource[] resources) { + for (SchemaResource resource : resources) { + redownloadResource(resource); + } + } + + private void deleteResourcesInSet(Set seenResources, boolean setToDelete) { + Set seenCacheEntries = new HashSet<>(); + for (SchemaResource resource : seenResources) { + seenCacheEntries.add(resource._cacheEntry); + } + + DownloadedSchemas downloadedSchemas = _importsDoc.getDownloadedSchemas(); + for (int i = 0; i < downloadedSchemas.sizeOfEntryArray(); i++) { + DownloadedSchemaEntry cacheEntry = downloadedSchemas.getEntryArray(i); + + if (seenCacheEntries.contains(cacheEntry) == setToDelete) { + SchemaResource resource = _resourceForCacheEntry.get(cacheEntry); + + if (resource != null) { + warning("Removing obsolete cache entry for " + resource.getFilename()); + _resourceForCacheEntry.remove(cacheEntry); + + if (resource == _resourceForFilename.get(resource.getFilename())) { + _resourceForFilename.remove(resource.getFilename()); + } + + if (resource == _resourceForDigest.get(resource.getSha1())) { + _resourceForDigest.remove(resource.getSha1()); + } + + if (resource == _resourceForNamespace.get(resource.getNamespace())) { + _resourceForNamespace.remove(resource.getNamespace()); + } + + // Finally, any or all URIs + String[] urls = resource.getSchemaLocationArray(); + for (String url : urls) { + if (resource == _resourceForURL.get(url)) { + _resourceForURL.remove(url); + } + } + } + + downloadedSchemas.removeEntry(i); + i -= 1; + } + } + } + + private SchemaResource updateResource(DownloadedSchemaEntry entry) { + // The file + String filename = entry.getFilename(); + if (filename == null) { + return null; + } + + SchemaResource resource = new SchemaResource(entry); + _resourceForCacheEntry.put(entry, resource); + + if (!_resourceForFilename.containsKey(filename)) { + _resourceForFilename.put(filename, resource); + } + + // The digest + String digest = resource.getSha1(); + if (digest != null) { + if (!_resourceForDigest.containsKey(digest)) { + _resourceForDigest.put(digest, resource); + } + } + + // Next, the namespace + String namespace = resource.getNamespace(); + if (namespace != null) { + if (!_resourceForNamespace.containsKey(namespace)) { + _resourceForNamespace.put(namespace, resource); + } + } + + // Finally, any or all URIs + String[] urls = resource.getSchemaLocationArray(); + for (String url : urls) { + if (!_resourceForURL.containsKey(url)) { + _resourceForURL.put(url, resource); + } + } + + return resource; + } + + private static DigestInputStream digestInputStream(InputStream input) { + MessageDigest sha; + try { + sha = MessageDigest.getInstance("SHA"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + + return new DigestInputStream(input, sha); + } + + private DownloadedSchemaEntry addNewEntry() { + return _importsDoc.getDownloadedSchemas().addNewEntry(); + } + + private class SchemaResource implements SchemaImportResolver.SchemaResource { + SchemaResource(DownloadedSchemaEntry entry) { + _cacheEntry = entry; + } + + DownloadedSchemaEntry _cacheEntry; + + public void setFilename(String filename) { + _cacheEntry.setFilename(filename); + } + + public String getFilename() { + return _cacheEntry.getFilename(); + } + + public Schema getSchema() { + if (!fileExists(getFilename())) { + redownloadResource(this); + } + + try { + return SchemaDocument.Factory.parse(inputStreamForFile(getFilename())).getSchema(); + } catch (Exception e) { + return null; // return null if _any_ problems reading schema file + } + } + + public String getSha1() { + return _cacheEntry.getSha1(); + } + + public String getNamespace() { + return _cacheEntry.getNamespace(); + } + + public void setNamespace(String namespace) { + _cacheEntry.setNamespace(namespace); + } + + public String getSchemaLocation() { + if (_cacheEntry.sizeOfSchemaLocationArray() > 0) { + return _cacheEntry.getSchemaLocationArray(0); + } + return null; + } + + public String[] getSchemaLocationArray() { + return _cacheEntry.getSchemaLocationArray(); + } + + public int hashCode() { + return getFilename().hashCode(); + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof SchemaResource)) { + return false; + } + + SchemaResource sr = (SchemaResource) obj; + return getFilename().equals(sr.getFilename()); + } + + public void addSchemaLocation(String schemaLocation) { + _cacheEntry.addSchemaLocation(schemaLocation); + } + } + + /** + * Called when the ImportLoader wishes to resolve the + * given import. Should return a SchemaResource whose + * "equals" relationship reveals when a SchemaResource is + * duplicated and shouldn't be examined again. + *

      + * Returns null if the resource reference should be ignored. + */ + public SchemaImportResolver.SchemaResource lookupResource(String nsURI, String schemaLocation) { + SchemaResource result = fetchFromCache(nsURI, schemaLocation); + if (result != null) { + if (_redownloadSet != null) { + redownloadResource(result); + } + return result; + } + + if (schemaLocation == null) { + warning("No cached schema for namespace '" + nsURI + "', and no url specified"); + return null; + } + + result = copyOrIdentifyDuplicateURL(schemaLocation, nsURI); + if (_redownloadSet != null) { + _redownloadSet.add(result); + } + return result; + } + + private SchemaResource fetchFromCache(String nsURI, String schemaLocation) { + SchemaResource result; + + if (schemaLocation != null) { + result = _resourceForURL.get(schemaLocation); + if (result != null) { + return result; + } + } + + if (nsURI != null) { + result = _resourceForNamespace.get(nsURI); + if (result != null) { + return result; + } + } + + return null; + } + + private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException { + String localFilename = new URI(schemaLocation).getRawPath(); + int i = localFilename.lastIndexOf('/'); + if (i >= 0) { + localFilename = localFilename.substring(i + 1); + } + if (localFilename.endsWith(".xsd")) { + localFilename = localFilename.substring(0, localFilename.length() - 4); + } + if (localFilename.length() == 0) { + localFilename = "schema"; + } + + // TODO: remove other unsafe characters for filenames? + + String candidateFilename = localFilename; + int suffix = 1; + while (suffix < 1000) { + String candidate = _defaultCopyDirectory + "/" + candidateFilename + ".xsd"; + if (!fileExists(candidate)) { + return candidate; + } + suffix += 1; + candidateFilename = localFilename + suffix; + } + + throw new IOException("Problem with filename " + localFilename + ".xsd"); + } + + private void redownloadResource(SchemaResource resource) { + if (_redownloadSet != null) { + if (_redownloadSet.contains(resource)) { + return; + } + _redownloadSet.add(resource); + } + + String filename = resource.getFilename(); + String schemaLocation = resource.getSchemaLocation(); + String digest; + + // nothing to do? + if (schemaLocation == null || filename == null) { + return; + } + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + try { + URL url = new URL(schemaLocation); + URLConnection conn = url.openConnection(); + conn.addRequestProperty("User-Agent", USER_AGENT); + conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); + DigestInputStream input = digestInputStream(conn.getInputStream()); + IOUtil.copyCompletely(input, buffer); + digest = HexBin.bytesToString(input.getMessageDigest().digest()); + } catch (Exception e) { + warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); + return; + } + + if (digest.equals(resource.getSha1()) && fileExists(filename)) { + warning("Resource " + filename + " is unchanged from " + schemaLocation + "."); + return; + } + + try { + InputStream source = new ByteArrayInputStream(buffer.toByteArray()); + writeInputStreamToFile(source, filename); + } catch (IOException e) { + warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage()); + return; + } + + warning("Refreshed " + filename + " from " + schemaLocation); + } + + private SchemaResource copyOrIdentifyDuplicateURL(String schemaLocation, String namespace) { + String targetFilename; + String digest; + SchemaResource result; + + try { + targetFilename = uniqueFilenameForURI(schemaLocation); + } catch (URISyntaxException e) { + warning("Invalid URI '" + schemaLocation + "':" + e.getMessage()); + return null; + } catch (IOException e) { + warning("Could not create local file for " + schemaLocation + ":" + e.getMessage()); + return null; + } + + try { + URL url = new URL(schemaLocation); + DigestInputStream input = digestInputStream(url.openStream()); + writeInputStreamToFile(input, targetFilename); + digest = HexBin.bytesToString(input.getMessageDigest().digest()); + } catch (Exception e) { + warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); + return null; + } + + result = _resourceForDigest.get(digest); + if (result != null) { + deleteFile(targetFilename); + result.addSchemaLocation(schemaLocation); + if (!_resourceForURL.containsKey(schemaLocation)) { + _resourceForURL.put(schemaLocation, result); + } + return result; + } + + warning("Downloaded " + schemaLocation + " to " + targetFilename); + + DownloadedSchemaEntry newEntry = addNewEntry(); + newEntry.setFilename(targetFilename); + newEntry.setSha1(digest); + if (namespace != null) { + newEntry.setNamespace(namespace); + } + newEntry.addSchemaLocation(schemaLocation); + return updateResource(newEntry); + } + + /** + * Updates actual namespace in the table. + */ + public void reportActualNamespace(SchemaImportResolver.SchemaResource rresource, String actualNamespace) { + SchemaResource resource = (SchemaResource) rresource; + String oldNamespace = resource.getNamespace(); + if (oldNamespace != null && _resourceForNamespace.get(oldNamespace) == resource) { + _resourceForNamespace.remove(oldNamespace); + } + if (!_resourceForNamespace.containsKey(actualNamespace)) { + _resourceForNamespace.put(actualNamespace, resource); + } + resource.setNamespace(actualNamespace); + } + + private String shaDigestForFile(String filename) throws IOException { + DigestInputStream str = digestInputStream(inputStreamForFile(filename)); + + byte[] dummy = new byte[4096]; + int i = 1; + while (i > 0) { + i = str.read(dummy); + } + + str.close(); + + return HexBin.bytesToString(str.getMessageDigest().digest()); + } + + // SOME METHODS TO OVERRIDE ============================ + + protected String getIndexFilename() { + return "./xsdownload.xml"; + } + + protected String getDefaultSchemaDir() { + return "./schema"; + } + + /** + * Produces diagnostic messages such as "downloading X to file Y". + */ + abstract protected void warning(String msg); + + /** + * Returns true if the given filename exists. The filenames + * are of the form "/foo/bar/zee.xsd" and should be construed + * as rooted at the root of the project. + */ + abstract protected boolean fileExists(String filename); + + /** + * Gets the data in the given filename as an InputStream. + */ + abstract protected InputStream inputStreamForFile(String filename) throws IOException; + + /** + * Writes an entire file in one step. An InputStream is passed and + * copied to the file. + */ + abstract protected void writeInputStreamToFile(InputStream input, String filename) throws IOException; + + /** + * Deletes a file. Sometimes immediately after writing a new file + * we notice that it's exactly the same as an existing file and + * we delete it. We never delete a file that was given to us + * by the user. + */ + abstract protected void deleteFile(String filename); + + /** + * Returns a list of all the XSD filesnames in the project. + */ + abstract protected String[] getAllXSDFilenames(); +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/CodeGenUtil.java b/src/main/java/org/apache/xmlbeans/impl/tool/CodeGenUtil.java new file mode 100644 index 0000000..7115cba --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/CodeGenUtil.java @@ -0,0 +1,301 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.SystemProperties; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +public class CodeGenUtil { + public static final String DEFAULT_MEM_START = "8m"; + public static final String DEFAULT_MEM_MAX = "256m"; + public static final String DEFAULT_COMPILER = "javac"; + + //workaround for Sun bug # 4723726 + public static URI resolve(URI base, URI child) { + URI ruri = base.resolve(child); + + //fix up normalization bug + if ("file".equals(ruri.getScheme()) && !child.equals(ruri)) { + if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//")) { + String path = "///".concat(ruri.getPath()); + try { + ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment()); + } catch (URISyntaxException ignored) { + } + } + } + return ruri; + } + + static void addAllJavaFiles(List srcFiles, List args) { + for (File f : srcFiles) { + if (f.isDirectory()) { + File[] files = f.listFiles( + file -> (file.isFile() && file.getName().endsWith(".java")) || file.isDirectory() + ); + if (files != null) { + addAllJavaFiles(Arrays.asList(files), args); + } + } else { + args.add(quoteAndEscapeFilename(f.getAbsolutePath())); + } + } + } + + static private String quoteAndEscapeFilename(String filename) { + // don't quote if there's no space + if (!filename.contains(" ")) { + return filename; + } + + // bizarre. javac expects backslash escaping if we quote the classpath + // bizarre also. replaceAll expects replacement backslashes to be double escaped. + return "\"" + filename.replaceAll("\\\\", "\\\\\\\\") + "\""; + } + + + /** + * Invokes javac on the generated source files in order to turn them + * into binary files in the output directory. This will return a list of + * GenFiles for all of the classes produced or null if an + * error occurred. + * + * @deprecated + */ + public static boolean externalCompile(List srcFiles, File outdir, File[] cp, boolean debug) { + return externalCompile(srcFiles, outdir, cp, debug, DEFAULT_COMPILER, null, DEFAULT_MEM_START, DEFAULT_MEM_MAX, false, false); + } + + // KHK: temporary to avoid build break + public static boolean externalCompile(List srcFiles, File outdir, File[] cp, boolean debug, String javacPath, String memStart, String memMax, boolean quiet, boolean verbose) { + return externalCompile(srcFiles, outdir, cp, debug, javacPath, null, memStart, memMax, quiet, verbose); + } + + /** + * Invokes javac on the generated source files in order to turn them + * into binary files in the output directory. This will return a list of + * GenFiles for all of the classes produced or null if an + * error occurred. + */ + public static boolean externalCompile(List srcFiles, File outdir, File[] cp, boolean debug, String javacPath, String genver, String memStart, String memMax, boolean quiet, boolean verbose) { + List args = new ArrayList<>(); + + File javac = findJavaTool(javacPath == null ? DEFAULT_COMPILER : javacPath); + assert (javac.exists()) : "compiler not found " + javac; + args.add(javac.getAbsolutePath()); + + if (outdir == null) { + outdir = new File("."); + } else { + args.add("-d"); + args.add(quoteAndEscapeFilename(outdir.getAbsolutePath())); + } + + if (cp == null) { + cp = systemClasspath(); + } + + if (cp.length > 0) { + StringBuilder classPath = new StringBuilder(); + // Add the output directory to the classpath. We do this so that + // javac will be able to find classes that were compiled + // previously but are not in the list of sources this time. + classPath.append(outdir.getAbsolutePath()); + + // Add everything on our classpath. + for (File file : cp) { + classPath.append(File.pathSeparator); + classPath.append(file.getAbsolutePath()); + } + + args.add("-classpath"); + + // bizarre. javac expects backslash escaping if we quote the classpath + args.add(quoteAndEscapeFilename(classPath.toString())); + } + + if (genver == null) { + genver = "1.8"; + } + + args.add("-source"); + args.add(genver); + + args.add("-target"); + args.add(genver); + + args.add(debug ? "-g" : "-g:none"); + + if (verbose) { + args.add("-verbose"); + } + + addAllJavaFiles(srcFiles, args); + + File clFile = null; + try { + clFile = File.createTempFile("javac", ""); + try (Writer fw = Files.newBufferedWriter(clFile.toPath(), StandardCharsets.ISO_8859_1)) { + Iterator i = args.iterator(); + for (i.next(); i.hasNext(); ) { + String arg = i.next(); + fw.write(arg); + fw.write('\n'); + } + } + List newargs = new ArrayList<>(); + newargs.add(args.get(0)); + + if (memStart != null && memStart.length() != 0) { + newargs.add("-J-Xms" + memStart); + } + if (memMax != null && memMax.length() != 0) { + newargs.add("-J-Xmx" + memMax); + } + + newargs.add("@" + clFile.getAbsolutePath()); + args = newargs; + } catch (Exception e) { + System.err.println("Could not create command-line file for javac"); + } + + try { + String[] strArgs = args.toArray(new String[0]); + + if (verbose) { + System.out.print("compile command:"); + for (String strArg : strArgs) { + System.out.print(" " + strArg); + } + System.out.println(); + } + + final Process proc = Runtime.getRuntime().exec(strArgs); + + StringBuilder errorBuffer = new StringBuilder(); + StringBuilder outputBuffer = new StringBuilder(); + + Thread out = copy(proc.getInputStream(), outputBuffer); + Thread err = copy(proc.getErrorStream(), errorBuffer); + + proc.waitFor(); + + if (verbose || proc.exitValue() != 0) { + if (outputBuffer.length() > 0) { + System.out.println(outputBuffer.toString()); + System.out.flush(); + } + if (errorBuffer.length() > 0) { + System.err.println(errorBuffer.toString()); + System.err.flush(); + } + + if (proc.exitValue() != 0) { + return false; + } + } + } catch (Throwable e) { + System.err.println(e.toString()); + System.err.println(e.getCause()); + e.printStackTrace(System.err); + return false; + } + + if (clFile != null) { + clFile.delete(); + } + + return true; + } + + public static File[] systemClasspath() { + List cp = new ArrayList<>(); + String jcp = SystemProperties.getProperty("java.class.path"); + if (jcp != null) { + String[] systemcp = jcp.split(File.pathSeparator); + for (String s : systemcp) { + cp.add(new File(s)); + } + } + return cp.toArray(new File[0]); + } + + + /** + * Look for tool in current directory and ${JAVA_HOME}/../bin and + * try with .exe file extension. + */ + private static File findJavaTool(String tool) { + File toolFile = new File(tool); + if (toolFile.isFile()) { + return toolFile; + } + + File result = new File(tool + ".exe"); + if (result.isFile()) { + return result; + } + + String home = SystemProperties.getProperty("java.home"); + + String sep = File.separator; + result = new File(home + sep + ".." + sep + "bin", tool); + + if (result.isFile()) { + return result; + } + + result = new File(result.getPath() + ".exe"); + if (result.isFile()) { + return result; + } + + result = new File(home + sep + "bin", tool); + if (result.isFile()) { + return result; + } + + result = new File(result.getPath() + ".exe"); + if (result.isFile()) { + return result; + } + + // just return the original toolFile and hope that it is on the PATH. + return toolFile; + } + + /** + * Reads the given input stream into the given buffer until there is + * nothing left to read. + */ + private static Thread copy(InputStream stream, final StringBuilder output) { + final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.ISO_8859_1)); + Thread readerThread = new Thread(() -> + reader.lines().forEach(s -> output.append(s).append("\n")) + ); + readerThread.start(); + return readerThread; + } +} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java b/src/main/java/org/apache/xmlbeans/impl/tool/CommandLine.java similarity index 97% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java rename to src/main/java/org/apache/xmlbeans/impl/tool/CommandLine.java index 55c1ecd..3fdffd7 100644 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java +++ b/src/main/java/org/apache/xmlbeans/impl/tool/CommandLine.java @@ -16,6 +16,7 @@ package org.apache.xmlbeans.impl.tool; import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.impl.common.DefaultClassLoaderResourceLoader; import org.apache.xmlbeans.impl.common.IOUtil; import java.io.File; @@ -76,7 +77,7 @@ public static void printLicense() { try { - IOUtil.copyCompletely(CommandLine.class.getResourceAsStream("LICENSE.txt"), System.out); + IOUtil.copyCompletely(new DefaultClassLoaderResourceLoader().getResourceAsStream("LICENSE.txt"), System.out); } catch (Exception e) { diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java b/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java new file mode 100644 index 0000000..34e6103 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/Extension.java @@ -0,0 +1,71 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import java.util.ArrayList; +import java.util.List; + + +/** + * An extension is a javabean that represents a SchemaCompilerExtension to be passed for callback into the + * XmlBeans Schema Compiler. + */ +public class Extension { + private Class className; + private List params = new ArrayList<>(); + + public Class getClassName() { + return className; + } + + public void setClassName(Class className) { + this.className = className; + } + + public List getParams() { + return params; + } + + public Param createParam() { + Param p = new Param(); + params.add(p); + return p; + } + + /** + * A Param is just a name value pair applicable to the extension. + */ + public class Param { + private String name; + private String value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/FactorImports.java b/src/main/java/org/apache/xmlbeans/impl/tool/FactorImports.java new file mode 100644 index 0000000..3938684 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/FactorImports.java @@ -0,0 +1,447 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.xb.xsdschema.*; + +import javax.xml.namespace.QName; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +/** + * This program takes a collection of .xsd files as input, finds all duplicate + * name definitions, and factors out the first instance of each of those into + * a common.xsd file, adding an appropriate statement in the original + * xsd file. + */ +public class FactorImports { + public static void printUsage() { + System.out.println("Refactors a directory of XSD files to remove name conflicts."); + System.out.println("Usage: sfactor [-import common.xsd] [-out outputdir] inputdir"); + System.out.println(" -import common.xsd - The XSD file to contain redundant "); + System.out.println(" definitions for importing."); + System.out.println(" -out outputdir - The directory into which to place XSD "); + System.out.println(" files resulting from refactoring, "); + System.out.println(" plus a commonly imported common.xsd."); + System.out.println(" inputdir - The directory containing the XSD files with"); + System.out.println(" redundant definitions."); + System.out.println(" -license - Print license information."); + System.out.println(); + + } + + public static void main(String[] args) throws Exception { + Set flags = new HashSet<>(); + flags.add("h"); + flags.add("help"); + flags.add("usage"); + flags.add("license"); + flags.add("version"); + + CommandLine cl = new CommandLine(args, flags, Arrays.asList("import", "out")); + if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null || args.length < 1) { + printUsage(); + System.exit(0); + return; + } + + String[] badopts = cl.getBadOpts(); + if (badopts.length > 0) { + for (String badopt : badopts) { + System.out.println("Unrecognized option: " + badopt); + } + printUsage(); + System.exit(0); + return; + } + + if (cl.getOpt("license") != null) { + CommandLine.printLicense(); + System.exit(0); + return; + } + + if (cl.getOpt("version") != null) { + CommandLine.printVersion(); + System.exit(0); + return; + } + + args = cl.args(); + if (args.length != 1) { + System.exit(0); + return; + } + + String commonName = cl.getOpt("import"); + if (commonName == null) { + commonName = "common.xsd"; + } + + String out = cl.getOpt("out"); + if (out == null) { + System.out.println("Using output directory 'out'"); + out = "out"; + } + File outdir = new File(out); + File basedir = new File(args[0]); + + // first, parse all the schema files + File[] files = cl.getFiles(); + Map schemaDocs = new HashMap<>(); + Set elementNames = new HashSet<>(); + Set attributeNames = new HashSet<>(); + Set typeNames = new HashSet<>(); + Set modelGroupNames = new HashSet<>(); + Set attrGroupNames = new HashSet<>(); + + Set dupeElementNames = new HashSet<>(); + Set dupeAttributeNames = new HashSet<>(); + Set dupeTypeNames = new HashSet<>(); + Set dupeModelGroupNames = new HashSet<>(); + Set dupeAttrGroupNames = new HashSet<>(); + Set dupeNamespaces = new HashSet<>(); + + for (File file : files) { + try { + // load schema + SchemaDocument doc = SchemaDocument.Factory.parse(file); + schemaDocs.put(doc, file); + + // warn about for imports, includes + if (doc.getSchema().sizeOfImportArray() > 0 || doc.getSchema().sizeOfIncludeArray() > 0) { + System.out.println("warning: " + file + " contains imports or includes that are being ignored."); + } + + // collect together names + String targetNamespace = doc.getSchema().getTargetNamespace(); + if (targetNamespace == null) { + targetNamespace = ""; + } + + TopLevelComplexType[] ct = doc.getSchema().getComplexTypeArray(); + for (TopLevelComplexType topLevelComplexType : ct) { + noteName(topLevelComplexType.getName(), targetNamespace, typeNames, dupeTypeNames, dupeNamespaces); + } + + TopLevelSimpleType[] st = doc.getSchema().getSimpleTypeArray(); + for (TopLevelSimpleType topLevelSimpleType : st) { + noteName(topLevelSimpleType.getName(), targetNamespace, typeNames, dupeTypeNames, dupeNamespaces); + } + + TopLevelElement[] el = doc.getSchema().getElementArray(); + for (TopLevelElement topLevelElement : el) { + noteName(topLevelElement.getName(), targetNamespace, elementNames, dupeElementNames, dupeNamespaces); + } + + TopLevelAttribute[] at = doc.getSchema().getAttributeArray(); + for (TopLevelAttribute topLevelAttribute : at) { + noteName(topLevelAttribute.getName(), targetNamespace, attributeNames, dupeAttributeNames, dupeNamespaces); + } + + NamedGroup[] gr = doc.getSchema().getGroupArray(); + for (NamedGroup namedGroup : gr) { + noteName(namedGroup.getName(), targetNamespace, modelGroupNames, dupeModelGroupNames, dupeNamespaces); + } + + NamedAttributeGroup[] ag = doc.getSchema().getAttributeGroupArray(); + for (NamedAttributeGroup namedAttributeGroup : ag) { + noteName(namedAttributeGroup.getName(), targetNamespace, attrGroupNames, dupeAttrGroupNames, dupeNamespaces); + } + + } catch (XmlException e) { + System.out.println("warning: " + file + " is not a schema file - " + e.getError().toString()); + } catch (IOException e) { + System.err.println("Unable to load " + file + " - " + e.getMessage()); + System.exit(1); + return; + } + } + + if (schemaDocs.size() == 0) { + System.out.println("No schema files found."); + System.exit(0); + return; + } + + if (dupeTypeNames.size() + dupeElementNames.size() + dupeAttributeNames.size() + + dupeModelGroupNames.size() + dupeAttrGroupNames.size() == 0) { + System.out.println("No duplicate names found."); + System.exit(0); + return; + } + + // create a schema doc for each namespace to be imported + Map commonDocs = new HashMap<>(); + Map commonFiles = new HashMap<>(); + int count = dupeNamespaces.size() == 1 ? 0 : 1; + for (String namespace : dupeNamespaces) { + SchemaDocument commonDoc = SchemaDocument.Factory.parse( + "" + ); + if (namespace.length() > 0) { + commonDoc.getSchema().setTargetNamespace(namespace); + } + commonDoc.getSchema().setElementFormDefault(FormChoice.QUALIFIED); + commonDocs.put(namespace, commonDoc); + commonFiles.put(commonDoc, commonFileFor(commonName, namespace, count++, outdir)); + } + + // pull out all the duplicate definitions and drop them into the file + // we reuse the elementNames (etc) sets to keep track of which definitions + // we have already inserted. + for (SchemaDocument doc : schemaDocs.keySet()) { + // collect together names + String targetNamespace = doc.getSchema().getTargetNamespace(); + if (targetNamespace == null) { + targetNamespace = ""; + } + + SchemaDocument commonDoc = commonDocs.get(targetNamespace); + + boolean needImport = false; + + TopLevelComplexType[] ct = doc.getSchema().getComplexTypeArray(); + for (int j = ct.length - 1; j >= 0; j--) { + if (!isDuplicate(ct[j].getName(), targetNamespace, dupeTypeNames)) { + continue; + } + if (isFirstDuplicate(ct[j].getName(), targetNamespace, typeNames, dupeTypeNames)) { + commonDoc.getSchema().addNewComplexType().set(ct[j]); + } + needImport = true; + doc.getSchema().removeComplexType(j); + } + + TopLevelSimpleType[] st = doc.getSchema().getSimpleTypeArray(); + for (int j = 0; j < st.length; j++) { + if (!isDuplicate(st[j].getName(), targetNamespace, dupeTypeNames)) { + continue; + } + if (isFirstDuplicate(st[j].getName(), targetNamespace, typeNames, dupeTypeNames)) { + commonDoc.getSchema().addNewSimpleType().set(st[j]); + } + needImport = true; + doc.getSchema().removeSimpleType(j); + } + + TopLevelElement[] el = doc.getSchema().getElementArray(); + for (int j = 0; j < el.length; j++) { + if (!isDuplicate(el[j].getName(), targetNamespace, dupeElementNames)) { + continue; + } + if (isFirstDuplicate(el[j].getName(), targetNamespace, elementNames, dupeElementNames)) { + commonDoc.getSchema().addNewElement().set(el[j]); + } + needImport = true; + doc.getSchema().removeElement(j); + } + + TopLevelAttribute[] at = doc.getSchema().getAttributeArray(); + for (int j = 0; j < at.length; j++) { + if (!isDuplicate(at[j].getName(), targetNamespace, dupeAttributeNames)) { + continue; + } + if (isFirstDuplicate(at[j].getName(), targetNamespace, attributeNames, dupeAttributeNames)) { + commonDoc.getSchema().addNewElement().set(at[j]); + } + needImport = true; + doc.getSchema().removeElement(j); + } + + NamedGroup[] gr = doc.getSchema().getGroupArray(); + for (int j = 0; j < gr.length; j++) { + if (!isDuplicate(gr[j].getName(), targetNamespace, dupeModelGroupNames)) { + continue; + } + if (isFirstDuplicate(gr[j].getName(), targetNamespace, modelGroupNames, dupeModelGroupNames)) { + commonDoc.getSchema().addNewElement().set(gr[j]); + } + needImport = true; + doc.getSchema().removeElement(j); + } + + NamedAttributeGroup[] ag = doc.getSchema().getAttributeGroupArray(); + for (int j = 0; j < ag.length; j++) { + if (!isDuplicate(ag[j].getName(), targetNamespace, dupeAttrGroupNames)) { + continue; + } + if (isFirstDuplicate(ag[j].getName(), targetNamespace, attrGroupNames, dupeAttrGroupNames)) { + commonDoc.getSchema().addNewElement().set(ag[j]); + } + needImport = true; + doc.getSchema().removeElement(j); + } + + if (needImport) { + IncludeDocument.Include newInclude = doc.getSchema().addNewInclude(); + File inputFile = (File) schemaDocs.get(doc); + File outputFile = outputFileFor(inputFile, basedir, outdir); + File commonFile = (File) commonFiles.get(commonDoc); + if (targetNamespace != null) { + newInclude.setSchemaLocation(relativeURIFor(outputFile, commonFile)); + } + } + } + + // make the directory for output + if (!outdir.isDirectory() && !outdir.mkdirs()) { + System.err.println("Unable to makedir " + outdir); + System.exit(1); + return; + } + + // now write all those docs back out. + for (SchemaDocument doc : schemaDocs.keySet()) { + File inputFile = schemaDocs.get(doc); + File outputFile = outputFileFor(inputFile, basedir, outdir); + if (outputFile == null) { + System.out.println("Cannot copy " + inputFile); + } else { + doc.save(outputFile, new XmlOptions().setSavePrettyPrint().setSaveAggressiveNamespaces()); + } + } + + for (SchemaDocument doc : commonFiles.keySet()) { + File outputFile = commonFiles.get(doc); + doc.save(outputFile, new XmlOptions().setSavePrettyPrint().setSaveAggressiveNamespaces()); + } + + } + + private static File outputFileFor(File file, File baseDir, File outdir) { + URI base = baseDir.getAbsoluteFile().toURI(); + URI abs = file.getAbsoluteFile().toURI(); + URI rel = base.relativize(abs); + if (rel.isAbsolute()) { + System.out.println("Cannot relativize " + file); + return null; + } + + URI outbase = outdir.toURI(); + URI out = CodeGenUtil.resolve(outbase, rel); + return new File(out); + } + + private static URI commonAncestor(URI first, URI second) { + String firstStr = first.toString(); + String secondStr = second.toString(); + int len = firstStr.length(); + if (secondStr.length() < len) { + len = secondStr.length(); + } + int i; + for (i = 0; i < len; i++) { + if (firstStr.charAt(i) != secondStr.charAt(i)) { + break; + } + } + i -= 1; + if (i >= 0) { + i = firstStr.lastIndexOf('/', i); + } + if (i < 0) { + return null; + } + try { + return new URI(firstStr.substring(0, i)); + } catch (URISyntaxException e) { + return null; + } + } + + + private static String relativeURIFor(File source, File target) { + URI base = source.getAbsoluteFile().toURI(); + URI abs = target.getAbsoluteFile().toURI(); + // find common substring... + URI commonBase = commonAncestor(base, abs); + if (commonBase == null) { + return abs.toString(); + } + + URI baserel = commonBase.relativize(base); + URI targetrel = commonBase.relativize(abs); + if (baserel.isAbsolute() || targetrel.isAbsolute()) { + return abs.toString(); + } + String prefix = ""; + String sourceRel = baserel.toString(); + for (int i = 0; i < sourceRel.length(); ) { + i = sourceRel.indexOf('/', i); + if (i < 0) { + break; + } + prefix += "../"; + i += 1; + } + return prefix + targetrel.toString(); + } + + private static File commonFileFor(String commonName, String namespace, int i, File outdir) { + String name = commonName; + if (i > 0) { + int index = commonName.lastIndexOf('.'); + if (index < 0) { + index = commonName.length(); + } + name = commonName.substring(0, index) + i + commonName.substring(index); + } + return new File(outdir, name); + } + + + private static void noteName(String name, String targetNamespace, Set seen, Set dupes, Set dupeNamespaces) { + if (name == null) { + return; + } + QName qName = new QName(targetNamespace, name); + if (seen.contains(qName)) { + dupes.add(qName); + dupeNamespaces.add(targetNamespace); + } else { + seen.add(qName); + } + + } + + private static boolean isFirstDuplicate(String name, String targetNamespace, Set notseen, Set dupes) { + if (name == null) { + return false; + } + QName qName = new QName(targetNamespace, name); + if (dupes.contains(qName) && notseen.contains(qName)) { + notseen.remove(qName); + return true; + } + return false; + } + + private static boolean isDuplicate(String name, String targetNamespace, Set dupes) { + if (name == null) { + return false; + } + QName qName = new QName(targetNamespace, name); + return (dupes.contains(qName)); + } + + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/InstanceValidator.java b/src/main/java/org/apache/xmlbeans/impl/tool/InstanceValidator.java new file mode 100644 index 0000000..1ce1e68 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/InstanceValidator.java @@ -0,0 +1,199 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.*; + +import java.io.File; +import java.util.*; + +public class InstanceValidator { + public static void printUsage() { + System.out.println("Validates the specified instance against the specified schema."); + System.out.println("Contrast with the svalidate tool, which validates using a stream."); + System.out.println("Usage: validate [-dl] [-nopvr] [-noupa] [-license] schema.xsd instance.xml"); + System.out.println("Options:"); + System.out.println(" -dl - permit network downloads for imports and includes (default is off)"); + System.out.println(" -noupa - do not enforce the unique particle attribution rule"); + System.out.println(" -nopvr - do not enforce the particle valid (restriction) rule"); + System.out.println(" -strict - performs strict(er) validation"); + System.out.println(" -partial - allow partial schema type system"); + System.out.println(" -license - prints license information"); + } + + public static void main(String[] args) { + System.exit(extraMain(args)); + } + + /** + * Use this method to avoid calling {@link java.lang.System#exit(int)} + * + * @param args are command line options + * @return exitCode + */ + public static int extraMain(String[] args) { + Set flags = new HashSet(); + flags.add("h"); + flags.add("help"); + flags.add("usage"); + flags.add("license"); + flags.add("version"); + flags.add("dl"); + flags.add("noupa"); + flags.add("nopvr"); + flags.add("strict"); + flags.add("partial"); + + CommandLine cl = new CommandLine(args, flags, Collections.EMPTY_SET); + + if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null || args.length < 1) { + printUsage(); + return 0; + } + + String[] badopts = cl.getBadOpts(); + if (badopts.length > 0) { + for (int i = 0; i < badopts.length; i++) { + System.out.println("Unrecognized option: " + badopts[i]); + } + printUsage(); + return 0; + } + + if (cl.getOpt("license") != null) { + CommandLine.printLicense(); + return 0; + } + + if (cl.getOpt("version") != null) { + CommandLine.printVersion(); + return 0; + } + + if (cl.args().length == 0) { + return 0; + } + + boolean dl = (cl.getOpt("dl") != null); + boolean nopvr = (cl.getOpt("nopvr") != null); + boolean noupa = (cl.getOpt("noupa") != null); + boolean strict = (cl.getOpt("strict") != null); + boolean partial = (cl.getOpt("partial") != null); + + File[] schemaFiles = cl.filesEndingWith(".xsd"); + File[] instanceFiles = cl.filesEndingWith(".xml"); + File[] jarFiles = cl.filesEndingWith(".jar"); + + List sdocs = new ArrayList<>(); + + + for (File schemaFile : schemaFiles) { + try { + sdocs.add(XmlObject.Factory.parse(schemaFile, (new XmlOptions()).setLoadLineNumbers().setLoadMessageDigest())); + } catch (Exception e) { + System.err.println(schemaFile + " not loadable: " + e); + } + } + + XmlObject[] schemas = (XmlObject[]) sdocs.toArray(new XmlObject[0]); + + SchemaTypeLoader sLoader = null; + Collection compErrors = new ArrayList<>(); + XmlOptions schemaOptions = new XmlOptions(); + schemaOptions.setErrorListener(compErrors); + if (dl) { + schemaOptions.setCompileDownloadUrls(); + } + if (nopvr) { + schemaOptions.setCompileNoPvrRule(); + } + if (noupa) { + schemaOptions.setCompileNoUpaRule(); + } + if (partial) { + schemaOptions.setCompilePartialTypesystem(); + } + + if (jarFiles != null && jarFiles.length > 0) { + sLoader = XmlBeans.typeLoaderForResource(XmlBeans.resourceLoaderForPath(jarFiles)); + } + + int returnCode = 0; + + try { + if (schemas != null && schemas.length > 0) { + sLoader = XmlBeans.compileXsd(schemas, sLoader, schemaOptions); + } + } catch (Exception e) { + if (compErrors.isEmpty() || !(e instanceof XmlException)) { + e.printStackTrace(System.err); + } + System.out.println("Schema invalid:" + (partial ? " couldn't recover from errors" : "")); + for (XmlError compError : compErrors) { + System.out.println(compError); + } + + returnCode = 10; + return returnCode; + } + + // recovered from errors, print out errors + if (partial && !compErrors.isEmpty()) { + returnCode = 11; + System.out.println("Schema invalid: partial schema type system recovered"); + for (XmlError compError : compErrors) { + System.out.println(compError); + } + } + + if (sLoader == null) { + sLoader = XmlBeans.getContextTypeLoader(); + } + + for (File instanceFile : instanceFiles) { + XmlObject xobj; + + try { + XmlOptions xo = new XmlOptions(); + xo.setLoadLineNumbersEndElement(); + xobj = sLoader.parse(instanceFile, null, xo); + } catch (Exception e) { + System.err.println(instanceFile + " not loadable: " + e); + e.printStackTrace(System.err); + continue; + } + + Collection errors = new ArrayList<>(); + + if (xobj.schemaType() == XmlObject.type) { + System.out.println(instanceFile + " NOT valid. "); + System.out.println(" Document type not found."); + } else if (xobj.validate(strict ? + new XmlOptions().setErrorListener(errors).setValidateStrict() : + new XmlOptions().setErrorListener(errors))) { + System.out.println(instanceFile + " valid."); + } else { + returnCode = 1; + System.out.println(instanceFile + " NOT valid."); + for (XmlError error : errors) { + System.out.println(error); + } + } + } + + return returnCode; + } +} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/PrettyPrinter.java b/src/main/java/org/apache/xmlbeans/impl/tool/PrettyPrinter.java similarity index 100% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/PrettyPrinter.java rename to src/main/java/org/apache/xmlbeans/impl/tool/PrettyPrinter.java diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java b/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java new file mode 100644 index 0000000..9ffe860 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/RunXQuery.java @@ -0,0 +1,226 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class RunXQuery { + public static void printUsage() { + System.out.println("Run an XQuery against an XML instance"); + System.out.println("Usage:"); + System.out.println("xquery [-verbose] [-pretty] [-q | -qf query.xq] [file.xml]*"); + System.out.println(" -q to specify a query on the command-line"); + System.out.println(" -qf to specify a file containing a query"); + System.out.println(" -pretty pretty-prints the results"); + System.out.println(" -license prints license information"); + System.out.println(" the query is run on each XML file specified"); + System.out.println(); + } + + public static void main(String[] args) throws Exception { + Set flags = new HashSet<>(); + flags.add("h"); + flags.add("help"); + flags.add("usage"); + flags.add("license"); + flags.add("version"); + flags.add("verbose"); + flags.add("pretty"); + + CommandLine cl = + new CommandLine( + args, flags, + Arrays.asList("q", "qf")); + + if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) { + printUsage(); + System.exit(0); + return; + } + + String[] badopts = cl.getBadOpts(); + if (badopts.length > 0) { + for (String badopt : badopts) { + System.out.println("Unrecognized option: " + badopt); + } + printUsage(); + System.exit(0); + return; + } + + if (cl.getOpt("license") != null) { + CommandLine.printLicense(); + System.exit(0); + return; + } + + if (cl.getOpt("version") != null) { + CommandLine.printVersion(); + System.exit(0); + return; + } + + args = cl.args(); + + if (args.length == 0) { + printUsage(); + System.exit(0); + return; + } + + boolean verbose = cl.getOpt("verbose") != null; + boolean pretty = cl.getOpt("pretty") != null; + + // + // Get and compile the query + // + + String query = cl.getOpt("q"); + String queryfile = cl.getOpt("qf"); + + if (query == null && queryfile == null) { + System.err.println("No query specified"); + System.exit(0); + return; + } + + if (query != null && queryfile != null) { + System.err.println("Specify -qf or -q, not both."); + System.exit(0); + return; + } + + try { + if (queryfile != null) { + File queryFile = new File(queryfile); + FileInputStream is = new FileInputStream(queryFile); + InputStreamReader r = new InputStreamReader(is, StandardCharsets.ISO_8859_1); + + StringBuilder sb = new StringBuilder(); + + for (; ; ) { + int ch = r.read(); + + if (ch < 0) { + break; + } + + sb.append((char) ch); + } + + r.close(); + is.close(); + + query = sb.toString(); + } + } catch (Throwable e) { + System.err.println("Cannot read query file: " + e.getMessage()); + System.exit(1); + return; + } + + if (verbose) { + System.out.println("Compile Query:"); + System.out.println(query); + System.out.println(); + } + + try { + query = XmlBeans.compileQuery(query); + } catch (Exception e) { + System.err.println("Error compiling query: " + e.getMessage()); + System.exit(1); + return; + } + + // + // Get the instance + // + + File[] files = cl.getFiles(); + + for (File file : files) { + XmlObject x; + + try { + if (verbose) { + InputStream is = new FileInputStream(file); + + for (; ; ) { + int ch = is.read(); + + if (ch < 0) { + break; + } + + System.out.write(ch); + } + + is.close(); + + System.out.println(); + } + + x = XmlObject.Factory.parse(file); + } catch (Throwable e) { + System.err.println("Error parsing instance: " + e.getMessage()); + System.exit(1); + return; + } + + if (verbose) { + System.out.println("Executing Query..."); + System.err.println(); + } + + XmlObject[] result; + + try { + result = x.execQuery(query); + } catch (Throwable e) { + System.err.println("Error executing query: " + e.getMessage()); + System.exit(1); + return; + } + + if (verbose) { + System.out.println("Query Result:"); + } + + XmlOptions opts = new XmlOptions(); + opts.setSaveOuter(); + if (pretty) { + opts.setSavePrettyPrint(); + } + + for (XmlObject xmlObject : result) { + xmlObject.save(System.out, opts); + System.out.println(); + } + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java new file mode 100644 index 0000000..3a01777 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java @@ -0,0 +1,224 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.Filer; +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.SystemProperties; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.repackage.Repackager; +import org.apache.xmlbeans.impl.util.FilerImpl; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +public class SchemaCodeGenerator { + /** + * Saves a SchemaTypeSystem to the specified directory. + * + * @param system the SchemaTypeSystem to save + * @param classesDir the destination directory for xsb's + * @param sourceFile if present, the TypeSystemHolder source will be + * generated in this file for subsequent compilation, + * if null then the source will be generated in a temp + * directory and then compiled to the destination dir + * @param repackager the repackager to use when generating the holder class + * @param options options. Can be null + * @deprecated Use {@link SchemaTypeSystem#save(Filer)} instead. + */ + public static void saveTypeSystem(SchemaTypeSystem system, File classesDir, + File sourceFile, Repackager repackager, XmlOptions options) + throws IOException { + Filer filer = new FilerImpl(classesDir, null, repackager, false, false); + system.save(filer); + } + + static void deleteObsoleteFiles(File rootDir, File srcDir, Set seenFiles) { + if (!(rootDir.isDirectory() && srcDir.isDirectory())) { + throw new IllegalArgumentException(); + } + String absolutePath = srcDir.getAbsolutePath(); + // Do a sanity check to make sure we don't delete by mistake some important dir + if (absolutePath.length() <= 5) { + return; + } + if (absolutePath.startsWith("/home/") && + (absolutePath.indexOf("/", 6) >= absolutePath.length() - 1 || + absolutePath.indexOf("/", 6) < 0)) { + return; + } + + // Go recursively starting with srcDir and delete all files that are + // not in the given Set + File[] files = srcDir.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteObsoleteFiles(rootDir, files[i], seenFiles); + } else if (seenFiles.contains(files[i])) { + ; + } else { + deleteXmlBeansFile(files[i]); + deleteDirRecursively(rootDir, files[i].getParentFile()); + } + } + } + + private static void deleteXmlBeansFile(File file) { + if (file.getName().endsWith(".java")) { + file.delete(); + } + } + + private static void deleteDirRecursively(File root, File dir) { + String[] list = dir.list(); + while (list != null && list.length == 0 && !dir.equals(root)) { + dir.delete(); + dir = dir.getParentFile(); + list = dir.list(); + } + } + + protected static File createTempDir() throws IOException { + +// Some beta builds of JDK1.5 are having troubles creating temp directories +// if the java.io.tmpdir doesn't exist. This seems to help. + try { + File tmpDirFile = new File(SystemProperties.getProperty("java.io.tmpdir")); + tmpDirFile.mkdirs(); + } catch (Exception e) { + e.printStackTrace(); + } + + File tmpFile = File.createTempFile("xbean", null); + String path = tmpFile.getAbsolutePath(); + if (!path.endsWith(".tmp")) { + throw new IOException("Error: createTempFile did not create a file ending with .tmp"); + } + path = path.substring(0, path.length() - 4); + File tmpSrcDir = null; + + for (int count = 0; count < 100; count++) { + String name = path + ".d" + (count == 0 ? "" : Integer.toString(count++)); + + tmpSrcDir = new File(name); + + if (!tmpSrcDir.exists()) { + boolean created = tmpSrcDir.mkdirs(); + assert created : "Could not create " + tmpSrcDir.getAbsolutePath(); + break; + } + } + tmpFile.deleteOnExit(); + + return tmpSrcDir; + } + + protected static void tryHardToDelete(File dir) { + tryToDelete(dir); + if (dir.exists()) { + tryToDeleteLater(dir); + } + } + + private static void tryToDelete(File dir) { + if (dir.exists()) { + if (dir.isDirectory()) { + String[] list = dir.list(); // can return null if I/O error + if (list != null) { + for (int i = 0; i < list.length; i++) { + tryToDelete(new File(dir, list[i])); + } + } + } + if (!dir.delete()) { + return; // don't try very hard, because we're just deleting tmp + } + } + } + + private static Set deleteFileQueue = new HashSet(); + private static int triesRemaining = 0; + + private static boolean tryNowThatItsLater() { + List files; + + synchronized (deleteFileQueue) { + files = new ArrayList(deleteFileQueue); + deleteFileQueue.clear(); + } + + List retry = new ArrayList(); + + for (Iterator i = files.iterator(); i.hasNext(); ) { + File file = (File) i.next(); + tryToDelete(file); + if (file.exists()) { + retry.add(file); + } + } + + synchronized (deleteFileQueue) { + if (triesRemaining > 0) { + triesRemaining -= 1; + } + + if (triesRemaining <= 0 || retry.size() == 0) // done? + { + triesRemaining = 0; + } else { + deleteFileQueue.addAll(retry); // try again? + } + + return (triesRemaining <= 0); + } + } + + private static void giveUp() { + synchronized (deleteFileQueue) { + deleteFileQueue.clear(); + triesRemaining = 0; + } + } + + private static void tryToDeleteLater(File dir) { + synchronized (deleteFileQueue) { + deleteFileQueue.add(dir); + if (triesRemaining == 0) { + new Thread() { + public void run() { + // repeats tryNow until triesRemaining == 0 + try { + for (; ; ) { + if (tryNowThatItsLater()) { + return; // succeeded + } + Thread.sleep(1000 * 3); // wait three seconds + } + } catch (InterruptedException e) { + giveUp(); + } + } + }; + } + + if (triesRemaining < 10) { + triesRemaining = 10; + } + } + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java new file mode 100644 index 0000000..0ab9824 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompiler.java @@ -0,0 +1,1094 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.*; +import org.apache.xmlbeans.impl.config.BindingConfigImpl; +import org.apache.xmlbeans.impl.repackage.Repackager; +import org.apache.xmlbeans.impl.schema.*; +import org.apache.xmlbeans.impl.util.FilerImpl; +import org.apache.xmlbeans.impl.values.XmlListImpl; +import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument; +import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; +import org.xml.sax.EntityResolver; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.net.URL; +import java.util.*; + +public class SchemaCompiler { + public static void printUsage() { + System.out.println("Compiles a schema into XML Bean classes and metadata."); + System.out.println("Usage: scomp [opts] [dirs]* [schema.xsd]* [service.wsdl]* [config.xsdconfig]*"); + System.out.println("Options include:"); + System.out.println(" -cp [a;b;c] - classpath"); + System.out.println(" -d [dir] - target binary directory for .class and .xsb files"); + System.out.println(" -src [dir] - target directory for generated .java files"); + System.out.println(" -srconly - do not compile .java files or jar the output."); + System.out.println(" -out [xmltypes.jar] - the name of the output jar"); + System.out.println(" -name - the name of the schema type - defaults to autogenerated name"); + System.out.println(" -dl - permit network downloads for imports and includes (default is off)"); + System.out.println(" -noupa - do not enforce the unique particle attribution rule"); + System.out.println(" -nopvr - do not enforce the particle valid (restriction) rule"); + System.out.println(" -noann - ignore annotations"); + System.out.println(" -novdoc - do not validate contents of "); + System.out.println(" -noext - ignore all extension (Pre/Post and Interface) found in .xsdconfig files"); + System.out.println(" -compiler - path to external java compiler"); + System.out.println(" -ms - initial memory for external java compiler (default '" + CodeGenUtil.DEFAULT_MEM_START + "')"); + System.out.println(" -mx - maximum memory for external java compiler (default '" + CodeGenUtil.DEFAULT_MEM_MAX + "')"); + System.out.println(" -debug - compile with debug symbols"); + System.out.println(" -quiet - print fewer informational messages"); + System.out.println(" -verbose - print more informational messages"); + System.out.println(" -version - prints version information"); + System.out.println(" -license - prints license information"); + System.out.println(" -allowmdef \"[ns] [ns] [ns]\" - ignores multiple defs in given namespaces (use ##local for no-namespace)"); + System.out.println(" -catalog [file] - catalog file for org.apache.xml.resolver.tools.CatalogResolver. (Note: needs resolver.jar from http://xml.apache.org/commons/components/resolver/index.html)"); + /* Undocumented feature - pass in one schema compiler extension and related parameters + System.out.println(" -repackage - repackage specification"); + System.out.println(" -extension - registers a schema compiler extension"); + System.out.println(" -extensionParms - specify parameters for the compiler extension"); + System.out.println(" -schemaCodePrinter - specify SchemaCodePrinter class"); + */ + System.out.println(); + } + + public static void main(String[] args) { + if (args.length == 0) { + printUsage(); + System.exit(0); + return; + } + + Set flags = new HashSet<>(); + flags.add("h"); + flags.add("help"); + flags.add("usage"); + flags.add("license"); + flags.add("quiet"); + flags.add("verbose"); + flags.add("version"); + flags.add("dl"); + flags.add("noupa"); + flags.add("nopvr"); + flags.add("noann"); + flags.add("novdoc"); + flags.add("noext"); + flags.add("srconly"); + flags.add("debug"); + + Set opts = new HashSet<>(); + opts.add("out"); + opts.add("name"); + opts.add("src"); + opts.add("d"); + opts.add("cp"); + opts.add("compiler"); + opts.add("jar"); // deprecated + opts.add("ms"); + opts.add("mx"); + opts.add("repackage"); + opts.add("schemaCodePrinter"); + opts.add("extension"); + opts.add("extensionParms"); + opts.add("allowmdef"); + opts.add("catalog"); + CommandLine cl = new CommandLine(args, flags, opts); + + if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) { + printUsage(); + System.exit(0); + return; + } + + String[] badopts = cl.getBadOpts(); + if (badopts.length > 0) { + for (String badopt : badopts) { + System.out.println("Unrecognized option: " + badopt); + } + printUsage(); + System.exit(0); + return; + } + + if (cl.getOpt("license") != null) { + CommandLine.printLicense(); + System.exit(0); + return; + } + + if (cl.getOpt("version") != null) { + CommandLine.printVersion(); + System.exit(0); + return; + } + + boolean verbose = (cl.getOpt("verbose") != null); + boolean quiet = (cl.getOpt("quiet") != null); + if (verbose) { + quiet = false; + } + + if (verbose) { + CommandLine.printVersion(); + } + + String outputfilename = cl.getOpt("out"); + + String repackage = cl.getOpt("repackage"); + + String codePrinterClass = cl.getOpt("schemaCodePrinter"); + SchemaCodePrinter codePrinter = null; + if (codePrinterClass != null) { + try { + codePrinter = (SchemaCodePrinter) + Class.forName(codePrinterClass).getDeclaredConstructor().newInstance(); + } catch (Exception e) { + System.err.println + ("Failed to load SchemaCodePrinter class " + + codePrinterClass + "; proceeding with default printer"); + } + } + + String name = cl.getOpt("name"); + + boolean download = (cl.getOpt("dl") != null); + boolean noUpa = (cl.getOpt("noupa") != null); + boolean noPvr = (cl.getOpt("nopvr") != null); + boolean noAnn = (cl.getOpt("noann") != null); + boolean noVDoc = (cl.getOpt("novdoc") != null); + boolean noExt = (cl.getOpt("noext") != null); + boolean nojavac = (cl.getOpt("srconly") != null); + boolean debug = (cl.getOpt("debug") != null); + + String allowmdef = cl.getOpt("allowmdef"); + Set mdefNamespaces = (allowmdef == null ? Collections.emptySet() : + new HashSet<>(Arrays.asList(XmlListImpl.split_list(allowmdef)))); + + List extensions = new ArrayList<>(); + if (cl.getOpt("extension") != null) { + try { + Extension e = new Extension(); + e.setClassName(Class.forName(cl.getOpt("extension"), false, Thread.currentThread().getContextClassLoader())); + extensions.add(e); + } catch (ClassNotFoundException e) { + System.err.println("Could not find extension class: " + cl.getOpt("extension") + " Is it on your classpath?"); + System.exit(1); + } + } + + if (extensions.size() > 0) { + // example: -extensionParms typeMappingFileLocation=d:\types + if (cl.getOpt("extensionParms") != null) { + Extension e = extensions.get(0); + // extensionParms are delimited by ';' + StringTokenizer parmTokens = new StringTokenizer(cl.getOpt("extensionParms"), ";"); + while (parmTokens.hasMoreTokens()) { + // get name value pair for each extension parms and stick into extension parms + String nvPair = parmTokens.nextToken(); + int index = nvPair.indexOf('='); + if (index < 0) { + System.err.println("extensionParms should be name=value;name=value"); + System.exit(1); + } + String n = nvPair.substring(0, index); + String v = nvPair.substring(index + 1); + Extension.Param param = e.createParam(); + param.setName(n); + param.setValue(v); + } + } + } + + String classesdir = cl.getOpt("d"); + File classes = null; + if (classesdir != null) { + classes = new File(classesdir); + } + + String srcdir = cl.getOpt("src"); + File src = null; + if (srcdir != null) { + src = new File(srcdir); + } + if (nojavac && srcdir == null && classes != null) { + src = classes; + } + + // create temp directory + File tempdir = null; + if (src == null || classes == null) { + try { + tempdir = SchemaCodeGenerator.createTempDir(); + } catch (java.io.IOException e) { + System.err.println("Error creating temp dir " + e); + System.exit(1); + } + } + + File jarfile = null; + if (outputfilename == null && classes == null && !nojavac) { + outputfilename = "xmltypes.jar"; + } + if (outputfilename != null) { + jarfile = new File(outputfilename); + } + + if (src == null) { + src = IOUtil.createDir(tempdir, "src"); + } + if (classes == null) { + classes = IOUtil.createDir(tempdir, "classes"); + } + + File[] classpath; + String cpString = cl.getOpt("cp"); + if (cpString != null) { + String[] cpparts = cpString.split(File.pathSeparator); + List cpList = new ArrayList<>(); + for (String cppart : cpparts) { + cpList.add(new File(cppart)); + } + classpath = cpList.toArray(new File[0]); + } else { + classpath = CodeGenUtil.systemClasspath(); + } + + String compiler = cl.getOpt("compiler"); + String jar = cl.getOpt("jar"); + if (verbose && jar != null) { + System.out.println("The 'jar' option is no longer supported."); + } + + String memoryInitialSize = cl.getOpt("ms"); + String memoryMaximumSize = cl.getOpt("mx"); + + File[] xsdFiles = cl.filesEndingWith(".xsd"); + File[] wsdlFiles = cl.filesEndingWith(".wsdl"); + File[] javaFiles = cl.filesEndingWith(".java"); + File[] configFiles = cl.filesEndingWith(".xsdconfig"); + URL[] urlFiles = cl.getURLs(); + + if (xsdFiles.length + wsdlFiles.length + urlFiles.length == 0) { + System.out.println("Could not find any xsd or wsdl files to process."); + System.exit(0); + } + File baseDir = cl.getBaseDir(); + URI baseURI = baseDir == null ? null : baseDir.toURI(); + + XmlErrorPrinter err = new XmlErrorPrinter(verbose, baseURI); + + String catString = cl.getOpt("catalog"); + + Parameters params = new Parameters(); + params.setBaseDir(baseDir); + params.setXsdFiles(xsdFiles); + params.setWsdlFiles(wsdlFiles); + params.setJavaFiles(javaFiles); + params.setConfigFiles(configFiles); + params.setUrlFiles(urlFiles); + params.setClasspath(classpath); + params.setOutputJar(jarfile); + params.setName(name); + params.setSrcDir(src); + params.setClassesDir(classes); + params.setCompiler(compiler); + params.setMemoryInitialSize(memoryInitialSize); + params.setMemoryMaximumSize(memoryMaximumSize); + params.setNojavac(nojavac); + params.setQuiet(quiet); + params.setVerbose(verbose); + params.setDownload(download); + params.setNoUpa(noUpa); + params.setNoPvr(noPvr); + params.setNoAnn(noAnn); + params.setNoVDoc(noVDoc); + params.setNoExt(noExt); + params.setDebug(debug); + params.setErrorListener(err); + params.setRepackage(repackage); + params.setExtensions(extensions); + params.setMdefNamespaces(mdefNamespaces); + params.setCatalogFile(catString); + params.setSchemaCodePrinter(codePrinter); + + boolean result = compile(params); + + if (tempdir != null) { + SchemaCodeGenerator.tryHardToDelete(tempdir); + } + + if (!result) { + System.exit(1); + } + + System.exit(0); + } + + public static class Parameters { + private File baseDir; + private File[] xsdFiles; + private File[] wsdlFiles; + private File[] javaFiles; + private File[] configFiles; + private URL[] urlFiles; + private File[] classpath; + private File outputJar; + private String name; + private File srcDir; + private File classesDir; + private String memoryInitialSize; + private String memoryMaximumSize; + private String compiler; + private boolean nojavac; + private boolean quiet; + private boolean verbose; + private boolean download; + private Collection errorListener; + private boolean noUpa; + private boolean noPvr; + private boolean noAnn; + private boolean noVDoc; + private boolean noExt; + private boolean debug; + private boolean incrementalSrcGen; + private String repackage; + private List extensions = Collections.emptyList(); + private Set mdefNamespaces = Collections.emptySet(); + private String catalogFile; + private SchemaCodePrinter schemaCodePrinter; + private EntityResolver entityResolver; + + public File getBaseDir() { + return baseDir; + } + + public void setBaseDir(File baseDir) { + this.baseDir = baseDir; + } + + public File[] getXsdFiles() { + return xsdFiles; + } + + public void setXsdFiles(File[] xsdFiles) { + this.xsdFiles = xsdFiles; + } + + public File[] getWsdlFiles() { + return wsdlFiles; + } + + public void setWsdlFiles(File[] wsdlFiles) { + this.wsdlFiles = wsdlFiles; + } + + public File[] getJavaFiles() { + return javaFiles; + } + + public void setJavaFiles(File[] javaFiles) { + this.javaFiles = javaFiles; + } + + public File[] getConfigFiles() { + return configFiles; + } + + public void setConfigFiles(File[] configFiles) { + this.configFiles = configFiles; + } + + public URL[] getUrlFiles() { + return urlFiles; + } + + public void setUrlFiles(URL[] urlFiles) { + this.urlFiles = urlFiles; + } + + public File[] getClasspath() { + return classpath; + } + + public void setClasspath(File[] classpath) { + this.classpath = classpath; + } + + public File getOutputJar() { + return outputJar; + } + + public void setOutputJar(File outputJar) { + this.outputJar = outputJar; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public File getSrcDir() { + return srcDir; + } + + public void setSrcDir(File srcDir) { + this.srcDir = srcDir; + } + + public File getClassesDir() { + return classesDir; + } + + public void setClassesDir(File classesDir) { + this.classesDir = classesDir; + } + + public boolean isNojavac() { + return nojavac; + } + + public void setNojavac(boolean nojavac) { + this.nojavac = nojavac; + } + + public boolean isQuiet() { + return quiet; + } + + public void setQuiet(boolean quiet) { + this.quiet = quiet; + } + + public boolean isVerbose() { + return verbose; + } + + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + public boolean isDownload() { + return download; + } + + public void setDownload(boolean download) { + this.download = download; + } + + public boolean isNoUpa() { + return noUpa; + } + + public void setNoUpa(boolean noUpa) { + this.noUpa = noUpa; + } + + public boolean isNoPvr() { + return noPvr; + } + + public void setNoPvr(boolean noPvr) { + this.noPvr = noPvr; + } + + public boolean isNoAnn() { + return noAnn; + } + + public void setNoAnn(boolean noAnn) { + this.noAnn = noAnn; + } + + public boolean isNoVDoc() { + return noVDoc; + } + + public void setNoVDoc(boolean newNoVDoc) { + this.noVDoc = newNoVDoc; + } + + public boolean isNoExt() { + return noExt; + } + + public void setNoExt(boolean newNoExt) { + this.noExt = newNoExt; + } + + public boolean isIncrementalSrcGen() { + return incrementalSrcGen; + } + + public void setIncrementalSrcGen(boolean incrSrcGen) { + this.incrementalSrcGen = incrSrcGen; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + public String getMemoryInitialSize() { + return memoryInitialSize; + } + + public void setMemoryInitialSize(String memoryInitialSize) { + this.memoryInitialSize = memoryInitialSize; + } + + public String getMemoryMaximumSize() { + return memoryMaximumSize; + } + + public void setMemoryMaximumSize(String memoryMaximumSize) { + this.memoryMaximumSize = memoryMaximumSize; + } + + public String getCompiler() { + return compiler; + } + + public void setCompiler(String compiler) { + this.compiler = compiler; + } + + public Collection getErrorListener() { + return errorListener; + } + + public void setErrorListener(Collection errorListener) { + this.errorListener = errorListener; + } + + public String getRepackage() { + return repackage; + } + + public void setRepackage(String newRepackage) { + repackage = newRepackage; + } + + public List getExtensions() { + return extensions; + } + + public void setExtensions(List extensions) { + this.extensions = extensions; + } + + public Set getMdefNamespaces() { + return mdefNamespaces; + } + + public void setMdefNamespaces(Set mdefNamespaces) { + this.mdefNamespaces = mdefNamespaces; + } + + public String getCatalogFile() { + return catalogFile; + } + + public void setCatalogFile(String catalogPropFile) { + this.catalogFile = catalogPropFile; + } + + public SchemaCodePrinter getSchemaCodePrinter() { + return schemaCodePrinter; + } + + public void setSchemaCodePrinter(SchemaCodePrinter schemaCodePrinter) { + this.schemaCodePrinter = schemaCodePrinter; + } + + public EntityResolver getEntityResolver() { + return entityResolver; + } + + public void setEntityResolver(EntityResolver entityResolver) { + this.entityResolver = entityResolver; + } + } + + private static SchemaTypeSystem loadTypeSystem(String name, File[] xsdFiles, File[] wsdlFiles, URL[] urlFiles, File[] configFiles, + File[] javaFiles, ResourceLoader cpResourceLoader, + boolean download, boolean noUpa, boolean noPvr, boolean noAnn, boolean noVDoc, boolean noExt, + Set mdefNamespaces, File baseDir, Map sourcesToCopyMap, + Collection outerErrorListener, File schemasDir, EntityResolver entResolver, File[] classpath) { + XmlErrorWatcher errorListener = new XmlErrorWatcher(outerErrorListener); + + // construct the state (have to initialize early in case of errors) + StscState state = StscState.start(); + try { + state.setErrorListener(errorListener); + + // For parsing XSD and WSDL files, we should use the SchemaDocument + // classloader rather than the thread context classloader. This is + // because in some situations (such as when being invoked by ant + // underneath the ide) the context classloader is potentially weird + // (because of the design of ant). + + SchemaTypeLoader loader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader()); + + // step 1, parse all the XSD files. + ArrayList scontentlist = new ArrayList<>(); + if (xsdFiles != null) { + for (File xsdFile : xsdFiles) { + try { + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setLoadMessageDigest(); + options.setEntityResolver(entResolver); + + XmlObject schemadoc = loader.parse(xsdFile, null, options); + if (!(schemadoc instanceof SchemaDocument)) { + StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, + new Object[]{xsdFile, "schema"}, schemadoc); + } else { + addSchema(xsdFile.toString(), (SchemaDocument) schemadoc, + errorListener, noVDoc, scontentlist); + } + } catch (XmlException e) { + errorListener.add(e.getError()); + } catch (Exception e) { + StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, + new Object[]{"xsd", xsdFile, e.getMessage()}, xsdFile); + } + } + } + + // step 2, parse all WSDL files + if (wsdlFiles != null) { + for (File wsdlFile : wsdlFiles) { + try { + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setLoadSubstituteNamespaces(Collections.singletonMap( + "http://schemas.xmlsoap.org/wsdl/", "http://www.apache.org/internal/xmlbeans/wsdlsubst" + )); + options.setEntityResolver(entResolver); + + XmlObject wsdldoc = loader.parse(wsdlFile, null, options); + + if (!(wsdldoc instanceof org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument)) { + StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, + new Object[]{wsdlFile, "wsdl"}, wsdldoc); + } else { + addWsdlSchemas(wsdlFile.toString(), (org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument) wsdldoc, errorListener, noVDoc, scontentlist); + } + } catch (XmlException e) { + errorListener.add(e.getError()); + } catch (Exception e) { + StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, + new Object[]{"wsdl", wsdlFile, e.getMessage()}, wsdlFile); + } + } + } + + // step 3, parse all URL files + // XMLBEANS-58 - Ability to pass URLs instead of Files for Wsdl/Schemas + if (urlFiles != null) { + for (URL urlFile : urlFiles) { + try { + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setLoadSubstituteNamespaces(Collections.singletonMap("http://schemas.xmlsoap.org/wsdl/", "http://www.apache.org/internal/xmlbeans/wsdlsubst")); + options.setEntityResolver(entResolver); + + XmlObject urldoc = loader.parse(urlFile, null, options); + + if ((urldoc instanceof org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument)) { + addWsdlSchemas(urlFile.toString(), (org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument) urldoc, errorListener, noVDoc, scontentlist); + } else if ((urldoc instanceof SchemaDocument)) { + addSchema(urlFile.toString(), (SchemaDocument) urldoc, + errorListener, noVDoc, scontentlist); + } else { + StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, + new Object[]{urlFile, "wsdl or schema"}, urldoc); + } + + } catch (XmlException e) { + errorListener.add(e.getError()); + } catch (Exception e) { + StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, + new Object[]{"url", urlFile, e.getMessage()}, urlFile); + } + } + } + + Schema[] sdocs = scontentlist.toArray(new Schema[0]); + + // now the config files. + ArrayList cdoclist = new ArrayList<>(); + if (configFiles != null) { + if (noExt) { + System.out.println("Pre/Post and Interface extensions will be ignored."); + } + + for (File configFile : configFiles) { + try { + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + options.setEntityResolver(entResolver); + options.setLoadSubstituteNamespaces(MAP_COMPATIBILITY_CONFIG_URIS); + + XmlObject configdoc = loader.parse(configFile, null, options); + if (!(configdoc instanceof ConfigDocument)) { + StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, + new Object[]{configFile, "xsd config"}, configdoc); + } else { + StscState.addInfo(errorListener, "Loading config file " + configFile); + if (configdoc.validate(new XmlOptions().setErrorListener(errorListener))) { + ConfigDocument.Config config = ((ConfigDocument) configdoc).getConfig(); + cdoclist.add(config); + if (noExt) { + //disable extensions + config.setExtensionArray(new Extensionconfig[]{}); + } + } + } + } catch (XmlException e) { + errorListener.add(e.getError()); + } catch (Exception e) { + StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, + new Object[]{"xsd config", configFile, e.getMessage()}, configFile); + } + } + } + ConfigDocument.Config[] cdocs = cdoclist.toArray(new ConfigDocument.Config[0]); + + SchemaTypeLoader linkTo = SchemaTypeLoaderImpl.build(null, cpResourceLoader, null); + + URI baseURI = null; + if (baseDir != null) { + baseURI = baseDir.toURI(); + } + + XmlOptions opts = new XmlOptions(); + if (download) { + opts.setCompileDownloadUrls(); + } + if (noUpa) { + opts.setCompileNoUpaRule(); + } + if (noPvr) { + opts.setCompileNoPvrRule(); + } + if (noAnn) { + opts.setCompileNoAnnotations(); + } + if (mdefNamespaces != null) { + opts.setCompileMdefNamespaces(mdefNamespaces); + } + opts.setCompileNoValidation(); // already validated here + opts.setEntityResolver(entResolver); + + // now pass it to the main compile function + SchemaTypeSystemCompiler.Parameters params = new SchemaTypeSystemCompiler.Parameters(); + params.setName(name); + params.setSchemas(sdocs); + params.setConfig(BindingConfigImpl.forConfigDocuments(cdocs, javaFiles, classpath)); + params.setLinkTo(linkTo); + params.setOptions(opts); + params.setErrorListener(errorListener); + params.setJavaize(true); + params.setBaseURI(baseURI); + params.setSourcesToCopyMap(sourcesToCopyMap); + params.setSchemasDir(schemasDir); + return SchemaTypeSystemCompiler.compile(params); + } finally { + StscState.end(); + } + } + + private static void addSchema(String name, SchemaDocument schemadoc, + XmlErrorWatcher errorListener, boolean noVDoc, List scontentlist) { + StscState.addInfo(errorListener, "Loading schema file " + name); + XmlOptions opts = new XmlOptions().setErrorListener(errorListener); + if (noVDoc) { + opts.setValidateTreatLaxAsSkip(); + } + if (schemadoc.validate(opts)) { + scontentlist.add((schemadoc).getSchema()); + } + } + + private static void addWsdlSchemas(String name, + org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument wsdldoc, + XmlErrorWatcher errorListener, boolean noVDoc, List scontentlist) { + if (wsdlContainsEncoded(wsdldoc)) { + StscState.addWarning(errorListener, "The WSDL " + name + " uses SOAP encoding. SOAP encoding is not compatible with literal XML Schema.", XmlErrorCodes.GENERIC_ERROR, wsdldoc); + } + StscState.addInfo(errorListener, "Loading wsdl file " + name); + XmlOptions opts = new XmlOptions().setErrorListener(errorListener); + if (noVDoc) { + opts.setValidateTreatLaxAsSkip(); + } + XmlObject[] types = wsdldoc.getDefinitions().getTypesArray(); + int count = 0; + for (XmlObject type : types) { + Schema[] schemas = (Schema[]) type.selectPath("declare namespace xs=\"http://www.w3.org/2001/XMLSchema\" xs:schema"); + if (schemas.length == 0) { + StscState.addWarning(errorListener, "The WSDL " + name + " did not have any schema documents in namespace 'http://www.w3.org/2001/XMLSchema'", XmlErrorCodes.GENERIC_ERROR, wsdldoc); + continue; + } + + for (Schema schema : schemas) { + if (schema.validate(opts)) { + count++; + scontentlist.add(schema); + } + } + } + StscState.addInfo(errorListener, "Processing " + count + " schema(s) in " + name); + } + + public static boolean compile(Parameters params) { + File baseDir = params.getBaseDir(); + File[] xsdFiles = params.getXsdFiles(); + File[] wsdlFiles = params.getWsdlFiles(); + URL[] urlFiles = params.getUrlFiles(); + File[] javaFiles = params.getJavaFiles(); + File[] configFiles = params.getConfigFiles(); + File[] classpath = params.getClasspath(); + File outputJar = params.getOutputJar(); + String name = params.getName(); + File srcDir = params.getSrcDir(); + File classesDir = params.getClassesDir(); + String compiler = params.getCompiler(); + String memoryInitialSize = params.getMemoryInitialSize(); + String memoryMaximumSize = params.getMemoryMaximumSize(); + boolean nojavac = params.isNojavac(); + boolean debug = params.isDebug(); + boolean verbose = params.isVerbose(); + boolean quiet = params.isQuiet(); + boolean download = params.isDownload(); + boolean noUpa = params.isNoUpa(); + boolean noPvr = params.isNoPvr(); + boolean noAnn = params.isNoAnn(); + boolean noVDoc = params.isNoVDoc(); + boolean noExt = params.isNoExt(); + boolean incrSrcGen = params.isIncrementalSrcGen(); + Collection outerErrorListener = params.getErrorListener(); + + String repackage = params.getRepackage(); + + if (repackage != null) { + SchemaTypeLoaderImpl.METADATA_PACKAGE_LOAD = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN; + + Repackager repackager = new Repackager(repackage); + + StringBuffer sb = new StringBuffer(SchemaTypeLoaderImpl.METADATA_PACKAGE_LOAD); + sb = repackager.repackage(sb); + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN = sb.toString(); + + System.out.println("SchemaCompiler Metadata LOAD:" + SchemaTypeLoaderImpl.METADATA_PACKAGE_LOAD + " GEN:" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN); + } + + SchemaCodePrinter codePrinter = params.getSchemaCodePrinter(); + List extensions = params.getExtensions(); + Set mdefNamespaces = params.getMdefNamespaces(); + + EntityResolver cmdLineEntRes = params.getEntityResolver() == null ? + ResolverUtil.resolverForCatalog(params.getCatalogFile()) : params.getEntityResolver(); + + if (srcDir == null || classesDir == null) { + throw new IllegalArgumentException("src and class gen directories may not be null."); + } + + long start = System.currentTimeMillis(); + + // Calculate the usenames based on the relativized filenames on the filesystem + if (baseDir == null) { + String userDir = SystemProperties.getProperty("user.dir"); + assert (userDir != null); + baseDir = new File(userDir); + } + + ResourceLoader cpResourceLoader = null; + + Map sourcesToCopyMap = new HashMap<>(); + + if (classpath != null) { + cpResourceLoader = new PathResourceLoader(classpath); + } + + boolean result = true; + + File schemasDir = IOUtil.createDir(classesDir, SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/src"); + + // build the in-memory type system + XmlErrorWatcher errorListener = new XmlErrorWatcher(outerErrorListener); + SchemaTypeSystem system = loadTypeSystem(name, xsdFiles, wsdlFiles, urlFiles, configFiles, + javaFiles, cpResourceLoader, download, noUpa, noPvr, noAnn, noVDoc, noExt, mdefNamespaces, + baseDir, sourcesToCopyMap, errorListener, schemasDir, cmdLineEntRes, classpath); + if (errorListener.hasError()) { + result = false; + } + long finish = System.currentTimeMillis(); + if (!quiet) { + System.out.println("Time to build schema type system: " + ((double) (finish - start) / 1000.0) + " seconds"); + } + + // now code generate and compile the JAR + if (result && system != null) // todo: don't check "result" here if we want to compile anyway, ignoring invalid schemas + { + start = System.currentTimeMillis(); + + // filer implementation writes binary .xsd and generated source to disk + Repackager repackager = (repackage == null ? null : new Repackager(repackage)); + FilerImpl filer = new FilerImpl(classesDir, srcDir, repackager, verbose, incrSrcGen); + + // currently just for schemaCodePrinter + XmlOptions options = new XmlOptions(); + if (codePrinter != null) { + options.setSchemaCodePrinter(codePrinter); + } + + // save .xsb files + system.save(filer); + + // gen source files + result = SchemaTypeSystemCompiler.generateTypes(system, filer, options); + + if (incrSrcGen) { + // We have to delete extra source files that may be out of date + SchemaCodeGenerator.deleteObsoleteFiles(srcDir, srcDir, + new HashSet<>(filer.getSourceFiles())); + } + + if (result) { + finish = System.currentTimeMillis(); + if (!quiet) { + System.out.println("Time to generate code: " + ((double) (finish - start) / 1000.0) + " seconds"); + } + } + + // compile source + if (result && !nojavac) { + start = System.currentTimeMillis(); + + List sourcefiles = filer.getSourceFiles(); + + if (javaFiles != null) { + sourcefiles.addAll(java.util.Arrays.asList(javaFiles)); + } + if (!CodeGenUtil.externalCompile(sourcefiles, classesDir, classpath, debug, compiler, memoryInitialSize, memoryMaximumSize, quiet, verbose)) { + result = false; + } + + finish = System.currentTimeMillis(); + if (result && !params.isQuiet()) { + System.out.println("Time to compile code: " + ((double) (finish - start) / 1000.0) + " seconds"); + } + + // jar classes and .xsb + if (result && outputJar != null) { + try { + new JarHelper().jarDir(classesDir, outputJar); + } catch (IOException e) { + System.err.println("IO Error " + e); + result = false; + } + + if (result && !params.isQuiet()) { + System.out.println("Compiled types to: " + outputJar); + } + } + } + } + + if (!result && !quiet) { + System.out.println("BUILD FAILED"); + } else { + // call schema compiler extension if registered + runExtensions(extensions, system, classesDir); + } + + if (cpResourceLoader != null) { + cpResourceLoader.close(); + } + return result; + } + + private static void runExtensions(List extensions, SchemaTypeSystem system, File classesDir) { + if (extensions != null && extensions.size() > 0) { + SchemaCompilerExtension sce; + Iterator i = extensions.iterator(); + Map extensionParms; + String classesDirName; + try { + classesDirName = classesDir.getCanonicalPath(); + } catch (java.io.IOException e) { + System.out.println("WARNING: Unable to get the path for schema jar file"); + classesDirName = classesDir.getAbsolutePath(); + } + + while (i.hasNext()) { + Extension extension = i.next(); + try { + sce = (SchemaCompilerExtension) extension.getClassName().getDeclaredConstructor().newInstance(); + } catch (NoSuchMethodException | InstantiationException e) { + System.out.println("UNABLE to instantiate schema compiler extension:" + extension.getClassName().getName()); + System.out.println("EXTENSION Class was not run"); + break; + } catch (InvocationTargetException | IllegalAccessException e) { + System.out.println("ILLEGAL ACCESS Exception when attempting to instantiate schema compiler extension: " + extension.getClassName().getName()); + System.out.println("EXTENSION Class was not run"); + break; + } + + System.out.println("Running Extension: " + sce.getExtensionName()); + extensionParms = new HashMap<>(); + for (Extension.Param p : extension.getParams()) { + extensionParms.put(p.getName(), p.getValue()); + } + extensionParms.put("classesDir", classesDirName); + sce.schemaCompilerExtension(system, extensionParms); + } + } + } + + + private static boolean wsdlContainsEncoded(XmlObject wsdldoc) { + // search for any etc. + XmlObject[] useAttrs = wsdldoc.selectPath( + "declare namespace soap='http://schemas.xmlsoap.org/wsdl/soap/' " + + ".//soap:body/@use|.//soap:header/@use|.//soap:fault/@use"); + for (XmlObject useAttr : useAttrs) { + if ("encoded".equals(((SimpleValue) useAttr).getStringValue())) { + return true; + } + } + return false; + } + + private static final String CONFIG_URI = "http://xml.apache.org/xmlbeans/2004/02/xbean/config"; + private static final String COMPATIBILITY_CONFIG_URI = "http://www.bea.com/2002/09/xbean/config"; + private static final Map MAP_COMPATIBILITY_CONFIG_URIS + = Collections.singletonMap(COMPATIBILITY_CONFIG_URI, CONFIG_URI); +} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompilerExtension.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompilerExtension.java similarity index 100% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompilerExtension.java rename to src/main/java/org/apache/xmlbeans/impl/tool/SchemaCompilerExtension.java diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCopy.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaCopy.java similarity index 100% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCopy.java rename to src/main/java/org/apache/xmlbeans/impl/tool/SchemaCopy.java diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaImportResolver.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaImportResolver.java similarity index 100% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaImportResolver.java rename to src/main/java/org/apache/xmlbeans/impl/tool/SchemaImportResolver.java diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaResourceManager.java b/src/main/java/org/apache/xmlbeans/impl/tool/SchemaResourceManager.java similarity index 100% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaResourceManager.java rename to src/main/java/org/apache/xmlbeans/impl/tool/SchemaResourceManager.java diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/StreamInstanceValidator.java b/src/main/java/org/apache/xmlbeans/impl/tool/StreamInstanceValidator.java similarity index 100% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/StreamInstanceValidator.java rename to src/main/java/org/apache/xmlbeans/impl/tool/StreamInstanceValidator.java diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/TypeHierarchyPrinter.java b/src/main/java/org/apache/xmlbeans/impl/tool/TypeHierarchyPrinter.java similarity index 98% rename from src/xmlcomp/org/apache/xmlbeans/impl/tool/TypeHierarchyPrinter.java rename to src/main/java/org/apache/xmlbeans/impl/tool/TypeHierarchyPrinter.java index cbca804..856e8a9 100644 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/TypeHierarchyPrinter.java +++ b/src/main/java/org/apache/xmlbeans/impl/tool/TypeHierarchyPrinter.java @@ -143,7 +143,7 @@ public static void main(String[] args) throws Exception if (noupa) schemaOptions.setCompileNoUpaRule(); if (partial) - schemaOptions.put("COMPILE_PARTIAL_TYPESYSTEM"); + schemaOptions.setCompilePartialTypesystem(); if (jarFiles != null && jarFiles.length > 0) linkTo = XmlBeans.typeLoaderForResource(XmlBeans.resourceLoaderForPath(jarFiles)); @@ -217,7 +217,7 @@ public static void main(String[] args) throws Exception // step 4: print the tree, starting from xs:anyType (i.e., XmlObject.type) List typesToPrint = new ArrayList(); typesToPrint.add(XmlObject.type); - StringBuffer spaces = new StringBuffer(); + StringBuilder spaces = new StringBuilder(); while (!typesToPrint.isEmpty()) { SchemaType sType = (SchemaType)typesToPrint.remove(typesToPrint.size() - 1); diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java new file mode 100644 index 0000000..337a47a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBean.java @@ -0,0 +1,811 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.FileScanner; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Jar; +import org.apache.tools.ant.taskdefs.Javac; +import org.apache.tools.ant.taskdefs.MatchingTask; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.Reference; +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.impl.common.IOUtil; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; +import java.util.*; + +/** + * Modeled after Ant's javac and zip tasks. + *

      + * Schema files to process, or directories of schema files, are set with the 'schema' + * attribute, and can be filtered with 'includes' and 'excludes'. + * Alternatively, one or more nested <fileset> elements can specify the + * files and directories to be used to generate this XMLBean. + * The include set can also define .java files that should be built as well. + * See the FileSet documentation at http://jakarta.apache.org/ant/manual/index.html + * for instructions on FileSets if you are unfamiliar with their usage. + */ + +public class XMLBean extends MatchingTask { + private final List schemas = new ArrayList<>(); + + private Set mdefnamespaces; + + private Path classpath; + + private File destfile, + schema, + srcgendir, + classgendir; + + private boolean quiet, + verbose, + debug, + optimize, + download, + srconly, + noupa, + nopvr, + noann, + novdoc, + noext = false, + failonerror = true, + fork = true, + includeAntRuntime = true, + noSrcRegen, + includeJavaRuntime = false, + nowarn = false; + + private String typesystemname, + forkedExecutable, + compiler, + debugLevel, + memoryInitialSize, + memoryMaximumSize, + catalog, + repackage; + + private final List extensions = new ArrayList<>(); + + private final Map> _extRouter = new HashMap<>(5); + + private static final String XSD = ".xsd", + WSDL = ".wsdl", + JAVA = ".java", + XSDCONFIG = ".xsdconfig"; + + + public void execute() throws BuildException { + /* VALIDATION */ + //required + if (schemas.size() == 0 + && schema == null + && fileset.getDir(project) == null) { + String msg = "The 'schema' or 'dir' attribute or a nested fileset is required."; + if (failonerror) { + throw new BuildException(msg); + } else { + log(msg, Project.MSG_ERR); + return; + } + } + + _extRouter.put(XSD, new HashSet<>()); + _extRouter.put(WSDL, new HashSet<>()); + _extRouter.put(JAVA, new HashSet<>()); + _extRouter.put(XSDCONFIG, new HashSet<>()); + + File theBasedir = schema; + + if (schema != null) { + if (schema.isDirectory()) { + FileScanner scanner = getDirectoryScanner(schema); + String[] paths = scanner.getIncludedFiles(); + processPaths(paths, scanner.getBasedir()); + } else { + theBasedir = schema.getParentFile(); + processPaths(new String[]{schema.getName()}, theBasedir); + } + } + + if (fileset.getDir(project) != null) { + schemas.add(fileset); + } + + for (FileSet fs : schemas) { + FileScanner scanner = fs.getDirectoryScanner(project); + File basedir = scanner.getBasedir(); + String[] paths = scanner.getIncludedFiles(); + + processPaths(paths, basedir); + } + + Set xsdList = _extRouter.get(XSD); + Set wsdlList = _extRouter.get(WSDL); + + if (xsdList.size() + wsdlList.size() == 0) { + log("Could not find any xsd or wsdl files to process.", Project.MSG_WARN); + return; + } + + //optional + Set javaList = _extRouter.get(JAVA); + Set xsdconfigList = _extRouter.get(XSDCONFIG); + + if (srcgendir == null && srconly) { + srcgendir = classgendir; + } + + if (destfile == null && classgendir == null && !srconly) { + destfile = new File("xmltypes.jar"); + } + + if (verbose) { + quiet = false; + } + + /* EXECUTION */ + + File[] xsdArray = xsdList.toArray(new File[0]); + File[] wsdlArray = wsdlList.toArray(new File[0]); + File[] javaArray = javaList.toArray(new File[0]); + File[] xsdconfigArray = xsdconfigList.toArray(new File[0]); + ErrorLogger err = new ErrorLogger(verbose); + + boolean success = false; + + try { + // create a temp directory + File tmpdir = null; + if (srcgendir == null || classgendir == null) { + tmpdir = SchemaCodeGenerator.createTempDir(); + } + if (srcgendir == null) { + srcgendir = IOUtil.createDir(tmpdir, "src"); + } + if (classgendir == null) { + classgendir = IOUtil.createDir(tmpdir, "classes"); + } + + // use the system classpath if user didn't provide any + if (classpath == null) { + classpath = new Path(project); + classpath.concatSystemClasspath(); + } + + // prepend the output directory on the classpath + Path.PathElement pathElement = classpath.createPathElement(); + pathElement.setLocation(classgendir); + + String[] paths = classpath.list(); + File[] cp = new File[paths.length]; + for (int i = 0; i < paths.length; i++) { + cp[i] = new File(paths[i]); + } + + // generate the source + SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); + params.setBaseDir(theBasedir); + params.setXsdFiles(xsdArray); + params.setWsdlFiles(wsdlArray); + params.setJavaFiles(javaArray); + params.setConfigFiles(xsdconfigArray); + params.setClasspath(cp); + params.setName(typesystemname); + params.setSrcDir(srcgendir); + params.setClassesDir(classgendir); + params.setNojavac(true); // always compile using javac task below + params.setDebug(debug); + params.setVerbose(verbose); + params.setQuiet(quiet); + params.setDownload(download); + params.setExtensions(extensions); + params.setErrorListener(err); + params.setCatalogFile(catalog); + params.setIncrementalSrcGen(noSrcRegen); + params.setMdefNamespaces(mdefnamespaces); + params.setNoUpa(noupa); + params.setNoPvr(nopvr); + params.setNoAnn(noann); + params.setNoVDoc(novdoc); + params.setNoExt(noext); + params.setRepackage(repackage); + success = SchemaCompiler.compile(params); + + if (success && !srconly) { + long start = System.currentTimeMillis(); + + // compile the source + Javac javac = new Javac(); + javac.setProject(project); + javac.setTaskName(getTaskName()); + javac.setClasspath(classpath); + if (compiler != null) { + javac.setCompiler(compiler); + } + javac.setDebug(debug); + if (debugLevel != null) { + javac.setDebugLevel(debugLevel); + } + javac.setDestdir(classgendir); + javac.setExecutable(forkedExecutable); + javac.setFailonerror(failonerror); + javac.setFork(fork); + javac.setSource("1.8"); + javac.setTarget("1.8"); + javac.setIncludeantruntime(includeAntRuntime); + javac.setIncludejavaruntime(includeJavaRuntime); + javac.setNowarn(nowarn); + javac.setSrcdir(new Path(project, srcgendir.getAbsolutePath())); + if (memoryInitialSize != null) { + javac.setMemoryInitialSize(memoryInitialSize); + } + if (memoryMaximumSize != null) { + javac.setMemoryMaximumSize(memoryMaximumSize); + } + javac.setOptimize(optimize); + javac.setVerbose(verbose); + javac.execute(); + + long finish = System.currentTimeMillis(); + if (!quiet) { + log("Time to compile code: " + ((double) (finish - start) / 1000.0) + " seconds"); + } + + if (destfile != null) { + // jar the compiled classes + Jar jar = new Jar(); + jar.setProject(project); + jar.setTaskName(getTaskName()); + jar.setBasedir(classgendir); + jar.setDestFile(destfile); + jar.execute(); + } + } + + if (tmpdir != null) { + SchemaCodeGenerator.tryHardToDelete(tmpdir); + } + } catch (BuildException e) { + // re-throw anything thrown from javac or jar task + throw e; + } catch (Throwable e) { + //interrupted means cancel + if (e instanceof InterruptedException || failonerror) { + throw new BuildException(e); + } + + log("Exception while building schemas: " + e.getMessage(), Project.MSG_ERR); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + log(sw.toString(), Project.MSG_VERBOSE); + } + + if (!success && failonerror) { + throw new BuildException(); //stop the build + } + } + + private void processPaths(String[] paths, File baseDir) { + for (String s : paths) { + int dot = s.lastIndexOf('.'); + if (dot > -1) { + String possExt = s.substring(dot).toLowerCase(Locale.ROOT); + Set set = _extRouter.get(possExt); + + if (set != null) { + set.add(new File(baseDir, s)); + } + } + } + } + + public void addFileset(FileSet fileset) { + schemas.add(fileset); + } + + ///////////////////////////// + //Getter/Setters + public File getSchema() { + return schema; + } + + /** + * A file that points to either an individual schema file or a directory of files. + * It is optional only if one or more <fileset> elements are nested in this + * task. + * + * @param schema Required, unless a fileset element is nested. + */ + public void setSchema(File schema) { + this.schema = schema; + } + + /** + * The classpath to use if schemas in the fileset import definitions that are + * supplied by other compiled xml beans JAR files, or if .java files are in the + * schema fileset. + * + * @param classpath Optional. + */ + public void setClasspath(Path classpath) { + if (this.classpath != null) { + this.classpath.append(classpath); + } else { + this.classpath = classpath; + } + } + + /** + * Adds a path to the classpath. + */ + public Path createClasspath() { + if (classpath == null) { + classpath = new Path(project); + } + return classpath.createPath(); + } + + /** + * Adds a reference to a classpath defined elsewhere. + * + * @param classpathref Optional. + */ + public void setClasspathRef(Reference classpathref) { + if (classpath == null) { + classpath = new Path(project); + } + + classpath.createPath().setRefid(classpathref); + } + + public Path getClasspath() { + return classpath; + } + + public File getDestfile() { + return destfile; + } + + /** + * Define the name of the jar file created. For instance, "myXMLBean.jar" + * will output the results of this task into a jar with the same name. + * Optional, defaults to "xmltypes.jar". + * + * @param destfile Optional. + */ + public void setDestfile(File destfile) { + this.destfile = destfile; + } + + public File getSrcgendir() { + return srcgendir; + } + + /** + * Set a location to generate .java files into. Optional, defaults to + * a temp dir. + * + * @param srcgendir Optional. + */ + public void setSrcgendir(File srcgendir) { + this.srcgendir = srcgendir; + } + + public File getClassgendir() { + return classgendir; + } + + /** + * Set a location to generate .class files into. Optional, defaults to + * a temp dir. + * + * @param classgendir Optional. + */ + public void setClassgendir(File classgendir) { + this.classgendir = classgendir; + } + + /** + * Choose the implementation for this particular task. + * + * @since Ant 1.5 + */ + public void setCompiler(String compiler) { + this.compiler = compiler; + } + + public boolean isDownload() { + return download; + } + + /** + * Set to true to permit the compiler to download URLs for imports + * and includes. Defaults to false, meaning all imports and includes + * must be copied locally. + * + * @param download Optional. + */ + public void setDownload(boolean download) { + this.download = download; + } + + /** + * If true, compiles with optimization enabled. + */ + public void setOptimize(boolean optimize) { + this.optimize = optimize; + } + + /** + * Gets the optimize flag. + */ + public boolean getOptimize() { + return optimize; + } + + public boolean isVerbose() { + return verbose; + } + + /** + * Controls the amount of output. Defaults to true. + * + * @param verbose Optional. + */ + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + public boolean isQuiet() { + return quiet; + } + + /** + * Controls the amount of output. Defaults to false. + * + * @param quiet Optional. + */ + public void setQuiet(boolean quiet) { + this.quiet = quiet; + } + + public boolean isDebug() { + return debug; + } + + /** + * Get the value of debugLevel. + * + * @return value of debugLevel. + */ + public String getDebugLevel() { + return debugLevel; + } + + /** + * Keyword list to be appended to the -g command-line switch. + *

      + * This will be ignored by all implementations except modern + * and classic(ver >= 1.2). Legal values are none or a + * comma-separated list of the following keywords: lines, vars, + * and source. If debuglevel is not specified, by default, :none + * will be appended to -g. If debug is not turned on, this attribute + * will be ignored. + * + * @param v Value to assign to debugLevel. + */ + public void setDebugLevel(String v) { + this.debugLevel = v; + } + + /** + * Generate debugging symbols. + * + * @param debug Optional. + */ + public void setDebug(boolean debug) { + this.debug = debug; + } + + /** + * If true, forks the javac compiler. + * + * @param f "true|false|on|off|yes|no" + */ + public void setFork(boolean f) { + fork = f; + } + + /** + * Sets the the name of the javac executable. + * + *

      Ignored unless fork is true or extJavac has been specified + * as the compiler.

      + */ + public void setExecutable(String forkExec) { + forkedExecutable = forkExec; + } + + public String getExecutable() { + return forkedExecutable; + } + + public boolean isSrconly() { + return srconly; + } + + /** + * A value of true means that only source will be generated. Optional, + * default is false. + * + * @param srconly Optional. + */ + public void setSrconly(boolean srconly) { + this.srconly = srconly; + } + + public String getTypesystemname() { + return typesystemname; + } + + /** + * One or more SchemaCompiler extensions can be passed in via the <extension> subelement. + * Schema Compiler extensions must implement the interface com.xbean.too.SchemaCompilerExtension + */ + public Extension createExtension() { + Extension e = new Extension(); + extensions.add(e); + return e; + } + + /** + * One or more namespaces in which duplicate definitions are to be ignored + * can be passed in via the <ignoreDuplicatesInNamespaces> subelement. + */ + public void setIgnoreDuplicatesInNamespaces(String namespaces) { + mdefnamespaces = new HashSet<>(); + StringTokenizer st = new StringTokenizer(namespaces, ","); + while (st.hasMoreTokens()) { + String namespace = st.nextToken().trim(); + mdefnamespaces.add(namespace); + } + } + + public String getIgnoreDuplicatesInNamespaces() { + return mdefnamespaces == null ? null : String.join(",", mdefnamespaces); + + } + + /** + * The name of the package that the TypeSystemHolder class should be + * generated in. Normally this should be left unspecified. None of + * the xml beans are generated in this package. + *

      Use .xsdconfig files to modify xml bean package or class names. + * + * @param typesystemname Optional. + */ + public void setTypesystemname(String typesystemname) { + this.typesystemname = typesystemname; + } + + public boolean isFailonerror() { + return failonerror; + } + + /** + * Determines whether or not the ant target will continue if the XMLBean + * creation encounters a build error. Defaults to true. Optional. + * + * @param failonerror Optional. + */ + public void setFailonerror(boolean failonerror) { + this.failonerror = failonerror; + } + + public boolean isIncludeAntRuntime() { + return includeAntRuntime; + } + + public void setIncludeAntRuntime(boolean includeAntRuntime) { + this.includeAntRuntime = includeAntRuntime; + } + + public boolean isIncludeJavaRuntime() { + return includeJavaRuntime; + } + + public void setIncludeJavaRuntime(boolean includeJavaRuntime) { + this.includeJavaRuntime = includeJavaRuntime; + } + + public boolean isNowarn() { + return nowarn; + } + + public void setNowarn(boolean nowarn) { + this.nowarn = nowarn; + } + + public boolean isNoSrcRegen() { + return noSrcRegen; + } + + public void setNoSrcRegen(boolean noSrcRegen) { + this.noSrcRegen = noSrcRegen; + } + + /** + * Set the initial memory size of the underlying javac process. + */ + public String getMemoryInitialSize() { + return memoryInitialSize; + } + + public void setMemoryInitialSize(String memoryInitialSize) { + this.memoryInitialSize = memoryInitialSize; + } + + /** + * Set the maximum memory size of the underlying javac process. + */ + public String getMemoryMaximumSize() { + return memoryMaximumSize; + } + + public void setMemoryMaximumSize(String memoryMaximumSize) { + this.memoryMaximumSize = memoryMaximumSize; + } + + /** + * Do not enforce the unique particle attribution rule. + */ + public void setNoUpa(boolean noupa) { + this.noupa = noupa; + } + + public boolean isNoUpa() { + return noupa; + } + + /** + * Do not enforce the particle valid (restriction) rule. + */ + public void setNoPvr(boolean nopvr) { + this.nopvr = nopvr; + } + + public boolean isNoPvr() { + return nopvr; + } + + /** + * Skip over schema <annotation%gt; elements. + */ + public void setNoAnnotations(boolean noann) { + this.noann = noann; + } + + public boolean isNoAnnotations() { + return noann; + } + + /** + * Do not validate the contents of schema <documentation> elements. + */ + public void setNoValidateDoc(boolean novdoc) { + this.novdoc = novdoc; + } + + public boolean isNoValidateDoc() { + return novdoc; + } + + /** + * Ignore extensions found in .xsdconfig files + * + * @param noext Ignore extensions + */ + public void setNoExt(boolean noext) { + this.noext = noext; + } + + public boolean isNoExt() { + return noext; + } + + //REVIEW this allows people to deal with the case where they drag in + //more files for compilation than they should. not sure if this is + //a good thing or not + private String source = null; + + public void setSource(String s) { + source = s; + } + + /** + * Gets the XML Catalog file for org.apache.xml.resolver.tools.CatalogResolver. (Note: needs resolver.jar from http://xml.apache.org/commons/components/resolver/index.html) + */ + public String getCatalog() { + return catalog; + } + + /** + * Sets the XML Catalog file for org.apache.xml.resolver.tools.CatalogResolver. (Note: needs resolver.jar from http://xml.apache.org/commons/components/resolver/index.html) + */ + public void setCatalog(String catalog) { + this.catalog = catalog; + } + + public String getRepackage() { + return repackage; + } + + public void setRepackage(String repackage) { + this.repackage = repackage; + } + + private static URI uriFromFile(File f) { + if (f == null) { + return null; + } + + try { + return f.getCanonicalFile().toURI(); + } catch (java.io.IOException e) { + // Don't spit out an exception here because on Windows you'll get one + // if the filename is "aux", "lpt1", etc. It's the caller's responsibility + // to deal with those cases correctly, usually by calling FileSvc.invalidPathCheck() + // MessageSvc.get().logException(e); + return f.getAbsoluteFile().toURI(); + } + } + + public class ErrorLogger extends AbstractCollection { + private final boolean _noisy; + private final URI _baseURI; + + public ErrorLogger(boolean noisy) { + _noisy = noisy; + _baseURI = uriFromFile(project.getBaseDir()); + } + + public boolean add(XmlError err) { + if (err.getSeverity() == XmlError.SEVERITY_ERROR) { + log(err.toString(_baseURI), Project.MSG_ERR); + } else if (err.getSeverity() == XmlError.SEVERITY_WARNING) { + log(err.toString(_baseURI), Project.MSG_WARN); + } else if (_noisy) { + log(err.toString(_baseURI), Project.MSG_INFO); + } + return false; + } + + public Iterator iterator() { + return Collections.emptyIterator(); + } + + public int size() { + return 0; + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java new file mode 100644 index 0000000..a73782a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java @@ -0,0 +1,90 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.*; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +public class XMLBeanXSTCHarness implements XSTCTester.Harness { + public void runTestCase(XSTCTester.TestCaseResult result) { + XSTCTester.TestCase testCase = result.getTestCase(); + + Collection errors = new ArrayList<>(); + boolean schemaValid = true; + boolean instanceValid = true; + + if (testCase.getSchemaFile() == null) { + return; + } + + // step 1, load schema file etc. + SchemaTypeLoader loader = null; + try { + XmlObject schema = XmlObject.Factory.parse(testCase.getSchemaFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers()); + XmlObject schema2 = null; + if (testCase.getResourceFile() != null) { + schema2 = XmlObject.Factory.parse(testCase.getResourceFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers()); + } + XmlObject[] schemas = schema2 == null ? new XmlObject[]{schema} : new XmlObject[]{schema, schema2}; + SchemaTypeSystem system = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), new XmlOptions().setErrorListener(errors)); + loader = XmlBeans.typeLoaderUnion(system, XmlBeans.getBuiltinTypeSystem()); + } catch (Exception e) { + schemaValid = false; + if (!(e instanceof XmlException) || errors.isEmpty()) { + result.setCrash(true); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + result.addSvMessages(Collections.singleton(XmlError.forMessage(sw.toString()))); + } + } + + result.addSvMessages(errors); + result.setSvActual(schemaValid); + errors.clear(); + + if (loader == null) { + return; + } + + if (testCase.getInstanceFile() == null) { + return; + } + + // step 2, load instance file and validate + try { + XmlObject instance = loader.parse(testCase.getInstanceFile(), null, new XmlOptions().setErrorListener(errors).setLoadLineNumbers()); + if (!instance.validate(new XmlOptions().setErrorListener(errors))) { + instanceValid = false; + } + } catch (Exception e) { + instanceValid = false; + if (!(e instanceof XmlException) || errors.isEmpty()) { + result.setCrash(true); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + result.addIvMessages(Collections.singleton(XmlError.forMessage(sw.toString()))); + } + } + result.addIvMessages(errors); + result.setIvActual(instanceValid); + + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java b/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java new file mode 100644 index 0000000..11b0f29 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/XSTCTester.java @@ -0,0 +1,473 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.xb.ltgfmt.FileDesc; +import org.apache.xmlbeans.impl.xb.ltgfmt.TestsDocument; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.*; +import java.util.regex.Pattern; + +public class XSTCTester { + public static void printUsage() { + System.out.println("Usage: xstc [-showpass] [-errcode] foo_LTGfmt.xml ..."); + } + + public static void main(String[] args) throws IOException { + Set flags = new HashSet<>(); + flags.add("h"); + flags.add("help"); + flags.add("usage"); + flags.add("version"); + flags.add("showpass"); + flags.add("errcode"); + + long start = System.currentTimeMillis(); + + CommandLine cl = new CommandLine(args, flags, Collections.EMPTY_SET); + if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) { + printUsage(); + System.exit(0); + return; + } + + if (cl.getOpt("version") != null) { + CommandLine.printVersion(); + System.exit(0); + return; + } + + String[] badopts = cl.getBadOpts(); + if (badopts.length > 0) { + for (String badopt : badopts) { + System.out.println("Unrecognized option: " + badopt); + } + printUsage(); + System.exit(0); + return; + } + + if (cl.args().length == 0) { + printUsage(); + return; + } + + boolean showpass = (cl.getOpt("showpass") != null); + boolean errcode = (cl.getOpt("errcode") != null); + + File[] allFiles = cl.getFiles(); + Collection ltgFiles = new ArrayList<>(); + Harness harness = new XMLBeanXSTCHarness(); + + for (File allFile : allFiles) { + if (allFile.getName().contains("LTG")) { + ltgFiles.add(allFile); + } + } + + File resultsFile = new File("out.html"); + try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(resultsFile.toPath(), StandardCharsets.ISO_8859_1))) { + writer.println(""); + writer.println(""); + writer.println(""); + + writer.println(""); + + writer.println("

      XML Schema Test Collection Results

      "); + writer.println("

      Run on " + (new XmlCalendar(new Date())) + "

      "); + writer.println("

      Values in schema or instance valid columns are results from compiling or validating respectively."); + writer.println("Red or orange background mean the test failed.

      "); + writer.println(""); + writer.println(""); + int failures = 0; + int cases = 0; + for (File ltgFile : ltgFiles) { + System.out.println("Processing test cases in " + ltgFile); + Collection ltgErrors = new ArrayList<>(); + TestCase[] testCases = parseLTGFile(ltgFile, ltgErrors); + final Collection results = new ArrayList<>(); + if (testCases != null) { + for (TestCase testCase : testCases) { + TestCaseResult result = new TestCaseResult(); + result.testCase = testCase; + harness.runTestCase(result); + cases += 1; + if (!result.succeeded(errcode)) { + failures += 1; + } else if (!showpass) { + continue; + } + results.add(result); + } + } + writer.println(""); + if (!ltgErrors.isEmpty()) { + writer.println(""); + } else { + if (results.size() == 0) { + writer.println(""); + } + } + for (TestCaseResult result : results) { + summarizeResultAsHTMLTableRows(result, writer, errcode); + } + } + writer.println(""); + writer.println("
      idDescriptionsch vins v
      " + ltgFile + "
      Errors within the LTG file:"); + writer.println(""); + for (String ltgError : ltgErrors) { + writer.println(ltgError); + } + writer.println(""); + writer.println("
      Nothing to report
      Summary: " + failures + " failures out of " + cases + " cases run.
      "); + } + + long finish = System.currentTimeMillis(); + System.out.println("Time run tests: " + ((double) (finish - start) / 1000.0) + " seconds"); + + // Launch results + System.out.println("Results output to " + resultsFile); + String osName = SystemProperties.getProperty("os.name"); + assert (osName != null); + if (osName.toLowerCase(Locale.ROOT).contains("windows")) { + Runtime.getRuntime().exec("cmd /c start iexplore \"" + resultsFile.getAbsolutePath() + "\""); + } else { + Runtime.getRuntime().exec("mozilla file://" + resultsFile.getAbsolutePath()); + } + } + + public static class TestCase { + private File ltgFile; + private String id; + private String origin; + private String description; + private File schemaFile; + private File instanceFile; + private File resourceFile; + private boolean svExpected; + private boolean ivExpected; + private boolean rvExpected; + private String errorCode; + + public File getLtgFile() { + return ltgFile; + } + + public String getId() { + return id; + } + + public String getOrigin() { + return origin; + } + + public String getDescription() { + return description; + } + + public File getSchemaFile() { + return schemaFile; + } + + public File getInstanceFile() { + return instanceFile; + } + + public File getResourceFile() { + return resourceFile; + } + + public boolean isSvExpected() { + return svExpected; + } + + public boolean isIvExpected() { + return ivExpected; + } + + public boolean isRvExpected() { + return rvExpected; + } + + public String getErrorCode() { + return errorCode; + } + + } + + public static class TestCaseResult { + private TestCase testCase; + private boolean svActual; + private final Collection svMessages = new ArrayList<>(); + private boolean ivActual; + private final Collection ivMessages = new ArrayList<>(); + private boolean crash; + + public TestCase getTestCase() { + return testCase; + } + + public boolean isSvActual() { + return svActual; + } + + public void setSvActual(boolean svActual) { + this.svActual = svActual; + } + + public boolean isIvActual() { + return ivActual; + } + + public void setIvActual(boolean ivActual) { + this.ivActual = ivActual; + } + + public Collection getSvMessages() { + return Collections.unmodifiableCollection(svMessages); + } + + public void addSvMessages(Collection svMessages) { + this.svMessages.addAll(svMessages); + } + + public Collection getIvMessages() { + return Collections.unmodifiableCollection(ivMessages); + } + + public void addIvMessages(Collection ivMessages) { + this.ivMessages.addAll(ivMessages); + } + + public void setCrash(boolean crash) { + this.crash = crash; + } + + public boolean isCrash() { + return crash; + } + + public boolean succeeded(boolean errcode) { + boolean success = !crash && + (isIvActual() == testCase.isIvExpected()) && + (isSvActual() == testCase.isSvExpected()); + if (errcode && testCase.getErrorCode() != null) { + success &= errorReported(testCase.getErrorCode(), svMessages) || errorReported(testCase.getErrorCode(), ivMessages); + } + return success; + } + + } + + public interface Harness { + void runTestCase(TestCaseResult result); + } + + public static String makeHTMLLink(File file, boolean value) { + if (file == null) { + return " "; + } + URI uri = file.getAbsoluteFile().toURI(); + return "" + value + ""; + } + + private static final Pattern leadingSpace = Pattern.compile("^\\s+", Pattern.MULTILINE); + + public static String makeHTMLDescription(TestCase testCase) { + StringBuilder sb = new StringBuilder(); + sb.append(""); + sb.append(leadingSpace.matcher(testCase.getDescription()).replaceAll("")); + sb.append(""); + return sb.toString(); + } + + public static void summarizeResultAsHTMLTableRows(TestCaseResult result, PrintWriter out, boolean errcode) { + TestCase testCase = result.getTestCase(); + + boolean errorRow = errcode && testCase.getErrorCode() != null; + boolean messagesRow = !result.getIvMessages().isEmpty() || !result.getSvMessages().isEmpty(); + + boolean sRight = testCase.getSchemaFile() == null || testCase.isSvExpected() == result.isSvActual(); + boolean iRight = testCase.getInstanceFile() == null || testCase.isIvExpected() == result.isIvActual(); + boolean codeRight = true; + if (errorRow) { + codeRight = (errorReported(testCase.getErrorCode(), result.svMessages) || errorReported(testCase.getErrorCode(), result.ivMessages)); + } + + out.println(result.isCrash() ? "" : ""); + int idRowSpan = 1 + (errorRow ? 1 : 0) + (messagesRow ? 1 : 0); + out.println("" + testCase.getId() + ""); + out.println("" + makeHTMLDescription(testCase) + ""); + String sLinks; + if (testCase.getResourceFile() == null) { + sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual()); + } else { + sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual()) + "
      " + makeHTMLLink(testCase.getResourceFile(), result.isSvActual()); + } + + out.println((sRight ? "" : result.isSvActual() ? "" : "") + sLinks + ""); + out.println((iRight ? "" : result.isIvActual() ? "" : "") + makeHTMLLink(testCase.getInstanceFile(), result.isIvActual()) + ""); + out.println(""); + if (errorRow) { + out.println(""); + out.println((codeRight ? "" : "") + "expected error: " + testCase.getErrorCode() + ""); + out.println(""); + } + if (messagesRow) { + if (!result.succeeded(errcode)) { + out.println(""); + } else { + out.println("<tr><td colspan=4><xmp>"); + } + for (XmlError s : result.getSvMessages()) { + out.println(s); + } + for (XmlError xmlError : result.getIvMessages()) { + out.println(xmlError); + } + out.println(""); + } + } + + public static TestCase[] parseLTGFile(File ltgFile, Collection outerErrors) { + Collection errors = new ArrayList<>(); + try { + XmlOptions ltgOptions = new XmlOptions(); + ltgOptions.setLoadSubstituteNamespaces(Collections.singletonMap("", "http://www.bea.com/2003/05/xmlbean/ltgfmt")); + ltgOptions.setErrorListener(errors); + ltgOptions.setLoadLineNumbers(); + TestsDocument doc = TestsDocument.Factory.parse(ltgFile, ltgOptions); + if (!doc.validate(ltgOptions)) { + throw new Exception("Document " + ltgFile + " not valid."); + } + + org.apache.xmlbeans.impl.xb.ltgfmt.TestCase[] testCases = doc.getTests().getTestArray(); + + Collection result = new ArrayList<>(); + for (org.apache.xmlbeans.impl.xb.ltgfmt.TestCase testCase : testCases) { + TestCase newCase = new TestCase(); + newCase.ltgFile = ltgFile; + newCase.id = testCase.getId(); + newCase.origin = testCase.getOrigin(); + newCase.description = testCase.getDescription(); + FileDesc[] filedescs = testCase.getFiles().getFileArray(); + testCase.getOrigin(); + for (FileDesc filedesc : filedescs) { + String dir = filedesc.getFolder(); + String filename = filedesc.getFileName(); + File theFile = new File(ltgFile.getParentFile(), dir + "/" + filename); + if (!theFile.exists() || !theFile.isFile() || !theFile.canRead()) { + outerErrors.add(XmlError.forObject("Can't read file " + theFile, filedesc).toString()); + continue; + } + + switch (filedesc.getRole().intValue()) { + case FileDesc.Role.INT_INSTANCE: + if (newCase.instanceFile != null) { + outerErrors.add(XmlError.forObject("More than one instance file speicifed - ignoring all but last", filedesc).toString()); + } + newCase.instanceFile = theFile; + newCase.ivExpected = filedesc.getValidity(); + break; + + case FileDesc.Role.INT_SCHEMA: + if (newCase.schemaFile != null) { + outerErrors.add(XmlError.forObject("More than one schema file speicifed - ignoring all but last", filedesc).toString()); + } + newCase.schemaFile = theFile; + newCase.svExpected = filedesc.getValidity(); + break; + + case FileDesc.Role.INT_RESOURCE: + if (newCase.resourceFile != null) { + outerErrors.add(XmlError.forObject("More than one resource file speicifed - ignoring all but last", filedesc).toString()); + } + newCase.resourceFile = theFile; + newCase.rvExpected = filedesc.getValidity(); + break; + + default: + throw new XmlException(XmlError.forObject("Unexpected file role", filedesc)); + } + + if (filedesc.getCode() != null) { + newCase.errorCode = filedesc.getCode().getID(); + } + } + result.add(newCase); + } + return result.toArray(new TestCase[0]); + } catch (Exception e) { + if (errors.isEmpty()) { + outerErrors.add(e.getMessage()); + } else { + for (XmlError error : errors) { + outerErrors.add(error.toString()); + } + } + return null; + } + } + + public static boolean errorReported(String errorCode, Collection set) { + if (errorCode == null || set == null || set.size() == 0) { + return false; + } + + for (XmlError xmlError : set) { + if (errorCode.equals(xmlError.getErrorCode())) { + return true; + } + } + + return false; + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java b/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java new file mode 100644 index 0000000..7d85166 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/tool/XsbDumper.java @@ -0,0 +1,1394 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.util.HexBin; +import org.apache.xmlbeans.soap.SOAPArrayType; + +import javax.xml.namespace.QName; +import java.io.*; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +public class XsbDumper { + public static void printUsage() { + System.out.println("Prints the contents of an XSB file in human-readable form."); + System.out.println("An XSB file contains schema meta information needed to "); + System.out.println("perform tasks such as binding and validation."); + System.out.println("Usage: dumpxsb myfile.xsb"); + System.out.println(" myfile.xsb - Path to an XSB file."); + System.out.println(); + } + + public static void main(String[] args) { + if (args.length == 0) { + printUsage(); + System.exit(0); + return; + } + + for (String arg : args) { + dump(new File(arg), true); + } + } + + private static void dump(File file, boolean force) { + if (file.isDirectory()) { + File[] files = file.listFiles( + file1 -> file1.isDirectory() || file1.isFile() && file1.getName().endsWith(".xsb") + ); + if (files != null) { + for (File value : files) { + dump(value, false); + } + } + } else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) { + dumpZip(file); + } else if (force || file.getName().endsWith(".xsb")) { + try { + System.out.println(file.toString()); + dump(new FileInputStream(file), " "); + System.out.println(); + } catch (FileNotFoundException e) { + System.out.println(e.toString()); + } + } + } + + public static void dumpZip(File file) { + try { + ZipFile zipFile = new ZipFile(file); + Enumeration e = zipFile.entries(); + while (e.hasMoreElements()) { + ZipEntry entry = e.nextElement(); + if (entry.getName().endsWith(".xsb")) { + System.out.println(entry.getName()); + dump(zipFile.getInputStream(entry), " "); + System.out.println(); + } + } + } catch (IOException e) { + System.out.println(e.toString()); + } + } + + public static void dump(InputStream input) { + dump(input, "", System.out); + } + + public static void dump(InputStream input, String indent) { + dump(input, indent, System.out); + } + + public static void dump(InputStream input, String indent, PrintStream output) { + XsbDumper dumper = new XsbDumper(input, indent, output); + dumper.dumpAll(); + } + + private XsbDumper(InputStream stream, String indent, PrintStream ostream) { + _input = new DataInputStream(stream); + _indent = indent; + _out = ostream; + } + + void flush() { + _out.flush(); + } + + void emit(String str) { + _out.println(_indent + str); + flush(); + } + + void error(Exception e) { + _out.println(e.toString()); + flush(); + throw new IllegalStateException(e.getMessage(), e); + } + + void error(String str) { + _out.println(str); + flush(); + throw new IllegalStateException(str); + } + + private String _indent; + private final PrintStream _out; + + void indent() { + _indent += " "; + } + + void outdent() { + _indent = _indent.substring(0, _indent.length() - 2); + } + + public static final int DATA_BABE = 0xDA7ABABE; + public static final int MAJOR_VERSION = 2; + public static final int MINOR_VERSION = 24; + + public static final int FILETYPE_SCHEMAINDEX = 1; + public static final int FILETYPE_SCHEMATYPE = 2; + public static final int FILETYPE_SCHEMAELEMENT = 3; + public static final int FILETYPE_SCHEMAATTRIBUTE = 4; + public static final int FILETYPE_SCHEMAPOINTER = 5; + public static final int FILETYPE_SCHEMAMODELGROUP = 6; + public static final int FILETYPE_SCHEMAATTRIBUTEGROUP = 7; + + static String filetypeString(int code) { + switch (code) { + case FILETYPE_SCHEMAINDEX: + return "FILETYPE_SCHEMAINDEX"; + case FILETYPE_SCHEMATYPE: + return "FILETYPE_SCHEMATYPE"; + case FILETYPE_SCHEMAELEMENT: + return "FILETYPE_SCHEMAELEMENT"; + case FILETYPE_SCHEMAATTRIBUTE: + return "FILETYPE_SCHEMAATTRIBUTE"; + case FILETYPE_SCHEMAPOINTER: + return "FILETYPE_SCHEMAPOINTER"; + case FILETYPE_SCHEMAMODELGROUP: + return "FILETYPE_SCHEMAMODELGROUP"; + case FILETYPE_SCHEMAATTRIBUTEGROUP: + return "FILETYPE_SCHEMAATTRIBUTEGROUP"; + default: + return "Unknown FILETYPE (" + code + ")"; + } + } + + public static final int FLAG_PART_SKIPPABLE = 1; + public static final int FLAG_PART_FIXED = 4; + public static final int FLAG_PART_NILLABLE = 8; + public static final int FLAG_PART_BLOCKEXT = 16; + public static final int FLAG_PART_BLOCKREST = 32; + public static final int FLAG_PART_BLOCKSUBST = 64; + public static final int FLAG_PART_ABSTRACT = 128; + public static final int FLAG_PART_FINALEXT = 256; + public static final int FLAG_PART_FINALREST = 512; + + static String particleflagsString(int flags) { + StringBuilder result = new StringBuilder(); + if ((flags & FLAG_PART_SKIPPABLE) != 0) { + result.append("FLAG_PART_SKIPPABLE | "); + } + if ((flags & FLAG_PART_FIXED) != 0) { + result.append("FLAG_PART_FIXED | "); + } + if ((flags & FLAG_PART_NILLABLE) != 0) { + result.append("FLAG_PART_NILLABLE | "); + } + if ((flags & FLAG_PART_BLOCKEXT) != 0) { + result.append("FLAG_PART_BLOCKEXT | "); + } + if ((flags & FLAG_PART_BLOCKREST) != 0) { + result.append("FLAG_PART_BLOCKREST | "); + } + if ((flags & FLAG_PART_BLOCKSUBST) != 0) { + result.append("FLAG_PART_BLOCKSUBST | "); + } + if ((flags & FLAG_PART_ABSTRACT) != 0) { + result.append("FLAG_PART_ABSTRACT | "); + } + if ((flags & FLAG_PART_FINALEXT) != 0) { + result.append("FLAG_PART_FINALEXT | "); + } + if ((flags & FLAG_PART_FINALREST) != 0) { + result.append("FLAG_PART_FINALREST | "); + } + if (result.length() == 0) { + result.append("0 | "); + } + return result.substring(0, result.length() - 3); + } + + public static final int FLAG_PROP_ISATTR = 1; + public static final int FLAG_PROP_JAVASINGLETON = 2; + public static final int FLAG_PROP_JAVAOPTIONAL = 4; + public static final int FLAG_PROP_JAVAARRAY = 8; + + static String propertyflagsString(int flags) { + StringBuilder result = new StringBuilder(); + if ((flags & FLAG_PROP_ISATTR) != 0) { + result.append("FLAG_PROP_ISATTR | "); + } + if ((flags & FLAG_PROP_JAVASINGLETON) != 0) { + result.append("FLAG_PROP_JAVASINGLETON | "); + } + if ((flags & FLAG_PROP_JAVAOPTIONAL) != 0) { + result.append("FLAG_PROP_JAVAOPTIONAL | "); + } + if ((flags & FLAG_PROP_JAVAARRAY) != 0) { + result.append("FLAG_PROP_JAVAARRAY | "); + } + if (result.length() == 0) { + result.append("0 | "); + } + return result.substring(0, result.length() - 3); + } + + public static final int FIELD_NONE = 0; + public static final int FIELD_GLOBAL = 1; + public static final int FIELD_LOCALATTR = 2; + public static final int FIELD_LOCALELT = 3; + + static String containerfieldTypeString(int code) { + switch (code) { + case FIELD_NONE: + return "FIELD_NONE"; + case FIELD_GLOBAL: + return "FIELD_GLOBAL"; + case FIELD_LOCALATTR: + return "FIELD_LOCALATTR"; + case FIELD_LOCALELT: + return "FIELD_LOCALELT"; + default: + return "Unknown container field type (" + code + ")"; + } + } + + // type flags + static final int FLAG_SIMPLE_TYPE = 0x1; + static final int FLAG_DOCUMENT_TYPE = 0x2; + static final int FLAG_ORDERED = 0x4; + static final int FLAG_BOUNDED = 0x8; + static final int FLAG_FINITE = 0x10; + static final int FLAG_NUMERIC = 0x20; + static final int FLAG_STRINGENUM = 0x40; + static final int FLAG_UNION_OF_LISTS = 0x80; + static final int FLAG_HAS_PATTERN = 0x100; + static final int FLAG_ORDER_SENSITIVE = 0x200; + static final int FLAG_TOTAL_ORDER = 0x400; + static final int FLAG_COMPILED = 0x800; + static final int FLAG_BLOCK_EXT = 0x1000; + static final int FLAG_BLOCK_REST = 0x2000; + static final int FLAG_FINAL_EXT = 0x4000; + static final int FLAG_FINAL_REST = 0x8000; + static final int FLAG_FINAL_UNION = 0x10000; + static final int FLAG_FINAL_LIST = 0x20000; + static final int FLAG_ABSTRACT = 0x40000; + static final int FLAG_ATTRIBUTE_TYPE = 0x80000; + + static String typeflagsString(int flags) { + StringBuilder result = new StringBuilder(); + if ((flags & FLAG_SIMPLE_TYPE) != 0) { + result.append("FLAG_SIMPLE_TYPE | "); + } + if ((flags & FLAG_DOCUMENT_TYPE) != 0) { + result.append("FLAG_DOCUMENT_TYPE | "); + } + if ((flags & FLAG_ATTRIBUTE_TYPE) != 0) { + result.append("FLAG_ATTRIBUTE_TYPE | "); + } + if ((flags & FLAG_ORDERED) != 0) { + result.append("FLAG_ORDERED | "); + } + if ((flags & FLAG_BOUNDED) != 0) { + result.append("FLAG_BOUNDED | "); + } + if ((flags & FLAG_FINITE) != 0) { + result.append("FLAG_FINITE | "); + } + if ((flags & FLAG_NUMERIC) != 0) { + result.append("FLAG_NUMERIC | "); + } + if ((flags & FLAG_STRINGENUM) != 0) { + result.append("FLAG_STRINGENUM | "); + } + if ((flags & FLAG_UNION_OF_LISTS) != 0) { + result.append("FLAG_UNION_OF_LISTS | "); + } + if ((flags & FLAG_HAS_PATTERN) != 0) { + result.append("FLAG_HAS_PATTERN | "); + } + if ((flags & FLAG_TOTAL_ORDER) != 0) { + result.append("FLAG_TOTAL_ORDER | "); + } + if ((flags & FLAG_COMPILED) != 0) { + result.append("FLAG_COMPILED | "); + } + if ((flags & FLAG_BLOCK_EXT) != 0) { + result.append("FLAG_BLOCK_EXT | "); + } + if ((flags & FLAG_BLOCK_REST) != 0) { + result.append("FLAG_BLOCK_REST | "); + } + if ((flags & FLAG_FINAL_EXT) != 0) { + result.append("FLAG_FINAL_EXT | "); + } + if ((flags & FLAG_FINAL_REST) != 0) { + result.append("FLAG_FINAL_REST | "); + } + if ((flags & FLAG_FINAL_UNION) != 0) { + result.append("FLAG_FINAL_UNION | "); + } + if ((flags & FLAG_FINAL_LIST) != 0) { + result.append("FLAG_FINAL_LIST | "); + } + if ((flags & FLAG_ABSTRACT) != 0) { + result.append("FLAG_ABSTRACT | "); + } + if (result.length() == 0) { + result.append("0 | "); + } + return result.substring(0, result.length() - 3); + } + + void dumpAll() { + int filetype = dumpHeader(); + switch (filetype) { + case FILETYPE_SCHEMAINDEX: + dumpIndexData(); + return; + case FILETYPE_SCHEMATYPE: + dumpTypeFileData(); + break; + case FILETYPE_SCHEMAELEMENT: + dumpParticleData(true); + break; + case FILETYPE_SCHEMAATTRIBUTE: + dumpAttributeData(true); + break; + case FILETYPE_SCHEMAPOINTER: + dumpPointerData(); + break; + case FILETYPE_SCHEMAMODELGROUP: + dumpModelGroupData(); + break; + case FILETYPE_SCHEMAATTRIBUTEGROUP: + dumpAttributeGroupData(); + break; + } + readEnd(); + } + + static String hex32String(int i) { + return Integer.toHexString(i); + } + + protected int dumpHeader() { + int magic = readInt(); + emit("Magic cookie: " + hex32String(magic)); + + if (magic != DATA_BABE) { + emit("Wrong magic cookie."); + return 0; + } + + _majorver = readShort(); + _minorver = readShort(); + if (atLeast(2, 18, 0)) { + _releaseno = readShort(); + } + + emit("Major version: " + _majorver); + emit("Minor version: " + _minorver); + emit("Release number: " + _releaseno); + + if (_majorver != MAJOR_VERSION || _minorver > MINOR_VERSION) { + emit("Incompatible version."); + return 0; + } + + int actualfiletype = readShort(); + emit("Filetype: " + filetypeString(actualfiletype)); + + _stringPool = new StringPool(); + _stringPool.readFrom(_input); + + return actualfiletype; + } + + void dumpPointerData() { + emit("Type system: " + readString()); + } + + protected void dumpIndexData() { + // has a handle pool (count, handle/type, handle/type...) + int size = readShort(); + emit("Handle pool (" + size + "):"); + indent(); + for (int i = 0; i < size; i++) { + String handle = readString(); + int code = readShort(); + emit(handle + " (" + filetypeString(code) + ")"); + } + outdent(); + + dumpQNameMap("Global elements"); + + // qname map of global attributes + dumpQNameMap("Global attributes"); + + // attr groups and model groups + dumpQNameMap("Model groups"); + dumpQNameMap("Attribute groups"); + + dumpQNameMap("Identity constraints"); + + // qname map of global types + dumpQNameMap("Global types"); + + // qname map of document types, by the qname of the contained element + dumpQNameMap("Document types"); + + // qname map of attribute types, by the qname of the contained attribute + dumpQNameMap("Attribute types"); + + // all the types indexed by classname + dumpClassnameIndex("All types by classname"); + + // all the namespaces + dumpStringArray("Defined namespaces"); + + // version 15 stuff for redefines + if (atLeast(2, 15, 0)) { + dumpQNameMap("Redefined global types"); + dumpQNameMap("Redfined model groups"); + dumpQNameMap("Redfined attribute groups"); + } + + // version 19 annotations + if (atLeast(2, 19, 0)) { + dumpAnnotations(); + } + + readEnd(); + } + + + class StringPool { + private final List intsToStrings = new ArrayList<>(); + private final Map stringsToInts = new HashMap<>(); + + StringPool() { + intsToStrings.add(null); + } + + String stringForCode(int code) { + if (code == 0) { + return null; + } + return intsToStrings.get(code); + } + + int codeForString(String str) { + if (str == null) { + return 0; + } + Integer result = stringsToInts.get(str); + if (result == null) { + result = intsToStrings.size(); + intsToStrings.add(str); + stringsToInts.put(str, result); + } + return result; + } + + void readFrom(DataInputStream input) { + if (intsToStrings.size() != 1 || stringsToInts.size() != 0) { + throw new IllegalStateException(); + } + + try { + int size = input.readShort(); + emit("String pool (" + size + "):"); + indent(); + for (int i = 1; i < size; i++) { + String str = input.readUTF(); + int code = codeForString(str); + if (code != i) { + throw new IllegalStateException(); + } + emit(code + " = \"" + str + "\""); + } + outdent(); + } catch (IOException e) { + emit(e.toString()); + } + } + } + + // active while loading one type. + DataInputStream _input; + StringPool _stringPool; + + int readShort() { + try { + return _input.readUnsignedShort(); + } catch (IOException e) { + error(e); + return 0; + } + } + + int readInt() { + try { + return _input.readInt(); + } catch (IOException e) { + error(e); + return 0; + } + } + + String readString() { + return _stringPool.stringForCode(readShort()); + } + + QName readQName() { + String namespace = readString(); + String localname = readString(); + if (localname == null) { + return null; + } + return new QName(namespace, localname); + } + + String readHandle() { + return readString(); + } + + String readType() { + return readHandle(); + } + + static String qnameString(QName qname) { + if (qname == null) { + return "(null)"; + } + if (qname.getNamespaceURI() != null) { + return qname.getLocalPart() + "@" + qname.getNamespaceURI(); + } else { + return qname.getLocalPart(); + } + } + + static String qnameSetString(QNameSet set) { + return set.toString(); + } + + void dumpQNameMap(String fieldname) { + int size = readShort(); + emit(fieldname + " (" + size + "):"); + indent(); + for (int i = 0; i < size; i++) { + emit(qnameString(readQName()) + " = " + readHandle()); + } + outdent(); + } + + void dumpTypeArray(String fieldname) { + int size = readShort(); + emit(fieldname + " (" + size + "):"); + indent(); + for (int i = 0; i < size; i++) { + emit(i + " = " + readType()); + } + outdent(); + } + + void dumpClassnameIndex(String fieldname) { + int size = readShort(); + emit(fieldname + " (" + size + "):"); + indent(); + for (int i = 0; i < size; i++) { + emit(readString() + " = " + readType()); + } + outdent(); + } + + void dumpStringArray(String fieldname) { + int size = readShort(); + emit(fieldname + " (" + size + "):"); + indent(); + for (int i = 0; i < size; i++) { + emit(readString()); + } + outdent(); + } + + void readEnd() { + try { + _input.close(); + } catch (IOException e) { + // oh, well. + } + _input = null; + _stringPool = null; + } + + static String particleTypeString(int spt) { + switch (spt) { + case SchemaParticle.ALL: + return "ALL"; + case SchemaParticle.CHOICE: + return "CHOICE"; + case SchemaParticle.ELEMENT: + return "ELEMENT"; + case SchemaParticle.SEQUENCE: + return "SEQUENCE"; + case SchemaParticle.WILDCARD: + return "WILDCARD"; + default: + return "Unknown particle type (" + spt + ")"; + } + } + + static String bigIntegerString(BigInteger bigint) { + if (bigint == null) { + return "(null)"; + } + return bigint.toString(); + } + + static String wcprocessString(int code) { + switch (code) { + case SchemaParticle.STRICT: + return "STRICT"; + case SchemaParticle.SKIP: + return "SKIP"; + case SchemaParticle.LAX: + return "LAX"; + case 0: + return "NOT_WILDCARD"; + default: + return "Unknown process type (" + code + ")"; + } + } + + void dumpAnnotation() { + if (!atLeast(2, 19, 0)) { + return; // no annotations in this version of the file + } + + int n = readInt(); + if (n == -1) { + return; // no annotation present + } + emit("Annotation"); + boolean empty = true; + indent(); + if (n > 0) { + emit("Attributes (" + n + "):"); + indent(); + for (int i = 0; i < n; i++) { + if (atLeast(2, 24, 0)) { + emit("Name: " + qnameString(readQName()) + + ", Value: " + readString() + + ", ValueURI: " + readString()); + } else { + emit("Name: " + qnameString(readQName()) + + ", Value: " + readString()); + } + } + outdent(); + empty = false; + } + + n = readInt(); + if (n > 0) { + emit("Documentation elements (" + n + "):"); + indent(); + for (int i = 0; i < n; i++) { + emit(readString()); + } + outdent(); + empty = false; + } + + n = readInt(); + if (n > 0) { + emit("Appinfo elements (" + n + "):"); + indent(); + for (int i = 0; i < n; i++) { + emit(readString()); + } + outdent(); + empty = false; + } + if (empty) { + emit(""); + } + outdent(); + } + + void dumpAnnotations() { + int n = readInt(); + if (n > 0) { + emit("Top-level annotations (" + n + "):"); + indent(); + for (int i = 0; i < n; i++) { + dumpAnnotation(); + } + outdent(); + } + } + + void dumpParticleData(boolean global) { + int particleType = readShort(); + emit(particleTypeString(particleType) + ":"); + indent(); + int particleFlags = readShort(); + emit("Flags: " + particleflagsString(particleFlags)); + + emit("MinOccurs: " + bigIntegerString(readBigInteger())); + emit("MaxOccurs: " + bigIntegerString(readBigInteger())); + + emit("Transition: " + qnameSetString(readQNameSet())); + + switch (particleType) { + case SchemaParticle.WILDCARD: + emit("Wildcard set: " + qnameSetString(readQNameSet())); + emit("Wildcard process: " + wcprocessString(readShort())); + break; + + case SchemaParticle.ELEMENT: + emit("Name: " + qnameString(readQName())); + emit("Type: " + readType()); + emit("Default: " + readString()); + if (atLeast(2, 16, 0)) { + emit("Default value: " + readXmlValueObject()); + } + emit("WsdlArrayType: " + SOAPArrayTypeString(readSOAPArrayType())); + dumpAnnotation(); + if (global) { + if (atLeast(2, 17, 0)) { + emit("Substitution group ref: " + readHandle()); + } + int substGroupCount = readShort(); + emit("Substitution group members (" + substGroupCount + ")"); + indent(); + for (int i = 0; i < substGroupCount; i++) { + emit(qnameString(readQName())); + } + outdent(); + } + int count = readShort(); + emit("Identity constraints (" + count + "):"); + indent(); + for (int i = 0; i < count; i++) { + emit(readHandle()); + } + outdent(); + if (global) { + emit("Filename: " + readString()); + } + break; + + case SchemaParticle.ALL: + case SchemaParticle.SEQUENCE: + case SchemaParticle.CHOICE: + dumpParticleArray("Particle children"); + break; + + default: + error("Unrecognized schema particle type"); + } + outdent(); + } + + void dumpParticleArray(String fieldname) { + int count = readShort(); + emit(fieldname + "(" + count + "):"); + indent(); + for (int i = 0; i < count; i++) { + dumpParticleData(false); + } + outdent(); + } + + static String complexVarietyString(int code) { + switch (code) { + case SchemaType.EMPTY_CONTENT: + return "EMPTY_CONTENT"; + case SchemaType.SIMPLE_CONTENT: + return "SIMPLE_CONTENT"; + case SchemaType.ELEMENT_CONTENT: + return "ELEMENT_CONTENT"; + case SchemaType.MIXED_CONTENT: + return "MIXED_CONTENT"; + default: + return "Unknown complex variety (" + code + ")"; + } + } + + static String simpleVarietyString(int code) { + switch (code) { + case SchemaType.ATOMIC: + return "ATOMIC"; + case SchemaType.LIST: + return "LIST"; + case SchemaType.UNION: + return "UNION"; + default: + return "Unknown simple variety (" + code + ")"; + } + } + + String facetCodeString(int code) { + switch (code) { + case SchemaType.FACET_LENGTH: + return "FACET_LENGTH"; + case SchemaType.FACET_MIN_LENGTH: + return "FACET_MIN_LENGTH"; + case SchemaType.FACET_MAX_LENGTH: + return "FACET_MAX_LENGTH"; + case SchemaType.FACET_MIN_EXCLUSIVE: + return "FACET_MIN_EXCLUSIVE"; + case SchemaType.FACET_MIN_INCLUSIVE: + return "FACET_MIN_INCLUSIVE"; + case SchemaType.FACET_MAX_INCLUSIVE: + return "FACET_MAX_INCLUSIVE"; + case SchemaType.FACET_MAX_EXCLUSIVE: + return "FACET_MAX_EXCLUSIVE"; + case SchemaType.FACET_TOTAL_DIGITS: + return "FACET_TOTAL_DIGITS"; + case SchemaType.FACET_FRACTION_DIGITS: + return "FACET_FRACTION_DIGITS"; + default: + return "Unknown facet code (" + code + ")"; + } + } + + String whitespaceCodeString(int code) { + switch (code) { + case SchemaType.WS_COLLAPSE: + return "WS_COLLAPSE"; + case SchemaType.WS_PRESERVE: + return "WS_PRESERVE"; + case SchemaType.WS_REPLACE: + return "WS_REPLACE"; + case SchemaType.WS_UNSPECIFIED: + return "WS_UNSPECIFIED"; + default: + return "Unknown whitespace code (" + code + ")"; + } + } + + String derivationTypeString(int code) { + switch (code) { + case SchemaType.DT_NOT_DERIVED: + return "DT_NOT_DERIVED"; + case SchemaType.DT_RESTRICTION: + return "DT_RESTRICTION"; + case SchemaType.DT_EXTENSION: + return "DT_EXTENSION"; + default: + return "Unknown derivation code (" + code + ")"; + } + } + + void dumpTypeFileData() { + emit("Name: " + qnameString(readQName())); + emit("Outer type: " + readType()); + emit("Depth: " + readShort()); + emit("Base type: " + readType()); + emit("Derivation type: " + derivationTypeString(readShort())); + dumpAnnotation(); + + emit("Container field:"); + indent(); + int containerfieldtype = readShort(); + emit("Reftype: " + containerfieldTypeString(containerfieldtype)); + switch (containerfieldtype) { + case FIELD_GLOBAL: + emit("Handle: " + readHandle()); + break; + case FIELD_LOCALATTR: + emit("Index: " + readShort()); + break; + case FIELD_LOCALELT: + emit("Index: " + readShort()); + break; + } + outdent(); + emit("Java class name: " + readString()); + emit("Java impl class name: " + readString()); + + dumpTypeArray("Anonymous types"); + + emit("Anonymous union member ordinal: " + readShort()); + + int flags; + flags = readInt(); + emit("Flags: " + typeflagsString(flags)); + boolean isComplexType = ((flags & FLAG_SIMPLE_TYPE) == 0); + + int complexVariety = SchemaType.NOT_COMPLEX_TYPE; + if (isComplexType) { + complexVariety = readShort(); + emit("Complex variety: " + complexVarietyString(complexVariety)); + + if (atLeast(2, 23, 0)) { + emit("Content based on type: " + readType()); + } + + int attrCount = readShort(); + emit("Attribute model (" + attrCount + "):"); + indent(); + for (int i = 0; i < attrCount; i++) { + dumpAttributeData(false); + } + + emit("Wildcard set: " + qnameSetString(readQNameSet())); + emit("Wildcard process: " + wcprocessString(readShort())); + outdent(); + + // Attribute Property Table + int attrPropCount = readShort(); + emit("Attribute properties (" + attrPropCount + "):"); + indent(); + for (int i = 0; i < attrPropCount; i++) { + dumpPropertyData(); + } + outdent(); + + if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT) { + emit("IsAll: " + readShort()); + + // Content model tree + dumpParticleArray("Content model"); + + // Element Property Table + int elemPropCount = readShort(); + emit("Element properties (" + elemPropCount + "):"); + indent(); + for (int i = 0; i < elemPropCount; i++) { + dumpPropertyData(); + } + outdent(); + } + } + + if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT) { + int simpleVariety = readShort(); + emit("Simple type variety: " + simpleVarietyString(simpleVariety)); + + boolean isStringEnum = ((flags & FLAG_STRINGENUM) != 0); + + int facetCount = readShort(); + emit("Facets (" + facetCount + "):"); + indent(); + for (int i = 0; i < facetCount; i++) { + emit(facetCodeString(readShort())); + emit("Value: " + readXmlValueObject()); + emit("Fixed: " + readShort()); + } + outdent(); + + emit("Whitespace rule: " + whitespaceCodeString(readShort())); + + int patternCount = readShort(); + emit("Patterns (" + patternCount + "):"); + indent(); + for (int i = 0; i < patternCount; i++) { + emit(readString()); + } + outdent(); + + int enumCount = readShort(); + emit("Enumeration values (" + enumCount + "):"); + indent(); + for (int i = 0; i < enumCount; i++) { + emit(readXmlValueObject()); + } + outdent(); + + emit("Base enum type: " + readType()); + if (isStringEnum) { + int seCount = readShort(); + emit("String enum entries (" + seCount + "):"); + indent(); + for (int i = 0; i < seCount; i++) { + emit("\"" + readString() + "\" -> " + readShort() + " = " + readString()); + } + outdent(); + } + + switch (simpleVariety) { + case SchemaType.ATOMIC: + emit("Primitive type: " + readType()); + emit("Decimal size: " + readInt()); + break; + + case SchemaType.LIST: + emit("List item type: " + readType()); + break; + + case SchemaType.UNION: + dumpTypeArray("Union members"); + break; + + default: + error("Unknown simple type variety"); + } + } + + emit("Filename: " + readString()); + } + + static String attruseCodeString(int code) { + switch (code) { + case SchemaLocalAttribute.OPTIONAL: + return "OPTIONAL"; + case SchemaLocalAttribute.REQUIRED: + return "REQUIRED"; + case SchemaLocalAttribute.PROHIBITED: + return "PROHIBITED"; + default: + return "Unknown use code (" + code + ")"; + } + } + + void dumpAttributeData(boolean global) { + emit("Name: " + qnameString(readQName())); + emit("Type: " + readType()); + emit("Use: " + attruseCodeString(readShort())); + emit("Default: " + readString()); + if (atLeast(2, 16, 0)) { + emit("Default value: " + readXmlValueObject()); + } + emit("Fixed: " + readShort()); + emit("WsdlArrayType: " + SOAPArrayTypeString(readSOAPArrayType())); + dumpAnnotation(); + if (global) { + emit("Filename: " + readString()); + } + } + + private static final XmlOptions prettyOptions = + new XmlOptions().setSavePrettyPrint(); + + void dumpXml() { + String xml = readString(); + try { + emit(XmlObject.Factory.parse(xml).xmlText(prettyOptions)); + } catch (XmlException x) { + emit("!!!!!! BAD XML !!!!!"); + emit(xml); + } + } + + void dumpModelGroupData() { + emit("Name: " + qnameString(readQName())); + emit("Target namespace: " + readString()); + emit("Chameleon: " + readShort()); + if (atLeast(2, 22, 0)) { + emit("Element form default: " + readString()); + } + if (atLeast(2, 22, 0)) { + emit("Attribute form default: " + readString()); + } + if (atLeast(2, 15, 0)) { + emit("Redefine: " + readShort()); + } + emit("Model Group Xml: "); + dumpXml(); + dumpAnnotation(); + if (atLeast(2, 21, 0)) { + emit("Filename: " + readString()); + } + } + + void dumpAttributeGroupData() { + emit("Name: " + qnameString(readQName())); + emit("Target namespace: " + readString()); + emit("Chameleon: " + readShort()); + if (atLeast(2, 22, 0)) { + emit("Form default: " + readString()); + } + if (atLeast(2, 15, 0)) { + emit("Redefine: " + readShort()); + } + emit("Attribute Group Xml: "); + dumpXml(); + dumpAnnotation(); + if (atLeast(2, 21, 0)) { + emit("Filename: " + readString()); + } + } + + static String alwaysString(int code) { + switch (code) { + case SchemaProperty.CONSISTENTLY: + return "CONSISTENTLY"; + case SchemaProperty.NEVER: + return "NEVER"; + case SchemaProperty.VARIABLE: + return "VARIABLE"; + default: + return "Unknown frequency code (" + code + ")"; + } + } + + static String jtcString(int code) { + switch (code) { + case SchemaProperty.XML_OBJECT: + return "XML_OBJECT"; + case SchemaProperty.JAVA_BOOLEAN: + return "JAVA_BOOLEAN"; + case SchemaProperty.JAVA_FLOAT: + return "JAVA_FLOAT"; + case SchemaProperty.JAVA_DOUBLE: + return "JAVA_DOUBLE"; + case SchemaProperty.JAVA_BYTE: + return "JAVA_BYTE"; + case SchemaProperty.JAVA_SHORT: + return "JAVA_SHORT"; + case SchemaProperty.JAVA_INT: + return "JAVA_INT"; + case SchemaProperty.JAVA_LONG: + return "JAVA_LONG"; + + case SchemaProperty.JAVA_BIG_DECIMAL: + return "JAVA_BIG_DECIMAL"; + case SchemaProperty.JAVA_BIG_INTEGER: + return "JAVA_BIG_INTEGER"; + case SchemaProperty.JAVA_STRING: + return "JAVA_STRING"; + case SchemaProperty.JAVA_BYTE_ARRAY: + return "JAVA_BYTE_ARRAY"; + case SchemaProperty.JAVA_GDATE: + return "JAVA_GDATE"; + case SchemaProperty.JAVA_GDURATION: + return "JAVA_GDURATION"; + case SchemaProperty.JAVA_DATE: + return "JAVA_DATE"; + case SchemaProperty.JAVA_QNAME: + return "JAVA_QNAME"; + case SchemaProperty.JAVA_CALENDAR: + return "JAVA_CALENDAR"; + case SchemaProperty.JAVA_LIST: + return "JAVA_LIST"; + + case SchemaProperty.JAVA_ENUM: + return "JAVA_ENUM"; + case SchemaProperty.JAVA_OBJECT: + return "JAVA_OBJECT"; + + default: + return "Unknown java type code (" + code + ")"; + } + } + + void dumpPropertyData() { + emit("Property"); + indent(); + emit("Name: " + qnameString(readQName())); + emit("Type: " + readType()); + int propflags = readShort(); + emit("Flags: " + propertyflagsString(propflags)); + emit("Container type: " + readType()); + emit("Min occurances: " + bigIntegerString(readBigInteger())); + emit("Max occurances: " + bigIntegerString(readBigInteger())); + emit("Nillable: " + alwaysString(readShort())); + emit("Default: " + alwaysString(readShort())); + emit("Fixed: " + alwaysString(readShort())); + emit("Default text: " + readString()); + emit("Java prop name: " + readString()); + emit("Java type code: " + jtcString(readShort())); + emit("Type for java signature: " + readType()); + if (atMost(2, 19, 0)) { + emit("Java setter delimiter: " + qnameSetString(readQNameSet())); + } + if (atLeast(2, 16, 0)) { + emit("Default value: " + readXmlValueObject()); + } + if (((propflags & FLAG_PROP_ISATTR) == 0) && atLeast(2, 17, 0)) { + int size = readShort(); + emit("Accepted substitutions (" + size + "):"); + for (int i = 0; i < size; i++) { + emit(" Accepted name " + readQName()); + } + } + outdent(); + } + + String readXmlValueObject() { + String type = readType(); + if (type == null) { + return "null"; + } + + int btc = readShort(); + String value; + switch (btc) { + default: + assert (false); + case 0: + value = "nil"; + break; + + case SchemaType.BTC_ANY_SIMPLE: + case SchemaType.BTC_ANY_URI: + case SchemaType.BTC_STRING: + case SchemaType.BTC_DURATION: + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + case SchemaType.BTC_DECIMAL: + case SchemaType.BTC_BOOLEAN: + value = readString(); + break; + + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: { + value = new String(HexBin.encode(readByteArray()), StandardCharsets.ISO_8859_1); + if (value.length() > 19) { + value = value.subSequence(0, 16) + "..."; + } + break; + } + + case SchemaType.BTC_QNAME: + case SchemaType.BTC_NOTATION: + value = QNameHelper.pretty(readQName()); + break; + + case SchemaType.BTC_FLOAT: + case SchemaType.BTC_DOUBLE: + value = Double.toString(readDouble()); + break; + } + return value + " (" + type + ": " + btc + ")"; + } + + double readDouble() { + try { + return _input.readDouble(); + } catch (IOException e) { + error(e); + return 0.0; + } + } + + String SOAPArrayTypeString(SOAPArrayType t) { + if (t == null) { + return "null"; + } + return QNameHelper.pretty(t.getQName()) + t.soap11DimensionString(); + } + + SOAPArrayType readSOAPArrayType() { + QName qName = readQName(); + String dimensions = readString(); + if (qName == null) { + return null; + } + return new SOAPArrayType(qName, dimensions); + } + + QNameSet readQNameSet() { + int flag = readShort(); + + Set uriSet = new HashSet<>(); + int uriCount = readShort(); + for (int i = 0; i < uriCount; i++) { + uriSet.add(readString()); + } + + Set qnameSet1 = new HashSet<>(); + int qncount1 = readShort(); + for (int i = 0; i < qncount1; i++) { + qnameSet1.add(readQName()); + } + + Set qnameSet2 = new HashSet<>(); + int qncount2 = readShort(); + for (int i = 0; i < qncount2; i++) { + qnameSet2.add(readQName()); + } + + if (flag == 1) { + return QNameSet.forSets(uriSet, null, qnameSet1, qnameSet2); + } else { + return QNameSet.forSets(null, uriSet, qnameSet2, qnameSet1); + } + } + + byte[] readByteArray() { + try { + int len = _input.readShort(); + byte[] result = new byte[len]; + _input.readFully(result); + return result; + } catch (IOException e) { + error(e); + return null; + } + } + + BigInteger readBigInteger() { + byte[] result = readByteArray(); + if (result.length == 0) { + return null; + } + if (result.length == 1 && result[0] == 0) { + return BigInteger.ZERO; + } + if (result.length == 1 && result[0] == 1) { + return BigInteger.ONE; + } + return new BigInteger(result); + } + + private int _majorver; + private int _minorver; + private int _releaseno; + + + protected boolean atLeast(int majorver, int minorver, int releaseno) { + if (_majorver > majorver) { + return true; + } + if (_majorver < majorver) { + return false; + } + if (_minorver > minorver) { + return true; + } + if (_minorver < minorver) { + return false; + } + return (_releaseno >= releaseno); + } + + protected boolean atMost(int majorver, int minorver, int releaseno) { + if (_majorver > majorver) { + return false; + } + if (_majorver < majorver) { + return true; + } + if (_minorver > minorver) { + return false; + } + if (_minorver < minorver) { + return true; + } + return (_releaseno <= releaseno); + } + +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/util/Diff.java b/src/main/java/org/apache/xmlbeans/impl/util/Diff.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/util/Diff.java rename to src/main/java/org/apache/xmlbeans/impl/util/Diff.java diff --git a/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java b/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java new file mode 100755 index 0000000..de5862f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/util/FilerImpl.java @@ -0,0 +1,191 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.util; + +import org.apache.xmlbeans.Filer; +import org.apache.xmlbeans.impl.repackage.Repackager; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * This implementation of Filer writes to disk. + */ +public class FilerImpl implements Filer { + private final File classdir; + private final File srcdir; + private final Repackager repackager; + private final boolean verbose; + private final List sourceFiles; + private final boolean incrSrcGen; + private Set seenTypes; + private static final Charset CHARSET; + + static { + Charset temp = null; + try { + temp = Charset.forName(System.getProperty("file.encoding")); + } catch (Exception ignored) { + } + CHARSET = temp; + } + + public FilerImpl(File classdir, File srcdir, Repackager repackager, boolean verbose, boolean incrSrcGen) { + this.classdir = classdir; + this.srcdir = srcdir; + this.repackager = repackager; + this.verbose = verbose; + this.sourceFiles = new ArrayList<>(); + this.incrSrcGen = incrSrcGen; + if (this.incrSrcGen) { + seenTypes = new HashSet<>(); + } + } + + /** + * Creates a new schema binary file (.xsb) and returns a stream for writing to it. + * + * @param typename fully qualified type name + * @return a stream to write the type to + */ + public OutputStream createBinaryFile(String typename) throws IOException { + if (verbose) { + System.err.println("created binary: " + typename); + } + // KHK: for now the typename will already be a relative filename for the binary + //String filename = typename.replace('.', File.separatorChar) + ".xsb"; + File source = new File(classdir, typename); + source.getParentFile().mkdirs(); + + return new FileOutputStream(source); + } + + /** + * Creates a new binding source file (.java) and returns a writer for it. + * + * @param typename fully qualified type name + * @return a stream to write the type to + */ + public Writer createSourceFile(String typename) throws IOException { + if (incrSrcGen) { + seenTypes.add(typename); + } + + if (typename.indexOf('$') > 0) { + typename = + typename.substring(0, typename.lastIndexOf('.')) + "." + + typename.substring(typename.indexOf('$') + 1); + } + + String filename = typename.replace('.', File.separatorChar) + ".java"; + + File sourcefile = new File(srcdir, filename); + sourcefile.getParentFile().mkdirs(); + if (verbose) { + System.err.println("created source: " + sourcefile.getAbsolutePath()); + } + + sourceFiles.add(sourcefile); + + if (incrSrcGen && sourcefile.exists()) { + // Generate the file in a buffer and then compare it to the + // file already on disk + return new IncrFileWriter(sourcefile, repackager); + } else { + return repackager == null ? + writerForFile(sourcefile) : + new RepackagingWriter(sourcefile, repackager); + } + } + + public List getSourceFiles() { + return new ArrayList<>(sourceFiles); + } + + public Repackager getRepackager() { + return repackager; + } + + private static Writer writerForFile(File f) throws IOException { + if (CHARSET == null) { + return Files.newBufferedWriter(f.toPath(), StandardCharsets.ISO_8859_1); + } + + FileOutputStream fileStream = new FileOutputStream(f); + CharsetEncoder ce = CHARSET.newEncoder(); + ce.onUnmappableCharacter(CodingErrorAction.REPORT); + return new OutputStreamWriter(fileStream, ce); + } + + static class IncrFileWriter extends StringWriter { + private final File _file; + private final Repackager _repackager; + + public IncrFileWriter(File file, Repackager repackager) { + _file = file; + _repackager = repackager; + } + + public void close() throws IOException { + super.close(); + + // This is where all the real work happens + StringBuffer sb = _repackager != null ? + _repackager.repackage(getBuffer()) : + getBuffer(); + String str = sb.toString(); + List diffs = new ArrayList<>(); + + try (StringReader sReader = new StringReader(str); + Reader fReader = Files.newBufferedReader(_file.toPath(), StandardCharsets.ISO_8859_1)) { + Diff.readersAsText(sReader, "", fReader, _file.getName(), diffs); + } + + if (diffs.size() > 0) { + // Diffs encountered, replace the file on disk with text from the buffer + try (Writer fw = writerForFile(_file)) { + fw.write(str); + } + } + } + } + + static class RepackagingWriter extends StringWriter { + public RepackagingWriter(File file, Repackager repackager) { + _file = file; + _repackager = repackager; + } + + public void close() throws IOException { + super.close(); + + try (Writer fw = writerForFile(_file)) { + fw.write(_repackager.repackage(getBuffer()).toString()); + } + } + + private final File _file; + private final Repackager _repackager; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java b/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java new file mode 100644 index 0000000..3e84f9c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/util/HexBin.java @@ -0,0 +1,151 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.util; + +import java.nio.charset.StandardCharsets; + +/** + * format validation + *

      + * This class encodes/decodes hexadecimal data + */ +public final class HexBin { + static private final int BASELENGTH = 255; + static private final int LOOKUPLENGTH = 16; + static private final byte[] hexNumberTable = new byte[BASELENGTH]; + static private final byte[] lookUpHexAlphabet = new byte[LOOKUPLENGTH]; + + + static { + for (int i = 0; i < BASELENGTH; i++) { + hexNumberTable[i] = -1; + } + for (int i = '9'; i >= '0'; i--) { + hexNumberTable[i] = (byte) (i - '0'); + } + for (int i = 'F'; i >= 'A'; i--) { + hexNumberTable[i] = (byte) (i - 'A' + 10); + } + for (int i = 'f'; i >= 'a'; i--) { + hexNumberTable[i] = (byte) (i - 'a' + 10); + } + + for (int i = 0; i < 10; i++) { + lookUpHexAlphabet[i] = (byte) ('0' + i); + } + for (int i = 10; i <= 15; i++) { + lookUpHexAlphabet[i] = (byte) ('A' + i - 10); + } + } + + /** + * byte to be tested if it is Base64 alphabet + * + * @param octect + * @return + */ + static boolean isHex(byte octect) { + return (hexNumberTable[octect] != -1); + } + + /** + * Converts bytes to a hex string + */ + static public String bytesToString(byte[] binaryData) { + if (binaryData == null) { + return null; + } + return new String(encode(binaryData), StandardCharsets.ISO_8859_1); + } + + /** + * Converts a hex string to a byte array. + */ + static public byte[] stringToBytes(String hexEncoded) { + return decode(hexEncoded.getBytes(StandardCharsets.ISO_8859_1)); + } + + /** + * array of byte to encode + * + * @param binaryData + * @return return encode binary array + */ + static public byte[] encode(byte[] binaryData) { + if (binaryData == null) { + return null; + } + int lengthData = binaryData.length; + int lengthEncode = lengthData * 2; + byte[] encodedData = new byte[lengthEncode]; + for (int i = 0; i < lengthData; i++) { + encodedData[i * 2] = lookUpHexAlphabet[(binaryData[i] >> 4) & 0xf]; + encodedData[i * 2 + 1] = lookUpHexAlphabet[binaryData[i] & 0xf]; + } + return encodedData; + } + + static public byte[] decode(byte[] binaryData) { + if (binaryData == null) { + return null; + } + int lengthData = binaryData.length; + if (lengthData % 2 != 0) { + return null; + } + + int lengthDecode = lengthData / 2; + byte[] decodedData = new byte[lengthDecode]; + for (int i = 0; i < lengthDecode; i++) { + if (!isHex(binaryData[i * 2]) || !isHex(binaryData[i * 2 + 1])) { + return null; + } + decodedData[i] = (byte) ((hexNumberTable[binaryData[i * 2]] << 4) | hexNumberTable[binaryData[i * 2 + 1]]); + } + return decodedData; + } + + /** + * Decodes Hex data into octects + * + * @param binaryData String containing Hex data + * @return string containing decoded data. + */ + public static String decode(String binaryData) { + if (binaryData == null) { + return null; + } + + byte[] decoded = decode(binaryData.getBytes(StandardCharsets.ISO_8859_1)); + return decoded == null ? null : new String(decoded, StandardCharsets.UTF_8); + } + + /** + * Encodes octects (using utf-8) into Hex data + * + * @param binaryData String containing Hex data + * @return string containing decoded data. + */ + public static String encode(String binaryData) { + if (binaryData == null) { + return null; + } + + byte[] encoded = encode(binaryData.getBytes(StandardCharsets.UTF_8)); + return encoded == null ? null : new String(encoded, StandardCharsets.ISO_8859_1); + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java b/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java new file mode 100644 index 0000000..1de4d85 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/util/XsTypeConverter.java @@ -0,0 +1,682 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.util; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.InvalidLexicalValueException; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; + +public final class XsTypeConverter { + private static final String POS_INF_LEX = "INF"; + private static final String NEG_INF_LEX = "-INF"; + private static final String NAN_LEX = "NaN"; + + private static final char NAMESPACE_SEP = ':'; + private static final String EMPTY_PREFIX = ""; + private static final BigDecimal DECIMAL__ZERO = new BigDecimal(0.0); + + // See Section 2.4.3 of FRC2396 http://www.ietf.org/rfc/rfc2396.txt + private static final String[] URI_CHARS_TO_BE_REPLACED = {" ", "{", "}", "|", "\\", "^", "[", "]", "`"}; + private static final String[] URI_CHARS_REPLACED_WITH = {"%20", "%7b", "%7d", "%7c", "%5c", "%5e", "%5b", "%5d", "%60"}; + + // ======================== float ======================== + public static float lexFloat(CharSequence cs) + throws NumberFormatException { + final String v = cs.toString(); + try { + //current jdk impl of parseFloat calls trim() on the string. + //Any other space is illegal anyway, whether there are one or more spaces. + //so no need to do a collapse pass through the string. + if (cs.length() > 0) { + char ch = cs.charAt(cs.length() - 1); + if (ch == 'f' || ch == 'F') { + if (cs.charAt(cs.length() - 2) != 'N') { + throw new NumberFormatException("Invalid char '" + ch + "' in float."); + } + } + } + return Float.parseFloat(v); + } catch (NumberFormatException e) { + if (v.equals(POS_INF_LEX)) { + return Float.POSITIVE_INFINITY; + } + if (v.equals(NEG_INF_LEX)) { + return Float.NEGATIVE_INFINITY; + } + if (v.equals(NAN_LEX)) { + return Float.NaN; + } + + throw e; + } + } + + public static float lexFloat(CharSequence cs, Collection errors) { + try { + return lexFloat(cs); + } catch (NumberFormatException e) { + String msg = "invalid float: " + cs; + errors.add(XmlError.forMessage(msg)); + + return Float.NaN; + } + } + + public static String printFloat(float value) { + if (value == Float.POSITIVE_INFINITY) { + return POS_INF_LEX; + } else if (value == Float.NEGATIVE_INFINITY) { + return NEG_INF_LEX; + } else if (Float.isNaN(value)) { + return NAN_LEX; + } else { + return Float.toString(value); + } + } + + + // ======================== double ======================== + public static double lexDouble(CharSequence cs) + throws NumberFormatException { + final String v = cs.toString(); + + try { + //current jdk impl of parseDouble calls trim() on the string. + //Any other space is illegal anyway, whether there are one or more spaces. + //so no need to do a collapse pass through the string. + if (cs.length() > 0) { + char ch = cs.charAt(cs.length() - 1); + if (ch == 'd' || ch == 'D') { + throw new NumberFormatException("Invalid char '" + ch + "' in double."); + } + } + return Double.parseDouble(v); + } catch (NumberFormatException e) { + if (v.equals(POS_INF_LEX)) { + return Double.POSITIVE_INFINITY; + } + if (v.equals(NEG_INF_LEX)) { + return Double.NEGATIVE_INFINITY; + } + if (v.equals(NAN_LEX)) { + return Double.NaN; + } + + throw e; + } + } + + public static double lexDouble(CharSequence cs, Collection errors) { + try { + return lexDouble(cs); + } catch (NumberFormatException e) { + String msg = "invalid double: " + cs; + errors.add(XmlError.forMessage(msg)); + + return Double.NaN; + } + } + + public static String printDouble(double value) { + if (value == Double.POSITIVE_INFINITY) { + return POS_INF_LEX; + } else if (value == Double.NEGATIVE_INFINITY) { + return NEG_INF_LEX; + } else if (Double.isNaN(value)) { + return NAN_LEX; + } else { + return Double.toString(value); + } + } + + + // ======================== decimal ======================== + public static BigDecimal lexDecimal(CharSequence cs) + throws NumberFormatException { + final String v = cs.toString(); + + //TODO: review this + //NOTE: we trim unneeded zeros from the string because + //java.math.BigDecimal considers them significant for its + //equals() method, but the xml value + //space does not consider them significant. + //See http://www.w3.org/2001/05/xmlschema-errata#e2-44 + return new BigDecimal(trimTrailingZeros(v)); + } + + private static final char[] CH_ZEROS = new char[]{'0', '0', '0', '0', '0', '0', '0', '0', + '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'}; + + public static String printDecimal(BigDecimal value) { + // We can't simply use value.toString() here, because in JDK1.5 that returns an + // exponent String and exponents are not allowed in XMLSchema decimal values + // The following code comes from Apache Harmony + String intStr = value.unscaledValue().toString(); + int scale = value.scale(); + if ((scale == 0) || ((value.longValue() == 0) && (scale < 0))) { + return intStr; + } + + int begin = (value.signum() < 0) ? 1 : 0; + int delta = scale; + // We take space for all digits, plus a possible decimal point, plus 'scale' + StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale)); + + if (begin == 1) { + // If the number is negative, we insert a '-' character at front + result.append('-'); + } + if (scale > 0) { + delta -= (intStr.length() - begin); + if (delta >= 0) { + result.append("0."); //$NON-NLS-1$ + // To append zeros after the decimal point + for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) { + result.append(CH_ZEROS); + } + result.append(CH_ZEROS, 0, delta); + result.append(intStr.substring(begin)); + } else { + delta = begin - delta; + result.append(intStr.substring(begin, delta)); + result.append('.'); + result.append(intStr.substring(delta)); + } + } else {// (scale <= 0) + result.append(intStr.substring(begin)); + // To append trailing zeros + for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) { + result.append(CH_ZEROS); + } + result.append(CH_ZEROS, 0, -delta); + } + return result.toString(); + } + + // ======================== integer ======================== + public static BigInteger lexInteger(CharSequence cs) + throws NumberFormatException { + if (cs.length() > 1) { + if (cs.charAt(0) == '+' && cs.charAt(1) == '-') { + throw new NumberFormatException("Illegal char sequence '+-'"); + } + } + final String v = cs.toString(); + + //TODO: consider special casing zero and one to return static values + //from BigInteger to avoid object creation. + return new BigInteger(trimInitialPlus(v)); + } + + public static BigInteger lexInteger(CharSequence cs, Collection errors) { + try { + return lexInteger(cs); + } catch (NumberFormatException e) { + String msg = "invalid long: " + cs; + errors.add(XmlError.forMessage(msg)); + return BigInteger.ZERO; + } + } + + public static String printInteger(BigInteger value) { + return value.toString(); + } + + // ======================== long ======================== + public static long lexLong(CharSequence cs) + throws NumberFormatException { + final String v = cs.toString(); + return Long.parseLong(trimInitialPlus(v)); + } + + public static long lexLong(CharSequence cs, Collection errors) { + try { + return lexLong(cs); + } catch (NumberFormatException e) { + String msg = "invalid long: " + cs; + errors.add(XmlError.forMessage(msg)); + return 0L; + } + } + + public static String printLong(long value) { + return Long.toString(value); + } + + + // ======================== short ======================== + public static short lexShort(CharSequence cs) + throws NumberFormatException { + return parseShort(cs); + } + + public static short lexShort(CharSequence cs, Collection errors) { + try { + return lexShort(cs); + } catch (NumberFormatException e) { + String msg = "invalid short: " + cs; + errors.add(XmlError.forMessage(msg)); + return 0; + } + } + + public static String printShort(short value) { + return Short.toString(value); + } + + + // ======================== int ======================== + public static int lexInt(CharSequence cs) + throws NumberFormatException { + return parseInt(cs); + } + + public static int lexInt(CharSequence cs, Collection errors) { + try { + return lexInt(cs); + } catch (NumberFormatException e) { + String msg = "invalid int:" + cs; + errors.add(XmlError.forMessage(msg)); + return 0; + } + } + + public static String printInt(int value) { + return Integer.toString(value); + } + + + // ======================== byte ======================== + public static byte lexByte(CharSequence cs) + throws NumberFormatException { + return parseByte(cs); + } + + public static byte lexByte(CharSequence cs, Collection errors) { + try { + return lexByte(cs); + } catch (NumberFormatException e) { + String msg = "invalid byte: " + cs; + errors.add(XmlError.forMessage(msg)); + return 0; + } + } + + public static String printByte(byte value) { + return Byte.toString(value); + } + + + // ======================== boolean ======================== + public static boolean lexBoolean(CharSequence v) { + switch (v.length()) { + case 1: // "0" or "1" + final char c = v.charAt(0); + if ('0' == c) { + return false; + } + if ('1' == c) { + return true; + } + break; + case 4: //"true" + if ('t' == v.charAt(0) && + 'r' == v.charAt(1) && + 'u' == v.charAt(2) && + 'e' == v.charAt(3)) { + return true; + } + break; + case 5: //"false" + if ('f' == v.charAt(0) && + 'a' == v.charAt(1) && + 'l' == v.charAt(2) && + 's' == v.charAt(3) && + 'e' == v.charAt(4)) { + return false; + } + break; + } + + //reaching here means an invalid boolean lexical + String msg = "invalid boolean: " + v; + throw new InvalidLexicalValueException(msg); + } + + public static boolean lexBoolean(CharSequence value, Collection errors) { + try { + return lexBoolean(value); + } catch (InvalidLexicalValueException e) { + errors.add(XmlError.forMessage(e.getMessage())); + return false; + } + } + + public static String printBoolean(boolean value) { + return (value ? "true" : "false"); + } + + + // ======================== string ======================== + public static String printString(String value) { + return value; + } + + + // ======================== QName ======================== + public static QName lexQName(CharSequence charSeq, NamespaceContext nscontext) { + String prefix, localname; + + int firstcolon; + boolean hasFirstCollon = false; + for (firstcolon = 0; firstcolon < charSeq.length(); firstcolon++) { + if (charSeq.charAt(firstcolon) == NAMESPACE_SEP) { + hasFirstCollon = true; + break; + } + } + + if (hasFirstCollon) { + prefix = charSeq.subSequence(0, firstcolon).toString(); + localname = charSeq.subSequence(firstcolon + 1, charSeq.length()).toString(); + if (firstcolon == 0) { + throw new InvalidLexicalValueException("invalid xsd:QName '" + charSeq.toString() + "'"); + } + } else { + prefix = EMPTY_PREFIX; + localname = charSeq.toString(); + } + + String uri = nscontext.getNamespaceURI(prefix); + + if (uri == null) { + if (prefix != null && prefix.length() > 0) { + throw new InvalidLexicalValueException("Can't resolve prefix: " + prefix); + } + + uri = ""; + } + + return new QName(uri, localname); + } + + public static QName lexQName(String xsd_qname, Collection errors, + NamespaceContext nscontext) { + try { + return lexQName(xsd_qname, nscontext); + } catch (InvalidLexicalValueException e) { + errors.add(XmlError.forMessage(e.getMessage())); + final int idx = xsd_qname.indexOf(NAMESPACE_SEP); + return new QName(null, xsd_qname.substring(idx)); + } + } + + public static String printQName(QName qname, NamespaceContext nsContext, + Collection errors) { + final String uri = qname.getNamespaceURI(); + assert uri != null; //qname is not allowed to have null uri values + final String prefix; + if (uri.length() > 0) { + prefix = nsContext.getPrefix(uri); + if (prefix == null) { + String msg = "NamespaceContext does not provide" + + " prefix for namespaceURI " + uri; + errors.add(XmlError.forMessage(msg)); + } + } else { + prefix = null; + } + return getQNameString(uri, qname.getLocalPart(), prefix); + + } + + public static String getQNameString(String uri, + String localpart, + String prefix) { + if (prefix != null && + uri != null && + uri.length() > 0 && + prefix.length() > 0) { + return (prefix + NAMESPACE_SEP + localpart); + } else { + return localpart; + } + } + + // ======================== GDate ======================== + public static GDate lexGDate(CharSequence charSeq) { + return new GDate(charSeq); + } + + public static GDate lexGDate(String xsd_gdate, Collection errors) { + try { + return lexGDate(xsd_gdate); + } catch (IllegalArgumentException e) { + errors.add(XmlError.forMessage(e.getMessage())); + return new GDateBuilder().toGDate(); + } + } + + public static String printGDate(GDate gdate, Collection errors) { + return gdate.toString(); + } + + + // ======================== dateTime ======================== + public static XmlCalendar lexDateTime(CharSequence v) { + GDateSpecification value = getGDateValue(v, SchemaType.BTC_DATE_TIME); + return value.getCalendar(); + } + + + public static String printDateTime(Calendar c) { + return printDateTime(c, SchemaType.BTC_DATE_TIME); + } + + public static String printTime(Calendar c) { + return printDateTime(c, SchemaType.BTC_TIME); + } + + public static String printDate(Calendar c) { + return printDateTime(c, SchemaType.BTC_DATE); + } + + public static String printDate(Date d) { + GDateSpecification value = getGDateValue(d, SchemaType.BTC_DATE); + return value.toString(); + } + + public static String printDateTime(Calendar c, int type_code) { + GDateSpecification value = getGDateValue(c, type_code); + return value.toString(); + } + + public static String printDateTime(Date c) { + GDateSpecification value = getGDateValue(c, SchemaType.BTC_DATE_TIME); + return value.toString(); + } + + + // ======================== hexBinary ======================== + public static CharSequence printHexBinary(byte[] val) { + return HexBin.bytesToString(val); + } + + + // date utils + public static GDateSpecification getGDateValue(Date d, + int builtin_type_code) { + GDateBuilder gDateBuilder = new GDateBuilder(d); + gDateBuilder.setBuiltinTypeCode(builtin_type_code); + GDate value = gDateBuilder.toGDate(); + return value; + } + + + public static GDateSpecification getGDateValue(Calendar c, + int builtin_type_code) { + GDateBuilder gDateBuilder = new GDateBuilder(c); + gDateBuilder.setBuiltinTypeCode(builtin_type_code); + GDate value = gDateBuilder.toGDate(); + return value; + } + + public static GDateSpecification getGDateValue(CharSequence v, + int builtin_type_code) { + GDateBuilder gDateBuilder = new GDateBuilder(v); + gDateBuilder.setBuiltinTypeCode(builtin_type_code); + GDate value = gDateBuilder.toGDate(); + return value; + } + + private static String trimInitialPlus(String xml) { + if (xml.length() > 0 && xml.charAt(0) == '+') { + return xml.substring(1); + } else { + return xml; + } + } + + private static String trimTrailingZeros(String xsd_decimal) { + final int last_char_idx = xsd_decimal.length() - 1; + if (xsd_decimal.charAt(last_char_idx) == '0') { + final int last_point = xsd_decimal.lastIndexOf('.'); + if (last_point >= 0) { + //find last trailing zero + for (int idx = last_char_idx; idx > last_point; idx--) { + if (xsd_decimal.charAt(idx) != '0') { + return xsd_decimal.substring(0, idx + 1); + } + } + //reaching here means the string matched xxx.0* + return xsd_decimal.substring(0, last_point); + } + } + return xsd_decimal; + } + + private static int parseInt(CharSequence cs) { + return parseIntXsdNumber(cs, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + private static short parseShort(CharSequence cs) { + return (short) parseIntXsdNumber(cs, Short.MIN_VALUE, Short.MAX_VALUE); + } + + private static byte parseByte(CharSequence cs) { + return (byte) parseIntXsdNumber(cs, Byte.MIN_VALUE, Byte.MAX_VALUE); + } + + private static int parseIntXsdNumber(CharSequence ch, int min_value, int max_value) { + // int parser on a CharSequence + int length = ch.length(); + if (length < 1) { + throw new NumberFormatException("For input string: \"" + ch.toString() + "\""); + } + + int sign = 1; + int result = 0; + int start = 0; + int limit; + int limit2; + + char c = ch.charAt(0); + if (c == '-') { + start++; + limit = (min_value / 10); + limit2 = -(min_value % 10); + } else if (c == '+') { + start++; + sign = -1; + limit = -(max_value / 10); + limit2 = (max_value % 10); + } else { + sign = -1; + limit = -(max_value / 10); + limit2 = (max_value % 10); + } + + for (int i = 0; i < length - start; i++) { + c = ch.charAt(i + start); + int v = Character.digit(c, 10); + + if (v < 0) { + throw new NumberFormatException("For input string: \"" + ch.toString() + "\""); + } + + if (result < limit || (result == limit && v > limit2)) { + throw new NumberFormatException("For input string: \"" + ch.toString() + "\""); + } + + result = result * 10 - v; + } + + return sign * result; + } + + // ======================== anyURI ======================== + + /** + * Checkes the regular expression of URI, defined by RFC2369 http://www.ietf.org/rfc/rfc2396.txt Appendix B. + * Note: The whitespace normalization rule collapse must be applied priot to calling this method. + * + * @param lexical_value the lexical value + * @return same input value if input value is in the lexical space + * @throws InvalidLexicalValueException + */ + public static CharSequence lexAnyURI(CharSequence lexical_value) { + /* // Reg exp from RFC2396, but it's too forgiving for XQTS + Pattern p = Pattern.compile("^([^:/?#]+:)?(//[^/?#]*)?([^?#]*)(\\?[^#]*)?(#.*)?"); + Matcher m = p.matcher(lexical_value); + if ( !m.matches() ) + throw new InvalidLexicalValueException("invalid anyURI value"); + else + { + for ( int i = 0; i<= m.groupCount(); i++ ) + { + System.out.print(" " + i + ": " + m.group(i)); + } + System.out.println(""); + return lexical_value; + } */ + + // Per XMLSchema spec allow spaces inside URIs + StringBuilder s = new StringBuilder(lexical_value.toString()); + for (int ic = 0; ic < URI_CHARS_TO_BE_REPLACED.length; ic++) { + int i = 0; + while ((i = s.indexOf(URI_CHARS_TO_BE_REPLACED[ic], i)) >= 0) { + s.replace(i, i + 1, URI_CHARS_REPLACED_WITH[ic]); + i += 3; + } + } + + try { + URI.create(s.toString()); + } catch (IllegalArgumentException e) { + throw new InvalidLexicalValueException("invalid anyURI value: " + lexical_value, e); + } + + return lexical_value; + } +} \ No newline at end of file diff --git a/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingInfoXMLStreamReader.java b/src/main/java/org/apache/xmlbeans/impl/validator/ValidatingInfoXMLStreamReader.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingInfoXMLStreamReader.java rename to src/main/java/org/apache/xmlbeans/impl/validator/ValidatingInfoXMLStreamReader.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java b/src/main/java/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java similarity index 99% rename from src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java rename to src/main/java/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java index 99c8563..6aaad6d 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java +++ b/src/main/java/org/apache/xmlbeans/impl/validator/ValidatingXMLStreamReader.java @@ -52,8 +52,6 @@ public class ValidatingXMLStreamReader extends StreamReaderDelegate implements XMLStreamReader { - public static final String OPTION_ATTTRIBUTE_VALIDATION_COMPAT_MODE = "OPTION_ATTTRIBUTE_VALIDATION_COMPAT_MODE"; - private static final String URI_XSI = "http://www.w3.org/2001/XMLSchema-instance"; private static final QName XSI_TYPE = new QName(URI_XSI, "type"); private static final QName XSI_NIL = new QName(URI_XSI, "nil"); @@ -143,7 +141,7 @@ private static class PackTextXmlStreamReader implements XMLStreamReader { private boolean _hasBufferedText; - private StringBuffer _buffer = new StringBuffer(); + private StringBuilder _buffer = new StringBuilder(); private int _textEventType; void init(XMLStreamReader xmlstream) @@ -802,7 +800,7 @@ protected void validate_attributes(int attCount) validate_attribute(i); } - if (_options!=null && _options.hasOption(OPTION_ATTTRIBUTE_VALIDATION_COMPAT_MODE)) + if (_options!=null && _options.isAttributeValidationCompatMode()) {} else _validator.nextEvent(Validator.ENDATTRS, _simpleEvent); diff --git a/src/main/java/org/apache/xmlbeans/impl/validator/Validator.java b/src/main/java/org/apache/xmlbeans/impl/validator/Validator.java new file mode 100644 index 0000000..f39bb29 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/validator/Validator.java @@ -0,0 +1,1657 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.validator; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.*; +import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; +import org.apache.xmlbeans.impl.schema.SchemaTypeVisitorImpl; +import org.apache.xmlbeans.impl.util.XsTypeConverter; +import org.apache.xmlbeans.impl.values.*; + +import javax.xml.namespace.QName; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import java.util.stream.Collectors; + +public final class Validator + implements ValidatorListener { + public Validator( + SchemaType type, SchemaField field, SchemaTypeLoader globalLoader, + XmlOptions options, Collection defaultErrorListener) { + options = XmlOptions.maskNull(options); + _errorListener = options.getErrorListener(); + _treatLaxAsSkip = options.isValidateTreatLaxAsSkip(); + _strict = options.isValidateStrict(); + + if (_errorListener == null) { + _errorListener = defaultErrorListener; + } + + _constraintEngine = new IdentityConstraint(_errorListener, type.isDocumentType()); + + _globalTypes = globalLoader; + _rootType = type; + _rootField = field; + + _vc = new ValidatorVC(); + } + + private class ValidatorVC implements ValidationContext { + // KHK: remove this + public void invalid(String message) { + // TODO (dutta) Addtional Attributes for validation error have limited information + //at this time but will be a part of the second round of refactoring + + Validator.this.emitError(_event, message, null, null, + XmlValidationError.ATTRIBUTE_TYPE_INVALID); + } + + public void invalid(String code, Object[] args) { + // TODO (dutta) Addtional Attributes for validation error have limited information + //at this time but will be a part of the second round of refactoring + + Validator.this.emitError(_event, code, args, null, null, + XmlValidationError.ATTRIBUTE_TYPE_INVALID, null); + } + + Event _event; + } + + public boolean isValid() { + return !_invalid && _constraintEngine.isValid(); + } + + // KHK: remove this + private void emitError(Event event, String message, QName offendingQName, + SchemaType expectedSchemaType, + int errorType) { + emitError(event, message, null, null, XmlError.SEVERITY_ERROR, null, offendingQName, expectedSchemaType, + null, errorType, null); + } + + private void emitError(Event event, String code, Object[] args, QName offendingQName, + SchemaType expectedSchemaType, + int errorType, SchemaType badSchemaType) { + emitError(event, null, code, args, XmlError.SEVERITY_ERROR, null, offendingQName, expectedSchemaType, + null, errorType, badSchemaType); + } + + // KHK: remove 'message' parameter + private void emitError(Event event, String message, String code, Object[] args, int severity, + QName fieldName, QName offendingQName, + SchemaType expectedSchemaType, List expectedQNames, + int errorType, SchemaType badSchemaType) { + _errorState++; + + if (_suspendErrors == 0) { + if (severity == XmlError.SEVERITY_ERROR) { + _invalid = true; + } + + if (_errorListener != null) { + assert event != null; + XmlError error; + XmlCursor curs = event.getLocationAsCursor(); + if (curs != null) { + // non-streaming validation uses XmlCursor + error = XmlValidationError.forCursorWithDetails(message, code, args, severity, + curs, fieldName, offendingQName, expectedSchemaType, expectedQNames, + errorType, badSchemaType); + } else { + // streaming validation uses Location + error = XmlValidationError.forLocationWithDetails(message, code, args, severity, + event.getLocation(), fieldName, offendingQName, expectedSchemaType, expectedQNames, + errorType, badSchemaType); + } + + _errorListener.add(error); + } + } + } + + private void emitFieldError(Event event, String code, Object[] args, QName offendingQName, + SchemaType expectedSchemaType, List expectedQNames, + int errorType, SchemaType badSchemaType) { + QName fieldName = null; + if (_stateStack != null && _stateStack._field != null) { + fieldName = _stateStack._field.getName(); + } + + Validator.this.emitError(event, null, code, args, XmlError.SEVERITY_ERROR, fieldName, offendingQName, expectedSchemaType, + expectedQNames, errorType, badSchemaType); + } + + public void nextEvent(int kind, Event event) { + resetValues(); + + if (_eatContent > 0) { + switch (kind) { + case END: + _eatContent--; + break; + case BEGIN: + _eatContent++; + break; + } + } else { + assert + kind == BEGIN || kind == ATTR || + kind == END || kind == TEXT || kind == ENDATTRS; + + switch (kind) { + case BEGIN: + beginEvent(event); + break; + case ATTR: + attrEvent(event); + break; + case ENDATTRS: + endAttrsEvent(event); + break; + case TEXT: + textEvent(event); + break; + case END: + endEvent(event); + break; + } + } + } + + private void beginEvent(Event event) { + _localElement = null; + _wildcardElement = null; + State state = topState(); + + SchemaType elementType; + SchemaField elementField; + + if (state == null) { + elementType = _rootType; + elementField = _rootField; + } else { + + QName name = event.getName(); + + assert name != null; + + state._isEmpty = false; + + if (state._isNil) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$NIL_WITH_CONTENT, + null, state._field.getName(), state._type, null, + XmlValidationError.NIL_ELEMENT, state._type); + + _eatContent = 1; + return; + } + + if (state._field != null && state._field.isFixed()) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_WITH_CONTENT, + new Object[]{QNameHelper.pretty(state._field.getName())}, + state._field.getName(), state._type, null, + XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); + } + + if (!state.visit(name)) { + findDetailedErrorBegin(event, state, name); + + _eatContent = 1; + + return; + } + + SchemaParticle currentParticle = state.currentParticle(); + _wildcardElement = currentParticle; + + if (currentParticle.getParticleType() == SchemaParticle.WILDCARD) { + //_wildcardElement = currentParticle; + QNameSet elemWildcardSet = currentParticle.getWildcardSet(); + + if (!elemWildcardSet.contains(name)) { + // Additional processing may be needed to generate more + // descriptive messages + // KHK: cvc-complex-type.2.4? cvc-particle.1.3? cvc-wildcard-namespace ? + emitFieldError(event, XmlErrorCodes.PARTICLE_VALID$NOT_WILDCARD_VALID, + new Object[]{QNameHelper.pretty(name)}, + name, null, null, + XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); + + _eatContent = 1; + + return; + } + + int wildcardProcess = currentParticle.getWildcardProcess(); + + if (wildcardProcess == SchemaParticle.SKIP || + wildcardProcess == SchemaParticle.LAX && _treatLaxAsSkip) { + _eatContent = 1; + return; + } + + _localElement = _globalTypes.findElement(name); + elementField = _localElement; + + if (elementField == null) { + if (wildcardProcess == SchemaParticle.STRICT) { + // KHK: cvc-complex-type.2.4c? cvc-assess-elt.1.1.1.3.2? + emitFieldError(event, XmlErrorCodes.ASSESS_ELEM_SCHEMA_VALID$NOT_RESOLVED, + new Object[]{QNameHelper.pretty(name)}, + name, state._type, null, + XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); + } + + _eatContent = 1; + + return; + } + } else { + assert currentParticle.getParticleType() == SchemaParticle.ELEMENT; + + // If the current element particle name does not match the name + // of the event, then the current element is a substitute for + // the current particle. Replace the field with the global + // element for the replacement + + if (!currentParticle.getName().equals(name)) { + if (((SchemaLocalElement) currentParticle).blockSubstitution()) { + emitFieldError(event, XmlErrorCodes.PARTICLE_VALID$BLOCK_SUBSTITUTION, + new Object[]{QNameHelper.pretty(name)}, + name, state._type, null, + XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); + + _eatContent = 1; + return; + } + + SchemaGlobalElement newField = _globalTypes.findElement(name); + + assert newField != null; + + elementField = newField; + _localElement = newField; + } else { + elementField = (SchemaField) currentParticle; + } + } + + elementType = elementField.getType(); + } + + assert elementType != null; + + // + // the no-type is always invalid (even if there is an xsi:type) + // + + if (elementType.isNoType()) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$NO_TYPE, + null, event.getName(), null, null, + XmlValidationError.ELEMENT_TYPE_INVALID, null); + + _eatContent = 1; + } + + // + // See if the element has an xsi:type on it + // + + SchemaType xsiType = null; + + String value = event.getXsiType(); + + if (value != null) { + // Turn off the listener so a public error message + // does not get generated, but I can see if there was + // an error through the error state + + int originalErrorState = _errorState; + + _suspendErrors++; + + try { + _vc._event = null; + + xsiType = _globalTypes.findType(XmlQNameImpl.validateLexical(value, _vc, event)); + } catch (Throwable t) { + _errorState++; + } finally { + _suspendErrors--; + } + + if (originalErrorState != _errorState) { + // not sure how to extract this one + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_INVALID_QNAME, + new Object[]{value}, event.getName(), xsiType, null, + XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + + _eatContent = 1; + + return; + } else if (xsiType == null) { + // NOT SURE errorAttributes._expectedSchemaType = xsiType; + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_NOT_FOUND, + new Object[]{value}, event.getName(), null, null, + XmlValidationError.ELEMENT_TYPE_INVALID, null); + + _eatContent = 1; + + return; + } + } + + if (xsiType != null && !xsiType.equals(elementType)) { + if (!elementType.isAssignableFrom(xsiType)) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_NOT_DERIVED, + new Object[]{xsiType, elementType}, event.getName(), elementType, null, + XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + + _eatContent = 1; + + return; + } + + if (elementType.blockExtension()) { + for (SchemaType t = xsiType; !t.equals(elementType); + t = t.getBaseType()) { + if (t.getDerivationType() == SchemaType.DT_EXTENSION) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_BLOCK_EXTENSION, + new Object[]{xsiType, elementType}, event.getName(), elementType, null, + XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + + _eatContent = 1; + + return; + } + } + } + + if (elementType.blockRestriction()) { + for (SchemaType t = xsiType; !t.equals(elementType); + t = t.getBaseType()) { + if (t.getDerivationType() == SchemaType.DT_RESTRICTION) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_BLOCK_RESTRICTION, + new Object[]{xsiType, elementType}, event.getName(), elementType, null, + XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + + _eatContent = 1; + + return; + } + } + } + + if (elementField instanceof SchemaLocalElement) { + SchemaLocalElement sle = (SchemaLocalElement) elementField; + _localElement = sle; + + if (sle.blockExtension() || sle.blockRestriction()) { + for (SchemaType t = xsiType; !t.equals(elementType); + t = t.getBaseType()) { + if ((t.getDerivationType() == SchemaType.DT_RESTRICTION && sle.blockRestriction()) || + (t.getDerivationType() == SchemaType.DT_EXTENSION && sle.blockExtension())) { + //need to find a way to get the right type + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_PROHIBITED_SUBST, + new Object[]{xsiType, QNameHelper.pretty(sle.getName())}, + sle.getName(), null, null, XmlValidationError.ELEMENT_TYPE_INVALID, null); + + _eatContent = 1; + + return; + } + } + } + } + + elementType = xsiType; + } + + if (elementField instanceof SchemaLocalElement) { + SchemaLocalElement sle = (SchemaLocalElement) elementField; + _localElement = sle; + + if (sle.isAbstract()) { + //todo (dutta) need to find a way to get the right type + emitError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$ABSTRACT, + new Object[]{QNameHelper.pretty(sle.getName())}, + sle.getName(), null, XmlValidationError.ELEMENT_TYPE_INVALID, null); + + _eatContent = 1; + return; + } + } + + if (elementType.isAbstract()) { + emitError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$ABSTRACT, + new Object[]{elementType}, + event.getName(), elementType, XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + + _eatContent = 1; + + return; + } + + boolean isNil = false; + boolean hasNil = false; + + String nilValue = event.getXsiNil(); + + if (nilValue != null) { + _vc._event = event; + isNil = JavaBooleanHolder.validateLexical(nilValue, _vc); + hasNil = true; + } + + // note in schema spec 3.3.4, you're not even allowed to say xsi:nil="false" if you're not nillable! + if (hasNil && (elementField == null || !elementField.isNillable())) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$NOT_NILLABLE, null, + elementField == null ? null : elementField.getName(), elementType, null, + XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + + _eatContent = 1; + return; + } + + if (isNil && elementField != null && elementField.isFixed()) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$NIL_WITH_FIXED, null, + elementField.getName(), elementType, null, + XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); + } + + newState(elementType, elementField, isNil); + + // Dispatch this element event to any identity constraints + // As well as adding any new identity constraints that exist + + _constraintEngine.element( + event, + elementType, + elementField instanceof SchemaLocalElement + ? ((SchemaLocalElement) elementField).getIdentityConstraints() + : null); + } + + private void attrEvent(Event event) { + QName attrName = event.getName(); + + State state = topState(); + + if (state._attrs == null) { + state._attrs = new HashSet<>(); + } + + if (state._attrs.contains(attrName)) { + emitFieldError(event, XmlErrorCodes.XML_DUPLICATE_ATTRIBUTE, + new Object[]{QNameHelper.pretty(attrName)}, + attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + + return; + } + + state._attrs.add(attrName); + + if (!state._canHaveAttrs) { + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD, + new Object[]{QNameHelper.pretty(attrName)}, attrName, null, null, + XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + return; + } + + SchemaLocalAttribute attrSchema = + state._attrModel == null + ? null + : state._attrModel.getAttribute(attrName); + + if (attrSchema != null) { + _localAttribute = attrSchema; + + if (attrSchema.getUse() == SchemaLocalAttribute.PROHIBITED) { + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$PROHIBITED_ATTRIBUTE, + new Object[]{QNameHelper.pretty(attrName)}, + attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + + return; + } + + String value = + validateSimpleType( + attrSchema.getType(), attrSchema, event, false, false); + + _constraintEngine.attr(event, attrName, attrSchema.getType(), value); + + return; + } + + int wildcardProcess = state._attrModel.getWildcardProcess(); + + _wildcardAttribute = state._attrModel; + + if (wildcardProcess == SchemaAttributeModel.NONE) { + // todo (dutta) need additional logic to determine the expectedSchemaType + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD, + new Object[]{QNameHelper.pretty(attrName)}, + attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + + return; + } + + QNameSet attrWildcardSet = state._attrModel.getWildcardSet(); + + if (!attrWildcardSet.contains(attrName)) { + // todo (dutta) need additional logic to determine the expectedSchemaType + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NOT_WILDCARD_VALID, + new Object[]{QNameHelper.pretty(attrName)}, + attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + + return; + } + + if (wildcardProcess == SchemaAttributeModel.SKIP || + wildcardProcess == SchemaAttributeModel.LAX && _treatLaxAsSkip) { + return; + } + + attrSchema = _globalTypes.findAttribute(attrName); + _localAttribute = attrSchema; + + if (attrSchema == null) { + if (wildcardProcess == SchemaAttributeModel.LAX) { + return; + } + + assert wildcardProcess == SchemaAttributeModel.STRICT; + + // KHK: cvc-assess-attr.1.2 ? + // todo (dutta) need additional logic to determine the expectedSchemaType + emitFieldError(event, XmlErrorCodes.ASSESS_ATTR_SCHEMA_VALID$NOT_RESOLVED, + new Object[]{QNameHelper.pretty(attrName)}, + attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + + return; + } + + String value = + validateSimpleType( + attrSchema.getType(), attrSchema, event, false, false); + + _constraintEngine.attr(event, attrName, attrSchema.getType(), value); + } + + private void endAttrsEvent(Event event) { + State state = topState(); + + if (state._attrModel != null) { + SchemaLocalAttribute[] attrs = state._attrModel.getAttributes(); + + for (SchemaLocalAttribute sla : attrs) { + if (state._attrs == null || + !state._attrs.contains(sla.getName())) { + if (sla.getUse() == SchemaLocalAttribute.REQUIRED) { + // KHK: cvc-complex-type.4 + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_REQUIRED_ATTRIBUTE, + new Object[]{QNameHelper.pretty(sla.getName())}, + sla.getName(), null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); + } else if (sla.isDefault() || sla.isFixed()) { + _constraintEngine.attr(event, sla.getName(), sla.getType(), sla.getDefaultText()); + + // We don't need to validate attribute defaults because this is done at compiletime. + /* + String value = sla.getDefaultText(); + SchemaType type = sla.getType(); + + if (XmlQName.type.isAssignableFrom(type)) + { + emitFieldError( + event, + "Default QName values are unsupported for attribute: " + + QNameHelper.pretty(sla.getName()), + XmlError.SEVERITY_INFO); + } + + else + { + validateSimpleType( + type, sla.getDefaultText(), event ); + + _constraintEngine.attr( event, type, value ); + } + */ + } + } + } + } + } + + private void endEvent(Event event) { + _localElement = null; + _wildcardElement = null; + State state = topState(); + + if (!state._isNil) { + if (!state.end()) { + findDetailedErrorEnd(event, state); + } + + // This end event has no text, use this fact to pass no text to + // handleText + + if (state._isEmpty) { + handleText(event, true, state._field); + } + } + + popState(event); + + _constraintEngine.endElement(event); + } + + private void textEvent(Event event) { + State state = topState(); + + if (state._isNil) { + emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$NIL_WITH_CONTENT, null, + state._field.getName(), state._type, null, + XmlValidationError.NIL_ELEMENT, state._type); + } else { + handleText(event, false, state._field); + } + + state._isEmpty = false; + } + + + private void handleText( + Event event, boolean emptyContent, SchemaField field) { + State state = topState(); + + if (!state._sawText) { + if (state._hasSimpleContent) { + String value = + validateSimpleType( + state._type, field, event, emptyContent, true); + + _constraintEngine.text(event, state._type, value, false); + } else if (state._canHaveMixedContent) { + // handles cvc-elt.5.2.2.2.1, checking mixed content against fixed. + // if we see ac, we validate against + // the first 'a' text and we check the content of mixedType to + // be empty in beginElem(). we don't care about checking against + // the 'c' text since there will already be an error for + String value = + validateSimpleType( + XmlString.type, field, event, emptyContent, true); + + _constraintEngine.text(event, XmlString.type, value, false); + } else if (emptyContent) { + _constraintEngine.text(event, state._type, null, true); + } else { + _constraintEngine.text(event, state._type, "", false); + } + } + + if (!emptyContent && !state._canHaveMixedContent && + !event.textIsWhitespace() && !state._hasSimpleContent) { + if (field instanceof SchemaLocalElement) { + SchemaLocalElement e = (SchemaLocalElement) field; + + assert state._type.getContentType() == SchemaType.EMPTY_CONTENT || + state._type.getContentType() == SchemaType.ELEMENT_CONTENT; + + // KHK: cvc-complex-type.2.1 or .2.3 + String errorCode = (state._type.getContentType() == SchemaType.EMPTY_CONTENT ? + XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EMPTY_WITH_CONTENT : + XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_ONLY_WITH_TEXT); + + emitError(event, errorCode, new Object[]{QNameHelper.pretty(e.getName())}, + e.getName(), field.getType(), + XmlValidationError.ELEMENT_TYPE_INVALID, null); + } else { + // KHK: cvc-complex-type.2.1 or .2.3 + // todo (dutta) offendingQName = not sure how to get this(event.getName()??); + emitError(event, "Can't have mixed content", event.getName(), + state._type, XmlValidationError.ELEMENT_TYPE_INVALID); + } + } + + if (!emptyContent) { + state._sawText = true; + } + } + + private void findDetailedErrorBegin(Event event, State state, QName qName) { + ArrayList expectedNames = new ArrayList<>(); + ArrayList optionalNames = new ArrayList<>(); + + SchemaProperty[] eltProperties = state._type.getElementProperties(); + for (SchemaProperty sProp : eltProperties) { + //Get the element from the schema + // test if the element is valid + if (state.test(sProp.getName())) { + if (0 == BigInteger.ZERO.compareTo(sProp.getMinOccurs())) { + optionalNames.add(sProp.getName()); + } else { + expectedNames.add(sProp.getName()); + } + } + } + + List names = (expectedNames.size() > 0 ? expectedNames : optionalNames); + + if (names.size() > 0) { + String buf = names.stream().map(QNameHelper::pretty).collect(Collectors.joining(" ")); + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT, + new Object[]{names.size(), buf, QNameHelper.pretty(qName)}, + qName, null, names, XmlValidationError.INCORRECT_ELEMENT, state._type); + } else { + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_NOT_ALLOWED, + new Object[]{QNameHelper.pretty(qName)}, + qName, null, null, XmlValidationError.INCORRECT_ELEMENT, state._type); + } + } + + private void findDetailedErrorEnd(Event event, State state) { + SchemaProperty[] eltProperties = state._type.getElementProperties(); + + ArrayList expectedNames = new ArrayList<>(); + ArrayList optionalNames = new ArrayList<>(); + + for (SchemaProperty sProp : eltProperties) { + //Get the element from the schema + // test if the element is valid + if (state.test(sProp.getName())) { + if (0 == BigInteger.ZERO.compareTo(sProp.getMinOccurs())) { + optionalNames.add(sProp.getName()); + } else { + expectedNames.add(sProp.getName()); + } + } + } + + List names = (expectedNames.size() > 0 ? expectedNames : optionalNames); + + if (names.size() > 0) { + String buf = names.stream().map(QNameHelper::pretty).collect(Collectors.joining(" ")); + + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_ELEMENT, + new Object[]{names.size(), buf}, + null, null, names, XmlValidationError.INCORRECT_ELEMENT, state._type); + } else { + emitFieldError(event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_ELEMENT, + null, null, null, null, XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); + } + } + + + private static final class State { + boolean visit(QName name) { + return _canHaveElements && _visitor.visit(name); + } + + boolean test(QName name) { + return _canHaveElements && _visitor.testValid(name); + } + + boolean end() { + return !_canHaveElements || _visitor.visit(null); + } + + SchemaParticle currentParticle() { + assert _visitor != null; + return _visitor.currentParticle(); + } + + SchemaType _type; + SchemaField _field; + + boolean _canHaveAttrs; + boolean _canHaveMixedContent; + boolean _hasSimpleContent; + + boolean _sawText; + boolean _isEmpty; + boolean _isNil; + + SchemaTypeVisitorImpl _visitor; + boolean _canHaveElements; + + SchemaAttributeModel _attrModel; + + HashSet _attrs; + + State _next; + } + + private boolean derivedFromInteger(SchemaType type) { + int btc = type.getBuiltinTypeCode(); + + while (btc == SchemaType.BTC_NOT_BUILTIN) { + type = type.getBaseType(); + btc = type.getBuiltinTypeCode(); + } + // This depends on the ordering of the constant values, which is not ideal but is easier + return btc >= SchemaType.BTC_INTEGER && btc <= SchemaType.BTC_UNSIGNED_BYTE; + } + + private void newState(SchemaType type, SchemaField field, boolean isNil) { + State state = new State(); + + state._type = type; + state._field = field; + state._isEmpty = true; + state._isNil = isNil; + + if (type.isSimpleType()) { + state._hasSimpleContent = true; + } else { + state._canHaveAttrs = true; + state._attrModel = type.getAttributeModel(); + + switch (type.getContentType()) { + case SchemaType.EMPTY_CONTENT: + break; + + case SchemaType.SIMPLE_CONTENT: + state._hasSimpleContent = true; + break; + + case SchemaType.MIXED_CONTENT: + state._canHaveMixedContent = true; + // Fall through + + case SchemaType.ELEMENT_CONTENT: + + SchemaParticle particle = type.getContentModel(); + + state._canHaveElements = particle != null; + + if (state._canHaveElements) { + state._visitor = initVisitor(particle); + } + + break; + + default: + throw new RuntimeException("Unexpected content type"); + } + } + + pushState(state); + } + + private void popState(Event e) { + if (_stateStack._visitor != null) { + poolVisitor(_stateStack._visitor); + _stateStack._visitor = null; + } + + _stateStack = _stateStack._next; + } + + private void pushState(State state) { + state._next = _stateStack; + _stateStack = state; + } + + private final LinkedList _visitorPool = new LinkedList<>(); + + private void poolVisitor(SchemaTypeVisitorImpl visitor) { + _visitorPool.add(visitor); + } + + private SchemaTypeVisitorImpl initVisitor(SchemaParticle particle) { + if (_visitorPool.isEmpty()) { + return new SchemaTypeVisitorImpl(particle); + } + + SchemaTypeVisitorImpl result = + (SchemaTypeVisitorImpl) _visitorPool.removeLast(); + + result.init(particle); + + return result; + } + + private State topState() { + return _stateStack; + } + + // + // Simple Type Validation + // + // emptyContent means that you can't use the event to get text: there is + // no text, but you can use the event to do prefix resolution (in the case + // where the default is a qname) + // + + private String validateSimpleType( + SchemaType type, SchemaField field, Event event, + boolean emptyContent, boolean canApplyDefault) { + if (!type.isSimpleType() && + type.getContentType() != SchemaType.SIMPLE_CONTENT) { + assert false; + // throw new RuntimeException( "Not a simple type" ); + return null; // should never happen + } + + // + // the no-type is always invalid + // + + if (type.isNoType()) { + emitError(event, (field.isAttribute() ? XmlErrorCodes.ATTR_LOCALLY_VALID$NO_TYPE : XmlErrorCodes.ELEM_LOCALLY_VALID$NO_TYPE), + null, field.getName(), type, XmlValidationError.ELEMENT_TYPE_INVALID, null); + + return null; + } + + // Get the value as a string (as normalized by the white space rule + // TODO - will want to optimize this later + + String value = ""; + + if (!emptyContent) { + int wsr = type.getWhiteSpaceRule(); + value = wsr == SchemaType.WS_PRESERVE ? event.getText() : event.getText(wsr); + } + + // See if I can apply a default/fixed value + + if (value.length() == 0 && canApplyDefault && field != null && + (field.isDefault() || field.isFixed())) { + if (XmlQName.type.isAssignableFrom(type)) { + // TODO: will be fixed in XmlSchema 1.1 + emitError(event, "Default QName values are unsupported for " + + QNameHelper.readable(type) + " - ignoring.", null, null, + XmlError.SEVERITY_INFO, field.getName(), null, type, null, + XmlValidationError.ELEMENT_TYPE_INVALID, null); + + return null; + } + + String defaultValue = + XmlWhitespace.collapse( + field.getDefaultText(), type.getWhiteSpaceRule()); + +// BUGBUG - should validate defaultValue at compile time + // KHK: cvc-elt.5.1.2 ? + return + validateSimpleType(type, defaultValue, event) + ? defaultValue + : null; + } + + // KHK: cvc-elt.5.2.1 ? + if (!validateSimpleType(type, value, event)) { + return null; + } + + if (field != null && field.isFixed()) { +// TODO - fixed value should have been cooked at compile time + String fixedValue = + XmlWhitespace.collapse( + field.getDefaultText(), type.getWhiteSpaceRule()); + + if (!validateSimpleType(type, fixedValue, event)) { + return null; + } + + XmlObject val = type.newValue(value); + XmlObject def = type.newValue(fixedValue); + + if (!val.valueEquals(def)) { + // TODO (dutta) - make this more verbose + if (field.isAttribute()) { + // KHK: check for is cvc-complex-type.3.1 or cvc-au + emitError(event, XmlErrorCodes.ATTR_LOCALLY_VALID$FIXED, + new Object[]{value, fixedValue, QNameHelper.pretty(event.getName())}, + null, field.getType(), XmlValidationError.ELEMENT_TYPE_INVALID, null); + } else { + String errorCode = null; + + // see rule 5 of cvc-elt: Element Locally Valid (Element) + if (field.getType().getContentType() == SchemaType.MIXED_CONTENT) { + errorCode = XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_VALID_MIXED_CONTENT; + } else if (type.isSimpleType()) { + errorCode = XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_VALID_SIMPLE_TYPE; + } else { + assert false : "Element with fixed may not be EMPTY or ELEMENT_ONLY"; + } + + emitError(event, errorCode, new Object[]{value, fixedValue}, + field.getName(), field.getType(), XmlValidationError.ELEMENT_TYPE_INVALID, null); + } + + return null; + } + } + + return value; + } + + private boolean validateSimpleType( + SchemaType type, String value, Event event) { + if (!type.isSimpleType() && + type.getContentType() != SchemaType.SIMPLE_CONTENT) { + assert false; + throw new RuntimeException("Not a simple type"); + } + + int retState = _errorState; + + switch (type.getSimpleVariety()) { + case SchemaType.ATOMIC: + validateAtomicType(type, value, event); + break; + case SchemaType.UNION: + validateUnionType(type, value, event); + break; + case SchemaType.LIST: + validateListType(type, value, event); + break; + + default: + throw new RuntimeException("Unexpected simple variety"); + } + + return retState == _errorState; + } + + private void validateAtomicType( + SchemaType type, String value, Event event) { + // Now we should have only an atomic type to validate + + assert type.getSimpleVariety() == SchemaType.ATOMIC; + + // Record the current error state to see if any new errors are made + int errorState = _errorState; + _vc._event = event; + + switch (type.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_ANY_SIMPLE: { + // Always valid! + _stringValue = value; + break; + } + case SchemaType.BTC_STRING: { + JavaStringEnumerationHolderEx.validateLexical(value, type, _vc); + _stringValue = value; + break; + } + case SchemaType.BTC_DECIMAL: { + JavaDecimalHolderEx.validateLexical(value, type, _vc); + + // An additional rule states that if the type is xs:integer or derived from it, + // then the decimal dot is not allowed. + // verify that values extending xsd:integer don't have a decimal point + if (derivedFromInteger(type) && value.lastIndexOf('.') >= 0) { + _vc.invalid(XmlErrorCodes.INTEGER, new Object[]{value}); + } + + if (errorState == _errorState) { + _decimalValue = new BigDecimal(value); + JavaDecimalHolderEx.validateValue(_decimalValue, type, _vc); + } + + break; + } + case SchemaType.BTC_BOOLEAN: { + _booleanValue = JavaBooleanHolderEx.validateLexical(value, type, _vc); + break; + } + case SchemaType.BTC_FLOAT: { + float f = + JavaFloatHolderEx.validateLexical(value, type, _vc); + + if (errorState == _errorState) { + JavaFloatHolderEx.validateValue(f, type, _vc); + } + + _floatValue = f; + break; + } + case SchemaType.BTC_DOUBLE: { + double d = + JavaDoubleHolderEx.validateLexical(value, type, _vc); + + if (errorState == _errorState) { + JavaDoubleHolderEx.validateValue(d, type, _vc); + } + + _doubleValue = d; + break; + } + case SchemaType.BTC_QNAME: { + QName n = + JavaQNameHolderEx.validateLexical( + value, type, _vc, event); + + if (errorState == _errorState) { + JavaQNameHolderEx.validateValue(n, type, _vc); + } + + _qnameValue = n; + break; + } + case SchemaType.BTC_ANY_URI: { + JavaUriHolderEx.validateLexical(value, type, _vc); + // Do strict validation + if (_strict) { + try { + XsTypeConverter.lexAnyURI(value); + } catch (InvalidLexicalValueException ilve) { + _vc.invalid(XmlErrorCodes.ANYURI, new Object[]{value}); + } + } + _stringValue = value; + break; + } + case SchemaType.BTC_G_MONTH: { + // In the case of gMonth, there is some strict mode validation to do + if (_strict && value.length() == 6 && + value.charAt(4) == '-' && value.charAt(5) == '-') { + _vc.invalid(XmlErrorCodes.DATE, new Object[]{value}); + } + // Fall through + } + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: { + GDate d = XmlDateImpl.validateLexical(value, type, _vc); + + if (d != null) { + XmlDateImpl.validateValue(d, type, _vc); + } + + _gdateValue = d; + break; + } + case SchemaType.BTC_DURATION: { + GDuration d = XmlDurationImpl.validateLexical(value, type, _vc); + + if (d != null) { + XmlDurationImpl.validateValue(d, type, _vc); + } + + _gdurationValue = d; + break; + } + case SchemaType.BTC_BASE_64_BINARY: { + byte[] v = + JavaBase64HolderEx.validateLexical(value, type, _vc); + + if (v != null) { + JavaBase64HolderEx.validateValue(v, type, _vc); + } + + _byteArrayValue = v; + break; + } + case SchemaType.BTC_HEX_BINARY: { + byte[] v = + JavaHexBinaryHolderEx.validateLexical(value, type, _vc); + + if (v != null) { + JavaHexBinaryHolderEx.validateValue(v, type, _vc); + } + + _byteArrayValue = v; + break; + } + case SchemaType.BTC_NOTATION: { + QName n = + JavaNotationHolderEx.validateLexical( + value, type, _vc, event); + + if (errorState == _errorState) { + JavaNotationHolderEx.validateValue(n, type, _vc); + } + + _qnameValue = n; + break; + } + + default: + throw new RuntimeException("Unexpected primitive type code"); + } + } + + private void validateListType( + SchemaType type, String value, Event event) { + int errorState = _errorState; + + if (!type.matchPatternFacet(value)) { + emitError(event, XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"list", value, QNameHelper.readable(type)}, + null, type, XmlValidationError.LIST_INVALID, null); + } + + String[] items = XmlListImpl.split_list(value); + + int i; + XmlObject o; + + if ((o = type.getFacet(SchemaType.FACET_LENGTH)) != null) { + if ((i = ((SimpleValue) o).getIntValue()) != items.length) { + //offending Qname not valid + emitError(event, XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, + new Object[]{value, items.length, i, QNameHelper.readable(type)}, + null, type, XmlValidationError.LIST_INVALID, null); + } + } + + if ((o = type.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) { + if ((i = ((SimpleValue) o).getIntValue()) > items.length) { + //offending Qname not valid + emitError(event, XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, + new Object[]{value, items.length, i, QNameHelper.readable(type)}, + null, type, XmlValidationError.LIST_INVALID, null); + } + } + + if ((o = type.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) { + if ((i = ((SimpleValue) o).getIntValue()) < items.length) { + //offending Qname not valid + emitError(event, XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, + new Object[]{value, items.length, i, QNameHelper.readable(type)}, + null, type, XmlValidationError.LIST_INVALID, null); + } + } + + SchemaType itemType = type.getListItemType(); + _listValue = new ArrayList<>(); + _listTypes = new ArrayList<>(); + + for (i = 0; i < items.length; i++) { + validateSimpleType( + itemType, items[i], event); + addToList(itemType); + } + + // If no errors up to this point, then I can create an + // XmlList from this value and campare it again enums. + + if (errorState == _errorState) { + if (type.getEnumerationValues() != null) { + // Lists which contain QNames will need a resolver + + NamespaceContext.push( + new NamespaceContext(event)); + + try { + XmlObject listValue = ((SchemaTypeImpl) type).newValidatingValue(value); + } catch (XmlValueOutOfRangeException e) { + //offending Qname not valid ?? + emitError(event, XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"list", value, QNameHelper.readable(type)}, + null, type, XmlValidationError.LIST_INVALID, null); + } finally { + NamespaceContext.pop(); + } + } + } + } + + private void validateUnionType( + SchemaType type, String value, Event event) { + // TODO - if xsi:type is specified on a union, it selects + // that union member type + + if (!type.matchPatternFacet(value)) { + //offending Qname not valid ?? + emitError(event, XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"union", value, QNameHelper.readable(type)}, + null, type, XmlValidationError.UNION_INVALID, null); + } + + int currentWsr = SchemaType.WS_PRESERVE; + String currentValue = value; + + SchemaType[] types = type.getUnionMemberTypes(); + + int originalState = _errorState; + + int i; + for (i = 0; i < types.length; i++) { + int memberWsr = types[i].getWhiteSpaceRule(); + + if (memberWsr == SchemaType.WS_UNSPECIFIED) { + memberWsr = SchemaType.WS_PRESERVE; + } + + if (memberWsr != currentWsr) { + currentWsr = memberWsr; + currentValue = XmlWhitespace.collapse(value, currentWsr); + } + + int originalErrorState = _errorState; + + _suspendErrors++; + + try { + validateSimpleType(types[i], currentValue, event); + } finally { + _suspendErrors--; + } + + if (originalErrorState == _errorState) { + _unionType = types[i]; + break; + } + } + + _errorState = originalState; + + if (i >= types.length) { + //offending Qname not valid ?? + emitError(event, XmlErrorCodes.DATATYPE_VALID$UNION, + new Object[]{value, QNameHelper.readable(type)}, + null, type, XmlValidationError.UNION_INVALID, null); + } else { + XmlObject[] unionEnumvals = type.getEnumerationValues(); + + if (unionEnumvals != null) { + // Unions which contain QNames will need a resolver + + NamespaceContext.push(new NamespaceContext(event)); + + try { + XmlObject unionValue = type.newValue(value); + + for (i = 0; i < unionEnumvals.length; i++) { + if (unionValue.valueEquals(unionEnumvals[i])) { + break; + } + } + + if (i >= unionEnumvals.length) { + //offending Qname not valid ?? + emitError(event, XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"union", value, QNameHelper.readable(type)}, + null, type, XmlValidationError.UNION_INVALID, null); + } + } catch (XmlValueOutOfRangeException e) { + // actually, the current union code always ends up here when invalid + + //offending Qname not valid ?? + emitError(event, XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"union", value, QNameHelper.readable(type)}, + null, type, XmlValidationError.UNION_INVALID, null); + } finally { + NamespaceContext.pop(); + } + } + } + } + + private void addToList(SchemaType type) { + if (type.getSimpleVariety() != SchemaType.ATOMIC && + type.getSimpleVariety() != SchemaType.UNION) { + return; + } + + if (type.getUnionMemberTypes().length > 0 && getUnionType() != null) { + type = getUnionType(); + _unionType = null; + } + + _listTypes.add(type); + + if (type.getPrimitiveType() == null) { + // instance has an error for this value so there is no primitive type. + // an error should already have been produced. + _listValue.add(null); + return; + } + + switch (type.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_ANY_SIMPLE: + case SchemaType.BTC_ANY_URI: { + _listValue.add(_stringValue); + break; + } + case SchemaType.BTC_STRING: { + _listValue.add(_stringValue); + _stringValue = null; + break; + } + case SchemaType.BTC_DECIMAL: { + _listValue.add(_decimalValue); + _decimalValue = null; + break; + } + case SchemaType.BTC_BOOLEAN: { + _listValue.add(_booleanValue ? Boolean.TRUE : Boolean.FALSE); + _booleanValue = false; + break; + } + case SchemaType.BTC_FLOAT: { + _listValue.add(_floatValue); + _floatValue = 0; + break; + } + case SchemaType.BTC_DOUBLE: { + _listValue.add(_doubleValue); + _doubleValue = 0; + break; + } + case SchemaType.BTC_QNAME: + case SchemaType.BTC_NOTATION: { + _listValue.add(_qnameValue); + _qnameValue = null; + break; + } + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: { + _listValue.add(_gdateValue); + _gdateValue = null; + break; + } + case SchemaType.BTC_DURATION: { + _listValue.add(_gdurationValue); + _gdurationValue = null; + break; + } + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: { + _listValue.add(_byteArrayValue); + _byteArrayValue = null; + break; + } + + default: + throw new RuntimeException("Unexpected primitive type code"); + } + } + + // + // Members of the validator class + // + + private boolean _invalid; + private final SchemaType _rootType; + private final SchemaField _rootField; + private final SchemaTypeLoader _globalTypes; + private State _stateStack; + private int _errorState; + private Collection _errorListener; + private final boolean _treatLaxAsSkip; + private final boolean _strict; + private final ValidatorVC _vc; + private int _suspendErrors; + private final IdentityConstraint _constraintEngine; + private int _eatContent; + + private SchemaLocalElement _localElement; + private SchemaParticle _wildcardElement; + private SchemaLocalAttribute _localAttribute; + private SchemaAttributeModel _wildcardAttribute; + private SchemaType _unionType; + + // Strongly typed values + private String _stringValue; + private BigDecimal _decimalValue; + private boolean _booleanValue; + private float _floatValue; + private double _doubleValue; + private QName _qnameValue; + private GDate _gdateValue; + private GDuration _gdurationValue; + private byte[] _byteArrayValue; + private List _listValue; + private List _listTypes; + + private void resetValues() { + _localAttribute = null; + _wildcardAttribute = null; + _stringValue = null; + _decimalValue = null; + _booleanValue = false; + _floatValue = 0; + _doubleValue = 0; + _qnameValue = null; + _gdateValue = null; + _gdurationValue = null; + _byteArrayValue = null; + _listValue = null; + _listTypes = null; + _unionType = null; + } + + /** + * @return Returns the SchemaType of the current element. + * This can be different than getCurrentElement().getType() if xsi:type attribute is used. + * Null is returned if no schema type is available. + * For attribute types use {@link #getCurrentAttribute()}.getType(). + * Warning: the returned SchemaType can be an {@link org.apache.xmlbeans.XmlBeans#NO_TYPE}, + * see {@link SchemaType#isNoType}. Or can be the parent type, for unrecognized elements + * that are part of wildcards. + */ + public SchemaType getCurrentElementSchemaType() { + State state = topState(); + if (state != null) { + return state._type; + } + + return null; + } + + /** + * @return Returns the curent local element, null if one is not available, see {@link #getCurrentWildcardElement()}. + */ + public SchemaLocalElement getCurrentElement() { + if (_localElement != null) { + return _localElement; + } + + // it means the element is to be skiped and it doesn't have a known SchemaLocalElement + + if (_eatContent > 0) { + return null; + } + + //try getting it from the stack (this should happen after END) + + if (_stateStack != null && _stateStack._field instanceof SchemaLocalElement) { + return (SchemaLocalElement) _stateStack._field; + } + + return null; + } + + /** + * @return Returns the current particle, if this is a wildcard particle {@link SchemaParticle#WILDCARD} + * method {@link #getCurrentElement()} might return null if wildcard's processContents is skip or lax. + */ + public SchemaParticle getCurrentWildcardElement() { + return _wildcardElement; + } + + /** + * @return Returns the curent local attribute, global attribute if the current attribute is part of an + * attribute wildcard, or null if none is available. + */ + public SchemaLocalAttribute getCurrentAttribute() { + return _localAttribute; + } + + /** + * @return Returns the attribute model for attributes if available, else null is returned. + */ + public SchemaAttributeModel getCurrentWildcardAttribute() { + return _wildcardAttribute; + } + + public String getStringValue() { + return _stringValue; + } + + public BigDecimal getDecimalValue() { + return _decimalValue; + } + + public boolean getBooleanValue() { + return _booleanValue; + } + + public float getFloatValue() { + return _floatValue; + } + + public double getDoubleValue() { + return _doubleValue; + } + + public QName getQNameValue() { + return _qnameValue; + } + + public GDate getGDateValue() { + return _gdateValue; + } + + public GDuration getGDurationValue() { + return _gdurationValue; + } + + public byte[] getByteArrayValue() { + return _byteArrayValue; + } + + public List getListValue() { + return _listValue; + } + + public List getListTypes() { + return _listTypes; + } + + public SchemaType getUnionType() { + return _unionType; + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatorUtil.java b/src/main/java/org/apache/xmlbeans/impl/validator/ValidatorUtil.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatorUtil.java rename to src/main/java/org/apache/xmlbeans/impl/validator/ValidatorUtil.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java new file mode 100644 index 0000000..8f254e1 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java @@ -0,0 +1,137 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlBase64Binary; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; + +public abstract class JavaBase64Holder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_BASE_64_BINARY; + } + + protected byte[] _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets raw text value + protected String compute_text(NamespaceManager nsm) { + return Base64.getEncoder().encodeToString(_value); + } + + protected void set_text(String s) { + _hashcached = false; + if (_validateOnSet()) { + _value = validateLexical(s, schemaType(), _voorVc); + } else { + _value = lex(s, _voorVc); + } + } + + protected void set_nil() { + _hashcached = false; + _value = null; + } + + public static byte[] lex(String v, ValidationContext c) { + try { + byte[] vBytes = v.getBytes(StandardCharsets.UTF_8); + return Base64.getDecoder().decode(vBytes); + } catch (IllegalArgumentException e) { + // TODO - get a decent error with line numbers and such here + c.invalid(XmlErrorCodes.BASE64BINARY, new Object[]{"not encoded properly"}); + return null; + } + } + + public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context) { + final byte[] bytes = lex(v, context); + if (bytes == null) { + return null; + } + + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID$NO_VALUE, + new Object[]{"base 64", QNameHelper.readable(sType)}); + return null; + } + + return bytes; + } + + public byte[] getByteArrayValue() { + check_dated(); + if (_value == null) { + return null; + } + + byte[] result = new byte[_value.length]; + System.arraycopy(_value, 0, result, 0, _value.length); + return result; + } + + // setters + protected void set_ByteArray(byte[] ba) { + _hashcached = false; + _value = new byte[ba.length]; + System.arraycopy(ba, 0, _value, 0, ba.length); + } + + // comparators + protected boolean equal_to(XmlObject i) { + byte[] ival = ((XmlBase64Binary) i).getByteArrayValue(); + return Arrays.equals(_value, ival); + } + + //because computing hashcode is expensive we'll cache it + protected boolean _hashcached = false; + protected int hashcode = 0; + protected static final MessageDigest md5; + + static { + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Cannot find MD5 hash Algorithm"); + } + } + + protected int value_hash_code() { + if (_hashcached) { + return hashcode; + } + + _hashcached = true; + + if (_value == null) { + return hashcode = 0; + } + + byte[] res = md5.digest(_value); + return hashcode = (res[0] << 24) | (res[1] << 16) | (res[2] << 8) | res[3]; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java new file mode 100644 index 0000000..821f706 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java @@ -0,0 +1,124 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +public abstract class JavaBase64HolderEx extends JavaBase64Holder { + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + public JavaBase64HolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + protected int get_wscanon_rule() { + return schemaType().getWhiteSpaceRule(); + } + + protected void set_text(String s) { + final byte[] v; + + if (_validateOnSet()) { + v = validateLexical(s, schemaType(), _voorVc); + } else { + v = lex(s, _voorVc); + } + + if (v != null && _validateOnSet()) { + validateValue(v, schemaType(), XmlObjectBase._voorVc); + } + + if (v != null) { + super.set_ByteArray(v); + } + } + + // setters + protected void set_ByteArray(byte[] v) { + if (_validateOnSet()) { + validateValue(v, schemaType(), _voorVc); + } + + super.set_ByteArray(v); + } + + public static void validateValue(byte[] v, SchemaType sType, ValidationContext context) { + int i; + XmlObject o; + + if ((o = sType.getFacet(SchemaType.FACET_LENGTH)) != null) { + if ((i = ((XmlObjectBase) o).getBigIntegerValue().intValue()) != v.length) { + context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$BINARY, + new Object[]{"base64Binary", v.length, i, QNameHelper.readable(sType)}); + } + } + + if ((o = sType.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) { + if ((i = ((XmlObjectBase) o).getBigIntegerValue().intValue()) > v.length) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$BINARY, + new Object[]{"base64Binary", v.length, i, QNameHelper.readable(sType)}); + } + } + + if ((o = sType.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) { + if ((i = ((XmlObjectBase) o).getBigIntegerValue().intValue()) < v.length) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$BINARY, + new Object[]{"base64Binary", v.length, i, QNameHelper.readable(sType)}); + } + } + + XmlObject[] vals = sType.getEnumerationValues(); + + if (vals != null) { + enumLoop: + for (i = 0; i < vals.length; i++) { + byte[] enumBytes = ((XmlObjectBase) vals[i]).getByteArrayValue(); + + if (enumBytes.length != v.length) { + continue; + } + + for (int j = 0; j < enumBytes.length; j++) { + if (enumBytes[j] != v[j]) { + continue enumLoop; + } + } + + break; + } + + if (i >= vals.length) { + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID$NO_VALUE, + new Object[]{"base64Binary", QNameHelper.readable(sType)}); + } + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getByteArrayValue(), schemaType(), ctx); + } + +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBooleanHolder.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolder.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaBooleanHolder.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java similarity index 76% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java index 1cf9f7a..4a8023f 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaBooleanHolderEx.java @@ -15,47 +15,46 @@ package org.apache.xmlbeans.impl.values; -import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +public abstract class JavaBooleanHolderEx extends JavaBooleanHolder { + private final SchemaType _schemaType; -public abstract class JavaBooleanHolderEx extends JavaBooleanHolder -{ - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } + public SchemaType schemaType() { + return _schemaType; + } - public static boolean validateLexical(String v, SchemaType sType, ValidationContext context) - { + public static boolean validateLexical(String v, SchemaType sType, ValidationContext context) { boolean b = JavaBooleanHolder.validateLexical(v, context); validatePattern(v, sType, context); return b; } - - public static void validatePattern(String v, SchemaType sType, ValidationContext context) - { + + public static void validatePattern(String v, SchemaType sType, ValidationContext context) { // the only new facet that can apply to booleans is pattern! - if (!sType.matchPatternFacet(v)) + if (!sType.matchPatternFacet(v)) { context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "boolean", v, QNameHelper.readable(sType) }); + new Object[]{"boolean", v, QNameHelper.readable(sType)}); + } + } + + public JavaBooleanHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); } - - public JavaBooleanHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - protected void set_text(String s) - { - if (_validateOnSet()) + protected void set_text(String s) { + if (_validateOnSet()) { validatePattern(s, _schemaType, _voorVc); + } super.set_text(s); } - protected void validate_simpleval(String lexical, ValidationContext ctx) - { + protected void validate_simpleval(String lexical, ValidationContext ctx) { validateLexical(lexical, schemaType(), ctx); } } diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java new file mode 100644 index 0000000..20a3d31 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java @@ -0,0 +1,176 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; + +public class JavaDecimalHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_DECIMAL; + } + + private BigDecimal _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // sets/gets raw text value + protected String compute_text(NamespaceManager nsm) { + return XsTypeConverter.printDecimal(_value); + } + + protected void set_text(String s) { + if (_validateOnSet()) { + validateLexical(s, _voorVc); + } + + try { + set_BigDecimal(new BigDecimal(s)); + } catch (NumberFormatException e) { + _voorVc.invalid(XmlErrorCodes.DECIMAL, new Object[]{s}); + } + } + + protected void set_nil() { + _value = null; + } + + /** + * Performs lexical validation only. + */ + + public static void validateLexical(String v, ValidationContext context) { + // TODO - will want to validate Chars with built in white space handling + // However, this fcn sometimes takes a value with wsr applied + // already + int l = v.length(); + int i = 0; + + if (i < l) { + int ch = v.charAt(i); + + if (ch == '+' || ch == '-') { + i++; + } + } + + boolean sawDot = false; + boolean sawDigit = false; + + for (; i < l; i++) { + int ch = v.charAt(i); + + if (ch == '.') { + if (sawDot) { + context.invalid(XmlErrorCodes.DECIMAL, + new Object[]{"saw '.' more than once: " + v}); + return; + } + + sawDot = true; + } else if (ch >= '0' && ch <= '9') { + sawDigit = true; + } else { + // TODO - may need to escape error char + context.invalid(XmlErrorCodes.DECIMAL, + new Object[]{"unexpected char '" + ch + "'"}); + return; + } + } + + if (!sawDigit) { + context.invalid(XmlErrorCodes.DECIMAL, + new Object[]{"expected at least one digit"}); + } + } + + // numerics: fractional + public BigDecimal getBigDecimalValue() { + check_dated(); + return _value; + } + + // setters + protected void set_BigDecimal(BigDecimal v) { + _value = v; + } + + // comparators + protected int compare_to(XmlObject decimal) { + return _value.compareTo(((XmlObjectBase) decimal).getBigDecimalValue()); + } + + protected boolean equal_to(XmlObject decimal) { + return (_value.compareTo(((XmlObjectBase) decimal).getBigDecimalValue())) == 0; + } + + private static final BigInteger _maxlong = BigInteger.valueOf(Long.MAX_VALUE); + private static final BigInteger _minlong = BigInteger.valueOf(Long.MIN_VALUE); + + /** + * Note, this is carefully aligned with hash codes for all xsd:decimal + * primitives. + */ + protected int value_hash_code() { + if (_value.scale() > 0) { + if (_value.setScale(0, RoundingMode.DOWN).compareTo(_value) != 0) { + return decimalHashCode(); + } + } + + BigInteger intval = _value.toBigInteger(); + + if (intval.compareTo(_maxlong) > 0 || + intval.compareTo(_minlong) < 0) { + return intval.hashCode(); + } + + long longval = intval.longValue(); + + return (int) ((longval >> 32) * 19 + longval); + } + + /** + * This method will has BigDecimals with the same arithmetic value to + * the same hash code (eg, 2.3 & 2.30 will have the same hash.) + * This differs from BigDecimal.hashCode() + */ + protected int decimalHashCode() { + assert _value.scale() > 0; + + // Get decimal value as string, and strip off zeroes on the right + String strValue = _value.toString(); + int i; + for (i = strValue.length() - 1; i >= 0; i--) { + if (strValue.charAt(i) != '0') { + break; + } + } + + assert strValue.indexOf('.') < i; + + // Return the canonicalized string hashcode + return strValue.substring(0, i + 1).hashCode(); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java new file mode 100644 index 0000000..7cde65e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java @@ -0,0 +1,196 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public abstract class JavaDecimalHolderEx extends JavaDecimalHolder { + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + public JavaDecimalHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + protected void set_text(String s) { + if (_validateOnSet()) { + validateLexical(s, _schemaType, _voorVc); + } + + BigDecimal v = null; + try { + v = new BigDecimal(s); + } catch (NumberFormatException e) { + _voorVc.invalid(XmlErrorCodes.DECIMAL, new Object[]{s}); + } + + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + + super.set_BigDecimal(v); + } + + protected void set_BigDecimal(BigDecimal v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + super.set_BigDecimal(v); + } + + public static void validateLexical(String v, SchemaType sType, ValidationContext context) { + JavaDecimalHolder.validateLexical(v, context); + + // check pattern + if (sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + // TODO - describe string and pattern here in error + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"decimal", v, QNameHelper.readable(sType)}); + } + } + } + + /** + * Performs facet validation only. + */ + + public static void validateValue(BigDecimal v, SchemaType sType, ValidationContext context) { + // fractional digits + XmlObject fd = sType.getFacet(SchemaType.FACET_FRACTION_DIGITS); + if (fd != null) { + int scale = ((XmlObjectBase) fd).getBigIntegerValue().intValue(); + try { + // used only for side-effect - this does not change v despite + // the name of the method + // noinspection ResultOfMethodCallIgnored + v.setScale(scale, RoundingMode.UNNECESSARY); + } catch (ArithmeticException e) { + // ArithmeticException will be thrown if cannot represent as an Integer + // with this scale - i.e. would need a fraction which would correspond + // to digits beyond the allowed number + context.invalid(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_VALID, + new Object[]{v.scale(), v.toString(), scale, QNameHelper.readable(sType)}); + return; + } + } + + // total digits + XmlObject td = sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); + if (td != null) { + String temp = v.unscaledValue().toString(); + int tdf = ((XmlObjectBase) td).getBigIntegerValue().intValue(); + int origLen = temp.length(); + int len = origLen; + if (origLen > 0) { + // don't count leading minus + if (temp.charAt(0) == '-') { + len -= 1; + } + + // don't count trailing zeros if we can absorb them into scale + int insignificantTrailingZeros = 0; + int vScale = v.scale(); + for (int j = origLen - 1; + temp.charAt(j) == '0' && j > 0 && insignificantTrailingZeros < vScale; + j--) { + insignificantTrailingZeros++; + } + + len -= insignificantTrailingZeros; + } + + if (len > tdf) { + context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, + new Object[]{len, v.toString(), tdf, QNameHelper.readable(sType)}); + return; + } + } + + // min ex + XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (mine != null) { + BigDecimal m = ((XmlObjectBase) mine).getBigDecimalValue(); + if (v.compareTo(m) <= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"decimal", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // min in + XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (mini != null) { + BigDecimal m = ((XmlObjectBase) mini).getBigDecimalValue(); + if (v.compareTo(m) < 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"decimal", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max in + XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (maxi != null) { + BigDecimal m = ((XmlObjectBase) maxi).getBigDecimalValue(); + if (v.compareTo(m) > 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"decimal", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max ex + XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (maxe != null) { + BigDecimal m = ((XmlObjectBase) maxe).getBigDecimalValue(); + if (v.compareTo(m) >= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"decimal", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // enumeration + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (v.compareTo(((XmlObjectBase) val).getBigDecimalValue()) == 0) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"decimal", v, QNameHelper.readable(sType)}); + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getBigDecimalValue(), schemaType(), ctx); + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java new file mode 100644 index 0000000..2ee47c1 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java @@ -0,0 +1,136 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +import java.math.BigDecimal; +import java.math.BigInteger; + +public abstract class JavaDoubleHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_DOUBLE; + } + + double _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets/sets raw text value + protected String compute_text(NamespaceManager nsm) { + return serialize(_value); + } + + public static String serialize(double d) { + if (d == Double.POSITIVE_INFINITY) { + return "INF"; + } else if (d == Double.NEGATIVE_INFINITY) { + return "-INF"; + } else if (Double.isNaN(d)) { + return "NaN"; + } else { + return Double.toString(d); + } + } + + protected void set_text(String s) { + set_double(validateLexical(s, _voorVc)); + } + + public static double validateLexical(String v, ValidationContext context) { + try { + return XsTypeConverter.lexDouble(v); + } catch (NumberFormatException e) { + context.invalid(XmlErrorCodes.DOUBLE, new Object[]{v}); + + return Double.NaN; + } + } + + protected void set_nil() { + _value = 0.0; + } + + // numerics: fractional + public BigDecimal getBigDecimalValue() { + check_dated(); + return new BigDecimal(_value); + } + + public double getDoubleValue() { + check_dated(); + return _value; + } + + public float getFloatValue() { + check_dated(); + return (float) _value; + } + + // setters + protected void set_double(double v) { + _value = v; + } + + protected void set_float(float v) { + set_double(v); + } + + protected void set_long(long v) { + set_double((double) v); + } + + protected void set_BigDecimal(BigDecimal v) { + set_double(v.doubleValue()); + } + + protected void set_BigInteger(BigInteger v) { + set_double(v.doubleValue()); + } + + // comparators + protected int compare_to(XmlObject d) { + return compare(_value, ((XmlObjectBase) d).getDoubleValue()); + } + + static int compare(double thisValue, double thatValue) { + if (thisValue < thatValue) { + return -1; + } + if (thisValue > thatValue) { + return 1; + } + + long thisBits = Double.doubleToLongBits(thisValue); + long thatBits = Double.doubleToLongBits(thatValue); + + return Long.compare(thisBits, thatBits); + } + + protected boolean equal_to(XmlObject d) { + return compare(_value, ((XmlObjectBase) d).getDoubleValue()) == 0; + } + + protected int value_hash_code() { + long v = Double.doubleToLongBits(_value); + return (int) ((v >> 32) * 19 + v); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java new file mode 100644 index 0000000..8076428 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java @@ -0,0 +1,103 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + + +public abstract class JavaDoubleHolderEx extends JavaDoubleHolder { + public JavaDoubleHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + protected void set_double(double v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + super.set_double(v); + } + + public static double validateLexical(String v, SchemaType sType, ValidationContext context) { + double d = JavaDoubleHolder.validateLexical(v, context); + + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"double", v, QNameHelper.readable(sType)}); + } + + return d; + } + + public static void validateValue(double v, SchemaType sType, ValidationContext context) { + XmlObject x; + double d; + + if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) { + if (compare(v, d = ((XmlObjectBase) x).getDoubleValue()) <= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"double", v, d, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) { + if (compare(v, d = ((XmlObjectBase) x).getDoubleValue()) < 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"double", v, d, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) { + if (compare(v, d = ((XmlObjectBase) x).getDoubleValue()) > 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"double", v, d, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) { + if (compare(v, d = ((XmlObjectBase) x).getDoubleValue()) >= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"double", v, d, QNameHelper.readable(sType)}); + } + } + + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (compare(v, ((XmlObjectBase) val).getDoubleValue()) == 0) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"double", v, QNameHelper.readable(sType)}); + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getDoubleValue(), schemaType(), ctx); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaFloatHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaFloatHolder.java new file mode 100644 index 0000000..e2365c7 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaFloatHolder.java @@ -0,0 +1,135 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +import java.math.BigDecimal; +import java.math.BigInteger; + +public abstract class JavaFloatHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_FLOAT; + } + + private float _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets+sets raw text value + protected String compute_text(NamespaceManager nsm) { + return serialize(_value); + } + + public static String serialize(float f) { + if (f == Float.POSITIVE_INFINITY) { + return "INF"; + } else if (f == Float.NEGATIVE_INFINITY) { + return "-INF"; + } else if (Float.isNaN(f)) { + return "NaN"; + } else { + return Float.toString(f); + } + } + + protected void set_text(String s) { + set_float(validateLexical(s, _voorVc)); + } + + public static float validateLexical(String v, ValidationContext context) { + try { + return XsTypeConverter.lexFloat(v); + } catch (NumberFormatException e) { + context.invalid(XmlErrorCodes.FLOAT, new Object[]{v}); + + return Float.NaN; + } + } + + protected void set_nil() { + _value = 0.0f; + } + + // numerics: fractional + public BigDecimal getBigDecimalValue() { + check_dated(); + return new BigDecimal(_value); + } + + public double getDoubleValue() { + check_dated(); + return _value; + } + + public float getFloatValue() { + check_dated(); + return _value; + } + + // setters + protected void set_double(double v) { + set_float((float) v); + } + + protected void set_float(float v) { + _value = v; + } + + protected void set_long(long v) { + set_float((float) v); + } + + protected void set_BigDecimal(BigDecimal v) { + set_float(v.floatValue()); + } + + protected void set_BigInteger(BigInteger v) { + set_float(v.floatValue()); + } + + // comparators + protected int compare_to(XmlObject f) { + return compare(_value, ((XmlObjectBase) f).getFloatValue()); + } + + static int compare(float thisValue, float thatValue) { + if (thisValue < thatValue) { + return -1; + } + if (thisValue > thatValue) { + return 1; + } + + int thisBits = Float.floatToIntBits(thisValue); + int thatBits = Float.floatToIntBits(thatValue); + + return Integer.compare(thisBits, thatBits); + } + + protected boolean equal_to(XmlObject f) { + return compare(_value, ((XmlObjectBase) f).getFloatValue()) == 0; + } + + protected int value_hash_code() { + return Float.floatToIntBits(_value); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java new file mode 100644 index 0000000..9b6030a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java @@ -0,0 +1,104 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + + +public abstract class JavaFloatHolderEx extends JavaFloatHolder { + public JavaFloatHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + protected void set_float(float v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + super.set_float(v); + } + + public static float validateLexical(String v, SchemaType sType, ValidationContext context) { + float f = JavaFloatHolder.validateLexical(v, context); + + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"float", v, QNameHelper.readable(sType)}); + } + + return f; + } + + public static void validateValue(float v, SchemaType sType, ValidationContext context) { + XmlObject x; + float f; + + if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) { + if (compare(v, f = ((XmlObjectBase) x).getFloatValue()) <= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"float", v, f, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) { + if (compare(v, f = ((XmlObjectBase) x).getFloatValue()) < 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"float", v, f, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) { + if (compare(v, f = ((XmlObjectBase) x).getFloatValue()) > 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"float", v, f, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) { + if (compare(v, f = ((XmlObjectBase) x).getFloatValue()) >= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"float", v, f, QNameHelper.readable(sType)}); + } + } + + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (compare(v, ((XmlObjectBase) val).getFloatValue()) == 0) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"float", v, QNameHelper.readable(sType)}); + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getFloatValue(), schemaType(), ctx); + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java new file mode 100644 index 0000000..58021b1 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java @@ -0,0 +1,314 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +import java.util.Calendar; +import java.util.Date; + +public abstract class JavaGDateHolderEx extends XmlObjectBase { + public JavaGDateHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + public SchemaType schemaType() { + return _schemaType; + } + + private final SchemaType _schemaType; + private GDate _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // sets/gets raw text value + protected String compute_text(NamespaceManager nsm) { + return _value == null ? "" : _value.toString(); + } + + protected void set_text(String s) { + GDate newVal; + if (_validateOnSet()) { + newVal = validateLexical(s, _schemaType, _voorVc); + } else { + newVal = lex(s, _schemaType, _voorVc); + } + + if (_validateOnSet() && newVal != null) { + validateValue(newVal, _schemaType, _voorVc); + } + + _value = newVal; + } + + public static GDate lex(String v, SchemaType sType, ValidationContext context) { + GDate date = null; + + try { + date = new GDate(v); + } catch (Exception e) { + context.invalid(XmlErrorCodes.DATE, new Object[]{v}); + } + + if (date != null) { + if (date.getBuiltinTypeCode() != sType.getPrimitiveType().getBuiltinTypeCode()) { + context.invalid(XmlErrorCodes.DATE, new Object[]{"wrong type: " + v}); + date = null; + } else if (!date.isValid()) { + context.invalid(XmlErrorCodes.DATE, new Object[]{v}); + date = null; + } + } + + return date; + } + + public static GDate validateLexical(String v, SchemaType sType, ValidationContext context) { + + GDate date = lex(v, sType, context); + + if (date != null && sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"date", v, QNameHelper.readable(sType)}); + } + } + + return date; + } + + public static void validateValue(GDateSpecification v, SchemaType sType, ValidationContext context) { + XmlObject x; + GDate g; + + if (v.getBuiltinTypeCode() != sType.getPrimitiveType().getBuiltinTypeCode()) { + context.invalid(XmlErrorCodes.DATE, new Object[]{"Date (" + v + ") does not have the set of fields required for " + QNameHelper.readable(sType)}); + } + + if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) { + if (v.compareToGDate(g = ((XmlObjectBase) x).getGDateValue()) <= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"date", v, g, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) { + if (v.compareToGDate(g = ((XmlObjectBase) x).getGDateValue()) < 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"date", v, g, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) { + if (v.compareToGDate(g = ((XmlObjectBase) x).getGDateValue()) >= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"date", v, g, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) { + if (v.compareToGDate(g = ((XmlObjectBase) x).getGDateValue()) > 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"date", v, g, QNameHelper.readable(sType)}); + } + } + + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (v.compareToGDate(((XmlObjectBase) val).getGDateValue()) == 0) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"date", v, QNameHelper.readable(sType)}); + } + } + + protected void set_nil() { + _value = null; + } + + // numerics: gYear, gMonth, gDay accept an integer + public int getIntValue() { + int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); + + if (code != SchemaType.BTC_G_DAY && + code != SchemaType.BTC_G_MONTH && + code != SchemaType.BTC_G_YEAR) { + throw new XmlValueOutOfRangeException(); + } + + check_dated(); + + if (_value == null) { + return 0; + } + + switch (code) { + case SchemaType.BTC_G_DAY: + return _value.getDay(); + case SchemaType.BTC_G_MONTH: + return _value.getMonth(); + case SchemaType.BTC_G_YEAR: + return _value.getYear(); + default: + assert (false); + throw new IllegalStateException(); + } + } + + public GDate getGDateValue() { + check_dated(); + + if (_value == null) { + return null; + } + + return _value; + } + + public Calendar getCalendarValue() { + check_dated(); + + if (_value == null) { + return null; + } + + return _value.getCalendar(); + } + + public Date getDateValue() { + check_dated(); + + if (_value == null) { + return null; + } + + return _value.getDate(); + } + + // setters + protected void set_int(int v) { + int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); + + if (code != SchemaType.BTC_G_DAY && + code != SchemaType.BTC_G_MONTH && + code != SchemaType.BTC_G_YEAR) { + throw new XmlValueOutOfRangeException(); + } + + GDateBuilder value = new GDateBuilder(); + + switch (code) { + case SchemaType.BTC_G_DAY: + value.setDay(v); + break; + case SchemaType.BTC_G_MONTH: + value.setMonth(v); + break; + case SchemaType.BTC_G_YEAR: + value.setYear(v); + break; + } + + if (_validateOnSet()) { + validateValue(value, _schemaType, _voorVc); + } + + _value = value.toGDate(); + } + + protected void set_GDate(GDateSpecification v) { + int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); + + GDate candidate; + + if (v.isImmutable() && (v instanceof GDate) && v.getBuiltinTypeCode() == code) { + candidate = (GDate) v; + } else { + // truncate extra fields from the date if necessary. + if (v.getBuiltinTypeCode() != code) { + GDateBuilder gDateBuilder = new GDateBuilder(v); + gDateBuilder.setBuiltinTypeCode(code); + v = gDateBuilder; + } + candidate = new GDate(v); + } + + if (_validateOnSet()) { + validateValue(candidate, _schemaType, _voorVc); + } + + _value = candidate; + } + + protected void set_Calendar(Calendar c) { + int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); + + GDateBuilder gDateBuilder = new GDateBuilder(c); + gDateBuilder.setBuiltinTypeCode(code); + GDate value = gDateBuilder.toGDate(); + + if (_validateOnSet()) { + validateValue(value, _schemaType, _voorVc); + } + + _value = value; + } + + protected void set_Date(Date v) { + int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); + + if (code != SchemaType.BTC_DATE && code != SchemaType.BTC_DATE_TIME || + v == null) { + throw new XmlValueOutOfRangeException(); + } + + GDateBuilder gDateBuilder = new GDateBuilder(v); + gDateBuilder.setBuiltinTypeCode(code); + GDate value = gDateBuilder.toGDate(); + + if (_validateOnSet()) { + validateValue(value, _schemaType, _voorVc); + } + + _value = value; + } + + + // comparators + protected int compare_to(XmlObject obj) { + return _value.compareToGDate(((XmlObjectBase) obj).getGDateValue()); + } + + protected boolean equal_to(XmlObject obj) { + return _value.equals(((XmlObjectBase) obj).getGDateValue()); + } + + protected int value_hash_code() { + return _value.hashCode(); + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getGDateValue(), schemaType(), ctx); + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java new file mode 100644 index 0000000..8d24904 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java @@ -0,0 +1,161 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +public abstract class JavaGDurationHolderEx extends XmlObjectBase { + public JavaGDurationHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + GDuration _value; + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + protected void set_text(String s) { + GDuration newVal; + if (_validateOnSet()) { + newVal = validateLexical(s, _schemaType, _voorVc); + } else { + newVal = lex(s, _voorVc); + } + + if (_validateOnSet() && newVal != null) { + validateValue(newVal, _schemaType, _voorVc); + } + + _value = newVal; + } + + protected void set_GDuration(GDurationSpecification v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + + if (v.isImmutable() && (v instanceof GDuration)) { + _value = (GDuration) v; + } else { + _value = new GDuration(v); + } + } + + protected String compute_text(NamespaceManager nsm) { + return _value == null ? "" : _value.toString(); + } + + protected void set_nil() { + _value = null; + } + + public GDuration getGDurationValue() { + check_dated(); + + return _value == null ? null : _value; + } + + public static GDuration lex(String v, ValidationContext context) { + GDuration duration = null; + + try { + duration = new GDuration(v); + } catch (Exception e) { + context.invalid(XmlErrorCodes.DURATION, new Object[]{v}); + } + + return duration; + } + + public static GDuration validateLexical(String v, SchemaType sType, ValidationContext context) { + GDuration duration = lex(v, context); + + if (duration != null && sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"duration", v, QNameHelper.readable(sType)}); + } + } + + return duration; + } + + public static void validateValue(GDurationSpecification v, SchemaType sType, ValidationContext context) { + XmlObject x; + GDuration g; + + if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) { + if (v.compareToGDuration(g = ((XmlObjectBase) x).getGDurationValue()) <= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"duration", v, g, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) { + if (v.compareToGDuration(g = ((XmlObjectBase) x).getGDurationValue()) < 0) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"duration", v, g, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) { + if (v.compareToGDuration(g = ((XmlObjectBase) x).getGDurationValue()) >= 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"duration", v, g, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) { + if (v.compareToGDuration(g = ((XmlObjectBase) x).getGDurationValue()) > 0) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"duration", v, g, QNameHelper.readable(sType)}); + } + } + + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (v.compareToGDuration(((XmlObjectBase) val).getGDurationValue()) == 0) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"duration", v, QNameHelper.readable(sType)}); + } + } + + protected int compare_to(XmlObject d) { + return _value.compareToGDuration(((XmlObjectBase) d).getGDurationValue()); + } + + protected boolean equal_to(XmlObject d) { + return _value.equals(((XmlObjectBase) d).getGDurationValue()); + } + + protected int value_hash_code() { + return _value.hashCode(); + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getGDurationValue(), schemaType(), ctx); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java new file mode 100644 index 0000000..51e0fe0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java @@ -0,0 +1,139 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlHexBinary; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.util.HexBin; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +public abstract class JavaHexBinaryHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_HEX_BINARY; + } + + protected byte[] _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets raw text value + protected String compute_text(NamespaceManager nsm) { + return new String(HexBin.encode(_value), StandardCharsets.ISO_8859_1); + } + + protected void set_text(String s) { + _hashcached = false; + if (_validateOnSet()) { + _value = validateLexical(s, schemaType(), _voorVc); + } else { + _value = lex(s, _voorVc); + } + } + + protected void set_nil() { + _hashcached = false; + _value = null; + } + + public static byte[] lex(String v, ValidationContext context) { + byte[] vBytes = v.getBytes(StandardCharsets.ISO_8859_1); + byte[] bytes = HexBin.decode(vBytes); + + if (bytes == null) { + // TODO - get a decent error with line numbers and such here + context.invalid(XmlErrorCodes.HEXBINARY, new Object[]{"not encoded properly"}); + } + + return bytes; + } + + public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context) { + byte[] bytes = lex(v, context); + + if (bytes == null) { + return null; + } + + if (!sType.matchPatternFacet(v)) { + context.invalid("Hex encoded data does not match pattern for " + QNameHelper.readable(sType)); + return null; + } + + return bytes; + } + + public byte[] getByteArrayValue() { + check_dated(); + if (_value == null) { + return null; + } + + byte[] result = new byte[_value.length]; + System.arraycopy(_value, 0, result, 0, _value.length); + return result; + } + + // setters + protected void set_ByteArray(byte[] ba) { + _hashcached = false; + _value = new byte[ba.length]; + System.arraycopy(ba, 0, _value, 0, ba.length); + } + + // comparators + protected boolean equal_to(XmlObject i) { + byte[] ival = ((XmlHexBinary) i).getByteArrayValue(); + return Arrays.equals(_value, ival); + } + + //because computing hashcode is expensive we'll cache it + protected boolean _hashcached = false; + protected int hashcode = 0; + protected static final MessageDigest md5; + + static { + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Cannot find MD5 hash Algorithm"); + } + } + + protected int value_hash_code() { + if (_hashcached) { + return hashcode; + } + + _hashcached = true; + + if (_value == null) { + return hashcode = 0; + } + + byte[] res = md5.digest(_value); + return hashcode = (res[0] << 24) | (res[1] << 16) | (res[2] << 8) | res[3]; + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java new file mode 100644 index 0000000..ccbce6a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java @@ -0,0 +1,127 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + + +public abstract class JavaHexBinaryHolderEx extends JavaHexBinaryHolder { + private final SchemaType _schemaType; + + + public SchemaType schemaType() { + return _schemaType; + } + + public JavaHexBinaryHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + protected int get_wscanon_rule() { + return schemaType().getWhiteSpaceRule(); + } + + protected void set_text(String s) { + byte[] v; + + if (_validateOnSet()) { + v = validateLexical(s, schemaType(), _voorVc); + } else { + v = lex(s, _voorVc); + } + + if (_validateOnSet() && v != null) { + validateValue(v, schemaType(), XmlObjectBase._voorVc); + } + + if (v != null) { + super.set_ByteArray(v); + } + + _value = v; + } + + // setters + protected void set_ByteArray(byte[] v) { + if (_validateOnSet()) { + validateValue(v, schemaType(), _voorVc); + } + + super.set_ByteArray(v); + } + + public static void validateValue(byte[] v, SchemaType sType, ValidationContext context) { + int i; + XmlObject o; + + if ((o = sType.getFacet(SchemaType.FACET_LENGTH)) != null) { + if ((i = ((XmlObjectBase) o).getBigIntegerValue().intValue()) != v.length) { + context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$BINARY, + new Object[]{"hexBinary", v.length, i, QNameHelper.readable(sType)}); + } + } + + if ((o = sType.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) { + if ((i = ((XmlObjectBase) o).getBigIntegerValue().intValue()) > v.length) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$BINARY, + new Object[]{"hexBinary", v.length, i, QNameHelper.readable(sType)}); + } + } + + if ((o = sType.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) { + if ((i = ((XmlObjectBase) o).getBigIntegerValue().intValue()) < v.length) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$BINARY, + new Object[]{"hexBinary", v.length, i, QNameHelper.readable(sType)}); + } + } + + XmlObject[] vals = sType.getEnumerationValues(); + + if (vals != null) { + enumLoop: + for (i = 0; i < vals.length; i++) { + byte[] enumBytes = ((XmlObjectBase) vals[i]).getByteArrayValue(); + + if (enumBytes.length != v.length) { + continue; + } + + for (int j = 0; j < enumBytes.length; j++) { + if (enumBytes[j] != v[j]) { + continue enumLoop; + } + } + + break; + } + + if (i >= vals.length) { + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID$NO_VALUE, + new Object[]{"hexBinary", QNameHelper.readable(sType)}); + } + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getByteArrayValue(), schemaType(), ctx); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaIntHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntHolder.java new file mode 100644 index 0000000..29b5edd --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntHolder.java @@ -0,0 +1,125 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +import java.math.BigDecimal; +import java.math.BigInteger; + +public abstract class JavaIntHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_INT; + } + + private int _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets raw text value + public String compute_text(NamespaceManager nsm) { + return Long.toString(_value); + } + + protected void set_text(String s) { + try { + set_int(XsTypeConverter.lexInt(s)); + } catch (Exception e) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.INT, new Object[]{s}); + } + } + + protected void set_nil() { + _value = 0; + } + + // numerics: fractional + public BigDecimal getBigDecimalValue() { + check_dated(); + return BigDecimal.valueOf((double) _value); + } + + public BigInteger getBigIntegerValue() { + check_dated(); + return BigInteger.valueOf(_value); + } + + public long getLongValue() { + check_dated(); + return _value; + } + + public int getIntValue() { + check_dated(); + return _value; + } + + static final BigInteger _max = BigInteger.valueOf(Integer.MAX_VALUE); + static final BigInteger _min = BigInteger.valueOf(Integer.MIN_VALUE); + + // setters + protected void set_BigDecimal(BigDecimal v) { + set_BigInteger(v.toBigInteger()); + } + + protected void set_BigInteger(BigInteger v) { + if (v.compareTo(_max) > 0 || v.compareTo(_min) < 0) { + throw new XmlValueOutOfRangeException(); + } + set_int(v.intValue()); + } + + protected void set_long(long l) { + if (l > Integer.MAX_VALUE || l < Integer.MIN_VALUE) { + throw new XmlValueOutOfRangeException(); + } + set_int((int) l); + } + + protected void set_int(int i) { + _value = i; + } + + // comparators + protected int compare_to(XmlObject i) { + if (((SimpleValue) i).instanceType().getDecimalSize() > SchemaType.SIZE_INT) { + return -i.compareTo(this); + } + + return Integer.compare(_value, ((XmlObjectBase) i).getIntValue()); + } + + protected boolean equal_to(XmlObject i) { + if (((SimpleValue) i).instanceType().getDecimalSize() > SchemaType.SIZE_INT) { + return i.valueEquals(this); + } + + return _value == ((XmlObjectBase) i).getIntValue(); + } + + /** + * Note, this is carefully aligned with hash codes for all xsd:decimal + * primitives. + */ + protected int value_hash_code() { + return _value; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java new file mode 100644 index 0000000..b22b70a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java @@ -0,0 +1,170 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +public abstract class JavaIntHolderEx extends JavaIntHolder { + public JavaIntHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + private final SchemaType _schemaType; + + + public SchemaType schemaType() { + return _schemaType; + } + + protected void set_text(String s) { + int v; + + try { + v = XsTypeConverter.lexInt(s); + } catch (Exception e) { + throw new XmlValueOutOfRangeException(); + } + + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + validateLexical(s, _schemaType, _voorVc); + } + + super.set_int(v); + } + + protected void set_int(int v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + + super.set_int(v); + } + + public static void validateLexical(String v, SchemaType sType, ValidationContext context) { + JavaDecimalHolder.validateLexical(v, context); + + // check pattern + if (sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"int", v, QNameHelper.readable(sType)}); + } + } + } + + private static void validateValue(int v, SchemaType sType, ValidationContext context) { + // total digits + XmlObject td = sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); + if (td != null) { + String temp = Integer.toString(v); + int len = temp.length(); + if (len > 0 && temp.charAt(0) == '-') { + len -= 1; + } + int m = getIntValue(td); + if (len > m) { + context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, + new Object[]{len, temp, getIntValue(td), QNameHelper.readable(sType)}); + return; + } + } + + // min ex + XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (mine != null) { + int m = getIntValue(mine); + if (!(v > m)) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"int", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // min in + XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (mini != null) { + int m = getIntValue(mini); + if (!(v >= m)) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"int", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max in + XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (maxi != null) { + int m = getIntValue(maxi); + if (!(v <= m)) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"int", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max ex + XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (maxe != null) { + int m = getIntValue(maxe); + if (!(v < m)) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"int", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // enumeration + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (v == getIntValue(val)) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"int", v, QNameHelper.readable(sType)}); + } + } + + private static int getIntValue(XmlObject o) { + SchemaType s = o.schemaType(); + switch (s.getDecimalSize()) { + case SchemaType.SIZE_BIG_DECIMAL: + return ((XmlObjectBase) o).getBigDecimalValue().intValue(); + case SchemaType.SIZE_BIG_INTEGER: + return ((XmlObjectBase) o).getBigIntegerValue().intValue(); + case SchemaType.SIZE_LONG: + return (int) ((XmlObjectBase) o).getLongValue(); + default: + return ((XmlObjectBase) o).getIntValue(); + } + + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getIntValue(), schemaType(), ctx); + } + +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java new file mode 100644 index 0000000..d3e4099 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java @@ -0,0 +1,117 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; + +import java.math.BigDecimal; +import java.math.BigInteger; + +public abstract class JavaIntegerHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_INTEGER; + } + + private BigInteger _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets/sets raw text value + protected String compute_text(NamespaceManager nsm) { + return _value.toString(); + } + + protected void set_text(String s) { + set_BigInteger(lex(s, _voorVc)); + } + + public static BigInteger lex(String s, ValidationContext vc) { + if (s.length() > 0 && s.charAt(0) == '+') { + s = s.substring(1); + } + + try { + return new BigInteger(s); + } catch (Exception e) { + vc.invalid(XmlErrorCodes.INTEGER, new Object[]{s}); + return null; + } + } + + protected void set_nil() { + _value = null; + } + + // numerics: fractional + public BigDecimal getBigDecimalValue() { + check_dated(); + return _value == null ? null : new BigDecimal(_value); + } + + public BigInteger getBigIntegerValue() { + check_dated(); + return _value; + } + + // setters + protected void set_BigDecimal(BigDecimal v) { + _value = v.toBigInteger(); + } + + protected void set_BigInteger(BigInteger v) { + _value = v; + } + + // comparators + protected int compare_to(XmlObject i) { + if (((SimpleValue) i).instanceType().getDecimalSize() > SchemaType.SIZE_BIG_INTEGER) { + return -i.compareTo(this); + } + + return _value.compareTo(((XmlObjectBase) i).getBigIntegerValue()); + } + + protected boolean equal_to(XmlObject i) { + if (((SimpleValue) i).instanceType().getDecimalSize() > SchemaType.SIZE_BIG_INTEGER) { + return i.valueEquals(this); + } + + return _value.equals(((XmlObjectBase) i).getBigIntegerValue()); + } + + private static final BigInteger _maxlong = BigInteger.valueOf(Long.MAX_VALUE); + private static final BigInteger _minlong = BigInteger.valueOf(Long.MIN_VALUE); + + /** + * Note, this is carefully aligned with hash codes for all xsd:decimal + * primitives. + */ + protected int value_hash_code() { + if (_value.compareTo(_maxlong) > 0 || + _value.compareTo(_minlong) < 0) { + return _value.hashCode(); + } + + long longval = _value.longValue(); + + return (int) ((longval >> 32) * 19 + longval); + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java new file mode 100644 index 0000000..6ecb2b3 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java @@ -0,0 +1,168 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlPositiveInteger; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +import java.math.BigInteger; + +public class JavaIntegerHolderEx extends JavaIntegerHolder { + public JavaIntegerHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + private final SchemaType _schemaType; + + + public SchemaType schemaType() { + return _schemaType; + } + + protected void set_text(String s) { + BigInteger v = lex(s, _voorVc); + + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + + if (_validateOnSet()) { + validateLexical(s, _schemaType, _voorVc); + } + + super.set_BigInteger(v); + } + + protected void set_BigInteger(BigInteger v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + + super.set_BigInteger(v); + } + + public static void validateLexical(String v, SchemaType sType, ValidationContext context) { + JavaDecimalHolder.validateLexical(v, context); + if (v.lastIndexOf('.') >= 0) { + context.invalid(XmlErrorCodes.INTEGER, + new Object[]{v}); + } + + // check pattern + if (sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"integer", v, QNameHelper.readable(sType)}); + } + } + } + + private static void validateValue(BigInteger v, SchemaType sType, ValidationContext context) { + // total digits + XmlPositiveInteger td = (XmlPositiveInteger) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); + if (td != null) { + String temp = v.toString(); + int len = temp.length(); + if (len > 0 && temp.charAt(0) == '-') { + len -= 1; + } + if (len > td.getBigIntegerValue().intValue()) { + context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, + new Object[]{len, temp, td.getBigIntegerValue().intValue(), QNameHelper.readable(sType)}); + return; + } + } + + // min ex + XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (mine != null) { + BigInteger m = getBigIntegerValue(mine); + if (!(v.compareTo(m) > 0)) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"integer", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // min in + XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (mini != null) { + BigInteger m = getBigIntegerValue(mini); + if (!(v.compareTo(m) >= 0)) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"integer", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max in + XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (maxi != null) { + BigInteger m = getBigIntegerValue(maxi); + if (!(v.compareTo(m) <= 0)) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"integer", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max ex + XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (maxe != null) { + BigInteger m = getBigIntegerValue(maxe); + if (!(v.compareTo(m) < 0)) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"integer", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // enumeration + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (v.equals(getBigIntegerValue(val))) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"integer", v, QNameHelper.readable(sType)}); + } + } + + private static BigInteger getBigIntegerValue(XmlObject o) { + SchemaType s = o.schemaType(); + switch (s.getDecimalSize()) { + case SchemaType.SIZE_BIG_DECIMAL: + return ((XmlObjectBase) o).getBigDecimalValue().toBigInteger(); + case SchemaType.SIZE_BIG_INTEGER: + return ((XmlObjectBase) o).getBigIntegerValue(); + default: + throw new IllegalStateException("Bad facet type for Big Int: " + s); + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getBigIntegerValue(), schemaType(), ctx); + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaLongHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaLongHolder.java new file mode 100644 index 0000000..d3ffbbe --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaLongHolder.java @@ -0,0 +1,114 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +import java.math.BigDecimal; +import java.math.BigInteger; + +public abstract class JavaLongHolder extends XmlObjectBase { + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_LONG; + } + + private long _value; + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // gets raw text value + protected String compute_text(NamespaceManager nsm) { + return Long.toString(_value); + } + + protected void set_text(String s) { + try { + set_long(XsTypeConverter.lexLong(s)); + } catch (Exception e) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.LONG, new Object[]{s}); + } + } + + protected void set_nil() { + _value = 0L; + } + + // numerics: fractional + public BigDecimal getBigDecimalValue() { + check_dated(); + return BigDecimal.valueOf(_value); + } + + public BigInteger getBigIntegerValue() { + check_dated(); + return BigInteger.valueOf(_value); + } + + public long getLongValue() { + check_dated(); + return _value; + } + + private static final BigInteger _max = BigInteger.valueOf(Long.MAX_VALUE); + private static final BigInteger _min = BigInteger.valueOf(Long.MIN_VALUE); + + // setters + protected void set_BigDecimal(BigDecimal v) { + set_BigInteger(v.toBigInteger()); + } + + protected void set_BigInteger(BigInteger v) { + if (v.compareTo(_max) > 0 || v.compareTo(_min) < 0) { + throw new XmlValueOutOfRangeException(); + } + _value = v.longValue(); + } + + protected void set_long(long l) { + _value = l; + } + + // comparators + protected int compare_to(XmlObject l) { + if (((SimpleValue) l).instanceType().getDecimalSize() > SchemaType.SIZE_LONG) { + return -l.compareTo(this); + } + + return Long.compare(_value, ((XmlObjectBase) l).getLongValue()); + } + + protected boolean equal_to(XmlObject l) { + if (((SimpleValue) l).instanceType().getDecimalSize() > SchemaType.SIZE_LONG) { + return l.valueEquals(this); + } + + return _value == ((XmlObjectBase) l).getLongValue(); + } + + /** + * Note, this is carefully aligned with hash codes for all xsd:decimal + * primitives. + */ + protected int value_hash_code() { + return (int) ((_value >> 32) * 19 + _value); + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java new file mode 100644 index 0000000..7552467 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java @@ -0,0 +1,168 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.util.XsTypeConverter; + +public abstract class JavaLongHolderEx extends JavaLongHolder { + public JavaLongHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + private final SchemaType _schemaType; + + + public SchemaType schemaType() { + return _schemaType; + } + + protected void set_text(String s) { + long v; + + try { + v = XsTypeConverter.lexLong(s); + } catch (Exception e) { + throw new XmlValueOutOfRangeException(); + } + + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + validateLexical(s, _schemaType, _voorVc); + } + + super.set_long(v); + } + + protected void set_long(long v) { + if (_validateOnSet()) { + validateValue(v, _schemaType, _voorVc); + } + + super.set_long(v); + } + + public static void validateLexical(String v, SchemaType sType, ValidationContext context) { + JavaDecimalHolder.validateLexical(v, context); + + // check pattern + if (sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"long", v, QNameHelper.readable(sType)}); + } + } + } + + private static void validateValue(long v, SchemaType sType, ValidationContext context) { + // total digits + XmlObject td = sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); + if (td != null) { + long m = getLongValue(td); + String temp = Long.toString(v); + int len = temp.length(); + if (len > 0 && temp.charAt(0) == '-') { + len -= 1; + } + if (len > m) { + context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, + new Object[]{len, temp, m, QNameHelper.readable(sType)}); + return; + } + } + + // min ex + XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (mine != null) { + long m = getLongValue(mine); + if (!(v > m)) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, + new Object[]{"long", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // min in + XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (mini != null) { + long m = getLongValue(mini); + if (!(v >= m)) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, + new Object[]{"long", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max in + XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (maxi != null) { + long m = getLongValue(maxi); + if (!(v <= m)) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, + new Object[]{"long", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // max ex + XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (maxe != null) { + long m = getLongValue(maxe); + if (!(v < m)) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, + new Object[]{"long", v, m, QNameHelper.readable(sType)}); + return; + } + } + + // enumeration + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (v == getLongValue(val)) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"long", v, QNameHelper.readable(sType)}); + } + } + + private static long getLongValue(XmlObject o) { + SchemaType s = o.schemaType(); + switch (s.getDecimalSize()) { + case SchemaType.SIZE_BIG_DECIMAL: + return ((XmlObjectBase) o).getBigDecimalValue().longValue(); + case SchemaType.SIZE_BIG_INTEGER: + return ((XmlObjectBase) o).getBigIntegerValue().longValue(); + case SchemaType.SIZE_LONG: + return ((XmlObjectBase) o).getLongValue(); + default: + throw new IllegalStateException("Bad facet type: " + s); + } + + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(lexical, schemaType(), ctx); + validateValue(getLongValue(), schemaType(), ctx); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaNotationHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaNotationHolder.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaNotationHolder.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaNotationHolder.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaNotationHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaNotationHolderEx.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaNotationHolderEx.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaNotationHolderEx.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaQNameHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaQNameHolder.java new file mode 100644 index 0000000..d4e435a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaQNameHolder.java @@ -0,0 +1,194 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlAnySimpleType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.PrefixResolver; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.common.XMLChar; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; + +import javax.xml.namespace.QName; + +public class JavaQNameHolder extends XmlObjectBase { + public JavaQNameHolder() { + } + + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_QNAME; + } + + private QName _value; + + protected int get_wscanon_rule() { + return SchemaType.WS_PRESERVE; + } + + // an ergonomic prefixer so that you can say stringValue() on a free-floating QName. + private static final NamespaceManager PRETTY_PREFIXER = new PrettyNamespaceManager(); + + private static class PrettyNamespaceManager implements NamespaceManager { + public String find_prefix_for_nsuri(String nsuri, String suggested_prefix) { + return QNameHelper.suggestPrefix(nsuri); + } + + public String getNamespaceForPrefix(String prefix) { + throw new RuntimeException("Should not be called"); + } + } + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + public String compute_text(NamespaceManager nsm) { + if (nsm == null) { + // we used to: throw new IllegalStateException("Cannot create QName prefix outside of a document"); + // but it's not nice to throw on stringValue() + nsm = PRETTY_PREFIXER; + } + +// TODO - what I really need to do here is that if there is no +// namespace for this qname, then instead of finding the prefix for the +// uri, I should make a call to set the default namespace for the +// immediate context for this qname to be "". + + String namespace = _value.getNamespaceURI(); + String localPart = _value.getLocalPart(); + + if (namespace == null || namespace.length() == 0) { + return localPart; + } + + String prefix = nsm.find_prefix_for_nsuri(namespace, null); + + assert prefix != null; + + return "".equals(prefix) ? localPart : prefix + ":" + localPart; + } + + public static QName validateLexical( + String v, ValidationContext context, PrefixResolver resolver) { + QName name; + + try { + name = parse(v, resolver); + } catch (XmlValueOutOfRangeException e) { + context.invalid(e.getMessage()); + name = null; + } + + return name; + } + + private static QName parse(String v, PrefixResolver resolver) { + String prefix, localname; + int start; + int end; + for (end = v.length(); end > 0; end -= 1) { + if (!XMLChar.isSpace(v.charAt(end - 1))) { + break; + } + } + for (start = 0; start < end; start += 1) { + if (!XMLChar.isSpace(v.charAt(start))) { + break; + } + } + + int firstcolon = v.indexOf(':', start); + if (firstcolon >= 0) { + prefix = v.substring(start, firstcolon); + localname = v.substring(firstcolon + 1, end); + } else { + prefix = ""; + localname = v.substring(start, end); + } + + if (prefix.length() > 0 && !XMLChar.isValidNCName(prefix)) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.QNAME, new Object[]{"Prefix not a valid NCName in '" + v + "'"}); + } + + if (!XMLChar.isValidNCName(localname)) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.QNAME, new Object[]{"Localname not a valid NCName in '" + v + "'"}); + } + + String uri = + resolver == null ? null : resolver.getNamespaceForPrefix(prefix); + + if (uri == null) { + if (prefix.length() > 0) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.QNAME, new Object[]{"Can't resolve prefix '" + prefix + "'"}); + } + + uri = ""; + } + + if (prefix != null && prefix.length() > 0) { + return new QName(uri, localname, prefix); + } else { + return new QName(uri, localname); + } + } + + protected void set_text(String s) { + PrefixResolver resolver = NamespaceContext.getCurrent(); + + if (resolver == null && has_store()) { + resolver = get_store(); + } + + _value = parse(s, resolver); + } + + // BUGBUG - having prefix here may not work + protected void set_QName(QName name) { + assert name != null; + + // Sync force of creation of namesapce mapping .. + + if (has_store()) { + get_store().find_prefix_for_nsuri(name.getNamespaceURI(), null); + } + + _value = name; + } + + protected void set_xmlanysimple(XmlAnySimpleType value) { + _value = parse(value.getStringValue(), NamespaceContext.getCurrent()); + } + + protected void set_nil() { + _value = null; + } + + // setters, getters (setter already handled via set_text) + + public QName getQNameValue() { + check_dated(); + return _value; + } + + // comparators + protected boolean equal_to(XmlObject obj) { + return _value.equals(((XmlObjectBase) obj).getQNameValue()); + } + + protected int value_hash_code() { + return _value.hashCode(); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaQNameHolderEx.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolderEx.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaQNameHolderEx.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringEnumerationHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaStringEnumerationHolderEx.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringEnumerationHolderEx.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaStringEnumerationHolderEx.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaStringHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaStringHolder.java new file mode 100644 index 0000000..74ef85e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaStringHolder.java @@ -0,0 +1,63 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; + +public class JavaStringHolder extends XmlObjectBase { + public JavaStringHolder() { + } + + public SchemaType schemaType() { + return BuiltinSchemaTypeSystem.ST_STRING; + } + + private String _value; + + protected int get_wscanon_rule() { + return SchemaType.WS_PRESERVE; + } + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + public String compute_text(NamespaceManager nsm) { + return _value; + } + + protected void set_text(String s) { + _value = s; + } + + protected void set_nil() { + _value = null; + } + + // string setter and getter already handled by XmlObjectBase + + // comparators + protected boolean equal_to(XmlObject obj) { + return _value.equals(((XmlObjectBase) obj).getStringValue()); + } + + protected int value_hash_code() { + return _value.hashCode(); + } + + protected boolean is_defaultable_ws(String v) { + return false; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java new file mode 100644 index 0000000..1a7fd8d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java @@ -0,0 +1,119 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlAnySimpleType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +public abstract class JavaStringHolderEx extends JavaStringHolder { + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + public JavaStringHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + protected int get_wscanon_rule() { + return schemaType().getWhiteSpaceRule(); + } + + protected void set_text(String s) { + if (_validateOnSet()) { + validateLexical(s, _schemaType, _voorVc); + } + + super.set_text(s); + } + + protected boolean is_defaultable_ws(String v) { + try { + validateLexical(v, _schemaType, _voorVc); + return false; + } catch (XmlValueOutOfRangeException e) { + return true; + } + } + + public static void validateLexical(String v, SchemaType sType, ValidationContext context) { + // check against pattern + if (!sType.matchPatternFacet(v)) { + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, new Object[]{"string", v, QNameHelper.readable(sType)}); + return; + } + + // check against length + XmlObject len = sType.getFacet(SchemaType.FACET_LENGTH); + if (len != null) { + int m = ((XmlObjectBase) len).getBigIntegerValue().intValue(); + if (v.length() != m) { + context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$STRING, + new Object[]{"string", v.length(), m, QNameHelper.readable(sType)}); + return; + } + } + + // check against min length + XmlObject min = sType.getFacet(SchemaType.FACET_MIN_LENGTH); + if (min != null) { + int m = ((XmlObjectBase) min).getBigIntegerValue().intValue(); + if (v.length() < m) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING, + new Object[]{"string", v.length(), m, QNameHelper.readable(sType)}); + return; + } + } + + // check against min length + XmlObject max = sType.getFacet(SchemaType.FACET_MAX_LENGTH); + if (max != null) { + int m = ((XmlObjectBase) max).getBigIntegerValue().intValue(); + if (v.length() > m) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING, + new Object[]{"string", v.length(), m, QNameHelper.readable(sType)}); + return; + } + } + + // enumeration + // NOTE: can't use .hasStringEnumValues() or .enumForString() + // here since we may be validating against a string enum value + // during StscSimpleTypeResolver.resolveFacets() and the string + // enum table hasn't been constructed yet. + XmlAnySimpleType[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlAnySimpleType val : vals) { + if (v.equals(val.getStringValue())) { + return; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"string", v, QNameHelper.readable(sType)}); + } + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(getStringValue(), schemaType(), ctx); + } + +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolder.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaUriHolder.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolder.java rename to src/main/java/org/apache/xmlbeans/impl/values/JavaUriHolder.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java b/src/main/java/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java new file mode 100644 index 0000000..74b1555 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java @@ -0,0 +1,155 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; + +public class JavaUriHolderEx extends JavaUriHolder { + private final SchemaType _schemaType; + + public SchemaType schemaType() { + return _schemaType; + } + + public JavaUriHolderEx(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + protected int get_wscanon_rule() { + return schemaType().getWhiteSpaceRule(); + } + + protected void set_text(String s) { + if (_validateOnSet()) { + if (!check(s, _schemaType)) { + throw new XmlValueOutOfRangeException(); + } + + if (!_schemaType.matchPatternFacet(s)) { + throw new XmlValueOutOfRangeException(); + } + } + + super.set_text(s); + } + +// // setters +// protected void set_uri(URI uri) +// { +// if (!check(uri.toString(), _schemaType)) +// throw new XmlValueOutOfRangeException(); +// +// super.set_uri(uri); +// } + + public static void validateLexical(String v, SchemaType sType, ValidationContext context) { + XmlAnyUriImpl.validateLexical(v, context); + + XmlObject[] vals = sType.getEnumerationValues(); + + if (vals != null) { + int i; + + for (i = 0; i < vals.length; i++) { + String e = ((SimpleValue) vals[i]).getStringValue(); + + if (e.equals(v)) { + break; + } + } + + if (i >= vals.length) { + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"anyURI", v, QNameHelper.readable(sType)}); + } + } + + // check pattern + if (sType.hasPatternFacet()) { + if (!sType.matchPatternFacet(v)) { + // TODO - describe string and pattern here in error + context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"anyURI", v, QNameHelper.readable(sType)}); + } + } + + XmlObject x; + int i; + + if ((x = sType.getFacet(SchemaType.FACET_LENGTH)) != null) { + if ((i = ((SimpleValue) x).getBigIntegerValue().intValue()) != v.length()) { + context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$STRING, + new Object[]{"anyURI", v, i, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) { + if ((i = ((SimpleValue) x).getBigIntegerValue().intValue()) > v.length()) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING, + new Object[]{"anyURI", v, i, QNameHelper.readable(sType)}); + } + } + + if ((x = sType.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) { + if ((i = ((SimpleValue) x).getBigIntegerValue().intValue()) < v.length()) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING, + new Object[]{"anyURI", v, i, QNameHelper.readable(sType)}); + } + } + } + + private static boolean check(String v, SchemaType sType) { + int length = v == null ? 0 : v.length(); + // check against length + XmlObject len = sType.getFacet(SchemaType.FACET_LENGTH); + if (len != null) { + int m = ((SimpleValue) len).getBigIntegerValue().intValue(); + if (length == m) { + return false; + } + } + + // check against min length + XmlObject min = sType.getFacet(SchemaType.FACET_MIN_LENGTH); + if (min != null) { + int m = ((SimpleValue) min).getBigIntegerValue().intValue(); + if (length < m) { + return false; + } + } + + // check against min length + XmlObject max = sType.getFacet(SchemaType.FACET_MAX_LENGTH); + if (max != null) { + int m = ((SimpleValue) max).getBigIntegerValue().intValue(); + if (length > m) { + return false; + } + } + + return true; + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateLexical(getStringValue(), schemaType(), ctx); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java b/src/main/java/org/apache/xmlbeans/impl/values/NamespaceContext.java similarity index 98% rename from src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java rename to src/main/java/org/apache/xmlbeans/impl/values/NamespaceContext.java index 692197c..f7be564 100644 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java +++ b/src/main/java/org/apache/xmlbeans/impl/values/NamespaceContext.java @@ -90,6 +90,10 @@ final void pop() private static ThreadLocal tl_namespaceContextStack = new ThreadLocal(); + public static void clearThreadLocals() { + tl_namespaceContextStack.remove(); + } + private static NamespaceContextStack getNamespaceContextStack() { NamespaceContextStack namespaceContextStack = (NamespaceContextStack) tl_namespaceContextStack.get(); diff --git a/src/typestore/org/apache/xmlbeans/impl/values/NamespaceManager.java b/src/main/java/org/apache/xmlbeans/impl/values/NamespaceManager.java similarity index 100% rename from src/typestore/org/apache/xmlbeans/impl/values/NamespaceManager.java rename to src/main/java/org/apache/xmlbeans/impl/values/NamespaceManager.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/StringEnumValue.java b/src/main/java/org/apache/xmlbeans/impl/values/StringEnumValue.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/StringEnumValue.java rename to src/main/java/org/apache/xmlbeans/impl/values/StringEnumValue.java diff --git a/src/typestore/org/apache/xmlbeans/impl/values/TypeStore.java b/src/main/java/org/apache/xmlbeans/impl/values/TypeStore.java similarity index 87% rename from src/typestore/org/apache/xmlbeans/impl/values/TypeStore.java rename to src/main/java/org/apache/xmlbeans/impl/values/TypeStore.java index 8dba3fa..ce67dbc 100644 --- a/src/typestore/org/apache/xmlbeans/impl/values/TypeStore.java +++ b/src/main/java/org/apache/xmlbeans/impl/values/TypeStore.java @@ -15,19 +15,13 @@ package org.apache.xmlbeans.impl.values; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.QNameSet; -import java.util.List; -import javax.xml.namespace.QName; +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.common.ValidatorListener; import org.apache.xmlbeans.impl.common.XmlLocale; +import javax.xml.namespace.QName; +import java.util.List; + public interface TypeStore extends NamespaceManager { /** @@ -81,10 +75,10 @@ public interface TypeStore extends NamespaceManager // BUGBUG (ericvas) 12111 String fetch_text(int whitespaceRule); - public static int WS_UNSPECIFIED = 0; - public static int WS_PRESERVE = 1; - public static int WS_REPLACE = 2; - public static int WS_COLLAPSE = 3; + int WS_UNSPECIFIED = 0; + int WS_PRESERVE = 1; + int WS_REPLACE = 2; + int WS_COLLAPSE = 3; /** * A user of a TypeStore calls store_text when he wants the TypeStore @@ -132,9 +126,9 @@ public interface TypeStore extends NamespaceManager */ SchemaField get_schema_field(); - public static final int NILLABLE = 1; - public static final int HASDEFAULT = 2; - public static final int FIXED = 4; // always set with HASDEFAULT + int NILLABLE = 1; + int HASDEFAULT = 2; + int FIXED = 4; // always set with HASDEFAULT /** * Called when the value has been nilled or unnilled, so the textstore @@ -170,11 +164,6 @@ public interface TypeStore extends NamespaceManager * and then follow with an add_element_etc if we choose to, * without randomly catching exceptions. */ -// BUGBUG - this should be called find_element -// BUGBUG - this should be called find_element -// BUGBUG - this should be called find_element -// BUGBUG - this should be called find_element -// BUGBUG - this should be called find_element TypeStoreUser find_element_user(QName name, int i); /** @@ -187,18 +176,14 @@ public interface TypeStore extends NamespaceManager * given name owned by this typestore, or the empty array of * TypeStoreUsers if none was found. */ -// BUGBUG - this should be called find_all_element -// BUGBUG - this should be called find_all_element -// BUGBUG - this should be called find_all_element -// BUGBUG - this should be called find_all_element - void find_all_element_users(QName name, List fillMeUp); + void find_all_element_users(QName name, List fillMeUp); /** * Returns all TypeStoreUsers corresponding to elements with one * of the names is the QNameSet. */ - void find_all_element_users(QNameSet name, List fillMeUp); + void find_all_element_users(QNameSet name, List fillMeUp); /** * Inserts a new element at the position that will make it @@ -214,10 +199,6 @@ public interface TypeStore extends NamespaceManager * Should throw an IndexOutOfBoundsException if i < 0 * or if i > # of elts */ - -// BUGBUG - this should be called insert_element -// BUGBUG - this should be called insert_element -// BUGBUG - this should be called insert_element TypeStoreUser insert_element_user(QName name, int i); /** @@ -233,10 +214,6 @@ public interface TypeStore extends NamespaceManager * Note that if there are no existing elements of the given * name, the same comment applies as with insert_element_user. */ -// BUGBUG - this should be called add_element -// BUGBUG - this should be called add_element -// BUGBUG - this should be called add_element -// BUGBUG - this should be called add_element TypeStoreUser add_element_user(QName name); /** @@ -327,7 +304,7 @@ public interface TypeStore extends NamespaceManager * 3. if i >= m and i < n, then the element #i and all its contents * are removed. */ - + void array_setter ( XmlObject[] sources, QName elementName ); /** @@ -336,13 +313,12 @@ public interface TypeStore extends NamespaceManager */ void visit_elements(TypeStoreVisitor visitor); - XmlObject[] exec_query ( String queryExpr, XmlOptions options ) - throws XmlException; + XmlObject[] exec_query ( String queryExpr, XmlOptions options ); /** * Returns the monitor object, used for synchronizing access to the doc. * @deprecated - */ + */ Object get_root_object(); /** diff --git a/src/typestore/org/apache/xmlbeans/impl/values/TypeStoreUser.java b/src/main/java/org/apache/xmlbeans/impl/values/TypeStoreUser.java similarity index 100% rename from src/typestore/org/apache/xmlbeans/impl/values/TypeStoreUser.java rename to src/main/java/org/apache/xmlbeans/impl/values/TypeStoreUser.java diff --git a/src/typestore/org/apache/xmlbeans/impl/values/TypeStoreUserFactory.java b/src/main/java/org/apache/xmlbeans/impl/values/TypeStoreUserFactory.java similarity index 100% rename from src/typestore/org/apache/xmlbeans/impl/values/TypeStoreUserFactory.java rename to src/main/java/org/apache/xmlbeans/impl/values/TypeStoreUserFactory.java diff --git a/src/typestore/org/apache/xmlbeans/impl/values/TypeStoreVisitor.java b/src/main/java/org/apache/xmlbeans/impl/values/TypeStoreVisitor.java similarity index 100% rename from src/typestore/org/apache/xmlbeans/impl/values/TypeStoreVisitor.java rename to src/main/java/org/apache/xmlbeans/impl/values/TypeStoreVisitor.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java new file mode 100644 index 0000000..99e00a8 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java @@ -0,0 +1,73 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlAnySimpleType; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; + +/** + * This class implements the anySimpleType for XML. + */ +public class XmlAnySimpleTypeImpl extends XmlObjectBase implements XmlAnySimpleType { + public XmlAnySimpleTypeImpl(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + public XmlAnySimpleTypeImpl() { + _schemaType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; + } + + public SchemaType schemaType() { + return _schemaType; + } + + private final SchemaType _schemaType; + + String _textvalue = ""; + + protected int get_wscanon_rule() { + return SchemaType.WS_PRESERVE; + } + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + // gets raw text value + protected String compute_text(NamespaceManager nsm) { + return _textvalue; + } + + protected void set_text(String s) { + _textvalue = s; + } + + protected void set_nil() { + _textvalue = null; + } + + // comparators + protected boolean equal_to(XmlObject obj) { + // compares against another anySimpleType + // rule is: lexical values must match. + return _textvalue.equals(((XmlAnySimpleType) obj).getStringValue()); + } + + protected int value_hash_code() { + // matches JavaStringHolder's value_hash_code, so we can be hased against strings + return (_textvalue == null ? 0 : _textvalue.hashCode()); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyTypeImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlAnyTypeImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyTypeImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlAnyTypeImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyUriImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlAnyUriImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyUriImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlAnyUriImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyUriRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlAnyUriRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnyUriRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlAnyUriRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBase64BinaryImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlBase64BinaryImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlBase64BinaryImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlBase64BinaryImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBase64BinaryRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlBase64BinaryRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlBase64BinaryRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlBase64BinaryRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBooleanImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlBooleanImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlBooleanImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlBooleanImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlBooleanRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlBooleanRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlBooleanRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlBooleanRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlByteImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlByteImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlByteImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlByteImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java new file mode 100644 index 0000000..65719f6 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java @@ -0,0 +1,491 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; +import org.apache.xmlbeans.impl.schema.SchemaTypeVisitorImpl; + +import javax.xml.namespace.QName; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.function.BiConsumer; + +public class XmlComplexContentImpl extends XmlObjectBase { + public XmlComplexContentImpl(SchemaType type) { + _schemaType = (SchemaTypeImpl) type; + initComplexType(true, true); + } + + public SchemaType schemaType() { + return _schemaType; + } + + private final SchemaTypeImpl _schemaType; + + public String compute_text(NamespaceManager nsm) { + return null; + } + + protected final void set_String(String v) { + assert _schemaType.getContentType() != SchemaType.SIMPLE_CONTENT; + + if (_schemaType.getContentType() != SchemaType.MIXED_CONTENT && + !_schemaType.isNoType()) { + throw new IllegalArgumentException( + "Type does not allow for textual content: " + _schemaType); + } + + super.set_String(v); + } + + public void set_text(String str) { + assert + _schemaType.getContentType() == SchemaType.MIXED_CONTENT || + _schemaType.isNoType(); + } + + protected void update_from_complex_content() { + // No complex caching yet ... + } + + public void set_nil() { /* BUGBUG: what to do? */ } + + // LEFT + public boolean equal_to(XmlObject complexObject) { + if (!_schemaType.equals(complexObject.schemaType())) { + return false; + } + + // BUGBUG: by-value structure comparison undone + return true; + } + + // LEFT + protected int value_hash_code() { + throw new IllegalStateException("Complex types cannot be used as hash keys"); + } + + // DONE + public TypeStoreVisitor new_visitor() { + return new SchemaTypeVisitorImpl(_schemaType.getContentModel()); + } + + // DONE + public boolean is_child_element_order_sensitive() { + return schemaType().isOrderSensitive(); + } + + public int get_elementflags(QName eltName) { + SchemaProperty prop = schemaType().getElementProperty(eltName); + if (prop == null) { + return 0; + } + if (prop.hasDefault() == SchemaProperty.VARIABLE || + prop.hasFixed() == SchemaProperty.VARIABLE || + prop.hasNillable() == SchemaProperty.VARIABLE) { + return -1; + } + return + (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | + (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED) | + (prop.hasNillable() == SchemaProperty.NEVER ? 0 : TypeStore.NILLABLE); + } + + // DONE + public String get_default_attribute_text(QName attrName) { + return super.get_default_attribute_text(attrName); + } + + // DONE + public String get_default_element_text(QName eltName) { + SchemaProperty prop = schemaType().getElementProperty(eltName); + if (prop == null) { + return ""; + } + return prop.getDefaultText(); + } + + // + // Code gen helpers + // + // So much redundant code ..... what I'd give for generics! + // + + protected void unionArraySetterHelper(Object[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setObjectValue); + } + + protected SimpleValue[] arraySetterHelper(int sourcesLength, QName elemName) { + SimpleValue[] sources = new SimpleValue[sourcesLength]; + commonSetterHelper(elemName, null, sources, (u, i) -> sources[i] = u); + return sources; + } + + protected SimpleValue[] arraySetterHelper(int sourcesLength, QName elemName, QNameSet set) { + SimpleValue[] sources = new SimpleValue[sourcesLength]; + commonSetterHelper(elemName, set, sources, (u, i) -> sources[i] = u); + return sources; + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(boolean[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setBooleanValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(float[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setFloatValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(double[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setDoubleValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(byte[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setByteValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(short[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setShortValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(int[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setIntValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(long[] sources, QName elemName) { + commonSetterHelper(elemName, null, (sources == null) ? 0 : sources.length, (u, i) -> u.setLongValue(sources[i])); + } + + protected void arraySetterHelper(BigDecimal[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setBigDecimalValue); + } + + protected void arraySetterHelper(BigInteger[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setBigIntegerValue); + } + + protected void arraySetterHelper(String[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setStringValue); + } + + protected void arraySetterHelper(byte[][] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setByteArrayValue); + } + + protected void arraySetterHelper(GDate[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setGDateValue); + } + + protected void arraySetterHelper(GDuration[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setGDurationValue); + } + + protected void arraySetterHelper(Calendar[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setCalendarValue); + } + + protected void arraySetterHelper(Date[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setDateValue); + } + + protected void arraySetterHelper(QName[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setQNameValue); + } + + protected void arraySetterHelper(StringEnumAbstractBase[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setEnumValue); + } + + + protected void arraySetterHelper(List[] sources, QName elemName) { + commonSetterHelper2(elemName, null, sources, XmlObjectBase::setListValue); + } + + protected void unionArraySetterHelper(Object[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setObjectValue); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(boolean[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setBooleanValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(float[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setFloatValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(double[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setDoubleValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(byte[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setByteValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(short[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setShortValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(int[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setIntValue(sources[i])); + } + + @SuppressWarnings("ConstantConditions") + protected void arraySetterHelper(long[] sources, QName elemName, QNameSet set) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, (u, i) -> u.setLongValue(sources[i])); + } + + protected void arraySetterHelper(BigDecimal[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setBigDecimalValue); + } + + protected void arraySetterHelper(BigInteger[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setBigIntegerValue); + } + + protected void arraySetterHelper(String[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setStringValue); + } + + protected void arraySetterHelper(byte[][] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setByteArrayValue); + } + + protected void arraySetterHelper(GDate[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setGDateValue); + } + + protected void arraySetterHelper(GDuration[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setGDurationValue); + } + + protected void arraySetterHelper(Calendar[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setCalendarValue); + } + + protected void arraySetterHelper(Date[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setDateValue); + } + + protected void arraySetterHelper(QName[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setQNameValue); + } + + protected void arraySetterHelper(StringEnumAbstractBase[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setEnumValue); + } + + protected void arraySetterHelper(List[] sources, QName elemName, QNameSet set) { + commonSetterHelper2(elemName, set, sources, XmlObjectBase::setListValue); + } + + protected void arraySetterHelper(XmlObject[] sources, QName elemName) { + arraySetterHelper(sources, elemName, null); + } + + protected void arraySetterHelper(XmlObject[] sources, QName elemName, QNameSet set) { + TypeStore store = get_store(); + + if (sources == null || sources.length == 0) { + int m = (set == null) ? store.count_elements(elemName) : store.count_elements(set); + for (; m > 0; m--) { + if (set == null) { + store.remove_element(elemName, 0); + } else { + store.remove_element(set, 0); + } + } + return; + } + + // Verify if the sources contain children of this node + int i; + // how many elements in the original array + int m = (set == null) ? store.count_elements(elemName) : store.count_elements(set); + int startSrc = 0, startDest = 0; + for (i = 0; i < sources.length; i++) { + if (sources[i].isImmutable()) { + continue; + } + XmlCursor c = sources[i].newCursor(); + if (c.toParent() && c.getObject() == this) { + c.dispose(); + break; + } + c.dispose(); + } + if (i < sources.length) { + TypeStoreUser current = (set == null) ? store.find_element_user(elemName, 0) : store.find_element_user(set, 0); + if (current == sources[i]) { + // The new object matches what already exists in the array + // Heuristic: we optimize for the case where the new elements + // in the array are the same as the existing elements with + // potentially new elements inserted + + // First insert the new element in the array at position 0 + int j; + for (j = 0; j < i; j++) { + TypeStoreUser user = (set == null) ? store.insert_element_user(elemName, j) : store.insert_element_user(set, elemName, j); + ((XmlObjectBase) user).set(sources[j]); + } + for (i++, j++; i < sources.length; i++, j++) { + XmlCursor c = sources[i].isImmutable() ? null : sources[i].newCursor(); + if (c != null && c.toParent() && c.getObject() == this) { + c.dispose(); + current = (set == null) ? store.find_element_user(elemName, j) : store.find_element_user(set, j); + if (current != sources[i]) { + // Fall back to the general case + break; + } + } else { + if (c != null) { + c.dispose(); + } + // Insert before the current element + TypeStoreUser user = (set == null) ? store.insert_element_user(elemName, j) : store.insert_element_user(set, elemName, j); + ((XmlObjectBase) user).set(sources[i]); + } + } + startDest = j; + startSrc = i; + m = store.count_elements(elemName); + } + // Fall through + } else { + // All of the elements in the existing array are to + // be deleted and replaced with elements from the + // sources array + } + + // The general case: we assume that some of the elements + // in the new array already exist, but at different indexes + + // Starting with position i in the sources array, copy the remaining elements + // to the end of the original array... + for (int j = i; j < sources.length; j++) { + TypeStoreUser user = store.add_element_user(elemName); + ((XmlObjectBase) user).set(sources[j]); + } + + // ... then come back and insert the elements starting with startSource + // up to i from the sources array into the current array, starting with + // startDest + int n = i; + for (; m > n - startSrc + startDest; m--) { + if (set == null) { + store.remove_element(elemName, m - 1); + } else { + store.remove_element(set, m - 1); + } + } + + int j; + for (i = startSrc, j = startDest; i < n; i++, j++) { + TypeStoreUser user; + + if (j >= m) { + user = store.add_element_user(elemName); + } else if (set == null) { + user = store.find_element_user(elemName, j); + } else { + user = store.find_element_user(set, j); + } + + ((XmlObjectBase) user).set(sources[i]); + } + + // We can't just delegate to array_setter because we need + // synchronization on the sources (potentially each element + // in the array on a different lock) + // get_store().array_setter( sources, elemName ); + } + + + private void commonSetterHelper(QName elemName, QNameSet set, T[] sources, BiConsumer fun) { + commonSetterHelper(elemName, set, (sources == null) ? 0 : sources.length, fun); + } + + private void commonSetterHelper(QName elemName, QNameSet set, int n, BiConsumer fun) { + TypeStore store = get_store(); + + int m = (set == null) ? store.count_elements(elemName) : store.count_elements(set); + + for (; m > n; m--) { + if (set == null) { + store.remove_element(elemName, m - 1); + } else { + store.remove_element(set, m - 1); + } + } + + for (int i = 0; i < n; i++) { + TypeStoreUser user; + + if (i >= m) { + user = store.add_element_user(elemName); + } else if (set == null) { + user = store.find_element_user(elemName, i); + } else { + user = store.find_element_user(set, i); + } + fun.accept((XmlObjectBase) user, i); + } + } + + private void commonSetterHelper2(QName elemName, QNameSet set, T[] sources, BiConsumer c) { + int n = (sources == null) ? 0 : sources.length; + + TypeStore store = get_store(); + + int m = (set == null) ? store.count_elements(elemName) : store.count_elements(set); + + for (; m > n; m--) { + if (set == null) { + store.remove_element(elemName, m - 1); + } else { + store.remove_element(set, m - 1); + } + } + + for (int i = 0; i < n; i++) { + TypeStoreUser user; + + if (i >= m) { + user = store.add_element_user(elemName); + } else if (set == null) { + user = store.find_element_user(elemName, i); + } else { + user = store.find_element_user(set, i); + } + c.accept((XmlObjectBase) user, sources[i]); + } + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDateImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDateImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDateImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDateImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDateTimeImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDateTimeImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDateTimeImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDateTimeImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDecimalImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDecimalImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDecimalImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDecimalImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDecimalRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDecimalRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDecimalRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDecimalRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDoubleImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDoubleImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDoubleImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDoubleImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDoubleRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDoubleRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDoubleRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDoubleRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlDurationImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlDurationImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlDurationImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlDurationImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlEntitiesImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlEntitiesImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlEntitiesImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlEntitiesImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlEntityImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlEntityImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlEntityImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlEntityImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlFloatImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlFloatImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlFloatImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlFloatImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlFloatRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlFloatRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlFloatRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlFloatRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGDayImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlGDayImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlGDayImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlGDayImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGMonthDayImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlGMonthDayImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlGMonthDayImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlGMonthDayImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGMonthImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlGMonthImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlGMonthImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlGMonthImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGYearImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlGYearImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlGYearImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlGYearImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlGYearMonthImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlGYearMonthImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlGYearMonthImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlGYearMonthImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlHexBinaryImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlHexBinaryImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlHexBinaryImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlHexBinaryImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlHexBinaryRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlHexBinaryRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlHexBinaryRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlHexBinaryRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIdImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIdImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdRefImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIdRefImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdRefImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIdRefImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdRefsImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIdRefsImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIdRefsImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIdRefsImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIntImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIntImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIntRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIntRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntegerImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIntegerImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntegerImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIntegerImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntegerRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlIntegerRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlIntegerRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlIntegerRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlLanguageImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlLanguageImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlLanguageImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlLanguageImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/XmlListImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlListImpl.java new file mode 100644 index 0000000..cc28804 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/XmlListImpl.java @@ -0,0 +1,314 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.PrefixResolver; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.common.XMLChar; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class XmlListImpl extends XmlObjectBase implements XmlAnySimpleType { + public XmlListImpl(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + public SchemaType schemaType() { + return _schemaType; + } + + private final SchemaType _schemaType; + private XmlSimpleList _value; + private XmlSimpleList _jvalue; + + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + // gets raw text value + + private static String compute_list_text(List xList) { + return xList.isEmpty() ? "" : xList.stream().map(XmlListImpl::object2String).collect(Collectors.joining(" ")); + + } + + private static String object2String(Object o) { + String s = (o instanceof SimpleValue) ? ((SimpleValue) o).getStringValue() : o.toString(); + return (s == null) ? "" : s; + } + + protected String compute_text(NamespaceManager nsm) { + return compute_list_text(_value); + } + + protected boolean is_defaultable_ws(String v) { + try { + XmlSimpleList savedValue = _value; + set_text(v); + + // restore the saved value + _value = savedValue; + + return false; + } catch (XmlValueOutOfRangeException e) { + return true; + } + } + + protected void set_text(String s) { + // first check against any patterns... + if (_validateOnSet() && !_schemaType.matchPatternFacet(s)) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"list", s, QNameHelper.readable(_schemaType)}); + } + + SchemaType itemType = _schemaType.getListItemType(); + + XmlSimpleList newval = lex(s, itemType, _voorVc, has_store() ? get_store() : null); + + // check enumeration + if (_validateOnSet()) { + validateValue(newval, _schemaType, _voorVc); + } + + // we made it all the way through; so we're OK. + _value = newval; + _jvalue = null; + } + + private static final String[] EMPTY_STRINGARRAY = new String[0]; + + public static String[] split_list(String s) { + if (s.length() == 0) { + return EMPTY_STRINGARRAY; + } + + List result = new ArrayList<>(); + int i = 0; + int start; + for (; ; ) { + while (i < s.length() && XMLChar.isSpace(s.charAt(i))) { + i += 1; + } + if (i >= s.length()) { + return result.toArray(EMPTY_STRINGARRAY); + } + start = i; + while (i < s.length() && !XMLChar.isSpace(s.charAt(i))) { + i += 1; + } + result.add(s.substring(start, i)); + } + } + + public static XmlSimpleList lex(String s, SchemaType itemType, ValidationContext ctx, PrefixResolver resolver) { + String[] parts = split_list(s); + + Function fun = (str) -> { + try { + return itemType.newValue(str); + } catch (XmlValueOutOfRangeException e) { + Object[] obj = {"item '" + str + "' is not a valid value of " + QNameHelper.readable(itemType)}; + ctx.invalid(XmlErrorCodes.LIST, obj); + return null; + } + }; + boolean pushed = false; + if (resolver != null) { + NamespaceContext.push(new NamespaceContext(resolver)); + pushed = true; + } + try { + List list = Stream.of(parts).map(fun).collect(Collectors.toList()); + return new XmlSimpleList<>(list); + } finally { + if (pushed) { + NamespaceContext.pop(); + } + } + } + + protected void set_nil() { + _value = null; + } + + @Override + public XmlSimpleList xgetListValue() { + check_dated(); + return _value; + } + + public List getListValue() { + check_dated(); + if (_value == null) { + return null; + } + if (_jvalue != null) { + return _jvalue; + } + List javaResult = new ArrayList<>(); + for (Object o : _value) { + javaResult.add(java_value((XmlObject) o)); + } + _jvalue = new XmlSimpleList<>(javaResult); + return _jvalue; + } + + private static boolean permits_inner_space(XmlObject obj) { + switch (((SimpleValue) obj).instanceType().getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_STRING: + case SchemaType.BTC_ANY_URI: + case SchemaType.BTC_ANY_SIMPLE: + case SchemaType.BTC_ANY_TYPE: + return true; + default: + return false; + } + } + + private static boolean contains_white_space(String s) { + return s.indexOf(' ') >= 0 || + s.indexOf('\t') >= 0 || + s.indexOf('\n') >= 0 || + s.indexOf('\r') >= 0; + } + + public void set_list(List list) { + SchemaType itemType = _schemaType.getListItemType(); + XmlSimpleList xList; + + boolean pushed = false; + if (has_store()) { + NamespaceContext.push(new NamespaceContext(get_store())); + pushed = true; + } + + Function fun = (entry) -> { + if ((entry instanceof XmlObject) && permits_inner_space((XmlObject) entry)) { + String stringrep = entry.toString(); + if (contains_white_space(stringrep)) { + throw new XmlValueOutOfRangeException(); + } + } + return itemType.newValue(entry); + }; + + try { + xList = new XmlSimpleList<>(list.stream().map(fun).collect(Collectors.toList())); + } finally { + if (pushed) { + NamespaceContext.pop(); + } + } + + if (_validateOnSet()) { + // check enumeration + min/max/etc + validateValue(xList, _schemaType, _voorVc); + } + + _value = xList; + _jvalue = null; + } + + public static void validateValue(XmlSimpleList items, SchemaType sType, ValidationContext context) { + XmlObject[] enumvals = sType.getEnumerationValues(); + checkEnum: + if (enumvals != null) { + for (XmlObject enumval : enumvals) { + if (equal_xmlLists(items, ((XmlObjectBase) enumval).xgetListValue())) { + break checkEnum; + } + } + context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, + new Object[]{"list", items, QNameHelper.readable(sType)}); + } + + XmlObject o; + int i; + + if ((o = sType.getFacet(SchemaType.FACET_LENGTH)) != null) { + if ((i = ((SimpleValue) o).getIntValue()) != items.size()) { + context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, + new Object[]{items, items.size(), i, QNameHelper.readable(sType)}); + } + } + + if ((o = sType.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) { + if ((i = ((SimpleValue) o).getIntValue()) > items.size()) { + context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$LIST_LENGTH, + new Object[]{items, items.size(), i, QNameHelper.readable(sType)}); + } + } + + if ((o = sType.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) { + if ((i = ((SimpleValue) o).getIntValue()) < items.size()) { + context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$LIST_LENGTH, + new Object[]{items, items.size(), i, QNameHelper.readable(sType)}); + } + } + } + + // comparators + // protected int compare_to(XmlObject i) - no sorting order; inherit from base + + protected boolean equal_to(XmlObject obj) { + return equal_xmlLists(_value, ((XmlObjectBase) obj).xgetListValue()); + } + + + private static boolean equal_xmlLists(List a, List b) { + if (a.size() != b.size()) { + return false; + } + for (int i = 0; i < a.size(); i++) { + if (!a.get(i).equals(b.get(i))) { + return false; + } + } + return true; + } + + protected int value_hash_code() { + if (_value == null) { + return 0; + } + + // hash code probes 9 distributed values, plus the last + int hash = _value.size(); + int incr = _value.size() / 9; + if (incr < 1) { + incr = 1; + } + + int i; + for (i = 0; i < _value.size(); i += incr) { + hash *= 19; + hash += _value.get(i).hashCode(); + } + + return hash; + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + validateValue(xgetListValue(), schemaType(), ctx); + } + +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlLongImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlLongImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlLongImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlLongImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlLongRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlLongRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlLongRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlLongRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNCNameImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNCNameImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNCNameImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNCNameImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNameImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNameImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNameImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNameImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNegativeIntegerImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNegativeIntegerImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNegativeIntegerImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNegativeIntegerImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNmTokenImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNmTokenImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNmTokenImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNmTokenImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNmTokensImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNmTokensImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNmTokensImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNmTokensImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNonNegativeIntegerImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNonNegativeIntegerImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNonNegativeIntegerImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNonNegativeIntegerImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNonPositiveIntegerImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNonPositiveIntegerImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNonPositiveIntegerImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNonPositiveIntegerImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNormalizedStringImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNormalizedStringImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNormalizedStringImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNormalizedStringImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNotationImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNotationImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNotationImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNotationImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlNotationRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlNotationRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlNotationRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlNotationRestriction.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/XmlObjectBase.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlObjectBase.java new file mode 100644 index 0000000..4b38c2e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/XmlObjectBase.java @@ -0,0 +1,3368 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.*; +import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; +import org.apache.xmlbeans.impl.schema.SchemaTypeVisitorImpl; +import org.apache.xmlbeans.impl.validator.Validator; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; +import java.io.*; +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import java.util.function.Function; +import java.util.function.IntFunction; + +public abstract class XmlObjectBase implements TypeStoreUser, Serializable, XmlObject, SimpleValue { + public static final short MAJOR_VERSION_NUMBER = (short) 1; // for serialization + public static final short MINOR_VERSION_NUMBER = (short) 1; // for serialization + + public static final short KIND_SETTERHELPER_SINGLETON = 1; + public static final short KIND_SETTERHELPER_ARRAYITEM = 2; + + public final Object monitor() { + if (has_store()) { + return get_store().get_locale(); + } + return this; + } + + private static XmlObjectBase underlying(XmlObject obj) { + if (obj == null) { + return null; + } + if (obj instanceof XmlObjectBase) { + return (XmlObjectBase) obj; + } + while (obj instanceof DelegateXmlObject) { + obj = ((DelegateXmlObject) obj).underlyingXmlObject(); + } + if (obj instanceof XmlObjectBase) { + return (XmlObjectBase) obj; + } + throw new IllegalStateException("Non-native implementations of XmlObject should extend FilterXmlObject or implement DelegateXmlObject"); + } + + public final XmlObject copy() { + if (preCheck()) { + return _copy(); + } else { + synchronized (monitor()) { + return _copy(); + } + } + } + + public final XmlObject copy(XmlOptions options) { + if (preCheck()) { + return _copy(options); + } else { + synchronized (monitor()) { + return _copy(options); + } + } + } + + private boolean preCheck() { +// if ( isImmutable() ) +// return true; + if (has_store()) { + return get_store().get_locale().noSync(); + } + return false; + } + + /** + * Same as copy() but unsynchronized. + * Warning: Using this method in mutithreaded environment can cause invalid states. + */ + public final XmlObject _copy() { + return _copy(null); + } + + /** + * Same as copy() but unsynchronized. + * If Locale.COPY_USE_NEW_LOCALE is set in the options, a new locale will be created for the copy. + * Warning: Using this method in mutithreaded environment can cause invalid states. + */ + public final XmlObject _copy(XmlOptions xmlOptions) { + // immutable objects don't get copied. They're immutable + if (isImmutable()) { + return this; + } + + check_orphaned(); + + SchemaTypeLoader stl = get_store().get_schematypeloader(); + + return (XmlObject) get_store().copy(stl, schemaType(), xmlOptions); + } + + public XmlDocumentProperties documentProperties() { + XmlCursor cur = newCursorForce(); + try { + return cur.documentProperties(); + } finally { + cur.dispose(); + } + } + + public XMLStreamReader newXMLStreamReader() { + return newXMLStreamReader(null); + } + + public XMLStreamReader newXMLStreamReader(XmlOptions options) { + XmlCursor cur = newCursorForce(); + try { + return cur.newXMLStreamReader(makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public InputStream newInputStream() { + return newInputStream(null); + } + + public InputStream newInputStream(XmlOptions options) { + XmlCursor cur = newCursorForce(); + try { + return cur.newInputStream(makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public Reader newReader() { + return newReader(null); + } + + public Reader newReader(XmlOptions options) { + XmlCursor cur = newCursorForce(); + try { + return cur.newReader(makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public Node getDomNode() { + XmlCursor cur = newCursorForce(); + try { + return cur.getDomNode(); + } finally { + cur.dispose(); + } + } + + public Node newDomNode() { + return newDomNode(null); + } + + public Node newDomNode(XmlOptions options) { + XmlCursor cur = newCursorForce(); + try { + return cur.newDomNode(makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException { + XmlCursor cur = newCursorForce(); + try { + cur.save(ch, lh, makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public void save(File file, XmlOptions options) throws IOException { + XmlCursor cur = newCursorForce(); + try { + cur.save(file, makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public void save(OutputStream os, XmlOptions options) throws IOException { + XmlCursor cur = newCursorForce(); + try { + cur.save(os, makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public void save(Writer w, XmlOptions options) throws IOException { + XmlCursor cur = newCursorForce(); + try { + cur.save(w, makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + public void save(ContentHandler ch, LexicalHandler lh) throws SAXException { + save(ch, lh, null); + } + + public void save(File file) throws IOException { + save(file, null); + } + + public void save(OutputStream os) throws IOException { + save(os, null); + } + + public void save(Writer w) throws IOException { + save(w, null); + } + + public void dump() { + XmlCursor cur = newCursorForce(); + try { + cur.dump(); + } finally { + cur.dispose(); + } + } + + public XmlCursor newCursorForce() { + synchronized (monitor()) { + return ensureStore().newCursor(); + } + } + + private XmlObject ensureStore() { + if ((_flags & FLAG_STORE) != 0) { + return this; + } + + check_dated(); + + String value = + (_flags & FLAG_NIL) != 0 + ? "" + : compute_text(has_store() ? get_store() : null); + + XmlOptions options = new XmlOptions().setDocumentType(schemaType()); + + XmlObject x = XmlObject.Factory.newInstance(options); + + XmlCursor c = x.newCursor(); + c.toNextToken(); + c.insertChars(value); + + return x; + } + + private static XmlOptions makeInnerOptions(XmlOptions options) { + XmlOptions innerOptions = new XmlOptions(options); + innerOptions.setSaveInner(); + return innerOptions; + } + + public XmlCursor newCursor() { + if ((_flags & FLAG_STORE) == 0) { + throw new IllegalStateException("XML Value Objects cannot create cursors"); + } + + check_orphaned(); + + // Note that new_cursor does not really need sync .... + + XmlLocale l = getXmlLocale(); + + if (l.noSync()) { + l.enter(); + try { + return get_store().new_cursor(); + } finally { + l.exit(); + } + } else { + synchronized (l) { + l.enter(); + try { + return get_store().new_cursor(); + } finally { + l.exit(); + } + } + } + + } + + public abstract SchemaType schemaType(); + + public SchemaType instanceType() { + synchronized (monitor()) { + return isNil() ? null : schemaType(); + } + } + + private SchemaField schemaField() { + SchemaType st = schemaType(); + SchemaField field; + + // First check if this field has an anonymous type + field = st.getContainerField(); + + if (field == null) { + field = get_store().get_schema_field(); + } + + return field; + } + + /** + * Use _voorVc when you want to throw a ValueOutOfRangeException when + * validating a simple type. + */ + private static final class ValueOutOfRangeValidationContext implements ValidationContext { + public void invalid(String message) { + throw new XmlValueOutOfRangeException(message); + } + + public void invalid(String code, Object[] args) { + throw new XmlValueOutOfRangeException(code, args); + } + } + + /** + * Used to supply validation context for the validate_value methods + */ + private static final class ImmutableValueValidationContext implements ValidationContext { + private final XmlObject _loc; + private final Collection _coll; + + ImmutableValueValidationContext(Collection coll, XmlObject loc) { + _coll = coll; + _loc = loc; + } + + public void invalid(String message) { + _coll.add(XmlError.forObject(message, _loc)); + } + + public void invalid(String code, Object[] args) { + _coll.add(XmlError.forObject(code, args, _loc)); + } + } + + public static final ValidationContext _voorVc = new ValueOutOfRangeValidationContext(); + + public boolean validate() { + return validate(null); + } + + public boolean validate(XmlOptions options) { + if ((_flags & FLAG_STORE) == 0) { + if ((_flags & FLAG_IMMUTABLE) != 0) { + return validate_immutable(options); + } + + throw new IllegalStateException( + "XML objects with no underlying store cannot be validated"); + } + + synchronized (monitor()) { + if ((_flags & FLAG_ORPHANED) != 0) { + throw new XmlValueDisconnectedException(); + } + + SchemaField field = schemaField(); + SchemaType type = schemaType(); + + TypeStore typeStore = get_store(); + + Validator validator = + new Validator( + type, field, typeStore.get_schematypeloader(), options, null); + + typeStore.validate(validator); + + return validator.isValid(); + } + } + + private boolean validate_immutable(XmlOptions options) { + Collection errorListener = options == null ? null : options.getErrorListener(); + XmlErrorWatcher watcher = new XmlErrorWatcher(errorListener); + if (!(schemaType().isSimpleType() || options != null && + options.isValidateTextOnly())) { + // cannot have any required attributes or elements + SchemaProperty[] properties = schemaType().getProperties(); + for (SchemaProperty property : properties) { + if (property.getMinOccurs().signum() > 0) { + // KHK: error code? + if (property.isAttribute()) { + watcher.add(XmlError.forObject(XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_REQUIRED_ATTRIBUTE, new Object[]{QNameHelper.pretty(property.getName()),}, this)); + } else { + watcher.add(XmlError.forObject(XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_ELEMENT, new Object[]{property.getMinOccurs(), QNameHelper.pretty(property.getName()),}, this)); + } + } + } + + if (schemaType().getContentType() != SchemaType.SIMPLE_CONTENT) { + return !watcher.hasError(); // don't validate non-simple-content + } + } + + String text = (String) _textsource; + if (text == null) { + text = ""; + } + validate_simpleval(text, new ImmutableValueValidationContext(watcher, this)); + return !watcher.hasError(); + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + } + + private static XmlObject[] _typedArray(XmlObject[] input) { + if (input.length == 0) { + return input; + } + SchemaType commonType = input[0].schemaType(); + if (commonType.equals(XmlObject.type) || commonType.isNoType()) { + return input; + } + for (int i = 1; i < input.length; i++) { + if (input[i].schemaType().isNoType()) { + return input; + } + commonType = commonType.getCommonBaseType(input[i].schemaType()); + if (commonType.equals(XmlObject.type)) { + return input; + } + } + Class desiredClass = commonType.getJavaClass(); + while (desiredClass == null) { + commonType = commonType.getBaseType(); + if (XmlObject.type.equals(commonType)) { + return input; + } + desiredClass = commonType.getJavaClass(); + } + + XmlObject[] result = (XmlObject[]) Array.newInstance(desiredClass, input.length); + System.arraycopy(input, 0, result, 0, input.length); + return result; + } + + public XmlObject[] selectPath(String path) { + return selectPath(path, null); + } + + public XmlObject[] selectPath(String path, XmlOptions options) { + XmlObject[] selections; + + // all user-level code; doesn't need to be synchronized + + XmlCursor c = newCursor(); + + if (c == null) { + throw new XmlValueDisconnectedException(); + } + + try { + c.selectPath(path, options); + + if (!c.hasNextSelection()) { + selections = EMPTY_RESULT; + } else { + selections = new XmlObject[c.getSelectionCount()]; + + for (int i = 0; c.toNextSelection(); i++) { + if ((selections[i] = c.getObject()) == null) { + if (!c.toParent() || (selections[i] = c.getObject()) == null) { + throw + new XmlRuntimeException( + "Path must select only elements " + + "and attributes"); + } + } + } + } + } finally { + c.dispose(); + } + + return _typedArray(selections); + } + + public XmlObject[] execQuery(String path) { + return execQuery(path, null); + } + + public XmlObject[] execQuery(String queryExpr, XmlOptions options) { + synchronized (monitor()) { + TypeStore typeStore = get_store(); + + if (typeStore == null) { + throw + new XmlRuntimeException( + "Cannot do XQuery on XML Value Objects"); + } + return _typedArray(typeStore.exec_query(queryExpr, options)); + } + } + + public XmlObject changeType(SchemaType type) { + if (type == null) { + throw new IllegalArgumentException("Invalid type (null)"); + } + + if ((_flags & FLAG_STORE) == 0) { + throw + new IllegalStateException( + "XML Value Objects cannot have thier type changed"); + } + + synchronized (monitor()) { + check_orphaned(); + return (XmlObject) get_store().change_type(type); + } + } + + public XmlObject substitute(QName name, SchemaType type) { + if (name == null) { + throw new IllegalArgumentException("Invalid name (null)"); + } + + if (type == null) { + throw new IllegalArgumentException("Invalid type (null)"); + } + + if ((_flags & FLAG_STORE) == 0) { + throw + new IllegalStateException( + "XML Value Objects cannot be used with substitution"); + } + + synchronized (monitor()) { + check_orphaned(); + return (XmlObject) get_store().substitute(name, type); + } + } + + private int _flags; + private Object _textsource; + + protected XmlObjectBase() { + _flags = FLAG_NILLABLE | FLAG_NIL; + } + + public void init_flags(SchemaProperty prop) { + if (prop == null) { + return; + } + + if (prop.hasDefault() == SchemaProperty.VARIABLE || + prop.hasFixed() == SchemaProperty.VARIABLE || + prop.hasNillable() == SchemaProperty.VARIABLE) { + return; + } + + _flags &= ~FLAGS_ELEMENT; + _flags |= + (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | + (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED) | + (prop.hasNillable() == SchemaProperty.NEVER ? 0 : TypeStore.NILLABLE) | + (FLAG_NOT_VARIABLE); + } + + private static final int FLAG_NILLABLE = TypeStore.NILLABLE; + private static final int FLAG_HASDEFAULT = TypeStore.HASDEFAULT; + private static final int FLAG_FIXED = TypeStore.FIXED; + private static final int FLAG_ATTRIBUTE = 8; + private static final int FLAG_STORE = 16; + private static final int FLAG_VALUE_DATED = 32; + private static final int FLAG_NIL = 64; + private static final int FLAG_NIL_DATED = 128; + private static final int FLAG_ISDEFAULT = 256; + private static final int FLAG_ELEMENT_DATED = 512; + private static final int FLAG_SETTINGDEFAULT = 1024; + private static final int FLAG_ORPHANED = 2048; + private static final int FLAG_IMMUTABLE = 4096; + private static final int FLAG_COMPLEXTYPE = 8192; + private static final int FLAG_COMPLEXCONTENT = 16384; + private static final int FLAG_NOT_VARIABLE = 32768; + private static final int FLAG_VALIDATE_ON_SET = 65536; + + + /** + * The three dated flags are always stacked: + * FLAG_ELEMENT_DATED implies FLAG_NIL_DATED is set + * FLAG_NIL_DATED implies FLAG_TEXT_DATED is set. + * checkers work on the flags from top to bottom. + */ + private static final int FLAGS_DATED = + FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED; + + /** + * The three element status flags have one interrlationshiop: + * FLAG_FIXED implies FLAG_HASDEFAULT is set. + * These flags are used when setting nils, defaults, strings. + * Since an initial get implies setting from text, they're + * also used during getting. + */ + private static final int FLAGS_ELEMENT = + FLAG_NILLABLE | FLAG_FIXED | FLAG_HASDEFAULT; + + + /** + * Called by restriction subclasses within their constructors to enable + * complex type support. + */ + protected void initComplexType(boolean complexType, boolean complexContent) { + _flags |= (complexType ? FLAG_COMPLEXTYPE : 0) | + (complexContent ? FLAG_COMPLEXCONTENT : 0); + } + + protected boolean _isComplexType() { + return (_flags & FLAG_COMPLEXTYPE) != 0; + } + + protected boolean _isComplexContent() { + return (_flags & FLAG_COMPLEXCONTENT) != 0; + } + + public void setValidateOnSet() { + _flags |= FLAG_VALIDATE_ON_SET; + } + + protected boolean _validateOnSet() { + return (_flags & FLAG_VALIDATE_ON_SET) != 0; + } + + /** + * True if the value is nilled. + */ + public final boolean isNil() { + synchronized (monitor()) { + check_dated(); + return ((_flags & FLAG_NIL) != 0); + } + } + + /** + * True if the value is fixed. + */ + public final boolean isFixed() { + check_element_dated(); + return ((_flags & FLAG_FIXED) != 0); + } + + /** + * True if the value is allowed to be nil. + */ + public final boolean isNillable() { + check_element_dated(); + return ((_flags & FLAG_NILLABLE) != 0); + } + + /** + * True if the value is currently defaulted. + */ + public final boolean isDefaultable() { + check_element_dated(); + return ((_flags & FLAG_HASDEFAULT) != 0); + } + + /** + * True if the value is currently defaulted. + */ + public final boolean isDefault() { + check_dated(); + return ((_flags & FLAG_ISDEFAULT) != 0); + } + + + /** + * Nils the value. + */ + public final void setNil() { + synchronized (monitor()) { + set_prepare(); + + // if we're not nillable, throw exception on setNil(true) + if ((_flags & FLAG_NILLABLE) == 0 && + (_flags & FLAG_VALIDATE_ON_SET) != 0) { + throw new XmlValueNotNillableException(); + } + + // the implementation should zero the value to reflect nil + set_nil(); + + // set the nil flag + _flags |= FLAG_NIL; + + // ordinary commit except no clearing of nil flag + if ((_flags & FLAG_STORE) != 0) { + get_store().invalidate_text(); + _flags &= ~FLAGS_DATED; + get_store().invalidate_nil(); + } else { + _textsource = null; + } + } + } + + /** + * Used for situations where these flags must be passed on to + * chained values. (See XmlAnySimpleType (allSimpleValue), union + * implementations). + */ + protected int elementFlags() { + check_element_dated(); + return (_flags & FLAGS_ELEMENT); + } + + /** + * Used to make a free-standing xml simple value instance immutable. + * This is a one-way street, and it is illegal to attempt to make a + * value that is embedded in an xml document immutable. + *

      + * Once a value is marked as immutable, it is illegal to call setters + * of any kind. + */ + public void setImmutable() { + if ((_flags & (FLAG_IMMUTABLE | FLAG_STORE)) != 0) { + throw new IllegalStateException(); + } + + _flags |= FLAG_IMMUTABLE; + } + + /** + * Is this instance an immutable value? + */ + public boolean isImmutable() { + return (_flags & FLAG_IMMUTABLE) != 0; + } + + + // TEXTUSER implementation + + /** + * Called to initialize the TypeStore associated with this XmlObject + * implementation. If not called, this is a free-floating value holder. + *

      + * When a value is first attached, it is put in a completely invalidated + * state. + */ + public final void attach_store(TypeStore store) { + _textsource = store; + if ((_flags & FLAG_IMMUTABLE) != 0) { + throw new IllegalStateException(); + } + _flags |= FLAG_STORE | FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED; + + if (store.is_attribute()) { + _flags |= FLAG_ATTRIBUTE; + } + + if (store.validate_on_set()) { + _flags |= FLAG_VALIDATE_ON_SET; + } + } + + /** + * Called by a TypeStore to indicate that the text has been + * invalidated and should be fetched next time the value is + * needed. + */ + public final void invalidate_value() { + assert ((_flags & FLAG_STORE) != 0); + _flags |= FLAG_VALUE_DATED; + } + + public final boolean uses_invalidate_value() { + SchemaType type = schemaType(); + return type.isSimpleType() || type.getContentType() == SchemaType.SIMPLE_CONTENT; + } + + /** + * Called by a TypeStore to indicate that the xsi:nil attribute + * on the containing element (and possibly the text) has been + * invalidated and both should be consulted next time the value + * is needed. + */ + public final void invalidate_nilvalue() { + assert ((_flags & FLAG_STORE) != 0); + _flags |= FLAG_VALUE_DATED | FLAG_NIL_DATED; + } + + /** + * Called by a TypeStore to indicate that the element's default + * value, nillability, fixedness, etc, may have changed by + * virtue of the element order changing (and xsi:nil and the + * text may have changed too); so the store should be consulted + * next time any setter or getter is called. + */ + public final void invalidate_element_order() { + assert ((_flags & FLAG_STORE) != 0); + _flags |= FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED; + } + + /** + * Used by the ComplexTypeImpl subclass to get direct access + * to the store. + */ + public final TypeStore get_store() { + assert ((_flags & FLAG_STORE) != 0); + return (TypeStore) _textsource; + } + + public final XmlLocale getXmlLocale() { + return get_store().get_locale(); + } + + protected final boolean has_store() { + return (_flags & FLAG_STORE) != 0; + } + + /** + * Called by a TypeStore to pull out the most reasonable + * text value from us. This is done after we have invalidated + * the store (typically when our value has been set). + */ + public final String build_text(NamespaceManager nsm) { + assert ((_flags & FLAG_STORE) != 0); + assert ((_flags & FLAG_VALUE_DATED) == 0); + if ((_flags & (FLAG_NIL | FLAG_ISDEFAULT)) != 0) { + return ""; + } + return compute_text( + nsm == null ? has_store() ? get_store() : null : nsm); + } + + /** + * A store will call back on build_nil after we've called invalidate_nil + * and it needs to know what the nil value is. + */ + public boolean build_nil() { + assert ((_flags & FLAG_STORE) != 0); + assert ((_flags & FLAG_VALUE_DATED) == 0); + return (_flags & FLAG_NIL) != 0; + } + + /** + * A store will call back on validate_now to force us to look at + * the text if we're in an invalid state. We're allowed to throw + * an exception if the text isn't valid for our type. + */ + public void validate_now() { + check_dated(); + } + + /** + * A store calls back here in order to force a disconnect. + * After this is done, the object should be considered invalid. + * Any attempt to access or set a value should result in an + * exception. + *

      + * Note that this is how we handle deletions and xsi:type changes. + */ + public void disconnect_store() { + assert ((_flags & FLAG_STORE) != 0); + _flags |= FLAGS_DATED | FLAG_ORPHANED; + // do NOT null out _textsource, because we need it non-null for synchronization + } + + /** + * A typestore user can create a new TypeStoreUser instance for + * a given element child name as long as you also pass the + * qname contained by the xsi:type attribute, if any. + *

      + * Note that we will ignore the xsiType if it turns out to be invalid. + *

      + * Returns null if there is no strongly typed information for that + * given element (which implies, recusively, no strongly typed information + * downwards). + */ + public TypeStoreUser create_element_user(QName eltName, QName xsiType) { + return + (TypeStoreUser) + ((SchemaTypeImpl) schemaType()).createElementType( + eltName, xsiType, get_store().get_schematypeloader()); + + /* + SchemaTypeImpl stype = (SchemaTypeImpl)schemaType().getElementType(eltName, xsiType, get_store().get_schematypeloader()); + if (stype == null) + return null; + return (TypeStoreUser)stype.createUnattachedNode(); + */ + } + + /** + * A typestore user can create a new TypeStoreUser instance for + * a given attribute child, based on the attribute name. + *

      + * Returns null if there is no strongly typed information for that + * given attributes. + */ + public TypeStoreUser create_attribute_user(QName attrName) { + return (TypeStoreUser) ((SchemaTypeImpl) schemaType()).createAttributeType(attrName, get_store().get_schematypeloader()); + } + + public SchemaType get_schema_type() { + return schemaType(); + } + + public SchemaType get_element_type(QName eltName, QName xsiType) { + return schemaType().getElementType( + eltName, xsiType, get_store().get_schematypeloader()); + } + + public SchemaType get_attribute_type(QName attrName) { + return schemaType().getAttributeType( + attrName, get_store().get_schematypeloader()); + } + + /** + * Returns the default element text, if it's consistent. If it's + * not consistent, returns null, and requires a visitor walk. + *

      + * Also returns null if there is no default at all (although + * that can also be discovered via get_elementflags without + * doing a walk). + */ + public String get_default_element_text(QName eltName) { + assert (_isComplexContent()); + if (!_isComplexContent()) { + throw new IllegalStateException(); + } + + SchemaProperty prop = schemaType().getElementProperty(eltName); + if (prop == null) { + return ""; + } + return prop.getDefaultText(); + } + + /** + * Returns the default attribute text for the attribute with + * the given name, or null if no default. + */ + public String get_default_attribute_text(QName attrName) { + assert (_isComplexType()); + if (!_isComplexType()) { + throw new IllegalStateException(); + } + + SchemaProperty prop = schemaType().getAttributeProperty(attrName); + if (prop == null) { + return ""; + } + return prop.getDefaultText(); + } + + /** + * Returns the elementflags, if they're consistent. If they're + * not, returns -1, and requires a vistor walk. + */ + public int get_elementflags(QName eltName) { + if (!_isComplexContent()) { + return 0; + } + + SchemaProperty prop = schemaType().getElementProperty(eltName); + if (prop == null) { + return 0; + } + if (prop.hasDefault() == SchemaProperty.VARIABLE || + prop.hasFixed() == SchemaProperty.VARIABLE || + prop.hasNillable() == SchemaProperty.VARIABLE) { + return -1; + } + return + (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | + (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED) | + (prop.hasNillable() == SchemaProperty.NEVER ? 0 : TypeStore.NILLABLE); + } + + /** + * Returns the flags for the given attribute. + */ + public int get_attributeflags(QName attrName) { + if (!_isComplexType()) { + return 0; + } + SchemaProperty prop = schemaType().getAttributeProperty(attrName); + if (prop == null) { + return 0; + } + return + (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | + (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED); + // BUGBUG: todo: hook up required? + } + + /** + * Returns false if child elements are insensitive to order; + * if it returns true, you're required to call invalidate_element_order + * on children to the right of any child order rearrangement. + */ + public boolean is_child_element_order_sensitive() { + if (!_isComplexType()) { + return false; + } + return schemaType().isOrderSensitive(); + } + + /** + * Inserting a new element is always unambiguous except in one + * situation: when adding an element after the last one with + * that name (or the first one if there are none). + *

      + * In that case, add the element at the first possible slot + * BEFORE any element whose qname is contained in the QNameSet + * given. (If the QNameSet is empty, that means add the new + * element at the very end.) + *

      + * If the returned QNameSet is null, treat it as if the QNameSet + * contained all QNames, i.e., add the new element at the very + * first position possible (adjacent to the last element of the + * same name, or at the very first slot if it is the first elt + * with that name). + */ + public final QNameSet get_element_ending_delimiters(QName eltname) { + SchemaProperty prop = schemaType().getElementProperty(eltname); + if (prop == null) { + return null; + } + return prop.getJavaSetterDelimiter(); + } + + /** + * A typestore user can return a visitor that is used to compute + * default text and elementflags for an arbitrary element. + */ + public TypeStoreVisitor new_visitor() { + if (!_isComplexContent()) { + return null; + } + return new SchemaTypeVisitorImpl(schemaType().getContentModel()); + } + + public SchemaField get_attribute_field(QName attrName) { + SchemaAttributeModel model = schemaType().getAttributeModel(); + if (model == null) { + return null; + } + return model.getAttribute(attrName); + } + + + /** + * Setting a string preserves any noncanonical literal + * representation. This is done by storing the actual + * string in the underlying store after checking it + * against the primitive type for validity. + */ + protected void set_String(String v) { + if ((_flags & FLAG_IMMUTABLE) != 0) { + throw new IllegalStateException(); + } + + boolean wasNilled = ((_flags & FLAG_NIL) != 0); + + // update the underlying value from the string + String wscanon = apply_wscanon(v); + update_from_wscanon_text(wscanon); + + // Now store the literal text immediately in the underlying + if ((_flags & FLAG_STORE) != 0) { + _flags &= ~FLAG_VALUE_DATED; + if ((_flags & FLAG_SETTINGDEFAULT) == 0) { + get_store().store_text(v); + } + if (wasNilled) { + get_store().invalidate_nil(); + } + } else { + _textsource = v; + } + } + + /** + * Update the value based on complex content. + */ + protected void update_from_complex_content() { + throw new XmlValueNotSupportedException("Complex content"); + } + + /** + * Utility to update the value based on a string that + * was passed either from the text store or from the user. + * This function handles the cases where there is a default + * that must be applied, and where the value must match + * a fixed value. + */ + private void update_from_wscanon_text(String v) { + // Whitespace is default if this type treats this space as defaultable + if ((_flags & FLAG_HASDEFAULT) != 0 && (_flags & FLAG_SETTINGDEFAULT) == 0) { + // This isn't quite correct since the .equals("") test should be + // done on the actual text, not the wscanon text + if ((_flags & FLAG_ATTRIBUTE) == 0 && v.equals("")) { + String def = get_store().compute_default_text(); + if (def == null) { + throw new XmlValueOutOfRangeException(); + } + + // protect against recursion with this flag + _flags |= FLAG_SETTINGDEFAULT; + try { + this.setStringValue(def); + } finally { + _flags &= ~FLAG_SETTINGDEFAULT; + } + _flags &= ~FLAG_NIL; + _flags |= FLAG_ISDEFAULT; + return; + } + } + // If we haven't returned yet, the default doesn't apply. + + // Ask underlying impl to parse ordinary non-default text + set_text(v); + _flags &= ~(FLAG_NIL | FLAG_ISDEFAULT); + } + + /** + * Types should return false if they don't treat the given + * whitespace as a default value. + */ + protected boolean is_defaultable_ws(String v) { + return true; + } + + /** + * Returns the whitespace rule that will be applied before + * building a string to pass to get_text(). + *

      + * Overridden by subclasses that don't need their text + * for set_text canonicalized; perhaps they already implement + * scanners that can deal with whitespace, and they know + * they have no regex pattern restrictions. + */ + protected int get_wscanon_rule() { + return SchemaType.WS_COLLAPSE; + } + + /** + * Called to canonicalize whitespace before calling set_text. + *

      + * Tries to avoid allocation when the string is already canonical, but + * otherwise this is not particularly efficient. Hopefully the common + * case is that we pass our wscanon rule to the store via fetch_text + * and it's canonicalized before we even see it as a string. + */ + private String apply_wscanon(String v) { + return XmlWhitespace.collapse(v, get_wscanon_rule()); + } + + /** + * Called before every set and get, to ensure that we have + * a correct picture of whether we're nillable, fixed, or + * if we have a default that can be applied. + */ + private void check_element_dated() { + if ((_flags & FLAG_ELEMENT_DATED) != 0 && + (_flags & FLAG_NOT_VARIABLE) == 0) { + if ((_flags & FLAG_ORPHANED) != 0) { + throw new XmlValueDisconnectedException(); + } + + int eltflags = get_store().compute_flags(); + // int eltflags = 0; + _flags &= ~(FLAGS_ELEMENT | FLAG_ELEMENT_DATED); + _flags |= eltflags; + } + if ((_flags & FLAG_NOT_VARIABLE) != 0) { + _flags &= ~(FLAG_ELEMENT_DATED); + } + } + + /** + * Describes the orphaned status of this object. + */ + protected final boolean is_orphaned() { + return (_flags & FLAG_ORPHANED) != 0; + } + + /** + * Called before every getter and setter on the strongly + * typed classes to ensure that the object has not been + * orphaned. + */ + protected final void check_orphaned() { + if (is_orphaned()) { + throw new XmlValueDisconnectedException(); + } + } + + /** + * Called prior to every get operation, to ensure + * that the value being read is valid. If the value + * has been invalidated, it is re-read from the underlying + * text store, and this may cause an out of range exception. + *

      + * This method deals with nils, nillability, defaults, etc. + */ + public final void check_dated() { + if ((_flags & FLAGS_DATED) != 0) { + if ((_flags & FLAG_ORPHANED) != 0) { + throw new XmlValueDisconnectedException(); + } + + assert ((_flags & FLAG_STORE) != 0); + + check_element_dated(); + + if ((_flags & FLAG_ELEMENT_DATED) != 0) { + int eltflags = get_store().compute_flags(); + _flags &= ~(FLAGS_ELEMENT | FLAG_ELEMENT_DATED); + _flags |= eltflags; + } + + boolean nilled = false; + + if ((_flags & FLAG_NIL_DATED) != 0) { + if (get_store().find_nil()) { + if ((_flags & FLAG_NILLABLE) == 0 && + (_flags & FLAG_VALIDATE_ON_SET) != 0) { + throw new XmlValueOutOfRangeException(); // nil not allowed + } + + // let the implementation know that we're nil now + set_nil(); + + _flags |= FLAG_NIL; + nilled = true; + } else { + _flags &= ~FLAG_NIL; + } + _flags &= ~FLAG_NIL_DATED; + } + + if (!nilled) { + String text; + + if ((_flags & FLAG_COMPLEXCONTENT) != 0 || (text = get_wscanon_text()) == null) { + update_from_complex_content(); + } else { + NamespaceContext.push(new NamespaceContext(get_store())); + try { + update_from_wscanon_text(text); + } finally { + NamespaceContext.pop(); + } + } + } + + _flags &= ~FLAG_VALUE_DATED; + } + } + + /** + * Called before every set operation (except for the + * special case of setting a string) to: + * (1) get the nillable, fixed, etc flags + * (2) throw an exception if it's fixed (not for strings) + */ + private void set_prepare() { + check_element_dated(); + if ((_flags & FLAG_IMMUTABLE) != 0) { + throw new IllegalStateException(); + } + } + + /** + * Called after every set operation to invalidate + * the attached raw text. Also, if we were dated, + * we make a note that we're now current, since the + * latest set beats the previous invalidate. Also, + * if we were nil, we're no longer. + */ + private void set_commit() { + boolean wasNilled = ((_flags & FLAG_NIL) != 0); + _flags &= ~(FLAG_NIL | FLAG_ISDEFAULT); + + if ((_flags & FLAG_STORE) != 0) { + _flags &= ~(FLAGS_DATED); + get_store().invalidate_text(); + if (wasNilled) { + get_store().invalidate_nil(); + } + } else { + _textsource = null; + } + } + + /** + * Grabs the undelying litral representation, applying the + * implementation's wscanon rule. + * Null if not simple content. + */ + public final String get_wscanon_text() { + if ((_flags & FLAG_STORE) == 0) { + return apply_wscanon((String) _textsource); + } else { + return get_store().fetch_text(get_wscanon_rule()); + } + } + + /** + * This should set the value of the type from text, + * or throw an XmlValueOutOfRangeException if it can't. + */ + abstract protected void set_text(String text); + + /** + * This should clear the value, and set it to whatever + * is supposed to be returned when the value is nilled. + */ + abstract protected void set_nil(); + + /** + * This should return the canonical string value of the primitive. + * Only called when non-nil. + */ + abstract protected String compute_text(NamespaceManager nsm); + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + + // numerics: fractional + public float getFloatValue() { + BigDecimal bd = getBigDecimalValue(); + return bd == null ? 0.0f : bd.floatValue(); + } + + public double getDoubleValue() { + BigDecimal bd = getBigDecimalValue(); + return bd == null ? 0.0 : bd.doubleValue(); + } + + public BigDecimal getBigDecimalValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "numeric"}); + } + + // numerics: integral + public BigInteger getBigIntegerValue() { + BigDecimal bd = getBigDecimalValue(); + return bd == null ? null : bd.toBigInteger(); + } + + public byte getByteValue() { + long l = getIntValue(); + if (l > Byte.MAX_VALUE) { + throw new XmlValueOutOfRangeException(); + } + if (l < Byte.MIN_VALUE) { + throw new XmlValueOutOfRangeException(); + } + return (byte) l; + } + + public short getShortValue() { + long l = getIntValue(); + if (l > Short.MAX_VALUE) { + throw new XmlValueOutOfRangeException(); + } + if (l < Short.MIN_VALUE) { + throw new XmlValueOutOfRangeException(); + } + return (short) l; + } + + public int getIntValue() { + long l = getLongValue(); + if (l > Integer.MAX_VALUE) { + throw new XmlValueOutOfRangeException(); + } + if (l < Integer.MIN_VALUE) { + throw new XmlValueOutOfRangeException(); + } + return (int) l; + } + + private static final BigInteger _max = BigInteger.valueOf(Long.MAX_VALUE); + private static final BigInteger _min = BigInteger.valueOf(Long.MIN_VALUE); + + public long getLongValue() { + BigInteger b = getBigIntegerValue(); + if (b == null) { + return 0L; + } + if (b.compareTo(_max) >= 0) { + throw new XmlValueOutOfRangeException(); + } + if (b.compareTo(_min) <= 0) { + throw new XmlValueOutOfRangeException(); + } + return b.longValue(); + } + + private static final XmlOptions _toStringOptions = + buildInnerPrettyOptions(); + + static XmlOptions buildInnerPrettyOptions() { + XmlOptions options = new XmlOptions(); + options.setSaveInner(); + options.setSavePrettyPrint(); + options.setSaveAggressiveNamespaces(); + options.setUseDefaultNamespace(); + + return options; + } + + /* + private static final void dumpStack ( String msg ) + { + try + { + java.io.FileOutputStream fos = new java.io.FileOutputStream( "C:\\ee.txt", true ); + java.io.PrintStream ps = new java.io.PrintStream( fos ); + ps.println( "======================================" ); + ps.println( msg ); + new Exception().printStackTrace( ps ); + ps.close(); + fos.close(); + } + catch ( Exception e ) + { + } + + } + */ + + public final String toString() { + synchronized (monitor()) { + return ensureStore().xmlText(_toStringOptions); + } + } + + public String xmlText() { + return xmlText(null); + } + + public String xmlText(XmlOptions options) { + XmlCursor cur = newCursorForce(); + + try { + return cur.xmlText(makeInnerOptions(options)); + } finally { + cur.dispose(); + } + } + + // enums + public StringEnumAbstractBase getEnumValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "enum"}); + } + + // various + public String getStringValue() { + if (isImmutable()) { + if ((_flags & FLAG_NIL) != 0) { + return null; + } + return compute_text(null); + } + // Since complex-content types don't have a "natural" string value, we + // emit the deeply concatenated, tag-removed content of the tag. + synchronized (monitor()) { + if (_isComplexContent()) { + return get_store().fetch_text(TypeStore.WS_PRESERVE); + } + + check_dated(); + if ((_flags & FLAG_NIL) != 0) { + return null; + } + return compute_text(has_store() ? get_store() : null); + } + } + + public byte[] getByteArrayValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "byte[]"}); + } + + public boolean getBooleanValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "boolean"}); + } + + public GDate getGDateValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "Date"}); + } + + public Date getDateValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "Date"}); + } + + public Calendar getCalendarValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "Calendar"}); + } + + public GDuration getGDurationValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "Duration"}); + } + + public QName getQNameValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "QName"}); + } + + public List getListValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "List"}); + } + + public List xgetListValue() { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, + new Object[]{getPrimitiveTypeName(), "List"}); + } + + public Object getObjectValue() { + return java_value(this); + } + + // set this value + public final void setBooleanValue(boolean v) { + synchronized (monitor()) { + set_prepare(); + set_boolean(v); + set_commit(); + } + } + + public final void setByteValue(byte v) { + synchronized (monitor()) { + set_prepare(); + set_byte(v); + set_commit(); + } + } + + public final void setShortValue(short v) { + synchronized (monitor()) { + set_prepare(); + set_short(v); + set_commit(); + } + } + + public final void setIntValue(int v) { + synchronized (monitor()) { + set_prepare(); + set_int(v); + set_commit(); + } + } + + public final void setLongValue(long v) { + synchronized (monitor()) { + set_prepare(); + set_long(v); + set_commit(); + } + } + + public final void setFloatValue(float v) { + synchronized (monitor()) { + set_prepare(); + set_float(v); + set_commit(); + } + } + + public final void setDoubleValue(double v) { + synchronized (monitor()) { + set_prepare(); + set_double(v); + set_commit(); + } + } + + public final void setByteArrayValue(byte[] obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_ByteArray(obj); + set_commit(); + } + } + } + + public final void setEnumValue(StringEnumAbstractBase obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_enum(obj); + set_commit(); + } + } + } + + public final void setBigIntegerValue(BigInteger obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_BigInteger(obj); + set_commit(); + } + } + } + + public final void setBigDecimalValue(BigDecimal obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_BigDecimal(obj); + set_commit(); + } + } + } + + public final void setCalendarValue(Calendar obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_Calendar(obj); + set_commit(); + } + } + } + + public final void setDateValue(Date obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_Date(obj); + set_commit(); + } + } + } + + public final void setGDateValue(GDate obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_GDate(obj); + set_commit(); + } + } + } + + public final void setGDateValue(GDateSpecification obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_GDate(obj); + set_commit(); + } + } + } + + public final void setGDurationValue(GDuration obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_GDuration(obj); + set_commit(); + } + } + } + + public final void setGDurationValue(GDurationSpecification obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_GDuration(obj); + set_commit(); + } + } + } + + public final void setQNameValue(QName obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_QName(obj); + set_commit(); + } + } + } + + public final void setListValue(List obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_list(obj); + set_commit(); + } + } + } + + public final void setStringValue(String obj) { + if (obj == null) { + setNil(); + } else { + synchronized (monitor()) { + set_prepare(); + set_String(obj); /* strings are special, so set_String does its own commit.*/ + } + } + } + + public void setObjectValue(Object o) { + if (o == null) { + setNil(); + return; + } + + if (o instanceof XmlObject) { + set((XmlObject) o); + } else if (o instanceof String) { + setStringValue((String) o); + } else if (o instanceof StringEnumAbstractBase) { + setEnumValue((StringEnumAbstractBase) o); + } else if (o instanceof BigInteger) { + setBigIntegerValue((BigInteger) o); + } else if (o instanceof BigDecimal) { + setBigDecimalValue((BigDecimal) o); + } else if (o instanceof Byte) { + setByteValue((Byte) o); + } else if (o instanceof Short) { + setShortValue((Short) o); + } else if (o instanceof Integer) { + setIntValue((Integer) o); + } else if (o instanceof Long) { + setLongValue((Long) o); + } else if (o instanceof Boolean) { + setBooleanValue((Boolean) o); + } else if (o instanceof Float) { + setFloatValue((Float) o); + } else if (o instanceof Double) { + setDoubleValue((Double) o); + } else if (o instanceof Calendar) { + setCalendarValue(((Calendar) o)); + } else if (o instanceof Date) { + setDateValue((Date) o); + } else if (o instanceof GDateSpecification) { + setGDateValue((GDateSpecification) o); + } else if (o instanceof GDurationSpecification) { + setGDurationValue((GDurationSpecification) o); + } else if (o instanceof QName) { + setQNameValue((QName) o); + } else if (o instanceof List) { + setListValue((List) o); + } else if (o instanceof byte[]) { + setByteArrayValue((byte[]) o); + } else { + throw + new XmlValueNotSupportedException( + "Can't set union object of class : " + + o.getClass().getName()); + } + } + + public final void set_newValue(XmlObject obj) { + if (obj == null || obj.isNil()) { + setNil(); + return; + } + + primitive: + if (obj instanceof XmlAnySimpleType) { + XmlAnySimpleType v = (XmlAnySimpleType) obj; + SchemaType instanceType = ((SimpleValue) v).instanceType(); + assert (instanceType != null) : "Nil case should have been handled already"; + + // handle lists + if (instanceType.getSimpleVariety() == SchemaType.LIST) { + synchronized (monitor()) { + set_prepare(); + set_list(((SimpleValue) v).xgetListValue()); + set_commit(); + return; + } + } + + // handle atomic types + synchronized (monitor()) { + assert (instanceType.getSimpleVariety() == SchemaType.ATOMIC); + switch (instanceType.getPrimitiveType().getBuiltinTypeCode()) { + default: + assert (false) : "encountered nonprimitive type."; + // case SchemaType.BTC_ANY_SIMPLE: This is handled below... + // but we eventually want to handle it with a treecopy, so + // eventually we should break here. + break primitive; + + case SchemaType.BTC_BOOLEAN: { + boolean bool = ((SimpleValue) v).getBooleanValue(); + set_prepare(); + set_boolean(bool); + break; + } + case SchemaType.BTC_BASE_64_BINARY: { + byte[] byteArr = ((SimpleValue) v).getByteArrayValue(); + set_prepare(); + set_b64(byteArr); + break; + } + case SchemaType.BTC_HEX_BINARY: { + byte[] byteArr = ((SimpleValue) v).getByteArrayValue(); + set_prepare(); + set_hex(byteArr); + break; + } + case SchemaType.BTC_QNAME: { + QName name = ((SimpleValue) v).getQNameValue(); + set_prepare(); + set_QName(name); + break; + } + case SchemaType.BTC_FLOAT: { + float f = ((SimpleValue) v).getFloatValue(); + set_prepare(); + set_float(f); + break; + } + case SchemaType.BTC_DOUBLE: { + double d = ((SimpleValue) v).getDoubleValue(); + set_prepare(); + set_double(d); + break; + } + case SchemaType.BTC_DECIMAL: { + switch (instanceType.getDecimalSize()) { + case SchemaType.SIZE_BYTE: { + byte b = ((SimpleValue) v).getByteValue(); + set_prepare(); + set_byte(b); + break; + } + case SchemaType.SIZE_SHORT: { + short s = ((SimpleValue) v).getShortValue(); + set_prepare(); + set_short(s); + break; + } + case SchemaType.SIZE_INT: { + int i = ((SimpleValue) v).getIntValue(); + set_prepare(); + set_int(i); + break; + } + case SchemaType.SIZE_LONG: { + long l = ((SimpleValue) v).getLongValue(); + set_prepare(); + set_long(l); + break; + } + case SchemaType.SIZE_BIG_INTEGER: { + BigInteger bi = ((SimpleValue) v).getBigIntegerValue(); + set_prepare(); + set_BigInteger(bi); + break; + } + default: { + assert (false) : "invalid numeric bit count"; + // fallthrough + } + case SchemaType.SIZE_BIG_DECIMAL: { + BigDecimal bd = ((SimpleValue) v).getBigDecimalValue(); + set_prepare(); + set_BigDecimal(bd); + break; + } + } + break; + } + case SchemaType.BTC_ANY_URI: { + String uri = v.getStringValue(); + set_prepare(); + set_text(uri); + break; + } + case SchemaType.BTC_NOTATION: { + String s = v.getStringValue(); + set_prepare(); + set_notation(s); + break; + } + case SchemaType.BTC_DURATION: { + GDuration gd = ((SimpleValue) v).getGDurationValue(); + set_prepare(); + set_GDuration(gd); + break; + } + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: { + GDate gd = ((SimpleValue) v).getGDateValue(); + set_prepare(); + set_GDate(gd); + break; + } + case SchemaType.BTC_STRING: { + String s = v.getStringValue(); + set_prepare(); + set_String(s); + break; + } + case SchemaType.BTC_ANY_SIMPLE: { + boolean pushed = false; + if (!v.isImmutable()) { + pushed = true; + NamespaceContext.push(new NamespaceContext(v)); + } + try { + set_prepare(); + set_xmlanysimple(v); + } finally { + if (pushed) { + NamespaceContext.pop(); + } + } + break; + } + } + set_commit(); + return; // primitive node tree copy handled. + } + } + + throw new IllegalStateException("Complex type unexpected"); + } + + private TypeStoreUser setterHelper(XmlObjectBase src) { + check_orphaned(); + + src.check_orphaned(); + + return + get_store().copy_contents_from(src.get_store()). + get_store().change_type(src.schemaType()); + } + + public final XmlObject set(XmlObject src) { + if (isImmutable()) { + throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); + } + + XmlObjectBase obj = underlying(src); + + TypeStoreUser newObj = this; + + if (obj == null) { + setNil(); + return this; + } + + if (obj.isImmutable()) { + setStringValue(obj.getStringValue()); + } else { + boolean noSyncThis = preCheck(); + boolean noSyncObj = obj.preCheck(); + + if (monitor() == obj.monitor()) // both are in the same locale + { + if (noSyncThis) // the locale is not sync + { + newObj = setterHelper(obj); + } else // the locale is sync + { + synchronized (monitor()) { + newObj = setterHelper(obj); + } + } + } else // on different locale's + { + if (noSyncThis) { + if (noSyncObj) // both unsync + { + newObj = setterHelper(obj); + } else // only obj is sync + { + synchronized (obj.monitor()) { + newObj = setterHelper(obj); + } + } + } else { + if (noSyncObj) // only this is sync + { + synchronized (monitor()) { + newObj = setterHelper(obj); + } + } else // both are sync can't avoid the global lock + { + boolean acquired = false; + + try { + // about to grab two locks: don't deadlock ourselves + GlobalLock.acquire(); + acquired = true; + + synchronized (monitor()) { + synchronized (obj.monitor()) { + GlobalLock.release(); + acquired = false; + + newObj = setterHelper(obj); + } + } + } catch (InterruptedException e) { + throw new XmlRuntimeException(e); + } finally { + if (acquired) { + GlobalLock.release(); + } + } + } + } + } + } + + return (XmlObject) newObj; + } + + public final XmlObject generatedSetterHelperImpl(XmlObject src, QName propName, int index, + short kindSetterHelper) { + + XmlObjectBase srcObj = underlying(src); + + if (srcObj == null) { + synchronized (monitor()) { + XmlObjectBase target = getTargetForSetter(propName, index, kindSetterHelper); + target.setNil(); + return target; + } + } + + if (srcObj.isImmutable()) { + synchronized (monitor()) { + XmlObjectBase target = getTargetForSetter(propName, index, kindSetterHelper); + target.setStringValue(srcObj.getStringValue()); + return target; + } + } + + + boolean noSyncThis = preCheck(); + boolean noSyncObj = srcObj.preCheck(); + + if (monitor() == srcObj.monitor()) { + // both are in the same locale + if (noSyncThis) { + // the locale is not sync + return (XmlObject) objSetterHelper(srcObj, propName, index, kindSetterHelper); + } else { + // the locale is sync + synchronized (monitor()) { + return (XmlObject) objSetterHelper(srcObj, propName, index, kindSetterHelper); + } + } + } + + if (noSyncThis) { + // on different locale's + if (noSyncObj) { + // both unsync + return (XmlObject) objSetterHelper(srcObj, propName, index, kindSetterHelper); + } else { + // only obj is sync + synchronized (srcObj.monitor()) { + return (XmlObject) objSetterHelper(srcObj, propName, index, kindSetterHelper); + } + } + } else { + if (noSyncObj) { + // only this is sync + synchronized (monitor()) { + return (XmlObject) objSetterHelper(srcObj, propName, index, kindSetterHelper); + } + } else { + // both are sync can't avoid the global lock + boolean acquired = false; + + try { + // about to grab two locks: don't deadlock ourselves + GlobalLock.acquire(); + acquired = true; + + synchronized (monitor()) { + synchronized (srcObj.monitor()) { + GlobalLock.release(); + acquired = false; + + return (XmlObject) objSetterHelper(srcObj, propName, index, kindSetterHelper); + } + } + } catch (InterruptedException e) { + throw new XmlRuntimeException(e); + } finally { + if (acquired) { + GlobalLock.release(); + } + } + } + } + } + + private TypeStoreUser objSetterHelper(XmlObjectBase srcObj, QName propName, int index, short kindSetterHelper) { + XmlObjectBase target = getTargetForSetter(propName, index, kindSetterHelper); + + target.check_orphaned(); + srcObj.check_orphaned(); + + return target.get_store().copy_contents_from(srcObj.get_store()). + get_store().change_type(srcObj.schemaType()); + } + + private XmlObjectBase getTargetForSetter(QName propName, int index, short kindSetterHelper) { + switch (kindSetterHelper) { + case KIND_SETTERHELPER_SINGLETON: { + check_orphaned(); + XmlObjectBase target; + target = (XmlObjectBase) get_store().find_element_user(propName, index); + if (target == null) { + target = (XmlObjectBase) get_store().add_element_user(propName); + } + + if (target.isImmutable()) { + throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); + } + + return target; + } + + case KIND_SETTERHELPER_ARRAYITEM: { + check_orphaned(); + XmlObjectBase target; + target = (XmlObjectBase) get_store().find_element_user(propName, index); + if (target == null) { + throw new IndexOutOfBoundsException(); + } + + if (target.isImmutable()) { + throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); + } + + return target; + } + + default: + throw new IllegalArgumentException("Unknown kindSetterHelper: " + kindSetterHelper); + } + } + + /** + * Same as set() but unsynchronized. + * Warning: Using this method in mutithreaded environment can cause invalid states. + */ + public final XmlObject _set(XmlObject src) { + if (isImmutable()) { + throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); + } + + XmlObjectBase obj = underlying(src); + + TypeStoreUser newObj = this; + + if (obj == null) { + setNil(); + return this; + } + + if (obj.isImmutable()) { + setStringValue(obj.getStringValue()); + } else { + check_orphaned(); + obj.check_orphaned(); + + newObj = get_store().copy_contents_from(obj.get_store()). + get_store().change_type(obj.schemaType()); + } + return (XmlObject) newObj; + } + + protected void set_list(List list) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"List", getPrimitiveTypeName()}); + } + + protected void set_boolean(boolean v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"boolean", getPrimitiveTypeName()}); + } + + protected void set_byte(byte v) { + set_int(v); + } + + protected void set_short(short v) { + set_int(v); + } + + protected void set_int(int v) { + set_long(v); + } + + protected void set_long(long v) { + set_BigInteger(BigInteger.valueOf(v)); + } + + protected void set_char(char v) { + set_String(Character.toString(v)); + } + + protected void set_float(float v) { + set_BigDecimal(new BigDecimal(v)); + } + + protected void set_double(double v) { + set_BigDecimal(new BigDecimal(v)); + } + + protected void set_enum(StringEnumAbstractBase e) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"enum", getPrimitiveTypeName()}); + } + + protected void set_ByteArray(byte[] b) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"byte[]", getPrimitiveTypeName()}); + } + + protected void set_b64(byte[] b) { + set_ByteArray(b); + } + + protected void set_hex(byte[] b) { + set_ByteArray(b); + } + + protected void set_BigInteger(BigInteger v) { + set_BigDecimal(new BigDecimal(v)); + } + + protected void set_BigDecimal(BigDecimal v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"numeric", getPrimitiveTypeName()}); + } + + protected void set_Date(Date v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"Date", getPrimitiveTypeName()}); + } + + protected void set_Calendar(Calendar v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"Calendar", getPrimitiveTypeName()}); + } + + protected void set_GDate(GDateSpecification v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"Date", getPrimitiveTypeName()}); + } + + protected void set_GDuration(GDurationSpecification v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"Duration", getPrimitiveTypeName()}); + } + + protected void set_ComplexXml(XmlObject v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"complex content", getPrimitiveTypeName()}); + } + + protected void set_QName(QName v) { + throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, + new Object[]{"QName", getPrimitiveTypeName()}); + } + + protected void set_notation(String v) { + throw new XmlValueNotSupportedException(); + } + + protected void set_xmlanysimple(XmlAnySimpleType v) { + set_String(v.getStringValue()); + } + + private String getPrimitiveTypeName() { + SchemaType type = schemaType(); + if (type.isNoType()) { + return "unknown"; + } + SchemaType t = type.getPrimitiveType(); + if (t == null) { + return "complex"; + } else { + return t.getName().getLocalPart(); + } + } + + private boolean comparable_value_spaces(SchemaType t1, SchemaType t2) { + assert (t1.getSimpleVariety() != SchemaType.UNION && t2.getSimpleVariety() != SchemaType.UNION); + + if (!t1.isSimpleType() && !t2.isSimpleType()) { + return (t1.getContentType() == t2.getContentType()); + } + + if (!t1.isSimpleType() || !t2.isSimpleType()) { + return false; + } + + if (t1.getSimpleVariety() == SchemaType.LIST && t2.getSimpleVariety() == SchemaType.LIST) { + return true; + } + + if (t1.getSimpleVariety() == SchemaType.LIST || t2.getSimpleVariety() == SchemaType.LIST) { + return false; + } + + return (t1.getPrimitiveType().equals(t2.getPrimitiveType())); + } + + private boolean valueEqualsImpl(XmlObject xmlobj) { + check_dated(); + + SchemaType typethis = instanceType(); + SchemaType typeother = ((SimpleValue) xmlobj).instanceType(); + + if (typethis == null && typeother == null) // detects nil + { + return true; + } + + if (typethis == null || typeother == null) { + return false; + } + + if (!comparable_value_spaces(typethis, typeother)) { + return false; + } + + if (xmlobj.schemaType().getSimpleVariety() == SchemaType.UNION) { + return (underlying(xmlobj)).equal_to(this); + } + + return equal_to(xmlobj); + } + + public final boolean valueEquals(XmlObject xmlobj) { + boolean acquired = false; + try { + if (isImmutable()) { + if (xmlobj.isImmutable()) { + return valueEqualsImpl(xmlobj); + } else { + synchronized (xmlobj.monitor()) { + return valueEqualsImpl(xmlobj); + } + } + } else { + if (xmlobj.isImmutable() || monitor() == xmlobj.monitor()) { + synchronized (monitor()) { + return valueEqualsImpl(xmlobj); + } + } else { + GlobalLock.acquire(); + acquired = true; + synchronized (monitor()) { + synchronized (xmlobj.monitor()) { + GlobalLock.release(); + acquired = false; + return valueEqualsImpl(xmlobj); + } + } + } + } + + } catch (InterruptedException e) { + throw new XmlRuntimeException(e); + } finally { + if (acquired) { + GlobalLock.release(); + } + } + } + + /** + * Implements Comparable. This compareTo is inconsistent with + * equals unless isImmutable() is true. + */ + public final int compareTo(Object obj) { + int result = compareValue((XmlObject) obj); // can throw ClassCast + if (result == 2) { + throw new ClassCastException(); + } + return result; + } + + /** + * Allowed to return 2 for incomparable. + */ + private int compareValueImpl(XmlObject xmlobj) { + SchemaType type1, type2; + + try { + type1 = instanceType(); + type2 = ((SimpleValue) xmlobj).instanceType(); + } catch (XmlValueOutOfRangeException e) { + return 2; + } + + if (type1 == null && type2 == null) { + return 0; + } + if (type1 == null || type2 == null) { + return 2; + } + + if (!type1.isSimpleType() || type1.isURType()) { + return 2; + } + + if (!type2.isSimpleType() || type2.isURType()) { + return 2; + } + + type1 = type1.getPrimitiveType(); + type2 = type2.getPrimitiveType(); + + // Different value spaces: different + if (type1.getBuiltinTypeCode() != type2.getBuiltinTypeCode()) { + return 2; + } + + // now we'll depend on our impl class to do the work + return compare_to(xmlobj); + } + + public final int compareValue(XmlObject xmlobj) { + if (xmlobj == null) { + return 2; + } + + boolean acquired = false; + try { + if (isImmutable()) { + if (xmlobj.isImmutable()) { + return compareValueImpl(xmlobj); + } else { + synchronized (xmlobj.monitor()) { + return compareValueImpl(xmlobj); + } + } + } else { + if (xmlobj.isImmutable() || monitor() == xmlobj.monitor()) { + synchronized (monitor()) { + return compareValueImpl(xmlobj); + } + } else { + GlobalLock.acquire(); + acquired = true; + synchronized (monitor()) { + synchronized (xmlobj.monitor()) { + GlobalLock.release(); + acquired = false; + return compareValueImpl(xmlobj); + } + } + } + } + + } catch (InterruptedException e) { + throw new XmlRuntimeException(e); + } finally { + if (acquired) { + GlobalLock.release(); + } + } + } + + /** + * This implementation of compare_to is allowed to do two + * unusual things: + * (1) it can assume that the xmlobj passed has a primitive + * type underlying the instance type that matches the + * current instance, and that neither is nil. + * (2) it is allowed to return 2 for "incomparable"; + * it should not throw an exception. + */ + protected int compare_to(XmlObject xmlobj) { + if (equal_to(xmlobj)) { + return 0; + } + return 2; + } + + protected abstract boolean equal_to(XmlObject xmlobj); + + protected abstract int value_hash_code(); + + public int valueHashCode() { + synchronized (monitor()) { + return value_hash_code(); + } + } + + + public boolean isInstanceOf(SchemaType type) { + SchemaType myType; + + if (type.getSimpleVariety() != SchemaType.UNION) { + for (myType = instanceType(); myType != null; myType = myType.getBaseType()) { + if (type == myType) { + return true; + } + } + } else { + Set ctypes = new HashSet<>(Arrays.asList(type.getUnionConstituentTypes())); + for (myType = instanceType(); myType != null; myType = myType.getBaseType()) { + if (ctypes.contains(myType)) { + return true; + } + } + } + return false; + } + + public final boolean equals(Object obj) { + if (!isImmutable()) { + return super.equals(obj); + } + + if (!(obj instanceof XmlObject)) { + return false; + } + + XmlObject xmlobj = (XmlObject) obj; + if (!xmlobj.isImmutable()) { + return false; + } + + return valueEquals(xmlobj); + } + + public final int hashCode() { + if (!isImmutable()) { + return super.hashCode(); + } + + synchronized (monitor()) { + if (isNil()) { + return 0; + } + + return value_hash_code(); + } + } + + private static final XmlObject[] EMPTY_RESULT = new XmlObject[0]; + + /** + * Selects the contents of the children elements with the given name. + */ + public XmlObject[] selectChildren(QName elementName) { + XmlCursor xc = this.newCursor(); + try { + if (!xc.isContainer()) { + return EMPTY_RESULT; + } + + List result = new ArrayList<>(); + + if (xc.toChild(elementName)) { + // look for elements + do { + result.add(xc.getObject()); + } + while (xc.toNextSibling(elementName)); + } + if (result.size() == 0) { + return EMPTY_RESULT; + } else { + return result.toArray(EMPTY_RESULT); + } + } finally { + xc.dispose(); + } + } + + /** + * Selects the contents of the children elements with the given name. + */ + public XmlObject[] selectChildren(String elementUri, String elementLocalName) { + return selectChildren(new QName(elementUri, elementLocalName)); + } + + /** + * Selects the contents of the children elements that are contained in the elementNameSet. + */ + public XmlObject[] selectChildren(QNameSet elementNameSet) { + if (elementNameSet == null) { + throw new IllegalArgumentException(); + } + + XmlCursor xc = this.newCursor(); + try { + if (!xc.isContainer()) { + return EMPTY_RESULT; + } + + List result = new ArrayList<>(); + + if (xc.toFirstChild()) { + // look for elements + do { + assert xc.isContainer(); + if (elementNameSet.contains(xc.getName())) { + result.add(xc.getObject()); + } + } + while (xc.toNextSibling()); + } + if (result.size() == 0) { + return EMPTY_RESULT; + } else { + return result.toArray(EMPTY_RESULT); + } + } finally { + xc.dispose(); + } + } + + /** + * Selects the content of the attribute with the given name. + */ + public XmlObject selectAttribute(QName attributeName) { + XmlCursor xc = this.newCursor(); + + try { + if (!xc.isContainer()) { + return null; + } + + if (xc.toFirstAttribute()) { + //look for attributes + do { + if (xc.getName().equals(attributeName)) { + return xc.getObject(); + } + } + while (xc.toNextAttribute()); + } + return null; + } finally { + xc.dispose(); + } + } + + /** + * Selects the content of the attribute with the given name. + */ + public XmlObject selectAttribute(String attributeUri, String attributeLocalName) { + return selectAttribute(new QName(attributeUri, attributeLocalName)); + } + + /** + * Selects the contents of the attributes that are contained in the elementNameSet. + */ + public XmlObject[] selectAttributes(QNameSet attributeNameSet) { + if (attributeNameSet == null) { + throw new IllegalArgumentException(); + } + + XmlCursor xc = this.newCursor(); + try { + if (!xc.isContainer()) { + return EMPTY_RESULT; + } + + List result = new ArrayList<>(); + + if (xc.toFirstAttribute()) { + //look for attributes + do { + if (attributeNameSet.contains(xc.getName())) { + result.add(xc.getObject()); + } + } + while (xc.toNextAttribute()); + } + + if (result.size() == 0) { + return EMPTY_RESULT; + } else { + return result.toArray(EMPTY_RESULT); + } + } finally { + xc.dispose(); + } + } + + /** + * This method can writeReplace either an unwrapped XmlObjectBase + * or an XBean proxy. A "true" argument means unwrapped. + *

      + * The serialization strategy for XmlObjects is this: + *

      + * (1) Only the root XmlObject for a document actually gets + * fully serialized; it is serialized as a SerializedRootObject, + * which simply saves itself as XML text. + *

      + * (2) Interior XmlObjects get serialized as a reference to the + * root XmlObject for their document, plus an integer which + * indicates the position of the XmlObject within the owner + * document. This pair is stored as a SerializedInteriorObject. + *

      + * Both objects can be maked as wrapped or unwrapped. If wrapped, + * then the proxy is returned when deserializing; if unwrapped, then + * the proxy is stripped when deserializing. + */ + public Object writeReplace() { + synchronized (monitor()) { + if (isRootXmlObject()) { + return new SerializedRootObject(this); + } + + return new SerializedInteriorObject(this, getRootXmlObject()); + } + } + + /** + * True if the object is at the root of the document. + */ + private boolean isRootXmlObject() { + XmlCursor cur = newCursor(); + if (cur == null) { + return false; + } + + boolean result = !cur.toParent(); + cur.dispose(); + return result; + } + + /** + * Gets the root XmlObject for this document. + */ + private XmlObject getRootXmlObject() { + XmlCursor cur = newCursor(); + if (cur == null) { + return this; + } + cur.toStartDoc(); + XmlObject result = cur.getObject(); + cur.dispose(); + return result; + } + + /** + * Serializable rewrite object that knows how to resolve + * to an XmlObjectBase or a proxy for the root object of + * a document. + */ + private static class SerializedRootObject implements Serializable { + private static final long serialVersionUID = 1; + + transient Class _xbeanClass; + transient XmlObject _impl; + + private SerializedRootObject(XmlObject impl) { + _xbeanClass = impl.schemaType().getJavaClass(); + _impl = impl; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeObject(_xbeanClass); + // the first short is written out for backwards compatibility + // it will always be zero for objects written with + // this code, but it used to be the first 2 bytes of the + // writeUTF() method + out.writeShort((short) 0); + out.writeShort(MAJOR_VERSION_NUMBER); + out.writeShort(MINOR_VERSION_NUMBER); + // CR122401 - need to use writeObject instead of writeUTF + // for xmlText as writeUTF has a length limitation of + // 65535 bytes + String xmlText = _impl.xmlText(); + out.writeObject(xmlText); + out.writeBoolean(false); + } + + @SuppressWarnings("unchecked") + private void readObject(ObjectInputStream in) throws IOException { + try { + // read class object first - this is + // first just for historical reasons - really + // it would be better to have the version numbers + // first + _xbeanClass = (Class) in.readObject(); + + int utfBytes = in.readUnsignedShort(); + + // determine version numbers + // if utfBytes is non-zero then we default to 0.0 + // otherwise expect major and minor version numbers + // to be next entries in stream + int majorVersionNum = 0; + int minorVersionNum = 0; + if (utfBytes == 0) { + majorVersionNum = in.readUnsignedShort(); + minorVersionNum = in.readUnsignedShort(); + } + + String xmlText; + switch (majorVersionNum) { + case 0: // original, unnumbered version + // minorVersionNum is always zero + xmlText = readObjectV0(in, utfBytes); + in.readBoolean(); // ignored + break; + + case 1: + if (minorVersionNum == 1) { + xmlText = (String) in.readObject(); + in.readBoolean(); // ignored + } else { + throw new IOException("Deserialization error: " + + "version number " + majorVersionNum + "." + + minorVersionNum + " not supported."); + } + break; + + default: + throw new IOException("Deserialization error: " + + "version number " + majorVersionNum + "." + + minorVersionNum + " not supported."); + } + + XmlOptions opts = new XmlOptions().setDocumentType(XmlBeans.typeForClass(_xbeanClass)); + _impl = XmlBeans.getContextTypeLoader().parse(xmlText, null, opts); + } catch (Exception e) { + throw new IOException(e.getMessage(), e); + } + } + + // this method is for reading the UTF-8 String that used to be + // written out for a serialized XmlObject according to the + // original format before this fix, i.e. it expects it + // to have been written using the following algorithm: + // + // writeObject(Class object) + // writeUTF(xmlText of object as String) + // writeBoolean() + // + // this method is passed the original input stream positioned as though + // it had just read the class object plus the next 2 bytes. Those 2 + // bytes are interpreted as an unsigned short saying how many more + // bytes there are representing the bytes of the UTF-8-formatted String; + // this value is passed in as the argument utfBytes + private String readObjectV0(ObjectInputStream in, int utfBytes) + throws IOException { + // allow an extra 2 bytes up front for the unsigned short + byte[] bArray = new byte[utfBytes + 2]; + + // for format of these first 2 bytes see + // Java API docs - DataOutputStream.writeShort() + bArray[0] = (byte) (0xff & (utfBytes >> 8)); + bArray[1] = (byte) (0xff & utfBytes); + + // read the next numBytes bytes from the input stream + // into the byte array starting at offset 2; this may + // take multiple calls to read() + int totalBytesRead = 0; + int numRead; + while (totalBytesRead < utfBytes) { + numRead = + in.read(bArray, 2 + totalBytesRead, utfBytes - totalBytesRead); + if (numRead == -1) // reached end of stream + { + break; + } + + totalBytesRead += numRead; + } + + if (totalBytesRead != utfBytes) { + throw new IOException("Error reading backwards compatible " + + "XmlObject: number of bytes read (" + totalBytesRead + + ") != number expected (" + utfBytes + ")"); + } + + // now set up a DataInputStream to read those + // bytes as a UTF-8 String i.e. as though we'd never + // read the first 2 bytes from the original stream + DataInputStream dis = null; + String str; + try { + dis = new DataInputStream(new ByteArrayInputStream(bArray)); + str = dis.readUTF(); + } finally { + if (dis != null) { + dis.close(); + } + } + + return str; + } + + private Object readResolve() throws ObjectStreamException { + return _impl; + } + } + + /** + * Serializable rewrite object that knows how to resolve + * to an XmlObjectBase or a proxy for an interior position + * within a document. + */ + private static class SerializedInteriorObject implements Serializable { + private static final long serialVersionUID = 1; + + transient XmlObject _impl; + transient XmlObject _root; + + private SerializedInteriorObject(XmlObject impl, XmlObject root) { + _impl = impl; + _root = root; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeObject(_root); + out.writeBoolean(false); + out.writeInt(distanceToRoot()); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + _root = (XmlObject) in.readObject(); + in.readBoolean(); + _impl = objectAtDistance(in.readInt()); + } + + private Object readResolve() throws ObjectStreamException { + return _impl; + } + + private int distanceToRoot() { + XmlCursor cur = _impl.newCursor(); + int count = 0; + while (!cur.toPrevToken().isNone()) { + if (!cur.currentTokenType().isNamespace()) { + count += 1; + // System.out.println("Count: " + count + " " + cur.currentTokenType().toString() + " " + QName.pretty(cur.getName())); + } + } + cur.dispose(); + return count; + } + + private XmlObject objectAtDistance(int count) { + XmlCursor cur = _root.newCursor(); + while (count > 0) { + cur.toNextToken(); + if (!cur.currentTokenType().isNamespace()) { + count -= 1; + // System.out.println("Count: " + count + " " + cur.currentTokenType().toString() + " " + QName.pretty(cur.getName())); + } + } + XmlObject result = cur.getObject(); + cur.dispose(); + return result; + } + } + + protected static Object java_value(XmlObject obj) { + if (obj.isNil()) { + return null; + } + + if (!(obj instanceof XmlAnySimpleType)) { + return obj; + } + + SchemaType instanceType = ((SimpleValue) obj).instanceType(); + assert (instanceType != null) : "Nil case should have been handled above"; + + // handle lists + if (instanceType.getSimpleVariety() == SchemaType.LIST) { + return ((SimpleValue) obj).getListValue(); + } + + SimpleValue base = (SimpleValue) obj; + + switch (instanceType.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_BOOLEAN: + return base.getBooleanValue() ? Boolean.TRUE : Boolean.FALSE; + + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: + return base.getByteArrayValue(); + + case SchemaType.BTC_QNAME: + return base.getQNameValue(); + + case SchemaType.BTC_FLOAT: + return base.getFloatValue(); + + case SchemaType.BTC_DOUBLE: + return base.getDoubleValue(); + + case SchemaType.BTC_DECIMAL: { + switch (instanceType.getDecimalSize()) { + case SchemaType.SIZE_BYTE: + return base.getByteValue(); + + case SchemaType.SIZE_SHORT: + return base.getShortValue(); + + case SchemaType.SIZE_INT: + return base.getIntValue(); + + case SchemaType.SIZE_LONG: + return base.getLongValue(); + + case SchemaType.SIZE_BIG_INTEGER: + return base.getBigIntegerValue(); + + default: + assert (false) : "invalid numeric bit count"; + // fallthrough + case SchemaType.SIZE_BIG_DECIMAL: + return base.getBigDecimalValue(); + } + } + case SchemaType.BTC_ANY_URI: + return base.getStringValue(); + + case SchemaType.BTC_DURATION: + return base.getGDurationValue(); + + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + return base.getCalendarValue(); + + default: + assert (false) : "encountered nonprimitive type."; + // fallthrough + + // NB: for string enums we just do java.lang.String + // when in the context of unions. It's easier on users. + case SchemaType.BTC_NOTATION: + case SchemaType.BTC_STRING: + case SchemaType.BTC_ANY_SIMPLE: + // return base.getStringValue(); + return base.getStringValue(); + } + } + + /** + * Called by code generated code to get the default attribute value + * for a given attribute name, or null if none. + */ + protected XmlAnySimpleType get_default_attribute_value(QName name) { + SchemaType sType = schemaType(); + SchemaAttributeModel aModel = sType.getAttributeModel(); + if (aModel == null) { + return null; + } + SchemaLocalAttribute sAttr = aModel.getAttribute(name); + if (sAttr == null) { + return null; + } + return sAttr.getDefaultValue(); + } + + private List getBaseArray(QName elementName) { + check_orphaned(); + List targetList = new java.util.ArrayList<>(); + get_store().find_all_element_users(elementName, targetList); + return targetList; + } + + private List getBaseArray(QNameSet elementSet) { + check_orphaned(); + List targetList = new java.util.ArrayList<>(); + get_store().find_all_element_users(elementSet, targetList); + return targetList; + } + + protected T[] getObjectArray(QName elementName, Function fun, IntFunction arrayCon) { + synchronized (monitor()) { + return getBaseArray(elementName).stream().map(fun).toArray(arrayCon); + } + } + + protected T[] getEnumArray(QName elementName, IntFunction arrayCon) { + synchronized (monitor()) { + return getBaseArray(elementName).stream().map(SimpleValue::getEnumValue).toArray(arrayCon); + } + } + + protected boolean[] getBooleanArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + boolean[] result = new boolean[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getBooleanValue(); + } + return result; + } + } + + protected float[] getFloatArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + float[] result = new float[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getFloatValue(); + } + return result; + } + } + + protected double[] getDoubleArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + return targetList.stream() + .map(org.apache.xmlbeans.SimpleValue.class::cast) + .mapToDouble(org.apache.xmlbeans.SimpleValue::getDoubleValue) + .toArray(); + } + } + + protected byte[] getByteArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + byte[] result = new byte[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getByteValue(); + } + return result; + } + } + + protected short[] getShortArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + short[] result = new short[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getShortValue(); + } + return result; + } + } + + protected int[] getIntArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + return targetList.stream() + .map(org.apache.xmlbeans.SimpleValue.class::cast) + .mapToInt(org.apache.xmlbeans.SimpleValue::getIntValue) + .toArray(); + } + } + + protected long[] getLongArray(QName elementName) { + synchronized (monitor()) { + List targetList = getBaseArray(elementName); + return targetList.stream() + .map(org.apache.xmlbeans.SimpleValue.class::cast) + .mapToLong(org.apache.xmlbeans.SimpleValue::getLongValue) + .toArray(); + } + } + + protected T[] getXmlObjectArray(QName elementName, T[] arrayCon) { + synchronized (monitor()) { + return getBaseArray(elementName).toArray(arrayCon); + } + } + + protected T[] getObjectArray(QNameSet elementSet, Function fun, IntFunction arrayCon) { + synchronized (monitor()) { + return getBaseArray(elementSet).stream().map(fun).toArray(arrayCon); + } + } + + protected T[] getEnumArray(QNameSet elementSet, IntFunction arrayCon) { + synchronized (monitor()) { + return getBaseArray(elementSet).stream().map(SimpleValue::getEnumValue).toArray(arrayCon); + } + } + + protected boolean[] getBooleanArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + boolean[] result = new boolean[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getBooleanValue(); + } + return result; + } + } + + protected float[] getFloatArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + float[] result = new float[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getFloatValue(); + } + return result; + } + } + + protected double[] getDoubleArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + return targetList.stream() + .map(org.apache.xmlbeans.SimpleValue.class::cast) + .mapToDouble(org.apache.xmlbeans.SimpleValue::getDoubleValue) + .toArray(); + } + } + + protected byte[] getByteArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + byte[] result = new byte[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getByteValue(); + } + return result; + } + } + + protected short[] getShortArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + short[] result = new short[targetList.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = ((org.apache.xmlbeans.SimpleValue) targetList.get(i)).getShortValue(); + } + return result; + } + } + + protected int[] getIntArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + return targetList.stream() + .map(org.apache.xmlbeans.SimpleValue.class::cast) + .mapToInt(org.apache.xmlbeans.SimpleValue::getIntValue) + .toArray(); + } + } + + protected long[] getLongArray(QNameSet elementSet) { + synchronized (monitor()) { + List targetList = getBaseArray(elementSet); + return targetList.stream() + .map(org.apache.xmlbeans.SimpleValue.class::cast) + .mapToLong(org.apache.xmlbeans.SimpleValue::getLongValue) + .toArray(); + } + } + + protected T[] getXmlObjectArray(QNameSet elementSet, T[] arrayCon) { + synchronized (monitor()) { + return getBaseArray(elementSet).toArray(arrayCon); + } + } + + protected T[] xgetArray(QName elementName, IntFunction arrayCon) { + synchronized (monitor()) { + check_orphaned(); + java.util.List targetList = new java.util.ArrayList<>(); + get_store().find_all_element_users(elementName, targetList); + return targetList.stream().toArray(arrayCon); + } + } + + protected T[] xgetArray(QNameSet elementSet, IntFunction arrayCon) { + synchronized (monitor()) { + check_orphaned(); + java.util.List targetList = new java.util.ArrayList<>(); + get_store().find_all_element_users(elementSet, targetList); + return targetList.stream().toArray(arrayCon); + } + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlPositiveIntegerImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlPositiveIntegerImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlPositiveIntegerImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlPositiveIntegerImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlQNameImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlQNameImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlQNameImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlQNameImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlQNameRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlQNameRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlQNameRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlQNameRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlShortImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlShortImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlShortImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlShortImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringEnumeration.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlStringEnumeration.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringEnumeration.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlStringEnumeration.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlStringImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlStringImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringRestriction.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlStringRestriction.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlStringRestriction.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlStringRestriction.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlTimeImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlTimeImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlTimeImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlTimeImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlTokenImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlTokenImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlTokenImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlTokenImpl.java diff --git a/src/main/java/org/apache/xmlbeans/impl/values/XmlUnionImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlUnionImpl.java new file mode 100644 index 0000000..dc52d69 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/values/XmlUnionImpl.java @@ -0,0 +1,602 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.values; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.ValidationContext; +import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; + +import javax.xml.namespace.QName; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + + +/** + * This class implements simple union types. + */ +public class XmlUnionImpl extends XmlObjectBase implements XmlAnySimpleType { + public XmlUnionImpl(SchemaType type, boolean complex) { + _schemaType = type; + initComplexType(complex, false); + } + + public SchemaType schemaType() { + return _schemaType; + } + + public SchemaType instanceType() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).instanceType(); + } + + private final SchemaType _schemaType; + private XmlAnySimpleType _value; // underlying value + private String _textvalue = ""; // textual value + + + // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- + // gets raw text value + + protected String compute_text(NamespaceManager nsm) { + return _textvalue; + } + + protected boolean is_defaultable_ws(String v) { + try { + XmlAnySimpleType savedValue = _value; + set_text(v); + + // restore the saved value + _value = savedValue; + + return false; + } catch (XmlValueOutOfRangeException e) { + return true; + } + } + + protected void set_text(String s) { + // first check against any patterns... + if (!_schemaType.matchPatternFacet(s) && _validateOnSet()) { + throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, + new Object[]{"string", s, QNameHelper.readable(_schemaType)}); + } + + + // save state for rollback + String original = _textvalue; + _textvalue = s; + + // iterate through the types, trying to create a type + SchemaType[] members = _schemaType.getUnionConstituentTypes(); + assert (members != null); + + boolean pushed = false; + // boolean wasstrict = set_strict(true); // tell types to complain ferverently about errors + if (has_store()) { + NamespaceContext.push(new NamespaceContext(get_store())); + pushed = true; + } + try { + for (boolean validate = true; validate || !_validateOnSet(); validate = false) { + for (SchemaType member : members) { + // From the point of view of the following call, "this" is a generic + // XmlAnySimpleType implementation, for which only getText can be called. + // (Note that "this" is not wrapped in the proxy object.) + try { + XmlAnySimpleType newval = ((SchemaTypeImpl) member).newValue(s, validate); + + // now we need to check against (enuemration) restrictions + if (!check(newval, _schemaType)) { + continue; + } + + // found one that works! + _value = newval; + return; + } catch (XmlValueOutOfRangeException ignored) { + } catch (Exception e) { + throw new RuntimeException("Troublesome union exception caused by unexpected " + e, e); + // assert(false) : "Unexpected " + e; + // continue; + } + } + if (!validate) { + break; + } + } + } finally { + if (pushed) { + NamespaceContext.pop(); + } + // set_strict(wasstrict); + } + + + // doesn't match any of the members; rollback and throw + _textvalue = original; + throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$UNION, + new Object[]{s, QNameHelper.readable(_schemaType)}); + } + + protected void set_nil() { + _value = null; + _textvalue = null; + } + + protected int get_wscanon_rule() { + return SchemaType.WS_PRESERVE; + } + + + // numerics + public float getFloatValue() { + check_dated(); + return _value == null ? 0.0f : ((SimpleValue) _value).getFloatValue(); + } + + public double getDoubleValue() { + check_dated(); + return _value == null ? 0.0 : ((SimpleValue) _value).getDoubleValue(); + } + + public BigDecimal getBigDecimalValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getBigDecimalValue(); + } + + public BigInteger getBigIntegerValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getBigIntegerValue(); + } + + public byte getByteValue() { + check_dated(); + return _value == null ? 0 : ((SimpleValue) _value).getByteValue(); + } + + public short getShortValue() { + check_dated(); + return _value == null ? 0 : ((SimpleValue) _value).getShortValue(); + } + + public int getIntValue() { + check_dated(); + return _value == null ? 0 : ((SimpleValue) _value).getIntValue(); + } + + public long getLongValue() { + check_dated(); + return _value == null ? 0 : ((SimpleValue) _value).getLongValue(); + } + + + // various + public byte[] getByteArrayValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getByteArrayValue(); + } + + public boolean getBooleanValue() { + check_dated(); + return _value != null && ((SimpleValue) _value).getBooleanValue(); + } + + public Calendar getCalendarValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getCalendarValue(); + } + + public Date getDateValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getDateValue(); + } + + public GDate getGDateValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getGDateValue(); + } + + public GDuration getGDurationValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getGDurationValue(); + } + + public QName getQNameValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getQNameValue(); + } + + public List getListValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getListValue(); + } + + public List xgetListValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).xgetListValue(); + } + + public StringEnumAbstractBase getEnumValue() { + check_dated(); + return _value == null ? null : ((SimpleValue) _value).getEnumValue(); + } + + public String getStringValue() { + check_dated(); + return _value == null ? null : _value.getStringValue(); + } + + /** + * True if the given schema type's logical type is a match for + * the given category of java concepts. + */ + + private static final int JAVA_NUMBER = SchemaType.BTC_LAST_BUILTIN + 1; + private static final int JAVA_DATE = SchemaType.BTC_LAST_BUILTIN + 2; + private static final int JAVA_CALENDAR = SchemaType.BTC_LAST_BUILTIN + 3; + private static final int JAVA_BYTEARRAY = SchemaType.BTC_LAST_BUILTIN + 4; + private static final int JAVA_LIST = SchemaType.BTC_LAST_BUILTIN + 5; + + private static boolean logical_overlap(SchemaType type, int javacode) { + // non-union types because it's being applied on irreducible union members! + assert (type.getSimpleVariety() != SchemaType.UNION); + + if (javacode <= SchemaType.BTC_LAST_BUILTIN) { + if (type.getSimpleVariety() != SchemaType.ATOMIC) { + return false; + } + + return (type.getPrimitiveType().getBuiltinTypeCode() == javacode); + } + + switch (javacode) { + case JAVA_NUMBER: { + if (type.getSimpleVariety() != SchemaType.ATOMIC) { + return false; + } + + switch (type.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_FLOAT: + case SchemaType.BTC_DOUBLE: + case SchemaType.BTC_DECIMAL: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH: + case SchemaType.BTC_G_DAY: + return true; + } + return false; + } + case JAVA_DATE: { + if (type.getSimpleVariety() != SchemaType.ATOMIC) { + return false; + } + + switch (type.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_DATE: + return true; + } + return false; + } + case JAVA_CALENDAR: { + if (type.getSimpleVariety() != SchemaType.ATOMIC) { + return false; + } + + switch (type.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_TIME: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH: + case SchemaType.BTC_G_DAY: + return true; + } + return false; + } + + case JAVA_BYTEARRAY: { + if (type.getSimpleVariety() != SchemaType.ATOMIC) { + return false; + } + + switch (type.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_BASE_64_BINARY: + case SchemaType.BTC_HEX_BINARY: + return true; + } + return false; + } + case JAVA_LIST: { + return (type.getSimpleVariety() == SchemaType.LIST); + } + } + + assert (false) : "missing case"; + return false; + } + + /** + * Grabs a chained value of type st, creating and attaching + * one if not present. + */ + private void set_primitive(int typecode, Object val) { + SchemaType[] members = _schemaType.getUnionConstituentTypes(); + assert (members != null); + + boolean pushed = false; + if (has_store()) { + NamespaceContext.push(new NamespaceContext(get_store())); + pushed = true; + } + try { + for (boolean validate = true; validate || !_validateOnSet(); validate = false) { + for (SchemaType member : members) { + // candidates must be a logical match for the desired typecode + if (logical_overlap(member, typecode)) { + XmlAnySimpleType newval; + + try { + newval = ((SchemaTypeImpl) member).newValue(val, validate); + } catch (XmlValueOutOfRangeException ignored) { + // doesn't match this type even though logical categories + // line up (probably because of restriciton); try the next type. + continue; + } catch (Exception e) { + assert (false) : "Unexpected " + e; + continue; + } + + /* TODO: rethink this - disabling for now. + + // OK, now we've got a newval... We have to verify + // that lexically it doesn't overlap with previous types + + String newvaltext = null; + + inner: for (int j = 0; j < i; j++) + { + if (members[j].getSimpleVariety() == SchemaType.LIST || + lexical_overlap(members[j].getPrimitiveType().getBuiltinTypeCode(), + newval.schemaType().getPrimitiveType().getBuiltinTypeCode())) + { + // there is a preceding type that may lexically overlap with ours... + // if it lexically contains the string representation of our new + // proposed value, then it's impossible for the union to have our + // logical value (because it would have been masked) and throw an + // error. + if (newvaltext == null) + newvaltext = newval.stringValue(); + try + { + // discard return value + members[i].newValue(newvaltext); + + // oh bad, we succeeded. Our instance lexically looks like a + // previous type, and this isn't a valid value. Keep on hunting. + continue outer; + } + catch (XmlValueOutOfRangeException e) + { + // this is good: this error means that our value doesn't look like + // the other type. + continue inner; + } + } + } + + */ + + // No lexical masking: we're OK + _value = newval; + _textvalue = _value.getStringValue(); + return; + } + } + if (!validate) { + break; + } + } + } finally { + if (pushed) { + NamespaceContext.pop(); + } + } + + // doesn't match any of the members; throw + throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$UNION, + new Object[]{val.toString(), QNameHelper.readable(_schemaType)}); + } + + // here are the setters + + protected void set_boolean(boolean v) { + set_primitive(SchemaType.BTC_BOOLEAN, v); + } + + protected void set_byte(byte v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_short(short v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_int(int v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_long(long v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_float(float v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_double(double v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_ByteArray(byte[] b) { + set_primitive(JAVA_BYTEARRAY, b); + } + + protected void set_hex(byte[] b) { + set_primitive(JAVA_BYTEARRAY, b); + } + + protected void set_b64(byte[] b) { + set_primitive(JAVA_BYTEARRAY, b); + } + + protected void set_BigInteger(BigInteger v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_BigDecimal(BigDecimal v) { + set_primitive(JAVA_NUMBER, v); + } + + protected void set_QName(QName v) { + set_primitive(SchemaType.BTC_QNAME, v); + } + + protected void set_Calendar(Calendar c) { + set_primitive(JAVA_CALENDAR, c); + } + + protected void set_Date(Date d) { + set_primitive(JAVA_DATE, d); + } + + protected void set_GDate(GDateSpecification d) { + int btc = d.getBuiltinTypeCode(); + if (btc <= 0) { + throw new XmlValueOutOfRangeException(); + } + set_primitive(btc, d); + } + + protected void set_GDuration(GDurationSpecification d) { + set_primitive(SchemaType.BTC_DURATION, d); + } + + protected void set_enum(StringEnumAbstractBase e) { + set_primitive(SchemaType.BTC_STRING, e); + } + + protected void set_list(List v) { + set_primitive(JAVA_LIST, v); + } + + + protected void set_xmlfloat(XmlObject v) { + set_primitive(SchemaType.BTC_FLOAT, v); + } + + protected void set_xmldouble(XmlObject v) { + set_primitive(SchemaType.BTC_DOUBLE, v); + } + + protected void set_xmldecimal(XmlObject v) { + set_primitive(SchemaType.BTC_DECIMAL, v); + } + + protected void set_xmlduration(XmlObject v) { + set_primitive(SchemaType.BTC_DURATION, v); + } + + protected void set_xmldatetime(XmlObject v) { + set_primitive(SchemaType.BTC_DATE_TIME, v); + } + + protected void set_xmltime(XmlObject v) { + set_primitive(SchemaType.BTC_TIME, v); + } + + protected void set_xmldate(XmlObject v) { + set_primitive(SchemaType.BTC_DATE, v); + } + + protected void set_xmlgyearmonth(XmlObject v) { + set_primitive(SchemaType.BTC_G_YEAR_MONTH, v); + } + + protected void set_xmlgyear(XmlObject v) { + set_primitive(SchemaType.BTC_G_YEAR, v); + } + + protected void set_xmlgmonthday(XmlObject v) { + set_primitive(SchemaType.BTC_G_MONTH_DAY, v); + } + + protected void set_xmlgday(XmlObject v) { + set_primitive(SchemaType.BTC_G_DAY, v); + } + + protected void set_xmlgmonth(XmlObject v) { + set_primitive(SchemaType.BTC_G_MONTH, v); + } + + + private static boolean check(XmlObject v, SchemaType sType) { + XmlObject[] vals = sType.getEnumerationValues(); + if (vals != null) { + for (XmlObject val : vals) { + if (val.valueEquals(v)) { + return true; + } + } + return false; + } + + return true; + } + + protected boolean equal_to(XmlObject xmlobj) { + return _value.valueEquals(xmlobj); + } + + protected int value_hash_code() { + return _value.hashCode(); + } + + protected void validate_simpleval(String lexical, ValidationContext ctx) { + try { + check_dated(); + } catch (Exception e) { + ctx.invalid(XmlErrorCodes.UNION, new Object[]{"'" + lexical + "' does not match any of the member types for " + QNameHelper.readable(schemaType())}); + return; + } + if (_value == null) { + ctx.invalid(XmlErrorCodes.UNION, new Object[]{"'" + lexical + "' does not match any of the member types for " + QNameHelper.readable(schemaType())}); + return; + } + + ((XmlObjectBase) _value).validate_simpleval(lexical, ctx); + } + + +} + diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedByteImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedByteImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedByteImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedByteImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedIntImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedIntImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedIntImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedIntImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedLongImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedLongImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedLongImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedLongImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedShortImpl.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedShortImpl.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnsignedShortImpl.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlUnsignedShortImpl.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueNotNillableException.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlValueNotNillableException.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueNotNillableException.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlValueNotNillableException.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueNotSupportedException.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlValueNotSupportedException.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueNotSupportedException.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlValueNotSupportedException.java diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueOutOfRangeException.java b/src/main/java/org/apache/xmlbeans/impl/values/XmlValueOutOfRangeException.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueOutOfRangeException.java rename to src/main/java/org/apache/xmlbeans/impl/values/XmlValueOutOfRangeException.java diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/Path.java b/src/main/java/org/apache/xmlbeans/impl/xpath/Path.java new file mode 100755 index 0000000..b59eccd --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/Path.java @@ -0,0 +1,24 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.store.Cur; + + +public interface Path { + XPathEngine execute(Cur c, XmlOptions options); +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XPath.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XPath.java new file mode 100644 index 0000000..8110066 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XPath.java @@ -0,0 +1,72 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlException; + +import java.util.Map; + + +public class XPath { + public static final String _NS_BOUNDARY = "$xmlbeans!ns_boundary"; + public static final String _DEFAULT_ELT_NS = "$xmlbeans!default_uri"; + final Selector _selector; + private final boolean _sawDeepDot; + + public static class XPathCompileException extends XmlException { + XPathCompileException(XmlError err) { + super(err.toString(), null, err); + } + } + + public static XPath compileXPath(String xpath) throws XPathCompileException { + return compileXPath(xpath, "$this", null); + } + + public static XPath compileXPath(String xpath, String currentNodeVar) + throws XPathCompileException { + return compileXPath(xpath, currentNodeVar, null); + } + + public static XPath compileXPath(String xpath, Map namespaces) + throws XPathCompileException { + return compileXPath(xpath, "$this", namespaces); + } + + public static XPath compileXPath(String xpath, String currentNodeVar, Map namespaces) + throws XPathCompileException { + return new XPathCompilationContext(namespaces, currentNodeVar).compile(xpath); + } + + static final class Selector { + Selector(XPathStep[] paths) { + _paths = paths; + } + + final XPathStep[] _paths; + } + + XPath(Selector selector, boolean sawDeepDot) { + _selector = selector; + _sawDeepDot = sawDeepDot; + } + + public boolean sawDeepDot() { + return _sawDeepDot; + } + +} \ No newline at end of file diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XPathCompilationContext.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathCompilationContext.java new file mode 100644 index 0000000..76f8e61 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathCompilationContext.java @@ -0,0 +1,607 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.impl.common.XMLChar; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import static org.apache.xmlbeans.impl.xpath.XPath._NS_BOUNDARY; + +class XPathCompilationContext { + private String _expr; + + private boolean _sawDeepDot; // Saw one overall + private boolean _lastDeepDot; + + private final String _currentNodeVar; + + // private Map _namespaces; + protected final Map _namespaces = new HashMap<>(); + private final Map _externalNamespaces; + + private int _offset; + private int _line; + private int _column; + + XPathCompilationContext(Map namespaces, String currentNodeVar) { + // TODO: checkme + // assert (_currentNodeVar == null || _currentNodeVar.startsWith("$")); + + _currentNodeVar = (currentNodeVar == null) ? "$this" : currentNodeVar; + + _externalNamespaces = (namespaces == null) ? new HashMap<>() : namespaces; + } + + XPath compile(String expr) throws XPath.XPathCompileException { + _offset = 0; + _line = 1; + _column = 1; + _expr = expr; + + return tokenizeXPath(); + } + + int currChar() { + return currChar(0); + } + + int currChar(int offset) { + return + _offset + offset >= _expr.length() + ? -1 + : _expr.charAt(_offset + offset); + } + + void advance() { + if (_offset < _expr.length()) { + char ch = _expr.charAt(_offset); + + _offset++; + _column++; + + if (ch == '\r' || ch == '\n') { + _line++; + _column = 1; + + if (_offset + 1 < _expr.length()) { + char nextCh = _expr.charAt(_offset + 1); + + if ((nextCh == '\r' || nextCh == '\n') && ch != nextCh) { + _offset++; + } + } + } + } + } + + void advance(int count) { + assert count >= 0; + + while (count-- > 0) { + advance(); + } + } + + boolean isWhitespace() { + return isWhitespace(0); + } + + boolean isWhitespace(int offset) { + int ch = currChar(offset); + return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'; + } + + boolean isNCNameStart() { + return currChar() != -1 && XMLChar.isNCNameStart(currChar()); + } + + boolean isNCName() { + return currChar() != -1 && XMLChar.isNCName(currChar()); + } + + boolean startsWith(String s, int offset) { + if (_offset + offset >= _expr.length()) { + return false; + } + + return _expr.startsWith(s, _offset + offset); + } + + private XPath.XPathCompileException newError(String msg) { + XmlError err = + XmlError.forLocation( + msg, XmlError.SEVERITY_ERROR, null, + _line, _column, _offset); + + return new XPath.XPathCompileException(err); + } + + String lookupPrefix(String prefix) throws XPath.XPathCompileException { + if (_namespaces.containsKey(prefix)) { + return _namespaces.get(prefix); + } + + if (_externalNamespaces.containsKey(prefix)) { + return _externalNamespaces.get(prefix); + } + + switch (prefix != null ? prefix : "") { + case "xml": + return "http://www.w3.org/XML/1998/namespace"; + + case "xs": + return "http://www.w3.org/2001/XMLSchema"; + + case "xsi": + return "http://www.w3.org/2001/XMLSchema-instance"; + + case "fn": + return "http://www.w3.org/2002/11/xquery-functions"; + + case "xdt": + return "http://www.w3.org/2003/11/xpath-datatypes"; + + case "local": + return "http://www.w3.org/2003/11/xquery-local-functions"; + } + + throw newError("Undefined prefix: " + prefix); + } + + private boolean parseWhitespace() { + boolean sawSpace = false; + + while (isWhitespace()) { + advance(); + sawSpace = true; + } + + return sawSpace; + } + + // + // Tokenizing will consume whitespace followed by the tokens, separated + // by whitespace. The whitespace following the last token is not + // consumed. + // + private boolean tokenize(String... tokens) { + int offset = 0; + + for (String s : tokens) { + assert (s != null && !s.isEmpty()); + + while (isWhitespace(offset)) { + offset++; + } + + if (!startsWith(s, offset)) { + return false; + } + + offset += s.length(); + } + + advance(offset); + + return true; + } + + + private String tokenizeNCName() throws XPath.XPathCompileException { + parseWhitespace(); + + if (!isNCNameStart()) { + throw newError("Expected non-colonized name"); + } + + StringBuilder sb = new StringBuilder(); + + sb.append((char) currChar()); + + for (advance(); isNCName(); advance()) { + sb.append((char) currChar()); + } + + return sb.toString(); + } + + private QName getAnyQName() { + return new QName("", ""); + } + + private QName tokenizeQName() throws XPath.XPathCompileException { + if (tokenize("*")) { + return getAnyQName(); + } + + String ncName = tokenizeNCName(); + + if (!tokenize(":")) { + return new QName(lookupPrefix(""), ncName); + } + + return + new QName( + lookupPrefix(ncName), + tokenize("*") ? "" : tokenizeNCName()); + } + + private String tokenizeQuotedUri() throws XPath.XPathCompileException { + char quote; + + if (tokenize("\"")) { + quote = '"'; + } else if (tokenize("'")) { + quote = '\''; + } else { + throw newError("Expected quote (\" or ')"); + } + + StringBuilder sb = new StringBuilder(); + + for (; ; ) { + if (currChar() == -1) { + throw newError("Path terminated in URI literal"); + } + + if (currChar() == quote) { + advance(); + + if (currChar() != quote) { + break; + } + } + + sb.append((char) currChar()); + + advance(); + } + + return sb.toString(); + } + + private XPathStep addStep(boolean deep, boolean attr, QName name, XPathStep steps) { + XPathStep step = new XPathStep(deep, attr, name); + + if (steps == null) { + return step; + } + + XPathStep s = steps; + + while (steps._next != null) { + steps = steps._next; + } + + steps._next = step; + step._prev = steps; + + return s; + } + + private XPathStep tokenizeSteps() throws XPath.XPathCompileException { + if (tokenize("/")) { + throw newError("Absolute paths unsupported"); + } + + boolean deep; + + if (tokenize("$", _currentNodeVar, "//") || tokenize(".", "//")) { + deep = true; + } else if (tokenize("$", _currentNodeVar, "/") || tokenize(".", "/")) { + deep = false; + } else if (tokenize("$", _currentNodeVar) || tokenize(".")) { + return addStep(false, false, null, null); + } else { + deep = false; + } + + XPathStep steps = null; + + // Compile the steps removing /. and mergind //. with the next step + + boolean deepDot = false; + + for (; ; ) { + if (tokenize("attribute", "::") || tokenize("@")) { + steps = addStep(deep, true, tokenizeQName(), steps); + break; + } + + QName name; + + if (tokenize(".")) { + deepDot = deepDot || deep; + } else { + tokenize("child", "::"); + name = tokenizeQName(); + steps = addStep(deep, false, name, steps); + deep = false; // only this step needs to be deep + // other folowing steps will be deep only if they are preceded by // wildcard + } + + if (tokenize("//")) { + deep = true; + deepDot = false; + } else if (tokenize("/")) { + if (deepDot) { + deep = true; + } + } else { + break; + } + } + + // If there was a //. at the end of th path, then we need to make + // two paths, one with * at the end and another with @* at the end. + + if ((_lastDeepDot = deepDot)) { + _lastDeepDot = true; + steps = addStep(true, false, getAnyQName(), steps); + } + + // Add sentinal step (_name == null) + + return addStep(false, false, null, steps); + } + + private void computeBacktrack(XPathStep steps) { + // + // Compute static backtrack information + // + // Note that I use the fact that _hasBacktrack is initialized to + // false and _backtrack to null in the following code. + // + + XPathStep s, t; + + for (s = steps; s != null; s = t) { + // Compute the segment from [ s, t ) + + for (t = s._next; t != null && !t._deep; ) { + t = t._next; + } + + // If the segment is NOT rooted at //, then the backtrack is + // null for the entire segment, including possible attr and/or + // sentinal + + if (!s._deep) { + for (XPathStep u = s; u != t; u = u._next) { + u._hasBacktrack = true; + } + + continue; + } + + // Compute the sequence [ s, u ) of length n which contain no + // wild steps. + + int n = 0; + XPathStep u = s; + + while (u != t && u._name != null && !u.isWild() && !u._attr) { + n++; + u = u._next; + } + + // Now, apply KMP to [ s, u ) for fast backtracking + + QName[] pattern = new QName[n + 1]; + int[] kmp = new int[n + 1]; + + XPathStep v = s; + + for (int i = 0; i < n; i++) { + pattern[i] = v._name; + v = v._next; + } + + pattern[n] = getAnyQName(); + + int i = 0; + int j = kmp[0] = -1; + + while (i < n) { + while (j > -1 && !pattern[i].equals(pattern[j])) { + j = kmp[j]; + } + + i++; + j++; + kmp[i] = (pattern[i].equals(pattern[j])) ? kmp[j] : j; + } + + i = 0; + + for (v = s; v != u; v = v._next) { + v._hasBacktrack = true; + v._backtrack = s; + + for (j = kmp[i]; j > 0; j--) { + v._backtrack = v._backtrack._next; + } + + i++; + } + + // Compute the success backtrack and stuff it into an attr and + // sentinal if they exist for this segment + + v = s; + + if (n > 1) { + for (j = kmp[n - 1]; j > 0; j--) { + v = v._next; + } + } + + if (u != t && u._attr) { + u._hasBacktrack = true; + u._backtrack = v; + u = u._next; + } + + if (u != t && u._name == null) { + u._hasBacktrack = true; + u._backtrack = v; + } + + // The first part of a deep segment always backtracks to itself + + assert s._deep; + + s._hasBacktrack = true; + s._backtrack = s; + } + } + + private void tokenizePath(ArrayList paths) + throws XPath.XPathCompileException { + _lastDeepDot = false; + + XPathStep steps = tokenizeSteps(); + + computeBacktrack(steps); + + paths.add(steps); + + // If the last path ended in //., that path will match all + // elements, here I make a path which matches all attributes. + + if (_lastDeepDot) { + _sawDeepDot = true; + + XPathStep s = null; + + for (XPathStep t = steps; t != null; t = t._next) { + boolean attr = (t._next != null && t._next._next == null) || t._attr; + s = addStep(t._deep, attr, t._name, s); + } + + computeBacktrack(s); + + paths.add(s); + } + } + + private XPath.Selector tokenizeSelector() throws XPath.XPathCompileException { + ArrayList paths = new ArrayList<>(); + + tokenizePath(paths); + + while (tokenize("|")) { + tokenizePath(paths); + } + + return new XPath.Selector(paths.toArray(new XPathStep[0])); + } + + private XPath tokenizeXPath() throws XPath.XPathCompileException { + for (; ; ) { + if (tokenize("declare", "namespace")) { + if (!parseWhitespace()) { + throw newError("Expected prefix after 'declare namespace'"); + } + + String prefix = tokenizeNCName(); + + if (!tokenize("=")) { + throw newError("Expected '='"); + } + + String uri = tokenizeQuotedUri(); + + if (_namespaces.containsKey(prefix)) { + throw newError("Redefinition of namespace prefix: " + prefix); + } + + _namespaces.put(prefix, uri); + + //return these to saxon:? Is it an error to pass external NS + //that conflicts? or should we just override it? + if (_externalNamespaces.containsKey(prefix)) { + throw newError("Redefinition of namespace prefix: " + prefix); + } + _externalNamespaces.put(prefix, uri); + + if (!tokenize(";")) { +// throw newError( "Namespace declaration must end with ;" ); + } + + _externalNamespaces.put(_NS_BOUNDARY, Integer.toString(_offset)); + + continue; + } + + if (tokenize("declare", "default", "element", "namespace")) { + String uri = tokenizeQuotedUri(); + + if (_namespaces.containsKey("")) { + throw newError("Redefinition of default element namespace"); + } + + _namespaces.put("", uri); + + //return these to saxon:? Is it an error to pass external NS + //that conflicts? or should we just override it? + if (_externalNamespaces.containsKey(XPath._DEFAULT_ELT_NS)) { + throw newError("Redefinition of default element namespace : "); + } + _externalNamespaces.put(XPath._DEFAULT_ELT_NS, uri); + + if (!tokenize(";")) { + throw newError("Default Namespace declaration must end with ;"); + } + //the boundary is the last ; in the prolog... + _externalNamespaces.put(_NS_BOUNDARY, Integer.toString(_offset)); + + continue; + } + + break; + } + + // Add the default prefix mapping if it has not been redefined + + if (!_namespaces.containsKey("")) { + _namespaces.put("", ""); + } + + XPath.Selector selector = tokenizeSelector(); + + parseWhitespace(); + + if (currChar() != -1) { + throw newError("Unexpected char '" + (char) currChar() + "'"); + } + + return new XPath(selector, _sawDeepDot); + } + + //split of prolog decls that are not standard XPath syntax + //but work in v1 + private void processNonXpathDecls() { + + } + +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XPathEngine.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathEngine.java new file mode 100644 index 0000000..e7dc9d1 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathEngine.java @@ -0,0 +1,24 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import org.apache.xmlbeans.impl.store.Cur; + +public interface XPathEngine { + void release(); + + boolean next(Cur c); +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XPathExecutionContext.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathExecutionContext.java new file mode 100644 index 0000000..a60744a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathExecutionContext.java @@ -0,0 +1,204 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class XPathExecutionContext { + + private XPath _xpath; + private final ArrayList _stack; + private PathContext[] _paths; + + public XPathExecutionContext() { + _stack = new ArrayList<>(); + } + + public static final int HIT = 0x1; + public static final int DESCEND = 0x2; + public static final int ATTRS = 0x4; + + public final void init(XPath xpath) { + if (_xpath != xpath) { + _xpath = xpath; + + _paths = new PathContext[xpath._selector._paths.length]; + + Arrays.setAll(_paths, i -> new PathContext()); + } + + _stack.clear(); + + for (int i = 0; i < _paths.length; i++) { + _paths[i].init(xpath._selector._paths[i]); + } + } + + public final int start() { + int result = 0; + + for (PathContext path : _paths) { + result |= path.start(); + } + + return result; + } + + public final int element(QName name) { + assert name != null; + + _stack.add(name); + + int result = 0; + + for (PathContext path : _paths) { + result |= path.element(name); + } + + return result; + } + + public final boolean attr(QName name) { + boolean hit = false; + + for (PathContext path : _paths) { + hit = hit | path.attr(name); + } + + return hit; + } + + public final void end() { + _stack.remove(_stack.size() - 1); + + for (PathContext path : _paths) { + path.end(); + } + } + + private final class PathContext { + + private XPathStep _curr; + private final List _prev = new ArrayList<>(); + + void init(XPathStep steps) { + _curr = steps; + _prev.clear(); + } + + private QName top(int i) { + return XPathExecutionContext.this._stack.get(_stack.size() - 1 - i); + } + + // goes back to the begining of the sequence since last // wildcard + private void backtrack() { + assert _curr != null; + + if (_curr._hasBacktrack) { // _backtrack seems to be a pointer to the step that follows a // wildcard + // ex: for .//b/c/d steps c and d should backtrack to b in case there isn't a match + _curr = _curr._backtrack; + return; + } + + assert !_curr._deep; + + _curr = _curr._prev; + + search: + for (; !_curr._deep; _curr = _curr._prev) { + int t = 0; + + for (XPathStep s = _curr; !s._deep; s = s._prev) { + if (!s.match(top(t++))) { + continue search; + } + } + + break; + } + } + + int start() { + assert _curr != null; + assert _curr._prev == null; + + if (_curr._name != null) { + return _curr._flags; + } + + // If the steps consist on only a terminator, then the path can + // only be '.'. In this case, we get a hit, but there is + // nothing else to match. No need to backtrack. + + _curr = null; + + return HIT; + } + + int element(QName name) { + //System.out.println(" Path.element: " + name); + _prev.add(_curr); + + if (_curr == null) { + return 0; + } + + assert _curr._name != null; + + if (!_curr._attr && _curr.match(name)) { + if ((_curr = _curr._next)._name != null) { + return _curr._flags; + } + + backtrack(); + + //System.out.println(" element - HIT " + _curr._flags); + return _curr == null ? HIT : HIT | _curr._flags; + } + + for (; ; ) { + backtrack(); + + if (_curr == null) { + return 0; + } + + if (_curr.match(name)) { + _curr = _curr._next; + break; + } + + if (_curr._deep) { + break; + } + } + + return _curr._flags; + } + + boolean attr(QName name) { + return _curr != null && _curr._attr && _curr.match(name); + } + + void end() { + //System.out.println(" Path.end "); + _curr = (XPathStep) _prev.remove(_prev.size() - 1); + } + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XPathFactory.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathFactory.java new file mode 100644 index 0000000..29029e9 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathFactory.java @@ -0,0 +1,189 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.store.Cur; +import org.apache.xmlbeans.impl.xpath.saxon.SaxonXPath; +import org.apache.xmlbeans.impl.xpath.saxon.SaxonXQuery; +import org.apache.xmlbeans.impl.xpath.xmlbeans.XmlbeansXPath; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class XPathFactory { + private static final int USE_XMLBEANS = 0x01; + private static final int USE_SAXON = 0x04; + + private static final Map> _xmlbeansPathCache = new WeakHashMap<>(); + private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + + static String getCurrentNodeVar(XmlOptions options) { + String currentNodeVar = "this"; + + options = XmlOptions.maskNull(options); + + String cnv = options.getXqueryCurrentNodeVar(); + if (cnv != null) { + currentNodeVar = cnv; + + if (currentNodeVar.startsWith("$")) { + throw new IllegalArgumentException("Omit the '$' prefix for the current node variable"); + } + } + + return currentNodeVar; + } + + public static Path getCompiledPath(String pathExpr, XmlOptions options) { + options = XmlOptions.maskNull(options); + return getCompiledPath(pathExpr, options, getCurrentNodeVar(options)); + } + + public static Path getCompiledPath(String pathExpr, XmlOptions options, String currentVar) { + int force = + options.isXPathUseSaxon() ? USE_SAXON + : options.isXPathUseXmlBeans() ? USE_XMLBEANS + : USE_XMLBEANS | USE_SAXON; + + Path path = null; + WeakReference pathWeakRef = null; + Map namespaces = (force & USE_SAXON) != 0 ? new HashMap<>() : null; + lock.readLock().lock(); + try { + if ((force & USE_XMLBEANS) != 0) { + pathWeakRef = _xmlbeansPathCache.get(pathExpr); + } + if (pathWeakRef != null) { + path = pathWeakRef.get(); + } + if (path != null) { + return path; + } + } finally { + lock.readLock().unlock(); + } + lock.writeLock().lock(); + try { + if ((force & USE_XMLBEANS) != 0) { + pathWeakRef = _xmlbeansPathCache.get(pathExpr); + if (pathWeakRef != null) { + path = pathWeakRef.get(); + } + if (path == null) { + path = getCompiledPathXmlBeans(pathExpr, currentVar, namespaces); + } + } + if (path == null && (force & USE_SAXON) != 0) { + path = getCompiledPathSaxon(pathExpr, currentVar, namespaces); + } + if (path == null) { + StringBuilder errMessage = new StringBuilder(); + if ((force & USE_XMLBEANS) != 0) { + errMessage.append(" Trying XmlBeans path engine..."); + } + if ((force & USE_SAXON) != 0) { + errMessage.append(" Trying Saxon path engine..."); + } + + throw new RuntimeException(errMessage.toString() + " FAILED on " + pathExpr); + } + } finally { + lock.writeLock().unlock(); + } + return path; + } + + private static Path getCompiledPathXmlBeans(String pathExpr, String currentVar, Map namespaces) { + try { + Path path = new XmlbeansXPath(pathExpr, currentVar, + XPath.compileXPath(pathExpr, currentVar, namespaces)); + _xmlbeansPathCache.put(pathExpr, new WeakReference<>(path)); + return path; + } catch (XPath.XPathCompileException ignored) { + return null; + } + } + + public static Path getCompiledPathSaxon(String pathExpr, String currentVar, Map namespaces) { + if (namespaces == null) { + namespaces = new HashMap<>(); + } + + try { + XPath.compileXPath(pathExpr, currentVar, namespaces); + } catch (XPath.XPathCompileException e) { + //do nothing, this function is only called to populate the namespaces map + } + + + int offset = Integer.parseInt(namespaces.getOrDefault(XPath._NS_BOUNDARY, "0")); + namespaces.remove(XPath._NS_BOUNDARY); + + return new SaxonXPath(pathExpr.substring(offset), currentVar, namespaces); + } + + + public static String compilePath(String pathExpr, XmlOptions options) { + getCompiledPath(pathExpr, options); + return pathExpr; + } + + // + // Xqrl store specific implementation of compiled path/query + // + + public static XmlObject[] objectExecQuery(Cur c, String queryExpr, XmlOptions options) { + return getCompiledQuery(queryExpr, options).objectExecute(c, options); + } + + public static XmlCursor cursorExecQuery(Cur c, String queryExpr, XmlOptions options) { + return getCompiledQuery(queryExpr, options).cursorExecute(c, options); + } + + public static synchronized XQuery getCompiledQuery(String queryExpr, XmlOptions options) { + return getCompiledQuery(queryExpr, XPathFactory.getCurrentNodeVar(options), options); + } + + static synchronized XQuery getCompiledQuery(String queryExpr, String currentVar, XmlOptions options) { + assert queryExpr != null; + options = XmlOptions.maskNull(options); + + //Parse the query via XmlBeans: need to figure out end of prolog + //in order to bind $this...not good but... + Map boundary = new HashMap<>(); + int boundaryVal; + try { + XPath.compileXPath(queryExpr, currentVar, boundary); + } catch (XPath.XPathCompileException e) { + //don't care if it fails, just care about boundary + } finally { + boundaryVal = Integer.parseInt(boundary.getOrDefault(XPath._NS_BOUNDARY, "0")); + } + + return new SaxonXQuery(queryExpr, currentVar, boundaryVal, options); + } + + public static synchronized String compileQuery(String queryExpr, XmlOptions options) { + getCompiledQuery(queryExpr, options); + return queryExpr; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XPathStep.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathStep.java new file mode 100644 index 0000000..ca2ef4c --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XPathStep.java @@ -0,0 +1,83 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import javax.xml.namespace.QName; + +class XPathStep { + + final boolean _attr; + final boolean _deep; + + int _flags; + + final QName _name; + + XPathStep _next, _prev; + + boolean _hasBacktrack; + XPathStep _backtrack; + + XPathStep(boolean deep, boolean attr, QName name) { + _name = name; + + _deep = deep; + _attr = attr; + + int flags = 0; + + if (_deep || !_attr) { + flags |= XPathExecutionContext.DESCEND; + } + + if (_attr) { + flags |= XPathExecutionContext.ATTRS; + } + + _flags = flags; + } + + boolean isWild() { + return _name.getLocalPart().length() == 0; + } + + boolean match(QName name) { + String local = _name.getLocalPart(); + String nameLocal = name.getLocalPart(); + + int localLength = local.length(); + + // match any name to _name when _name is empty ""@"" + if (localLength == 0) { + String uri = _name.getNamespaceURI(); + return uri.isEmpty() || uri.equals(name.getNamespaceURI()); + } + + if (localLength != nameLocal.length()) { + return false; + } + + String uri = _name.getNamespaceURI(); + String nameUri = name.getNamespaceURI(); + + if (uri.length() != nameUri.length()) { + return false; + } + + return local.equals(nameLocal) && uri.equals(nameUri); + } +} + diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/XQuery.java b/src/main/java/org/apache/xmlbeans/impl/xpath/XQuery.java new file mode 100644 index 0000000..9aae59b --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/XQuery.java @@ -0,0 +1,27 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.store.Cur; + +public interface XQuery { + XmlObject[] objectExecute(Cur c, XmlOptions options); + + XmlCursor cursorExecute(Cur c, XmlOptions options); +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPath.java b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPath.java new file mode 100644 index 0000000..be56ca0 --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPath.java @@ -0,0 +1,156 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath.saxon; + +import net.sf.saxon.Configuration; +import net.sf.saxon.dom.DOMNodeWrapper; +import net.sf.saxon.om.Item; +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.om.SequenceTool; +import net.sf.saxon.sxpath.*; +import net.sf.saxon.tree.wrapper.VirtualNode; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.store.Cur; +import org.apache.xmlbeans.impl.xpath.Path; +import org.apache.xmlbeans.impl.xpath.XPath; +import org.apache.xmlbeans.impl.xpath.XPathEngine; +import org.w3c.dom.Node; + +import javax.xml.transform.TransformerException; +import javax.xml.transform.dom.DOMSource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@SuppressWarnings("WeakerAccess") +public class SaxonXPath implements Path { + private final Map namespaceMap = new HashMap<>(); + private String path; + private String contextVar; + private String defaultNS; + + /** + * Construct given an XPath expression string. + * + * @param path The XPath expression + * @param contextVar The name of the context variable + * @param namespaceMap a map of prefix/uri bindings for NS support + */ + public SaxonXPath(String path, String contextVar, Map namespaceMap) { + this.path = path; + this.contextVar = contextVar; + this.defaultNS = namespaceMap.get(XPath._DEFAULT_ELT_NS); + this.namespaceMap.putAll(namespaceMap); + this.namespaceMap.remove(XPath._DEFAULT_ELT_NS); + } + + public XPathEngine execute(Cur c, XmlOptions options) { + return new SaxonXPathEngine(this, c); + } + + + /** + * Select all nodes that are selectable by this XPath + * expression. If multiple nodes match, multiple nodes + * will be returned. + *

      + *

      + * NOTE: In most cases, nodes will be returned + * in document-order, as defined by the XML Canonicalization + * specification. The exception occurs when using XPath + * expressions involving the union operator + * (denoted with the pipe '|' character). + *

      + *

      + *

      + * NOTE: Param node must be a DOM node which will be used + * during the xpath execution and iteration through the results. + * A call of node.dispose() must be done after reading all results. + *

      + * + * @param node The node, nodeset or Context object for evaluation. + * This value can be null. + * @return The List of all items selected + * by this XPath expression. + */ + public List selectNodes(Object node) { + try { + Node contextNode = (Node) node; + Configuration config = new Configuration(); + IndependentContext sc = new IndependentContext(config); + // Declare ns bindings + // also see https://saxonica.plan.io/issues/2130 + // (XPath referencing attribute with namespace fails when using DOM) + if (defaultNS != null) { + sc.setDefaultElementNamespace(defaultNS); + } + + namespaceMap.forEach(sc::declareNamespace); + + NodeInfo contextItem = config.unravel(new DOMSource(contextNode)); + + XPathEvaluator xpe = new XPathEvaluator(config); + xpe.setStaticContext(sc); + XPathVariable thisVar = sc.declareVariable("", contextVar); + XPathExpression xpath = xpe.createExpression(path); + XPathDynamicContext dc = xpath.createDynamicContext(null); + dc.setContextItem(contextItem); + dc.setVariable(thisVar, contextItem); + + List saxonNodes = xpath.evaluate(dc); + List retNodes = new ArrayList<>(saxonNodes.size()); + for (Item o : saxonNodes) { + if (o instanceof DOMNodeWrapper) { + Node n = getUnderlyingNode((DOMNodeWrapper) o); + retNodes.add(n); + } else if (o instanceof NodeInfo) { + retNodes.add(o.getStringValue()); + } else { + retNodes.add(SequenceTool.convertToJava(o)); + } + } + return retNodes; + } catch (TransformerException e) { + throw new RuntimeException(e); + } + } + + public List selectPath(Object node) { + return selectNodes(node); + } + + /** + * According to the Saxon javadoc: + * getUnderlyingNode in NodeWrapper implements + * the method specified in the interface VirtualNode, and + * the specification of the latter says that it may return another + * VirtualNode, and you may have to drill down through + * several layers of wrapping. + * To be safe, this method is provided to drill down through multiple + * layers of wrapping. + * + * @param v The VirtualNode + * @return The underlying node + */ + private static Node getUnderlyingNode(VirtualNode v) { + Object o = v; + while (o instanceof VirtualNode) { + o = ((VirtualNode) o).getUnderlyingNode(); + } + return (Node) o; + } +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPathEngine.java b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPathEngine.java new file mode 100644 index 0000000..ba64c5e --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXPathEngine.java @@ -0,0 +1,138 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath.saxon; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.store.Cur; +import org.apache.xmlbeans.impl.store.DomImpl; +import org.apache.xmlbeans.impl.store.Locale; +import org.apache.xmlbeans.impl.xpath.XPathEngine; +import org.apache.xmlbeans.impl.xpath.XPathExecutionContext; +import org.w3c.dom.Node; + +import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ConcurrentModificationException; +import java.util.Date; +import java.util.List; + +public class SaxonXPathEngine extends XPathExecutionContext implements XPathEngine { + // full datetime format: yyyy-MM-dd'T'HH:mm:ss'Z' + private final DateFormat xmlDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + + private Cur _cur; + private SaxonXPath _engine; + private boolean _firstCall = true; + private final long _version; + + + SaxonXPathEngine(SaxonXPath xpathImpl, Cur c) { + _engine = xpathImpl; + _version = c.getLocale().version(); + _cur = c.weakCur(this); + } + + public boolean next(Cur c) { + if (!_firstCall) { + return false; + } + + _firstCall = false; + + if (_cur != null && _version != _cur.getLocale().version()) { + throw new ConcurrentModificationException("Document changed during select"); + } + + List resultsList = _engine.selectPath(_cur.getDom()); + + int i; + for (i = 0; i < resultsList.size(); i++) { + //simple type function results + Object node = resultsList.get(i); + Cur pos = null; + if (!(node instanceof Node)) { + Object obj = resultsList.get(i); + String value; + if (obj instanceof Date) { + value = xmlDateFormat.format((Date) obj); + } else if (obj instanceof BigDecimal) { + value = ((BigDecimal) obj).toPlainString(); + } else { + value = obj.toString(); + } + + //we cannot leave the cursor's locale, as + //everything is done in the selections of this cursor + + org.apache.xmlbeans.impl.store.Locale l = c.getLocale(); + try { + pos = l.load("").tempCur(); + pos.setValue(value); + SchemaType type = getType(node); + Locale.autoTypeDocument(pos, type, null); + //move the cur to the actual text + pos.next(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + assert (node instanceof DomImpl.Dom) : + "New object created in XPATH!"; + pos = ((DomImpl.Dom) node).tempCur(); + + } + c.addToSelection(pos); + pos.release(); + } + release(); + _engine = null; + return true; + } + + private SchemaType getType(Object node) { + SchemaType type; + if (node instanceof Integer) { + type = XmlInteger.type; + } else if (node instanceof Double) { + type = XmlDouble.type; + } else if (node instanceof Long) { + type = XmlLong.type; + } else if (node instanceof Float) { + type = XmlFloat.type; + } else if (node instanceof BigDecimal) { + type = XmlDecimal.type; + } else if (node instanceof Boolean) { + type = XmlBoolean.type; + } else if (node instanceof String) { + type = XmlString.type; + } else if (node instanceof Date) { + type = XmlDate.type; + } else { + type = XmlAnySimpleType.type; + } + return type; + } + + public void release() { + if (_cur != null) { + _cur.release(); + _cur = null; + } + } + + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXQuery.java b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXQuery.java new file mode 100644 index 0000000..212b47b --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/saxon/SaxonXQuery.java @@ -0,0 +1,376 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath.saxon; + +import net.sf.saxon.Configuration; +import net.sf.saxon.dom.DocumentWrapper; +import net.sf.saxon.dom.NodeOverNodeInfo; +import net.sf.saxon.ma.map.HashTrieMap; +import net.sf.saxon.om.Item; +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.om.StructuredQName; +import net.sf.saxon.query.DynamicQueryContext; +import net.sf.saxon.query.StaticQueryContext; +import net.sf.saxon.query.XQueryExpression; +import net.sf.saxon.type.BuiltInAtomicType; +import net.sf.saxon.value.*; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.store.Cur; +import org.apache.xmlbeans.impl.store.Cursor; +import org.apache.xmlbeans.impl.store.Locale; +import org.apache.xmlbeans.impl.xpath.XQuery; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import javax.xml.datatype.DatatypeConstants; +import javax.xml.datatype.Duration; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPathException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.util.Date; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +public class SaxonXQuery implements XQuery { + private final XQueryExpression xquery; + private final String contextVar; + private final Configuration config; + + private Cur _cur; + private long _version; + private XmlOptions _options; + + + /** + * Construct given an XQuery expression string. + * + * @param query The XQuery expression + * @param contextVar The name of the context variable + * @param boundary The offset of the end of the prolog + */ + public SaxonXQuery(final String query, String contextVar, Integer boundary, XmlOptions xmlOptions) { + assert !(contextVar.startsWith(".") || contextVar.startsWith("..")); + + _options = xmlOptions; + + + config = new Configuration(); + StaticQueryContext sc = config.newStaticQueryContext(); + Map nsMap = xmlOptions.getLoadAdditionalNamespaces(); + if (nsMap != null) { + nsMap.forEach(sc::declareNamespace); + } + this.contextVar = contextVar; + //Saxon requires external variables at the end of the prolog... + try { + xquery = sc.compileQuery( + query.substring(0, boundary) + " declare variable $" + contextVar + " external;" + query.substring(boundary) + ); + } catch (TransformerException e) { + throw new XmlRuntimeException(e); + } + } + + + public XmlObject[] objectExecute(Cur c, XmlOptions options) { + _version = c.getLocale().version(); + _cur = c.weakCur(this); + this._options = options; + return objectExecute(); + } + + public XmlCursor cursorExecute(Cur c, XmlOptions options) { + _version = c.getLocale().version(); + _cur = c.weakCur(this); + this._options = options; + return cursorExecute(); + } + + + public List execQuery(Object node, Map variableBindings) { + try { + Node contextNode = (Node) node; + + Document dom = (contextNode.getNodeType() == Node.DOCUMENT_NODE) + ? (Document) contextNode : contextNode.getOwnerDocument(); + + DocumentWrapper docWrapper = new DocumentWrapper(dom, null, config); + NodeInfo root = docWrapper.wrap(contextNode); + + DynamicQueryContext dc = new DynamicQueryContext(config); + dc.setContextItem(root); + dc.setParameter(new StructuredQName("", null, contextVar), root); + // Set the other variables + if (variableBindings != null) { + for (Map.Entry me : ((Map) variableBindings).entrySet()) { + StructuredQName key = new StructuredQName("", null, me.getKey()); + Object value = me.getValue(); + if (value instanceof XmlTokenSource) { + Node paramObject = ((XmlTokenSource) value).getDomNode(); + dc.setParameter(key, docWrapper.wrap(paramObject)); + } else { + try { + dc.setParameter(key, objectToItem(value, config)); + } catch (XPathException e) { + throw new RuntimeException(e); + } + } + } + } + + List saxonNodes = xquery.evaluate(dc); + for (ListIterator it = saxonNodes.listIterator(); it.hasNext(); ) { + Object o = it.next(); + if (o instanceof NodeInfo) { + Node n = NodeOverNodeInfo.wrap((NodeInfo) o); + it.set(n); + } + } + return saxonNodes; + } catch (TransformerException e) { + throw new RuntimeException("Error binding " + contextVar, e); + } + } + + + private static Item objectToItem(Object value, Configuration config) throws XPathException, net.sf.saxon.trans.XPathException { + if (value == null) { + return null; + } + + // convert to switch.. + if (value instanceof Boolean) { + return BooleanValue.get((Boolean) value); + } else if (value instanceof byte[]) { + return new HexBinaryValue((byte[]) value); + } else if (value instanceof Byte) { + return new Int64Value((Byte) value, BuiltInAtomicType.BYTE, false); + } else if (value instanceof Float) { + return new FloatValue((Float) value); + } else if (value instanceof Double) { + return new DoubleValue((Double) value); + } else if (value instanceof Integer) { + return new Int64Value((Integer) value, BuiltInAtomicType.INT, false); + } else if (value instanceof Long) { + return new Int64Value((Long) value, BuiltInAtomicType.LONG, false); + } else if (value instanceof Short) { + return new Int64Value((Short) value, BuiltInAtomicType.SHORT, false); + } else if (value instanceof String) { + return new StringValue((String) value); + } else if (value instanceof BigDecimal) { + return new BigDecimalValue((BigDecimal) value); + } else if (value instanceof BigInteger) { + return new BigIntegerValue((BigInteger) value); + } else if (value instanceof SaxonDuration) { + return ((SaxonDuration) value).getDurationValue(); + } else if (value instanceof Duration) { + // this is simpler and safer (but perhaps slower) than extracting all the components + //return DurationValue.makeDuration(value.toString()).asAtomic(); + Duration dv = (Duration) value; + return new DurationValue(dv.getSign() >= 0, dv.getYears(), dv.getMonths(), dv.getDays(), + dv.getHours(), dv.getMinutes(), dv.getSeconds(), 0); // take correct millis.. + } else if (value instanceof SaxonXMLGregorianCalendar) { + return ((SaxonXMLGregorianCalendar) value).toCalendarValue(); + } else if (value instanceof XMLGregorianCalendar) { + XMLGregorianCalendar g = (XMLGregorianCalendar) value; + QName gtype = g.getXMLSchemaType(); + if (gtype.equals(DatatypeConstants.DATETIME)) { + return DateTimeValue.makeDateTimeValue(value.toString(), config.getConversionRules()).asAtomic(); + } else if (gtype.equals(DatatypeConstants.DATE)) { + return DateValue.makeDateValue(value.toString(), config.getConversionRules()).asAtomic(); + } else if (gtype.equals(DatatypeConstants.TIME)) { + return TimeValue.makeTimeValue(value.toString()).asAtomic(); + } else if (gtype.equals(DatatypeConstants.GYEAR)) { + return GYearValue.makeGYearValue(value.toString(), config.getConversionRules()).asAtomic(); + } else if (gtype.equals(DatatypeConstants.GYEARMONTH)) { + return GYearMonthValue.makeGYearMonthValue(value.toString(), config.getConversionRules()).asAtomic(); + } else if (gtype.equals(DatatypeConstants.GMONTH)) { + // a workaround for W3C schema bug + String val = value.toString(); + if (val.endsWith("--")) { + val = val.substring(0, val.length() - 2); + } + return GMonthValue.makeGMonthValue(val).asAtomic(); + } else if (gtype.equals(DatatypeConstants.GMONTHDAY)) { + return GMonthDayValue.makeGMonthDayValue(value.toString()).asAtomic(); + } else if (gtype.equals(DatatypeConstants.GDAY)) { + return GDayValue.makeGDayValue(value.toString()).asAtomic(); + } else { + throw new AssertionError("Unknown Gregorian date type"); + } + } else if (value instanceof QName) { + QName q = (QName) value; + return new QNameValue(q.getPrefix(), q.getNamespaceURI(), q.getLocalPart()); //BuiltInAtomicType.QNAME, null); + } else if (value instanceof URI) { + return new AnyURIValue(value.toString()); + } else if (value instanceof Map) { + HashTrieMap htm = new HashTrieMap(); + for (Map.Entry me : ((Map) value).entrySet()) { + htm.initialPut( + (AtomicValue) objectToItem(me.getKey(), config), + objectToItem(me.getValue(), config)); + } + return htm; + } else { + return new ObjectValue(value); + } + } + + + public XmlObject[] objectExecute() { + if (_cur != null && _version != _cur.getLocale().version()) + //throw new ConcurrentModificationException + // ("Document changed during select") + { + ; + } + + Map bindings = XmlOptions.maskNull(_options).getXqueryVariables(); + List resultsList = execQuery(_cur.getDom(), bindings); + + XmlObject[] result = new XmlObject[resultsList.size()]; + int i; + for (i = 0; i < resultsList.size(); i++) { + //copy objects into the locale + Locale l = Locale.getLocale(_cur.getLocale().getSchemaTypeLoader(), _options); + + l.enter(); + Object node = resultsList.get(i); + Cur res = null; + try { + //typed function results of XQuery + if (!(node instanceof Node)) { + //TODO: exact same code as Path.java + //make a common super-class and pull this--what to name that + //superclass??? + res = l.load("").tempCur(); + res.setValue(node.toString()); + SchemaType type = getType(node); + Locale.autoTypeDocument(res, type, null); + result[i] = res.getObject(); + } else { + res = loadNode(l, (Node) node); + } + result[i] = res.getObject(); + } catch (XmlException e) { + throw new RuntimeException(e); + } finally { + l.exit(); + } + res.release(); + } + release(); + return result; + } + + private SchemaType getType(Object node) { + SchemaType type; + if (node instanceof Integer) { + type = XmlInteger.type; + } else if (node instanceof Double) { + type = XmlDouble.type; + } else if (node instanceof Long) { + type = XmlLong.type; + } else if (node instanceof Float) { + type = XmlFloat.type; + } else if (node instanceof BigDecimal) { + type = XmlDecimal.type; + } else if (node instanceof Boolean) { + type = XmlBoolean.type; + } else if (node instanceof String) { + type = XmlString.type; + } else if (node instanceof Date) { + type = XmlDate.type; + } else { + type = XmlAnySimpleType.type; + } + return type; + } + + public XmlCursor cursorExecute() { + if (_cur != null && _version != _cur.getLocale().version()) + //throw new ConcurrentModificationException + // ("Document changed during select") + { + ; + } + + Map bindings = XmlOptions.maskNull(_options).getXqueryVariables(); + List resultsList = execQuery(_cur.getDom(), bindings); + + int i; + + Locale locale = Locale.getLocale(_cur.getLocale().getSchemaTypeLoader(), _options); + locale.enter(); + Locale.LoadContext _context = new Cur.CurLoadContext(locale, _options); + Cursor resultCur = null; + try { + for (i = 0; i < resultsList.size(); i++) { + loadNodeHelper(locale, (Node) resultsList.get(i), _context); + } + Cur c = _context.finish(); + Locale.associateSourceName(c, _options); + Locale.autoTypeDocument(c, null, _options); + resultCur = new Cursor(c); + } catch (Exception e) { + } finally { + locale.exit(); + } + release(); + return resultCur; + } + + + public void release() { + if (_cur != null) { + _cur.release(); + _cur = null; + } + } + + + private Cur loadNode(Locale locale, Node node) { + Locale.LoadContext context = new Cur.CurLoadContext(locale, _options); + + try { + loadNodeHelper(locale, node, context); + Cur c = context.finish(); + Locale.associateSourceName(c, _options); + Locale.autoTypeDocument(c, null, _options); + return c; + } catch (Exception e) { + throw new XmlRuntimeException(e.getMessage(), e); + } + } + + private void loadNodeHelper(Locale locale, Node node, Locale.LoadContext context) { + if (node.getNodeType() == Node.ATTRIBUTE_NODE) { + QName attName = new QName(node.getNamespaceURI(), + node.getLocalName(), + node.getPrefix()); + context.attr(attName, node.getNodeValue()); + } else { + locale.loadNode(node, context); + } + + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/xmlbeans/XmlbeansXPath.java b/src/main/java/org/apache/xmlbeans/impl/xpath/xmlbeans/XmlbeansXPath.java new file mode 100644 index 0000000..3ef314d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/xmlbeans/XmlbeansXPath.java @@ -0,0 +1,56 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath.xmlbeans; + +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.store.Cur; +import org.apache.xmlbeans.impl.xpath.Path; +import org.apache.xmlbeans.impl.xpath.XPath; +import org.apache.xmlbeans.impl.xpath.XPathEngine; +import org.apache.xmlbeans.impl.xpath.XPathFactory; + +// +// XmlBeans store specific implementation of compiled path +// + +public class XmlbeansXPath implements Path { + private final String _pathKey; + private final String _currentVar; + private final XPath _compiledPath; + + public XmlbeansXPath(String pathExpr, String currentVar, XPath xpath) { + _pathKey = pathExpr; + + _currentVar = currentVar; + _compiledPath = xpath; + } + + public XPathEngine execute(Cur c, XmlOptions options) { + options = XmlOptions.maskNull(options); + + // The builtin XPath engine works only on containers. Delegate to + // saxon otherwise. Also, if the path had a //. at the end, the + // simple xpath engine can't do the generate case, it only handles + // attrs and elements. + if (!c.isContainer() || _compiledPath.sawDeepDot()) { + Path xpe = XPathFactory.getCompiledPathSaxon(_pathKey, _currentVar, null); + return xpe.execute(c, options); + } else { + return new XmlbeansXPathEngine(_compiledPath, c); + } + } + +} diff --git a/src/main/java/org/apache/xmlbeans/impl/xpath/xmlbeans/XmlbeansXPathEngine.java b/src/main/java/org/apache/xmlbeans/impl/xpath/xmlbeans/XmlbeansXPathEngine.java new file mode 100644 index 0000000..82c583f --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xpath/xmlbeans/XmlbeansXPathEngine.java @@ -0,0 +1,126 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xpath.xmlbeans; + +import org.apache.xmlbeans.impl.store.Cur; +import org.apache.xmlbeans.impl.store.Locale; +import org.apache.xmlbeans.impl.xpath.XPath; +import org.apache.xmlbeans.impl.xpath.XPathEngine; +import org.apache.xmlbeans.impl.xpath.XPathExecutionContext; + +import java.util.ConcurrentModificationException; + +class XmlbeansXPathEngine extends XPathExecutionContext implements XPathEngine { + XmlbeansXPathEngine(XPath xpath, Cur c) { + assert c.isContainer(); + + _version = c.getLocale().version(); + _cur = c.weakCur(this); + + _cur.push(); + + init(xpath); + + int ret = start(); + + if ((ret & HIT) != 0) { + c.addToSelection(); + } + + doAttrs(ret, c); + + if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur)) { + release(); + } + } + + private void advance(Cur c) { + assert _cur != null; + + if (_cur.isFinish()) { + if (_cur.isAtEndOfLastPush()) { + release(); + } else { + end(); + _cur.next(); + } + } else if (_cur.isElem()) { + int ret = element(_cur.getName()); + + if ((ret & HIT) != 0) { + c.addToSelection(_cur); + } + + doAttrs(ret, c); + + if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur)) { + end(); + _cur.skip(); + } + } else { + do { + _cur.next(); + } + while (!_cur.isContainerOrFinish()); + } + } + + private void doAttrs(int ret, Cur c) { + assert _cur.isContainer(); + + if ((ret & ATTRS) != 0) { + if (_cur.toFirstAttr()) { + do { + if (attr(_cur.getName())) { + c.addToSelection(_cur); + } + } + while (_cur.toNextAttr()); + + _cur.toParent(); + } + } + } + + public boolean next(Cur c) { + if (_cur != null && _version != _cur.getLocale().version()) { + throw new ConcurrentModificationException("Document changed during select"); + } + + int startCount = c.selectionCount(); + + while (_cur != null) { + advance(c); + + if (startCount != c.selectionCount()) { + return true; + } + } + + return false; + } + + public void release() { + if (_cur != null) { + _cur.release(); + _cur = null; + } + } + + private final long _version; + private Cur _cur; +} + diff --git a/src/tools/org/apache/xmlbeans/impl/xpathgen/XPathGenerationException.java b/src/main/java/org/apache/xmlbeans/impl/xpathgen/XPathGenerationException.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/xpathgen/XPathGenerationException.java rename to src/main/java/org/apache/xmlbeans/impl/xpathgen/XPathGenerationException.java diff --git a/src/tools/org/apache/xmlbeans/impl/xpathgen/XPathGenerator.java b/src/main/java/org/apache/xmlbeans/impl/xpathgen/XPathGenerator.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/xpathgen/XPathGenerator.java rename to src/main/java/org/apache/xmlbeans/impl/xpathgen/XPathGenerator.java diff --git a/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java b/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java new file mode 100644 index 0000000..0c1b76a --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java @@ -0,0 +1,1050 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.xsd2inst; + +/* + * TODO: + * Comment on enumerations? + * Comment on facets? + * Have a verbose option? + * Have a sample data option, would create valid instance with sample data? + * Add the pattern facet; this is tricky, considering the relationship with length + */ + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.util.HexBin; +import org.apache.xmlbeans.soap.SOAPArrayType; +import org.apache.xmlbeans.soap.SchemaWSDLArrayType; + +import javax.xml.namespace.QName; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class SampleXmlUtil { + private final boolean _soapEnc; + private static final int MAX_ELEMENTS = 1000; + private int _nElements; + + private SampleXmlUtil(boolean soapEnc) { + _soapEnc = soapEnc; + } + + public static String createSampleForType(SchemaType sType) { + XmlObject object = XmlObject.Factory.newInstance(); + XmlCursor cursor = object.newCursor(); + // Skip the document node + cursor.toNextToken(); + // Using the type and the cursor, call the utility method to get a + // sample XML payload for that Schema element + new SampleXmlUtil(false).createSampleForType(sType, cursor); + // Cursor now contains the sample payload + // Pretty print the result. Note that the cursor is positioned at the + // end of the doc so we use the original xml object that the cursor was + // created upon to do the xmlText() against. + XmlOptions options = new XmlOptions(); + options.setSavePrettyPrint(); + options.setSavePrettyPrintIndent(2); + options.setSaveAggressiveNamespaces(); + return object.xmlText(options); + } + + Random _picker = new Random(1); + + /** + * Cursor position + * Before: + * ^ + * After: + * ^ + */ + private void createSampleForType(SchemaType stype, XmlCursor xmlc) { + if (_typeStack.contains(stype)) { + return; + } + + _typeStack.add(stype); + + try { + if (stype.isSimpleType() || stype.isURType()) { + processSimpleType(stype, xmlc); + return; + } + + // complex Type + // ^ + processAttributes(stype, xmlc); + + // ^ + switch (stype.getContentType()) { + case SchemaType.NOT_COMPLEX_TYPE: + case SchemaType.EMPTY_CONTENT: + // noop + break; + case SchemaType.SIMPLE_CONTENT: { + processSimpleType(stype, xmlc); + } + break; + case SchemaType.MIXED_CONTENT: + xmlc.insertChars(pick(WORDS) + " "); + if (stype.getContentModel() != null) { + processParticle(stype.getContentModel(), xmlc, true); + } + xmlc.insertChars(pick(WORDS)); + break; + case SchemaType.ELEMENT_CONTENT: + if (stype.getContentModel() != null) { + processParticle(stype.getContentModel(), xmlc, false); + } + break; + } + } finally { + _typeStack.remove(_typeStack.size() - 1); + } + } + + private void processSimpleType(SchemaType stype, XmlCursor xmlc) { + String sample = sampleDataForSimpleType(stype); + xmlc.insertChars(sample); + } + + private String sampleDataForSimpleType(SchemaType sType) { + if (XmlObject.type.equals(sType)) { + return "anyType"; + } + + if (XmlAnySimpleType.type.equals(sType)) { + return "anySimpleType"; + } + + if (sType.getSimpleVariety() == SchemaType.LIST) { + SchemaType itemType = sType.getListItemType(); + StringBuilder sb = new StringBuilder(); + int length = pickLength(sType); + if (length > 0) { + sb.append(sampleDataForSimpleType(itemType)); + } + for (int i = 1; i < length; i += 1) { + sb.append(' '); + sb.append(sampleDataForSimpleType(itemType)); + } + return sb.toString(); + } + + if (sType.getSimpleVariety() == SchemaType.UNION) { + SchemaType[] possibleTypes = sType.getUnionConstituentTypes(); + if (possibleTypes.length == 0) { + return ""; + } + return sampleDataForSimpleType(possibleTypes[pick(possibleTypes.length)]); + } + + XmlAnySimpleType[] enumValues = sType.getEnumerationValues(); + if (enumValues != null && enumValues.length > 0) { + return enumValues[pick(enumValues.length)].getStringValue(); + } + + switch (sType.getPrimitiveType().getBuiltinTypeCode()) { + default: + case SchemaType.BTC_NOT_BUILTIN: + return ""; + + case SchemaType.BTC_ANY_TYPE: + case SchemaType.BTC_ANY_SIMPLE: + return "anything"; + + case SchemaType.BTC_BOOLEAN: + return pick(2) == 0 ? "true" : "false"; + + case SchemaType.BTC_BASE_64_BINARY: { + byte[] v = formatToLength(pick(WORDS), sType).getBytes(StandardCharsets.UTF_8); + return Base64.getEncoder().encodeToString(v); + } + + case SchemaType.BTC_HEX_BINARY: + return HexBin.encode(formatToLength(pick(WORDS), sType)); + + case SchemaType.BTC_ANY_URI: + return formatToLength("http://www." + pick(DNS1) + "." + pick(DNS2) + "/" + pick(WORDS) + "/" + pick(WORDS), sType); + + case SchemaType.BTC_QNAME: + return formatToLength("qname", sType); + + case SchemaType.BTC_NOTATION: + return formatToLength("notation", sType); + + case SchemaType.BTC_FLOAT: + return "1.5E2"; + case SchemaType.BTC_DOUBLE: + return "1.051732E7"; + case SchemaType.BTC_DECIMAL: + switch (closestBuiltin(sType).getBuiltinTypeCode()) { + case SchemaType.BTC_SHORT: + return formatDecimal("1", sType); + case SchemaType.BTC_UNSIGNED_SHORT: + return formatDecimal("5", sType); + case SchemaType.BTC_BYTE: + return formatDecimal("2", sType); + case SchemaType.BTC_UNSIGNED_BYTE: + return formatDecimal("6", sType); + case SchemaType.BTC_INT: + return formatDecimal("3", sType); + case SchemaType.BTC_UNSIGNED_INT: + return formatDecimal("7", sType); + case SchemaType.BTC_LONG: + return formatDecimal("10", sType); + case SchemaType.BTC_UNSIGNED_LONG: + return formatDecimal("11", sType); + case SchemaType.BTC_INTEGER: + return formatDecimal("100", sType); + case SchemaType.BTC_NON_POSITIVE_INTEGER: + return formatDecimal("-200", sType); + case SchemaType.BTC_NEGATIVE_INTEGER: + return formatDecimal("-201", sType); + case SchemaType.BTC_NON_NEGATIVE_INTEGER: + return formatDecimal("200", sType); + case SchemaType.BTC_POSITIVE_INTEGER: + return formatDecimal("201", sType); + default: + case SchemaType.BTC_DECIMAL: + return formatDecimal("1000.00", sType); + } + + case SchemaType.BTC_STRING: { + String result = closestBuiltin(sType).getBuiltinTypeCode() == SchemaType.BTC_TOKEN ? "token" : "string"; + + return formatToLength(result, sType); + } + + case SchemaType.BTC_DURATION: + return formatDuration(sType); + + case SchemaType.BTC_DATE_TIME: + case SchemaType.BTC_TIME: + case SchemaType.BTC_DATE: + case SchemaType.BTC_G_YEAR_MONTH: + case SchemaType.BTC_G_YEAR: + case SchemaType.BTC_G_MONTH_DAY: + case SchemaType.BTC_G_DAY: + case SchemaType.BTC_G_MONTH: + return formatDate(sType); + } + } + + // a bit from the Aenid + public static final String[] WORDS = new String[] + { + "ipsa", "iovis", "rapidum", "iaculata", "e", "nubibus", "ignem", + "disiecitque", "rates", "evertitque", "aequora", "ventis", + "illum", "exspirantem", "transfixo", "pectore", "flammas", + "turbine", "corripuit", "scopuloque", "infixit", "acuto", + "ast", "ego", "quae", "divum", "incedo", "regina", "iovisque", + "et", "soror", "et", "coniunx", "una", "cum", "gente", "tot", "annos", + "bella", "gero", "et", "quisquam", "numen", "iunonis", "adorat", + "praeterea", "aut", "supplex", "aris", "imponet", "honorem", + "talia", "flammato", "secum", "dea", "corde", "volutans", + "nimborum", "in", "patriam", "loca", "feta", "furentibus", "austris", + "aeoliam", "venit", "hic", "vasto", "rex", "aeolus", "antro", + "luctantis", "ventos", "tempestatesque", "sonoras", + "imperio", "premit", "ac", "vinclis", "et", "carcere", "frenat", + "illi", "indignantes", "magno", "cum", "murmure", "montis", + "circum", "claustra", "fremunt", "celsa", "sedet", "aeolus", "arce", + "sceptra", "tenens", "mollitque", "animos", "et", "temperat", "iras", + "ni", "faciat", "maria", "ac", "terras", "caelumque", "profundum", + "quippe", "ferant", "rapidi", "secum", "verrantque", "per", "auras", + "sed", "pater", "omnipotens", "speluncis", "abdidit", "atris", + "hoc", "metuens", "molemque", "et", "montis", "insuper", "altos", + "imposuit", "regemque", "dedit", "qui", "foedere", "certo", + "et", "premere", "et", "laxas", "sciret", "dare", "iussus", "habenas", + }; + + + private static final String[] DNS1 = new String[]{"corp", "your", "my", "sample", "company", "test", "any"}; + private static final String[] DNS2 = new String[]{"com", "org", "com", "gov", "org", "com", "org", "com", "edu"}; + + private int pick(int n) { + return _picker.nextInt(n); + } + + private String pick(String[] a) { + return a[pick(a.length)]; + } + + private int pickLength(SchemaType sType) { + XmlInteger length = (XmlInteger) sType.getFacet(SchemaType.FACET_LENGTH); + if (length != null) { + return length.getBigIntegerValue().intValue(); + } + XmlInteger min = (XmlInteger) sType.getFacet(SchemaType.FACET_MIN_LENGTH); + XmlInteger max = (XmlInteger) sType.getFacet(SchemaType.FACET_MAX_LENGTH); + int minInt, maxInt; + if (min == null) { + minInt = 0; + } else { + minInt = min.getBigIntegerValue().intValue(); + } + if (max == null) { + maxInt = Integer.MAX_VALUE; + } else { + maxInt = max.getBigIntegerValue().intValue(); + } + // We try to keep the length of the array within reasonable limits, + // at least 1 item and at most 3 if possible + if (minInt == 0 && maxInt >= 1) { + minInt = 1; + } + if (maxInt > minInt + 2) { + maxInt = minInt + 2; + } + if (maxInt < minInt) { + maxInt = minInt; + } + return minInt + pick(maxInt - minInt); + } + + /** + * Formats a given string to the required length, using the following operations: + * - append the source string to itself as necessary to pass the minLength; + * - truncate the result of previous step, if necessary, to keep it within minLength. + */ + private String formatToLength(String s, SchemaType sType) { + String result = s; + try { + SimpleValue min = (SimpleValue) sType.getFacet(SchemaType.FACET_LENGTH); + if (min == null) { + min = (SimpleValue) sType.getFacet(SchemaType.FACET_MIN_LENGTH); + } + if (min != null) { + int len = min.getIntValue(); + while (result.length() < len) { + result = result + result; + } + } + SimpleValue max = (SimpleValue) sType.getFacet(SchemaType.FACET_LENGTH); + if (max == null) { + max = (SimpleValue) sType.getFacet(SchemaType.FACET_MAX_LENGTH); + } + if (max != null) { + int len = max.getIntValue(); + if (result.length() > len) { + result = result.substring(0, len); + } + } + } catch (Exception ignored) { + // intValue can be out of range + } + return result; + } + + private String formatDecimal(String start, SchemaType sType) { + BigDecimal result = new BigDecimal(start); + XmlDecimal xmlD; + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null; + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null; + boolean minInclusive = true, maxInclusive = true; + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (xmlD != null) { + BigDecimal minExcl = xmlD.getBigDecimalValue(); + if (min == null || min.compareTo(minExcl) < 0) { + min = minExcl; + minInclusive = false; + } + } + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (xmlD != null) { + BigDecimal maxExcl = xmlD.getBigDecimalValue(); + if (max == null || max.compareTo(maxExcl) > 0) { + max = maxExcl; + maxInclusive = false; + } + } + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); + int totalDigits = -1; + if (xmlD != null) { + totalDigits = xmlD.getBigDecimalValue().intValue(); + + StringBuilder sb = new StringBuilder(totalDigits); + for (int i = 0; i < totalDigits; i++) { + sb.append('9'); + } + BigDecimal digitsLimit = new BigDecimal(sb.toString()); + if (max != null && max.compareTo(digitsLimit) > 0) { + max = digitsLimit; + maxInclusive = true; + } + digitsLimit = digitsLimit.negate(); + if (min != null && min.compareTo(digitsLimit) < 0) { + min = digitsLimit; + minInclusive = true; + } + } + + int sigMin = min == null ? 1 : result.compareTo(min); + int sigMax = max == null ? -1 : result.compareTo(max); + boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive; + boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive; + + // Compute the minimum increment + xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS); + int fractionDigits = -1; + BigDecimal increment; + if (xmlD == null) { + increment = new BigDecimal(1); + } else { + fractionDigits = xmlD.getBigDecimalValue().intValue(); + if (fractionDigits > 0) { + StringBuilder sb = new StringBuilder("0."); + for (int i = 1; i < fractionDigits; i++) { + sb.append('0'); + } + sb.append('1'); + increment = new BigDecimal(sb.toString()); + } else { + increment = BigDecimal.ONE; + } + } + + //noinspection StatementWithEmptyBody + if (minOk && maxOk) { + // OK + } else if (minOk && !maxOk) { + // TOO BIG + if (maxInclusive) { + result = max; + } else { + result = max.subtract(increment); + } + } else if (!minOk && maxOk) { + // TOO SMALL + if (minInclusive) { + result = min; + } else { + result = min.add(increment); + } + } else { + // MIN > MAX!! + } + + // We have the number + // Adjust the scale according to the totalDigits and fractionDigits + int digits = 0; + BigDecimal ONE = new BigDecimal(BigInteger.ONE); + for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++) { + n = n.movePointLeft(1); + } + + if (fractionDigits > 0) { + if (totalDigits >= 0) { + result = result.setScale(Math.max(fractionDigits, totalDigits - digits)); + } else { + result = result.setScale(fractionDigits); + } + } else if (fractionDigits == 0) { + result = result.setScale(0); + } + + return result.toString(); + } + + private String formatDuration(SchemaType sType) { + XmlDuration d = + (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + GDuration minInclusive = null; + if (d != null) { + minInclusive = d.getGDurationValue(); + } + + d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + GDuration maxInclusive = null; + if (d != null) { + maxInclusive = d.getGDurationValue(); + } + + d = (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + GDuration minExclusive = null; + if (d != null) { + minExclusive = d.getGDurationValue(); + } + + d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + GDuration maxExclusive = null; + if (d != null) { + maxExclusive = d.getGDurationValue(); + } + + GDurationBuilder gdurb = new GDurationBuilder(); + + gdurb.setSecond(pick(800000)); + gdurb.setMonth(pick(20)); + + // Years + // Months + // Days + // Hours + // Minutes + // Seconds + // Fractions + if (minInclusive != null) { + if (gdurb.getYear() < minInclusive.getYear()) { + gdurb.setYear(minInclusive.getYear()); + } + if (gdurb.getMonth() < minInclusive.getMonth()) { + gdurb.setMonth(minInclusive.getMonth()); + } + if (gdurb.getDay() < minInclusive.getDay()) { + gdurb.setDay(minInclusive.getDay()); + } + if (gdurb.getHour() < minInclusive.getHour()) { + gdurb.setHour(minInclusive.getHour()); + } + if (gdurb.getMinute() < minInclusive.getMinute()) { + gdurb.setMinute(minInclusive.getMinute()); + } + if (gdurb.getSecond() < minInclusive.getSecond()) { + gdurb.setSecond(minInclusive.getSecond()); + } + if (gdurb.getFraction().compareTo(minInclusive.getFraction()) < 0) { + gdurb.setFraction(minInclusive.getFraction()); + } + } + + if (maxInclusive != null) { + if (gdurb.getYear() > maxInclusive.getYear()) { + gdurb.setYear(maxInclusive.getYear()); + } + if (gdurb.getMonth() > maxInclusive.getMonth()) { + gdurb.setMonth(maxInclusive.getMonth()); + } + if (gdurb.getDay() > maxInclusive.getDay()) { + gdurb.setDay(maxInclusive.getDay()); + } + if (gdurb.getHour() > maxInclusive.getHour()) { + gdurb.setHour(maxInclusive.getHour()); + } + if (gdurb.getMinute() > maxInclusive.getMinute()) { + gdurb.setMinute(maxInclusive.getMinute()); + } + if (gdurb.getSecond() > maxInclusive.getSecond()) { + gdurb.setSecond(maxInclusive.getSecond()); + } + if (gdurb.getFraction().compareTo(maxInclusive.getFraction()) > 0) { + gdurb.setFraction(maxInclusive.getFraction()); + } + } + + if (minExclusive != null) { + if (gdurb.getYear() <= minExclusive.getYear()) { + gdurb.setYear(minExclusive.getYear() + 1); + } + if (gdurb.getMonth() <= minExclusive.getMonth()) { + gdurb.setMonth(minExclusive.getMonth() + 1); + } + if (gdurb.getDay() <= minExclusive.getDay()) { + gdurb.setDay(minExclusive.getDay() + 1); + } + if (gdurb.getHour() <= minExclusive.getHour()) { + gdurb.setHour(minExclusive.getHour() + 1); + } + if (gdurb.getMinute() <= minExclusive.getMinute()) { + gdurb.setMinute(minExclusive.getMinute() + 1); + } + if (gdurb.getSecond() <= minExclusive.getSecond()) { + gdurb.setSecond(minExclusive.getSecond() + 1); + } + if (gdurb.getFraction().compareTo(minExclusive.getFraction()) <= 0) { + gdurb.setFraction(minExclusive.getFraction().add(new BigDecimal("0.001"))); + } + } + + if (maxExclusive != null) { + if (gdurb.getYear() > maxExclusive.getYear()) { + gdurb.setYear(maxExclusive.getYear()); + } + if (gdurb.getMonth() > maxExclusive.getMonth()) { + gdurb.setMonth(maxExclusive.getMonth()); + } + if (gdurb.getDay() > maxExclusive.getDay()) { + gdurb.setDay(maxExclusive.getDay()); + } + if (gdurb.getHour() > maxExclusive.getHour()) { + gdurb.setHour(maxExclusive.getHour()); + } + if (gdurb.getMinute() > maxExclusive.getMinute()) { + gdurb.setMinute(maxExclusive.getMinute()); + } + if (gdurb.getSecond() > maxExclusive.getSecond()) { + gdurb.setSecond(maxExclusive.getSecond()); + } + if (gdurb.getFraction().compareTo(maxExclusive.getFraction()) > 0) { + gdurb.setFraction(maxExclusive.getFraction()); + } + } + + gdurb.normalize(); + return gdurb.toString(); + } + + private String formatDate(SchemaType sType) { + GDateBuilder gdateb = new GDateBuilder(new Date(1000L * pick(365 * 24 * 60 * 60) + (30L + pick(20)) * 365 * 24 * 60 * 60 * 1000)); + GDate min = null, max = null; + + // Find the min and the max according to the type + switch (sType.getPrimitiveType().getBuiltinTypeCode()) { + case SchemaType.BTC_DATE_TIME: { + XmlDateTime x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_TIME: { + XmlTime x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_DATE: { + XmlDate x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_G_YEAR_MONTH: { + XmlGYearMonth x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_G_YEAR: { + XmlGYear x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_G_MONTH_DAY: { + XmlGMonthDay x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_G_DAY: { + XmlGDay x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + case SchemaType.BTC_G_MONTH: { + XmlGMonth x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); + if (x != null) { + min = x.getGDateValue(); + } + x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); + if (x != null) { + if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) { + min = x.getGDateValue(); + } + } + + x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); + if (x != null) { + max = x.getGDateValue(); + } + x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); + if (x != null) { + if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) { + max = x.getGDateValue(); + } + } + break; + } + } + + if (min != null && max == null) { + if (min.compareToGDate(gdateb) >= 0) { + // Reset the date to min + (1-8) hours + Calendar c = gdateb.getCalendar(); + c.add(Calendar.HOUR_OF_DAY, pick(8)); + gdateb = new GDateBuilder(c); + } + } else if (min == null && max != null) { + if (max.compareToGDate(gdateb) <= 0) { + // Reset the date to max - (1-8) hours + Calendar c = gdateb.getCalendar(); + c.add(Calendar.HOUR_OF_DAY, -pick(8)); + gdateb = new GDateBuilder(c); + } + } else if (min != null && max != null) { + if (min.compareToGDate(gdateb) >= 0 || max.compareToGDate(gdateb) <= 0) { + // Find a date between the two + Calendar c = min.getCalendar(); + Calendar cmax = max.getCalendar(); + c.add(Calendar.HOUR_OF_DAY, 1); + if (c.after(cmax)) { + c.add(Calendar.HOUR_OF_DAY, -1); + c.add(Calendar.MINUTE, 1); + if (c.after(cmax)) { + c.add(Calendar.MINUTE, -1); + c.add(Calendar.SECOND, 1); + if (c.after(cmax)) { + c.add(Calendar.SECOND, -1); + c.add(Calendar.MILLISECOND, 1); + if (c.after(cmax)) { + c.add(Calendar.MILLISECOND, -1); + } + } + } + } + gdateb = new GDateBuilder(c); + } + } + + gdateb.setBuiltinTypeCode(sType.getPrimitiveType().getBuiltinTypeCode()); + if (pick(2) == 0) { + gdateb.clearTimeZone(); + } + return gdateb.toString(); + } + + private SchemaType closestBuiltin(SchemaType sType) { + while (!sType.isBuiltinType()) { + sType = sType.getBaseType(); + } + return sType; + } + + /** + * Cracks a combined QName of the form URL:localname + */ + public static QName crackQName(String qName) { + String ns; + String name; + + int index = qName.lastIndexOf(':'); + if (index >= 0) { + ns = qName.substring(0, index); + name = qName.substring(index + 1); + } else { + ns = ""; + name = qName; + } + + return new QName(ns, name); + } + + + /** + * Cursor position: + * Before this call: + * ^ (cursor at the ^) + * After this call: + * <som text^ + */ + private void processParticle(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + int loop = determineMinMaxForSample(sp, xmlc); + + while (loop-- > 0) { + switch (sp.getParticleType()) { + case (SchemaParticle.ELEMENT): + processElement(sp, xmlc, mixed); + break; + case (SchemaParticle.SEQUENCE): + processSequence(sp, xmlc, mixed); + break; + case (SchemaParticle.CHOICE): + processChoice(sp, xmlc, mixed); + break; + case (SchemaParticle.ALL): + processAll(sp, xmlc, mixed); + break; + case (SchemaParticle.WILDCARD): + processWildCard(sp, xmlc, mixed); + break; + default: + // throw new Exception("No Match on Schema Particle Type: " + String.valueOf(sp.getParticleType())); + } + } + } + + private int determineMinMaxForSample(SchemaParticle sp, XmlCursor xmlc) { + int minOccurs = sp.getIntMinOccurs(); + int maxOccurs = sp.getIntMaxOccurs(); + + if (minOccurs == maxOccurs) { + return minOccurs; + } + + int result = minOccurs; + if (result == 0 && _nElements < MAX_ELEMENTS) { + result = 1; + } + + if (sp.getParticleType() != SchemaParticle.ELEMENT) { + return result; + } + + // it probably only makes sense to put comments in front of individual elements that repeat + + if (sp.getMaxOccurs() == null) { + // xmlc.insertComment("The next " + getItemNameOrType(sp, xmlc) + " may be repeated " + minOccurs + " or more times"); + if (minOccurs == 0) { + xmlc.insertComment("Zero or more repetitions:"); + } else { + xmlc.insertComment(minOccurs + " or more repetitions:"); + } + } else if (sp.getIntMaxOccurs() > 1) { + xmlc.insertComment(minOccurs + " to " + sp.getMaxOccurs() + " repetitions:"); + } else { + xmlc.insertComment("Optional:"); + } + return result; + } + + private void processElement(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + // cast as schema local element + SchemaLocalElement element = (SchemaLocalElement) sp; + /// ^ -> ^ + if (_soapEnc) { + xmlc.insertElement(element.getName().getLocalPart()); // soap encoded? drop namespaces. + } else { + xmlc.insertElement(element.getName().getLocalPart(), element.getName().getNamespaceURI()); + } + _nElements++; + /// -> ^ + xmlc.toPrevToken(); + // -> stuff^ + + createSampleForType(element.getType(), xmlc); + // -> stuff^ + xmlc.toNextToken(); + + } + + private static String formatQName(XmlCursor xmlc, QName qName) { + XmlCursor parent = xmlc.newCursor(); + parent.toParent(); + String prefix = parent.prefixForNamespace(qName.getNamespaceURI()); + parent.dispose(); + String name; + if (prefix == null || prefix.length() == 0) { + name = qName.getLocalPart(); + } else { + name = prefix + ":" + qName.getLocalPart(); + } + return name; + } + + private static final QName HREF = new QName("href"); + private static final QName ID = new QName("id"); + private static final QName XSI_TYPE = new QName("http://www.w3.org/2001/XMLSchema-instance", "type"); + private static final QName ENC_ARRAYTYPE = new QName("http://schemas.xmlsoap.org/soap/encoding/", "arrayType"); + private static final QName ENC_OFFSET = new QName("http://schemas.xmlsoap.org/soap/encoding/", "offset"); + + private static final Set SKIPPED_SOAP_ATTRS = new HashSet<>(Arrays.asList(HREF, ID, ENC_OFFSET)); + + private void processAttributes(SchemaType stype, XmlCursor xmlc) { + if (_soapEnc) { + QName typeName = stype.getName(); + if (typeName != null) { + xmlc.insertAttributeWithValue(XSI_TYPE, formatQName(xmlc, typeName)); + } + } + + SchemaProperty[] attrProps = stype.getAttributeProperties(); + for (SchemaProperty attr : attrProps) { + if (_soapEnc) { + if (SKIPPED_SOAP_ATTRS.contains(attr.getName())) { + continue; + } + if (ENC_ARRAYTYPE.equals(attr.getName())) { + SOAPArrayType arrayType = ((SchemaWSDLArrayType) stype.getAttributeModel().getAttribute(attr.getName())).getWSDLArrayType(); + if (arrayType != null) { + xmlc.insertAttributeWithValue(attr.getName(), formatQName(xmlc, arrayType.getQName()) + arrayType.soap11DimensionString()); + } + continue; + } + } + String defaultValue = attr.getDefaultText(); + xmlc.insertAttributeWithValue(attr.getName(), defaultValue == null ? + sampleDataForSimpleType(attr.getType()) : defaultValue); + } + } + + private void processSequence(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + SchemaParticle[] spc = sp.getParticleChildren(); + for (int i = 0; i < spc.length; i++) { + /// maybestuff^ + processParticle(spc[i], xmlc, mixed); + //maybestuff...morestuff^ + if (mixed && i < spc.length - 1) { + xmlc.insertChars(pick(WORDS)); + } + } + } + + private void processChoice(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + SchemaParticle[] spc = sp.getParticleChildren(); + xmlc.insertComment("You have a CHOICE of the next " + spc.length + " items at this level"); + for (SchemaParticle schemaParticle : spc) { + processParticle(schemaParticle, xmlc, mixed); + } + } + + private void processAll(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + SchemaParticle[] spc = sp.getParticleChildren(); + // xmlc.insertComment("You may enter the following " + String.valueOf(spc.length) + " items in any order"); + for (int i = 0; i < spc.length; i++) { + processParticle(spc[i], xmlc, mixed); + if (mixed && i < spc.length - 1) { + xmlc.insertChars(pick(WORDS)); + } + } + } + + private void processWildCard(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { + xmlc.insertComment("You may enter ANY elements at this point"); + xmlc.insertElement("AnyElement"); + } + + private final ArrayList _typeStack = new ArrayList<>(); +} diff --git a/src/tools/org/apache/xmlbeans/impl/xsd2inst/SchemaInstanceGenerator.java b/src/main/java/org/apache/xmlbeans/impl/xsd2inst/SchemaInstanceGenerator.java similarity index 100% rename from src/tools/org/apache/xmlbeans/impl/xsd2inst/SchemaInstanceGenerator.java rename to src/main/java/org/apache/xmlbeans/impl/xsd2inst/SchemaInstanceGenerator.java diff --git a/src/xmlpublic/org/apache/xmlbeans/package.html b/src/main/java/org/apache/xmlbeans/package.html similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/package.html rename to src/main/java/org/apache/xmlbeans/package.html diff --git a/src/main/java/org/apache/xmlbeans/soap/SOAPArrayType.java b/src/main/java/org/apache/xmlbeans/soap/SOAPArrayType.java new file mode 100644 index 0000000..48ecd2d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/soap/SOAPArrayType.java @@ -0,0 +1,362 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.soap; + +import org.apache.xmlbeans.impl.common.PrefixResolver; +import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.XmlWhitespace; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public final class SOAPArrayType { + // Example foo:bar[,][][,,][7,9] + // -> _type = QName(foo:bar) + // -> _ranks = {2,1,3} + // -> _dimensions = {7,9} + private QName _type; + private int[] _ranks; // if ranks is empty, it means there are no nested arrays + private int[] _dimensions; // Any dimension can be -1 to indicate "any". + + /** + * True if the ranks for the passed SOAPArrayType + * are equal to this one. + *

      + * Does NOT compare the _type fields. + */ + public boolean isSameRankAs(SOAPArrayType otherType) { + return Arrays.equals(_ranks, otherType._ranks) && + _dimensions.length == otherType._dimensions.length; + } + + private static int[] internalParseCommaIntString(String csl) { + List dimStrings = new ArrayList<>(); + int i = 0; + for (; ; ) { + int j = csl.indexOf(',', i); + if (j < 0) { + dimStrings.add(csl.substring(i)); + break; + } + dimStrings.add(csl.substring(i, j)); + i = j + 1; + } + + return dimStrings.stream().mapToInt(SOAPArrayType::collapseDimString).toArray(); + } + + private static int collapseDimString(String dimString2) { + String dimString = XmlWhitespace.collapse(dimString2, XmlWhitespace.WS_COLLAPSE); + try { + return ("*".equals(dimString) || dimString.isEmpty()) ? -1 : Integer.parseInt(dimString); + } catch (Exception e) { + throw new XmlValueOutOfRangeException("Malformed integer in SOAP array index"); + } + } + + /** + * Parses a SOAP 1.1 array type string. + *

      + * Since an array type string contains a QName, a prefix resolver + * must be passed. + */ + public SOAPArrayType(String s, PrefixResolver m) { + int firstbrace = s.indexOf('['); + if (firstbrace < 0) { + throw new XmlValueOutOfRangeException(); + } + + // grab the QName + String firstpart = XmlWhitespace.collapse(s.substring(0, firstbrace), XmlWhitespace.WS_COLLAPSE); + int firstcolon = firstpart.indexOf(':'); + String prefix = ""; + if (firstcolon >= 0) { + prefix = firstpart.substring(0, firstcolon); + } + + String uri = m.getNamespaceForPrefix(prefix); + if (uri == null) { + throw new XmlValueOutOfRangeException(); + } + + _type = QNameHelper.forLNS(firstpart.substring(firstcolon + 1), uri); + + initDimensions(s, firstbrace); + } + + private static final int[] EMPTY_INT_ARRAY = new int[0]; + + /** + * Parses SOAP 1.1(advanced) array type strings. + *

      + * Since in SOAP 1.1(advanced) the dimension specification is separated from the + * QName for the underlying type, these are passed in separate + * arguments. + */ + public SOAPArrayType(QName name, String dimensions) { + int firstbrace = dimensions.indexOf('['); + if (firstbrace < 0) { + _type = name; + _ranks = EMPTY_INT_ARRAY; + dimensions = XmlWhitespace.collapse(dimensions, XmlWhitespace.WS_COLLAPSE); + String[] dimStrings = dimensions.split(" "); + for (int i = 0; i < dimStrings.length; i++) { + String dimString = dimStrings[i]; + if (dimString.equals("*")) { + _dimensions[i] = -1; + // _hasIndeterminateDimensions = true; + } else { + try { + _dimensions[i] = Integer.parseInt(dimStrings[i]); + } catch (Exception e) { + throw new XmlValueOutOfRangeException(); + } + } + } + } else { + _type = name; + initDimensions(dimensions, firstbrace); + } + } + + /** + * Given a nested SOAPArrayType and a set of dimensions for the outermost + * array, comes up with the right SOAPArrayType for the whole thing. + *

      + * E.g., + * Nested foo:bar[,][][,,][1,2] + * Dimensions [6,7,8] + * Result -> foo:bar[,][][,,][,][6,7,8] + */ + public SOAPArrayType(SOAPArrayType nested, int[] dimensions) { + _type = nested._type; + + _ranks = new int[nested._ranks.length + 1]; + System.arraycopy(nested._ranks, 0, _ranks, 0, nested._ranks.length); + _ranks[_ranks.length - 1] = nested._dimensions.length; + + _dimensions = new int[dimensions.length]; + System.arraycopy(dimensions, 0, _dimensions, 0, dimensions.length); + } + + /** + * Initialize dimensions based on SOAP11 parsed dimension substring + */ + private void initDimensions(String s, int firstbrace) { + List braces = new ArrayList<>(); + int lastbrace = -1; + for (int i = firstbrace; i >= 0; ) { + lastbrace = s.indexOf(']', i); + if (lastbrace < 0) { + throw new XmlValueOutOfRangeException(); + } + braces.add(s.substring(i + 1, lastbrace)); + i = s.indexOf('[', lastbrace); + } + + String trailer = s.substring(lastbrace + 1); + if (!XmlWhitespace.isAllSpace(trailer)) { + throw new XmlValueOutOfRangeException(); + } + + // now fill in rank array + _ranks = new int[braces.size() - 1]; + for (int i = 0; i < _ranks.length; i++) { + String commas = braces.get(i); + int commacount = 0; + for (int j = 0; j < commas.length(); j++) { + char ch = commas.charAt(j); + if (ch == ',') { + commacount += 1; + } else if (!XmlWhitespace.isSpace(ch)) { + throw new XmlValueOutOfRangeException(); + } + } + _ranks[i] = commacount + 1; + } + + // finally fill in dimension array + _dimensions = internalParseCommaIntString(braces.get(braces.size() - 1)); + + /* + for (int i = 0; i < _dimensions.length; i++) + { + if (_dimensions[i] < 0) + _hasIndeterminateDimensions = true; + } + */ + } + + /** + * Returns the QName for the referenced type. + */ + public QName getQName() { + return _type; + } + + /** + * Returns the array of ranks for inner nested arrays. + * In SOAP 1.1-advanced, this is always an array of length zero. + * In SOAP 1.1, this array reflects the ranks of nested + * arrays. For example foo:bar[,][,,][][5,6] will produce + * a ranks result of 2, 3, 1. + */ + public int[] getRanks() { + int[] result = new int[_ranks.length]; + System.arraycopy(_ranks, 0, result, 0, result.length); + return result; + } + + /** + * Returns the array of dimensions. + */ + public int[] getDimensions() { + int[] result = new int[_dimensions.length]; + System.arraycopy(_dimensions, 0, result, 0, result.length); + return result; + } + + /** + * True if this array contains nested arrays. Equivalent + * to (getRanks().length > 0). + */ + public boolean containsNestedArrays() { + return (_ranks.length > 0); + } + + /** + * Returns the dimensions as a string, e.g., [,][2,3,4] + */ + public String soap11DimensionString() { + return soap11DimensionString(_dimensions); + } + + /** + * Given an actual set of dimensions that may differ from + * the default that is stored, outputs the soap arrayType + * string. + */ + public String soap11DimensionString(int[] actualDimensions) { + StringBuilder sb = new StringBuilder(); + for (int rank : _ranks) { + sb.append('['); + for (int j = 1; j < rank; j++) { + sb.append(','); + } + sb.append(']'); + } + + sb.append(IntStream.of(actualDimensions).mapToObj(i -> i >= 0 ? Integer.toString(i) : "").collect(Collectors.joining(",", "[", "]"))); + return sb.toString(); + } + + private SOAPArrayType() { + } + + /** + * SOAP 1.2 + * Constructs a SOAPArrayType from soap-enc:itemType and + * soap-enc:arraySize attributes + * + * @param itemType the item type QName + * @param arraySize a string with dimentions like: * 3 4 + * @return a SOAPArrayType to represent this + */ + public static SOAPArrayType newSoap12Array(QName itemType, String arraySize) { + arraySize = XmlWhitespace.collapse(arraySize, XmlWhitespace.WS_COLLAPSE); + String[] dimStrings = arraySize.split(" "); + int[] dimensions = new int[dimStrings.length]; + for (int i = 0; i < dimStrings.length; i++) { + String dimString = dimStrings[i]; + if (i == 0 && dimString.equals("*")) { + dimensions[i] = -1; + // _hasIndeterminateDimensions = true; + } else { + try { + dimensions[i] = Integer.parseInt(dimStrings[i]); + } catch (Exception e) { + throw new XmlValueOutOfRangeException(); + } + } + } + SOAPArrayType sot = new SOAPArrayType(); + sot._ranks = EMPTY_INT_ARRAY; + sot._type = itemType; + sot._dimensions = dimensions; + return sot; + } + + /** + * SOAP 1.2 + * Given an actual set of dimensions that may differ from + * the default that is stored, outputs the soap arraySize + * string. + */ + public String soap12DimensionString(int[] actualDimensions) { + return IntStream.of(actualDimensions). + mapToObj(i -> (i >= 0) ? Integer.toString(i) : ""). + collect(Collectors.joining(" ")); + } + + /** + * Constructs a SOAPArrayType reflecting the dimensions + * of the next nested array. + */ + public SOAPArrayType nestedArrayType() { + if (!containsNestedArrays()) { + throw new IllegalStateException(); + } + + SOAPArrayType result = new SOAPArrayType(); + + result._type = _type; + + result._ranks = new int[_ranks.length - 1]; + System.arraycopy(_ranks, 0, result._ranks, 0, result._ranks.length); + + result._dimensions = new int[_ranks[_ranks.length - 1]]; + Arrays.fill(result._dimensions, -1); + + // result._hasIndeterminateDimensions = (result._dimensions.length > 0); + + return result; + } + + public int hashCode() { + return (_type.hashCode() + _dimensions.length + _ranks.length + (_dimensions.length == 0 ? 0 : _dimensions[0])); + } + + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof SOAPArrayType)) { + return false; + } + + SOAPArrayType sat = (SOAPArrayType) obj; + + return _type.equals(sat._type) && + Arrays.equals(_ranks, sat._ranks) && + Arrays.equals(_dimensions, sat._dimensions); + } +} diff --git a/src/typeimpl/org/apache/xmlbeans/soap/SchemaWSDLArrayType.java b/src/main/java/org/apache/xmlbeans/soap/SchemaWSDLArrayType.java similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/soap/SchemaWSDLArrayType.java rename to src/main/java/org/apache/xmlbeans/soap/SchemaWSDLArrayType.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/Attribute.java b/src/main/java/org/apache/xmlbeans/xml/stream/Attribute.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/Attribute.java rename to src/main/java/org/apache/xmlbeans/xml/stream/Attribute.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/AttributeIterator.java b/src/main/java/org/apache/xmlbeans/xml/stream/AttributeIterator.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/AttributeIterator.java rename to src/main/java/org/apache/xmlbeans/xml/stream/AttributeIterator.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/ChangePrefixMapping.java b/src/main/java/org/apache/xmlbeans/xml/stream/ChangePrefixMapping.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/ChangePrefixMapping.java rename to src/main/java/org/apache/xmlbeans/xml/stream/ChangePrefixMapping.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/CharacterData.java b/src/main/java/org/apache/xmlbeans/xml/stream/CharacterData.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/CharacterData.java rename to src/main/java/org/apache/xmlbeans/xml/stream/CharacterData.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/Comment.java b/src/main/java/org/apache/xmlbeans/xml/stream/Comment.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/Comment.java rename to src/main/java/org/apache/xmlbeans/xml/stream/Comment.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/ElementFilter.java b/src/main/java/org/apache/xmlbeans/xml/stream/ElementFilter.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/ElementFilter.java rename to src/main/java/org/apache/xmlbeans/xml/stream/ElementFilter.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/EndDocument.java b/src/main/java/org/apache/xmlbeans/xml/stream/EndDocument.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/EndDocument.java rename to src/main/java/org/apache/xmlbeans/xml/stream/EndDocument.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/EndElement.java b/src/main/java/org/apache/xmlbeans/xml/stream/EndElement.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/EndElement.java rename to src/main/java/org/apache/xmlbeans/xml/stream/EndElement.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/EndPrefixMapping.java b/src/main/java/org/apache/xmlbeans/xml/stream/EndPrefixMapping.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/EndPrefixMapping.java rename to src/main/java/org/apache/xmlbeans/xml/stream/EndPrefixMapping.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/EntityReference.java b/src/main/java/org/apache/xmlbeans/xml/stream/EntityReference.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/EntityReference.java rename to src/main/java/org/apache/xmlbeans/xml/stream/EntityReference.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/Location.java b/src/main/java/org/apache/xmlbeans/xml/stream/Location.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/Location.java rename to src/main/java/org/apache/xmlbeans/xml/stream/Location.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/ProcessingInstruction.java b/src/main/java/org/apache/xmlbeans/xml/stream/ProcessingInstruction.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/ProcessingInstruction.java rename to src/main/java/org/apache/xmlbeans/xml/stream/ProcessingInstruction.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/Space.java b/src/main/java/org/apache/xmlbeans/xml/stream/Space.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/Space.java rename to src/main/java/org/apache/xmlbeans/xml/stream/Space.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartDocument.java b/src/main/java/org/apache/xmlbeans/xml/stream/StartDocument.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartDocument.java rename to src/main/java/org/apache/xmlbeans/xml/stream/StartDocument.java diff --git a/src/main/java/org/apache/xmlbeans/xml/stream/StartElement.java b/src/main/java/org/apache/xmlbeans/xml/stream/StartElement.java new file mode 100755 index 0000000..a450f6d --- /dev/null +++ b/src/main/java/org/apache/xmlbeans/xml/stream/StartElement.java @@ -0,0 +1,62 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.xml.stream; + +import java.util.Map; + +/** + * The StartElement interface provides access to information about + * start elements + * + * @version 1.0 + * @see org.apache.xmlbeans.xml.stream.AttributeIterator + * @since Weblogic XML Input Stream 1.0 + */ + +public interface StartElement extends XMLEvent { + /** + * Returns an AttributeIterator of non-namespace declared attributes + */ + AttributeIterator getAttributes(); + + /** + * Returns an AttributeIterator of namespaces declared in this element + */ + AttributeIterator getNamespaces(); + + /** + * Returns the union of declared attributes and namespaces + */ + AttributeIterator getAttributesAndNamespaces(); + + /** + * Returns the attribute referred to by this name + */ + Attribute getAttributeByName(XMLName name); + + /** + * Gets the value that the prefix is bound to in the + * context of this element. Returns null if + * the prefix is not bound in this context + */ + String getNamespaceUri(String prefix); + + /** + * Gets a java.util.Map from prefixes to URIs in scope for this + * element. + */ + Map getNamespaceMap(); +} diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartPrefixMapping.java b/src/main/java/org/apache/xmlbeans/xml/stream/StartPrefixMapping.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartPrefixMapping.java rename to src/main/java/org/apache/xmlbeans/xml/stream/StartPrefixMapping.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLEvent.java b/src/main/java/org/apache/xmlbeans/xml/stream/XMLEvent.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLEvent.java rename to src/main/java/org/apache/xmlbeans/xml/stream/XMLEvent.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLName.java b/src/main/java/org/apache/xmlbeans/xml/stream/XMLName.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLName.java rename to src/main/java/org/apache/xmlbeans/xml/stream/XMLName.java diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/events/ElementTypeNames.java b/src/main/java/org/apache/xmlbeans/xml/stream/events/ElementTypeNames.java similarity index 100% rename from src/xmlinputstream/org/apache/xmlbeans/xml/stream/events/ElementTypeNames.java rename to src/main/java/org/apache/xmlbeans/xml/stream/events/ElementTypeNames.java diff --git a/src/main/multimodule/java9/module-info.class b/src/main/multimodule/java9/module-info.class new file mode 100644 index 0000000..ada2703 Binary files /dev/null and b/src/main/multimodule/java9/module-info.class differ diff --git a/src/main/multimodule/java9/module-info.java b/src/main/multimodule/java9/module-info.java new file mode 100644 index 0000000..6ff24e5 --- /dev/null +++ b/src/main/multimodule/java9/module-info.java @@ -0,0 +1,61 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +module org.apache.xmlbeans { + requires java.xml; + requires jdk.xml.dom; + requires static ant; + requires static com.github.javaparser.core; + requires static Saxon.HE; + + exports org.apache.xmlbeans; + exports org.apache.xmlbeans.soap; + // exports org.apache.xmlbeans.impl; + exports org.apache.xmlbeans.impl.xpathgen; + exports org.apache.xmlbeans.impl.validator; + exports org.apache.xmlbeans.impl.repackage; + exports org.apache.xmlbeans.impl.common; + exports org.apache.xmlbeans.impl.config; + exports org.apache.xmlbeans.impl.richParser; + exports org.apache.xmlbeans.impl.soap; + exports org.apache.xmlbeans.impl.xpath; + exports org.apache.xmlbeans.impl.xpath.saxon; + exports org.apache.xmlbeans.impl.xpath.xmlbeans; + exports org.apache.xmlbeans.impl.regex; + exports org.apache.xmlbeans.impl.tool; + exports org.apache.xmlbeans.impl.schema; + exports org.apache.xmlbeans.impl.xsd2inst; + exports org.apache.xmlbeans.impl.values; + exports org.apache.xmlbeans.impl.inst2xsd; + exports org.apache.xmlbeans.impl.inst2xsd.util; + exports org.apache.xmlbeans.impl.store; + exports org.apache.xmlbeans.impl.util; + // exports org.apache.xmlbeans.xml; + exports org.apache.xmlbeans.xml.stream; + exports org.apache.xmlbeans.xml.stream.events; + // exports org.apache.xmlbeans.xml.stream.utils; + + exports org.apache.xmlbeans.impl.xb.xmlconfig; + exports org.apache.xmlbeans.impl.xb.xmlschema; + exports org.apache.xmlbeans.impl.xb.xsdschema; + exports org.apache.xmlbeans.impl.xb.xsdownload; + + opens org.apache.xmlbeans.metadata.system.sXMLCONFIG; + opens org.apache.xmlbeans.metadata.system.sXMLLANG; + opens org.apache.xmlbeans.metadata.system.sXMLSCHEMA; + opens org.apache.xmlbeans.metadata.system.sXMLTOOLS; +} \ No newline at end of file diff --git a/src/main/resources/maven/pom.xml b/src/main/resources/maven/pom.xml new file mode 100644 index 0000000..3ff51ed --- /dev/null +++ b/src/main/resources/maven/pom.xml @@ -0,0 +1,109 @@ + + + + + 4.0.0 + org.apache.xmlbeans + xmlbeans + @VERSION@ + + XmlBeans + XmlBeans main jar + https://xmlbeans.apache.org/ + + + jira + https://issues.apache.org/jira/browse/XMLBEANS + + + + + POI Users List + user-subscribe@poi.apache.org + user-unsubscribe@poi.apache.org + http://mail-archives.apache.org/mod_mbox/poi-user/ + + + POI Developer List + dev-subscribe@poi.apache.org + dev-unsubscribe@poi.apache.org + http://mail-archives.apache.org/mod_mbox/poi-dev/ + + + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:svn:https://svn.apache.org/repos/asf/xmlbeans/ + scm:svn:https://${maven.username}@svn.apache.org/repos/asf/xmlbeans/ + https://svn.apache.org/repos/asf/xmlbeans/ + + + + XmlBeans + https://xmlbeans.apache.org/ + + + + + POI Team + poi + user@poi.apache.org + Apache POI + + + + + + net.sf.saxon + Saxon-HE + 10.2 + provided + + + com.github.javaparser + javaparser-core + 3.16.1 + provided + + + + + + java8 + + 1.8 + + + + xml-apis + xml-apis + 1.4.01 + + + + + diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/message.properties b/src/main/resources/typeimpl/org/apache/xmlbeans/impl/regex/message.properties similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/message.properties rename to src/main/resources/typeimpl/org/apache/xmlbeans/impl/regex/message.properties diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/message_fr.properties b/src/main/resources/typeimpl/org/apache/xmlbeans/impl/regex/message_fr.properties similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/message_fr.properties rename to src/main/resources/typeimpl/org/apache/xmlbeans/impl/regex/message_fr.properties diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/message_ja.properties b/src/main/resources/typeimpl/org/apache/xmlbeans/impl/regex/message_ja.properties similarity index 100% rename from src/typeimpl/org/apache/xmlbeans/impl/regex/message_ja.properties rename to src/main/resources/typeimpl/org/apache/xmlbeans/impl/regex/message_ja.properties diff --git a/src/xmlpublic/org/apache/xmlbeans/message.properties b/src/main/resources/xmlpublic/org/apache/xmlbeans/message.properties similarity index 100% rename from src/xmlpublic/org/apache/xmlbeans/message.properties rename to src/main/resources/xmlpublic/org/apache/xmlbeans/message.properties diff --git a/src/configschema/schema/xmlconfig.xsd b/src/main/schema/config/xmlconfig.xsd similarity index 100% rename from src/configschema/schema/xmlconfig.xsd rename to src/main/schema/config/xmlconfig.xsd diff --git a/src/configschema/schema/xmlconfig.xsdconfig b/src/main/schema/config/xmlconfig.xsdconfig similarity index 100% rename from src/configschema/schema/xmlconfig.xsdconfig rename to src/main/schema/config/xmlconfig.xsdconfig diff --git a/src/toolschema/ltgfmt.xsd b/src/main/schema/tools/ltgfmt.xsd similarity index 100% rename from src/toolschema/ltgfmt.xsd rename to src/main/schema/tools/ltgfmt.xsd diff --git a/src/toolschema/ltgfmt.xsdconfig b/src/main/schema/tools/ltgfmt.xsdconfig similarity index 100% rename from src/toolschema/ltgfmt.xsdconfig rename to src/main/schema/tools/ltgfmt.xsdconfig diff --git a/src/toolschema/substwsdl.xsd b/src/main/schema/tools/substwsdl.xsd similarity index 100% rename from src/toolschema/substwsdl.xsd rename to src/main/schema/tools/substwsdl.xsd diff --git a/src/toolschema/substwsdl.xsdconfig b/src/main/schema/tools/substwsdl.xsdconfig similarity index 100% rename from src/toolschema/substwsdl.xsdconfig rename to src/main/schema/tools/substwsdl.xsdconfig diff --git a/src/toolschema/xsdownload.xsd b/src/main/schema/tools/xsdownload.xsd similarity index 100% rename from src/toolschema/xsdownload.xsd rename to src/main/schema/tools/xsdownload.xsd diff --git a/src/toolschema/xsdownload.xsdconfig b/src/main/schema/tools/xsdownload.xsdconfig similarity index 100% rename from src/toolschema/xsdownload.xsdconfig rename to src/main/schema/tools/xsdownload.xsdconfig diff --git a/src/xmlschema/schema/XML.xsd b/src/main/schema/xml/XML.xsd similarity index 100% rename from src/xmlschema/schema/XML.xsd rename to src/main/schema/xml/XML.xsd diff --git a/src/xmlschema/schema/XML.xsdconfig b/src/main/schema/xml/XML.xsdconfig similarity index 100% rename from src/xmlschema/schema/XML.xsdconfig rename to src/main/schema/xml/XML.xsdconfig diff --git a/src/xsdschema/schema/XMLSchema.xsd b/src/main/schema/xsd/XMLSchema.xsd similarity index 100% rename from src/xsdschema/schema/XMLSchema.xsd rename to src/main/schema/xsd/XMLSchema.xsd diff --git a/src/xsdschema/schema/XMLSchema.xsdconfig b/src/main/schema/xsd/XMLSchema.xsdconfig similarity index 100% rename from src/xsdschema/schema/XMLSchema.xsdconfig rename to src/main/schema/xsd/XMLSchema.xsdconfig diff --git a/bin/_setlib b/src/main/shell/_setlib similarity index 79% rename from bin/_setlib rename to src/main/shell/_setlib index c3beccc..16fd307 100755 --- a/bin/_setlib +++ b/src/main/shell/_setlib @@ -20,13 +20,13 @@ if [ -z "$XMLBEANS_HOME" ]; then fi XMLBEANS_LIB= -if [ -f "$XMLBEANS_HOME"/build/lib/xbean.jar ]; then +if [ -f "$XMLBEANS_HOME"/build/lib/xmlbeans*.jar ]; then XMLBEANS_LIB=$XMLBEANS_HOME/build/lib fi -if [ -f "$XMLBEANS_HOME"/lib/xbean.jar ]; then +if [ -f "$XMLBEANS_HOME"/lib/xmlbeans*.jar ]; then XMLBEANS_LIB=$XMLBEANS_HOME/lib fi if [ -z "$XMLBEANS_LIB" ]; then - echo "ERROR: Could not find xbean.jar, try set XMLBEANS_LIB to the directory containing xbean.jar" + echo "ERROR: Could not find xmlbeans*.jar, try set XMLBEANS_LIB to the directory containing xmlbeans*.jar" fi diff --git a/src/main/shell/_setlib.cmd b/src/main/shell/_setlib.cmd new file mode 100644 index 0000000..c52209b --- /dev/null +++ b/src/main/shell/_setlib.cmd @@ -0,0 +1,28 @@ +@REM +@REM Copyright 2004 The Apache Software Foundation +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM + +@rem Common script to set the XMLBEANS_LIB variable +@rem to the directory containing xmlbeans.jar +@echo off + +if "%XMLBEANS_HOME%" EQU "" (set XMLBEANS_HOME=%~dp0..) + +set XMLBEANS_LIB= + +if exist "%XMLBEANS_HOME%\build\lib\xmlbeans*.jar" set XMLBEANS_LIB=%XMLBEANS_HOME%\build\lib +if exist "%XMLBEANS_HOME%\lib\xmlbeans*.jar" set XMLBEANS_LIB=%XMLBEANS_HOME%\lib + +if "%XMLBEANS_LIB%" EQU "" echo "ERROR: Could not find xmlbeans*.jar, try setting XMLBEANS_LIB to the directory containing xmlbeans*.jar" diff --git a/bin/dumpxsb b/src/main/shell/dumpxsb similarity index 90% rename from bin/dumpxsb rename to src/main/shell/dumpxsb index 78ab292..9b60dcd 100755 --- a/bin/dumpxsb +++ b/src/main/shell/dumpxsb @@ -22,7 +22,7 @@ echo `dirname $0` if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/dumpxsb.cmd b/src/main/shell/dumpxsb.cmd similarity index 89% rename from bin/dumpxsb.cmd rename to src/main/shell/dumpxsb.cmd index 39fb50b..6d2f910 100644 --- a/bin/dumpxsb.cmd +++ b/src/main/shell/dumpxsb.cmd @@ -23,7 +23,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar;%XMLBEANS_LIB%\xmlbeans-qname.jar;%XMLBEANS_LIB%\jsr173_1.0_api.jar +set cp=%cp%;%XMLBEANS_LIB%\*;%XMLBEANS_LIB%\jsr173_1.0_api.jar java -classpath "%cp%" org.apache.xmlbeans.impl.tool.XsbDumper %* diff --git a/bin/inst2xsd b/src/main/shell/inst2xsd similarity index 90% rename from bin/inst2xsd rename to src/main/shell/inst2xsd index 9873954..9ab65cf 100755 --- a/bin/inst2xsd +++ b/src/main/shell/inst2xsd @@ -20,7 +20,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/inst2xsd.cmd b/src/main/shell/inst2xsd.cmd similarity index 93% rename from bin/inst2xsd.cmd rename to src/main/shell/inst2xsd.cmd index 9d1a3d8..da225c8 100644 --- a/bin/inst2xsd.cmd +++ b/src/main/shell/inst2xsd.cmd @@ -24,7 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar set cp=%cp%;%XMLBEANS_LIB%\resolver.jar diff --git a/bin/scomp b/src/main/shell/scomp similarity index 86% rename from bin/scomp rename to src/main/shell/scomp index 68d29b1..9906132 100755 --- a/bin/scomp +++ b/src/main/shell/scomp @@ -20,7 +20,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$JAVA_HOME/lib/tools.jar:$XMLBEANS_LIB/resolver.jar +cp=$XMLBEANS_LIB/*:$JAVA_HOME/lib/tools.jar case "`uname`" in CYGWIN*) diff --git a/bin/scomp.cmd b/src/main/shell/scomp.cmd similarity index 92% rename from bin/scomp.cmd rename to src/main/shell/scomp.cmd index e82a9e8..1681f7b 100644 --- a/bin/scomp.cmd +++ b/src/main/shell/scomp.cmd @@ -24,8 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar -set cp=%cp%;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar set cp=%cp%;%JAVA_HOME%\lib\tools.jar set cp=%cp%;%XMLBEANS_LIB%\resolver.jar diff --git a/bin/scopy.cmd b/src/main/shell/scopy.cmd similarity index 89% rename from bin/scopy.cmd rename to src/main/shell/scopy.cmd index ff68c31..9006b51 100644 --- a/bin/scopy.cmd +++ b/src/main/shell/scopy.cmd @@ -24,7 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar;%XMLBEANS_LIB%\xmlbeans-qname.jar;%XMLBEANS_LIB%\jsr173_1.0_api.jar +set cp=%cp%;%XMLBEANS_LIB%\*;%XMLBEANS_LIB%\jsr173_1.0_api.jar java -classpath "%cp%" org.apache.xmlbeans.impl.tool.SchemaCopy %* diff --git a/bin/sdownload b/src/main/shell/sdownload similarity index 90% rename from bin/sdownload rename to src/main/shell/sdownload index 118c717..49ebde7 100755 --- a/bin/sdownload +++ b/src/main/shell/sdownload @@ -20,7 +20,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/sdownload.cmd b/src/main/shell/sdownload.cmd similarity index 92% rename from bin/sdownload.cmd rename to src/main/shell/sdownload.cmd index 3d2b603..eaa1b54 100644 --- a/bin/sdownload.cmd +++ b/src/main/shell/sdownload.cmd @@ -24,8 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar -set cp=%cp%;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar set cp=%cp%;%XMLBEANS_LIB%\resolver.jar diff --git a/bin/sfactor b/src/main/shell/sfactor similarity index 89% rename from bin/sfactor rename to src/main/shell/sfactor index 0554b5e..a4f078f 100755 --- a/bin/sfactor +++ b/src/main/shell/sfactor @@ -22,7 +22,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar +cp=$XMLBEANS_LIB/*:$XMLBEANS_LIB/resolver.jar case "`uname`" in CYGWIN*) diff --git a/bin/sfactor.cmd b/src/main/shell/sfactor.cmd similarity index 87% rename from bin/sfactor.cmd rename to src/main/shell/sfactor.cmd index 27c6321..4d00d91 100644 --- a/bin/sfactor.cmd +++ b/src/main/shell/sfactor.cmd @@ -24,7 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar;%XMLBEANS_LIB%\xmlbeans-qname.jar;%XMLBEANS_LIB%\jsr173_1.0_api.jar;%XMLBEANS_LIB%\resolver.jar; +set cp=%cp%;%XMLBEANS_LIB%\*;%XMLBEANS_LIB%\jsr173_1.0_api.jar;%XMLBEANS_LIB%\resolver.jar; java -classpath "%cp%" org.apache.xmlbeans.impl.tool.FactorImports %* diff --git a/bin/svalidate b/src/main/shell/svalidate similarity index 88% rename from bin/svalidate rename to src/main/shell/svalidate index 13a6ad6..b4b60c4 100755 --- a/bin/svalidate +++ b/src/main/shell/svalidate @@ -21,7 +21,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/jsr173_1.0_ri.jar +cp=$XMLBEANS_LIB/*:$XMLBEANS_LIB/jsr173_1.0_ri.jar case "`uname`" in CYGWIN*) diff --git a/bin/svalidate.cmd b/src/main/shell/svalidate.cmd similarity index 92% rename from bin/svalidate.cmd rename to src/main/shell/svalidate.cmd index 551a952..e5dde53 100644 --- a/bin/svalidate.cmd +++ b/src/main/shell/svalidate.cmd @@ -24,8 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar -set cp=%cp%;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_ri.jar diff --git a/bin/validate b/src/main/shell/validate similarity index 90% rename from bin/validate rename to src/main/shell/validate index 62a75fa..7e3b8d5 100755 --- a/bin/validate +++ b/src/main/shell/validate @@ -21,7 +21,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/validate.cmd b/src/main/shell/validate.cmd similarity index 91% rename from bin/validate.cmd rename to src/main/shell/validate.cmd index d2fc318..32efc26 100644 --- a/bin/validate.cmd +++ b/src/main/shell/validate.cmd @@ -24,8 +24,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar -set cp=%cp%;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar java -classpath "%cp%" org.apache.xmlbeans.impl.tool.InstanceValidator %* diff --git a/bin/xpretty b/src/main/shell/xpretty similarity index 90% rename from bin/xpretty rename to src/main/shell/xpretty index 2deb8c6..001349b 100755 --- a/bin/xpretty +++ b/src/main/shell/xpretty @@ -19,7 +19,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/xpretty.cmd b/src/main/shell/xpretty.cmd similarity index 88% rename from bin/xpretty.cmd rename to src/main/shell/xpretty.cmd index aa1f581..ec379c0 100644 --- a/bin/xpretty.cmd +++ b/src/main/shell/xpretty.cmd @@ -22,6 +22,6 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar;%XMLBEANS_LIB%\xmlbeans-qname.jar;%XMLBEANS_LIB%\jsr173_1.0_api.jar +set cp=%cp%;%XMLBEANS_LIB%\*;%XMLBEANS_LIB%\jsr173_1.0_api.jar java -classpath "%cp%" org.apache.xmlbeans.impl.tool.PrettyPrinter %* diff --git a/bin/xsd2inst b/src/main/shell/xsd2inst similarity index 90% rename from bin/xsd2inst rename to src/main/shell/xsd2inst index c3e43f4..b1ea81f 100755 --- a/bin/xsd2inst +++ b/src/main/shell/xsd2inst @@ -19,7 +19,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/xsd2inst.cmd b/src/main/shell/xsd2inst.cmd similarity index 88% rename from bin/xsd2inst.cmd rename to src/main/shell/xsd2inst.cmd index a1a3d48..7ece129 100644 --- a/bin/xsd2inst.cmd +++ b/src/main/shell/xsd2inst.cmd @@ -23,8 +23,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar -set cp=%cp%;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar java -classpath "%cp%" org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator %* diff --git a/bin/xsdtree b/src/main/shell/xsdtree similarity index 90% rename from bin/xsdtree rename to src/main/shell/xsdtree index 03e140b..1962369 100755 --- a/bin/xsdtree +++ b/src/main/shell/xsdtree @@ -19,7 +19,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar +cp=$XMLBEANS_LIB/* case "`uname`" in CYGWIN*) diff --git a/bin/xsdtree.cmd b/src/main/shell/xsdtree.cmd similarity index 88% rename from bin/xsdtree.cmd rename to src/main/shell/xsdtree.cmd index 7ec0497..01cdd79 100644 --- a/bin/xsdtree.cmd +++ b/src/main/shell/xsdtree.cmd @@ -22,6 +22,6 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar;%XMLBEANS_LIB%\xmlbeans-qname.jar;%XMLBEANS_LIB%\jsr173_1.0_api.jar; +set cp=%cp%;%XMLBEANS_LIB%\*;%XMLBEANS_LIB%\jsr173_1.0_api.jar; java -classpath "%cp%" org.apache.xmlbeans.impl.tool.TypeHierarchyPrinter %* diff --git a/bin/xstc b/src/main/shell/xstc similarity index 87% rename from bin/xstc rename to src/main/shell/xstc index 80abf1c..7daf0d8 100755 --- a/bin/xstc +++ b/src/main/shell/xstc @@ -19,7 +19,7 @@ if [ -z "$XMLBEANS_LIB" ]; then . `dirname $0`/_setlib; fi -cp=$XMLBEANS_LIB/xbean.jar:$XMLBEANS_LIB/xmlbeans-qname.jar:$XMLBEANS_LIB/jsr173_1.0_api.jar:$XMLBEANS_LIB/resolver.jar +cp=$XMLBEANS_LIB/*:$XMLBEANS_LIB/resolver.jar case "`uname`" in CYGWIN*) diff --git a/bin/xstc.cmd b/src/main/shell/xstc.cmd similarity index 91% rename from bin/xstc.cmd rename to src/main/shell/xstc.cmd index f024a5a..b5ef780 100644 --- a/bin/xstc.cmd +++ b/src/main/shell/xstc.cmd @@ -22,8 +22,7 @@ setlocal if "%XMLBEANS_LIB%" EQU "" call "%~dp0_setlib" set cp= -set cp=%cp%;%XMLBEANS_LIB%\xbean.jar -set cp=%cp%;%XMLBEANS_LIB%\xmlbeans-qname.jar +set cp=%cp%;%XMLBEANS_LIB%\* set cp=%cp%;%XMLBEANS_LIB%\jsr173_1.0_api.jar set cp=%cp%;%XMLBEANS_LIB%\resolver.jar diff --git a/src/marshal/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java b/src/marshal/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java deleted file mode 100644 index 831ec01..0000000 --- a/src/marshal/org/apache/xmlbeans/impl/richParser/XMLStreamReaderExtImpl.java +++ /dev/null @@ -1,1341 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.richParser; - -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDateBuilder; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.XmlCalendar; -import org.apache.xmlbeans.impl.common.XMLChar; -import org.apache.xmlbeans.impl.util.XsTypeConverter; -import org.apache.xmlbeans.impl.util.Base64; -import org.apache.xmlbeans.impl.util.HexBin; -import org.apache.xmlbeans.impl.common.InvalidLexicalValueException; -import org.apache.xmlbeans.impl.common.XmlWhitespace; - -import javax.xml.namespace.NamespaceContext; -import javax.xml.namespace.QName; -import javax.xml.stream.Location; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Date; - -/** - * Author: Cezar Andrei (cezar.andrei at bea.com) - * Date: Nov 17, 2003 - */ -public class XMLStreamReaderExtImpl - implements XMLStreamReaderExt -{ - private final XMLStreamReader _xmlStream; - private final CharSeqTrimWS _charSeq; - private String _defaultValue; - - public XMLStreamReaderExtImpl(XMLStreamReader xmlStream) - { - if (xmlStream==null) - throw new IllegalArgumentException(); - - _xmlStream = xmlStream; - _charSeq = new CharSeqTrimWS(this); - } - - public XMLStreamReader getUnderlyingXmlStream() - { - return _xmlStream; - } - - // XMLStreamReaderExt methods - public String getStringValue() - throws XMLStreamException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_PRESERVE); - return _charSeq.toString(); - } - - public String getStringValue(int wsStyle) - throws XMLStreamException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_PRESERVE); - //REVIEW zieg 2004-01-11 - we should write a collapse method - //that takes a CharSequence to void creating this extra String object - return XmlWhitespace.collapse(_charSeq.toString(), wsStyle); - } - - public boolean getBooleanValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexBoolean(_charSeq); - } - catch(InvalidLexicalValueException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public byte getByteValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexByte(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public short getShortValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexShort(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public int getIntValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexInt(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public long getLongValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexLong(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public BigInteger getBigIntegerValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexInteger(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public BigDecimal getBigDecimalValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexDecimal(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public float getFloatValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexFloat(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public double getDoubleValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexDouble(_charSeq); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public InputStream getHexBinaryValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - String text = _charSeq.toString(); - byte[] buf = HexBin.decode(text.getBytes()); - if (buf!=null) - return new ByteArrayInputStream(buf); - else - throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation()); - } - - public InputStream getBase64Value() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - String text = _charSeq.toString(); - byte[] buf = Base64.decode(text.getBytes()); - if (buf!=null) - return new ByteArrayInputStream(buf); - else - throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation()); - } - - public XmlCalendar getCalendarValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return new GDateBuilder(_charSeq).getCalendar(); - } - catch( IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public Date getDateValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return new GDateBuilder(_charSeq).getDate(); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public GDate getGDateValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexGDate(_charSeq); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public GDuration getGDurationValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return new GDuration(_charSeq); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public QName getQNameValue() - throws XMLStreamException, InvalidLexicalValueException - { - _charSeq.reload(CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexQName(_charSeq, _xmlStream.getNamespaceContext()); - } - catch(InvalidLexicalValueException e) - { - throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation()); - } - } - - public String getAttributeStringValue(int index) throws XMLStreamException - { - return _xmlStream.getAttributeValue(index); - } - - public String getAttributeStringValue(int index, int wsStyle) throws XMLStreamException - { - return XmlWhitespace.collapse(_xmlStream.getAttributeValue(index), wsStyle); - } - - public boolean getAttributeBooleanValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexBoolean(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(InvalidLexicalValueException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public byte getAttributeByteValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexByte(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public short getAttributeShortValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexShort(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public int getAttributeIntValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexInt(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public long getAttributeLongValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexLong(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public BigInteger getAttributeBigIntegerValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexInteger(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public BigDecimal getAttributeBigDecimalValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexDecimal(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public float getAttributeFloatValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexFloat(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public double getAttributeDoubleValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexDouble(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public InputStream getAttributeHexBinaryValue(int index) throws XMLStreamException - { - String text = _charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM).toString(); - byte[] buf = HexBin.decode(text.getBytes()); - if (buf!=null) - return new ByteArrayInputStream(buf); - else - throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation()); - } - - public InputStream getAttributeBase64Value(int index) throws XMLStreamException - { - String text = _charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM).toString(); - byte[] buf = Base64.decode(text.getBytes()); - if (buf!=null) - return new ByteArrayInputStream(buf); - else - throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation()); - } - - public XmlCalendar getAttributeCalendarValue(int index) throws XMLStreamException - { - try - { - return new GDateBuilder(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)). - getCalendar(); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public Date getAttributeDateValue(int index) throws XMLStreamException - { - try - { - return new GDateBuilder(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)) - .getDate(); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public GDate getAttributeGDateValue(int index) throws XMLStreamException - { - try - { - return new GDate(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public GDuration getAttributeGDurationValue(int index) throws XMLStreamException - { - try - { - return new GDuration(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public QName getAttributeQNameValue(int index) throws XMLStreamException - { - try - { - return XsTypeConverter.lexQName(_charSeq.reloadAtt(index, CharSeqTrimWS.XMLWHITESPACE_TRIM), - _xmlStream.getNamespaceContext()); - } - catch(InvalidLexicalValueException e) - { - throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation()); - } - } - - public String getAttributeStringValue(String uri, String local) throws XMLStreamException - { - return _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_PRESERVE).toString(); - } - - public String getAttributeStringValue(String uri, String local, int wsStyle) throws XMLStreamException - { - return XmlWhitespace.collapse(_xmlStream.getAttributeValue(uri, local), wsStyle); - } - - public boolean getAttributeBooleanValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexBoolean(cs); - } - catch(InvalidLexicalValueException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public byte getAttributeByteValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexByte(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public short getAttributeShortValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexShort(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public int getAttributeIntValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexInt(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public long getAttributeLongValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexLong(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public BigInteger getAttributeBigIntegerValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexInteger(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public BigDecimal getAttributeBigDecimalValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexDecimal(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public float getAttributeFloatValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexFloat(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public double getAttributeDoubleValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexDouble(cs); - } - catch(NumberFormatException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public InputStream getAttributeHexBinaryValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - String text = cs.toString(); - byte[] buf = HexBin.decode(text.getBytes()); - if (buf!=null) - return new ByteArrayInputStream(buf); - else - throw new InvalidLexicalValueException("invalid hexBinary value", _charSeq.getLocation()); - } - - public InputStream getAttributeBase64Value(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - String text = cs.toString(); - byte[] buf = Base64.decode(text.getBytes()); - if (buf!=null) - return new ByteArrayInputStream(buf); - else - throw new InvalidLexicalValueException("invalid base64Binary value", _charSeq.getLocation()); - } - - public XmlCalendar getAttributeCalendarValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return new GDateBuilder(cs).getCalendar(); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public Date getAttributeDateValue(String uri, String local) throws XMLStreamException - { - try - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - return new GDateBuilder(cs).getDate(); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public GDate getAttributeGDateValue(String uri, String local) throws XMLStreamException - { - try - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - return new GDate(cs); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public GDuration getAttributeGDurationValue(String uri, String local) throws XMLStreamException - { - try - { - return new GDuration(_charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM)); - } - catch(IllegalArgumentException e) - { - throw new InvalidLexicalValueException(e, _charSeq.getLocation()); - } - } - - public QName getAttributeQNameValue(String uri, String local) throws XMLStreamException - { - CharSequence cs = _charSeq.reloadAtt(uri, local, CharSeqTrimWS.XMLWHITESPACE_TRIM); - try - { - return XsTypeConverter.lexQName(cs, _xmlStream.getNamespaceContext()); - } - catch (InvalidLexicalValueException e) - { - throw new InvalidLexicalValueException(e.getMessage(), _charSeq.getLocation()); - } - } - - public void setDefaultValue(String defaultValue) throws XMLStreamException - { - _defaultValue = defaultValue; - } - - /** - * Only trims the XML whaitspace at edges, it should not be used for WS collapse - * Used for int, short, byte - */ - private static class CharSeqTrimWS - implements CharSequence - { - final static int XMLWHITESPACE_PRESERVE = 1; - final static int XMLWHITESPACE_TRIM = 2; - - private static int INITIAL_SIZE = 100; - private char[] _buf = new char[INITIAL_SIZE]; - private int _start, _length = 0; - private int _nonWSStart = 0; - private int _nonWSEnd = 0; - private String _toStringValue; - private XMLStreamReaderExtImpl _xmlSteam; - //private boolean _supportForGetTextCharacters = true; - private final ExtLocation _location; - private boolean _hasText; - - CharSeqTrimWS(XMLStreamReaderExtImpl xmlSteam) - { - _xmlSteam = xmlSteam; - _location = new ExtLocation(); - } - - void reload(int style) - throws XMLStreamException - { - _toStringValue = null; - _location.reset(); - _hasText = false; - - fillBuffer(); - - if (style==XMLWHITESPACE_PRESERVE) - { - _nonWSStart = 0; - _nonWSEnd = _length; - - // takes defaultValue only if there wasn't any text - if (!_hasText && _xmlSteam._defaultValue!=null) - { - _length = 0; - fillBufferFromString(_xmlSteam._defaultValue); - } - } - else if (style==XMLWHITESPACE_TRIM) - { - for (_nonWSStart=0; _nonWSStart<_length; _nonWSStart++) - if (!XMLChar.isSpace(_buf[_nonWSStart])) - break; - for (_nonWSEnd=_length; _nonWSEnd>_nonWSStart; _nonWSEnd--) - if (!XMLChar.isSpace(_buf[_nonWSEnd-1])) - break; - - // takes defaultValue if length after triming is 0 - if (length()==0 && _xmlSteam._defaultValue!=null) - { - _length = 0; - fillBufferFromString(_xmlSteam._defaultValue); - - //apply whispace rule on the default value - for (_nonWSStart=0; _nonWSStart<_length; _nonWSStart++) - if (!XMLChar.isSpace(_buf[_nonWSStart])) - break; - for (_nonWSEnd=_length; _nonWSEnd>_nonWSStart; _nonWSEnd--) - if (!XMLChar.isSpace(_buf[_nonWSEnd-1])) - break; - } - } - _xmlSteam._defaultValue = null; - } - - private void fillBuffer() - throws XMLStreamException - { - _length = 0; - - if (_xmlSteam.getEventType() == XMLStreamReader.START_DOCUMENT) - _xmlSteam.next(); - if (_xmlSteam.isStartElement()) - _xmlSteam.next(); - - int depth = 0; - String error = null; - int eventType = _xmlSteam.getEventType(); - - loop: - while(true) - { - switch(eventType) - { - case XMLStreamReader.CDATA: - case XMLStreamReader.CHARACTERS: - case XMLStreamReader.SPACE: - _location.set(_xmlSteam.getLocation()); - - if (depth==0) - addTextToBuffer(); - - break; - - case XMLStreamReader.ATTRIBUTE: - case XMLStreamReader.COMMENT: - case XMLStreamReader.DTD: - case XMLStreamReader.ENTITY_DECLARATION: - case XMLStreamReader.NAMESPACE: - case XMLStreamReader.NOTATION_DECLARATION: - case XMLStreamReader.PROCESSING_INSTRUCTION: - case XMLStreamReader.START_DOCUMENT: - // ignore - break; - - case XMLStreamReader.END_DOCUMENT: - _location.set(_xmlSteam.getLocation()); - - break loop; - - case XMLStreamReader.END_ELEMENT: - _location.set(_xmlSteam.getLocation()); - depth--; - if (depth<0) - break loop; - break; - - case XMLStreamReader.ENTITY_REFERENCE: - _location.set(_xmlSteam.getLocation()); - - addEntityToBuffer(); - break; - - case XMLStreamReader.START_ELEMENT: - depth++; - error = "Unexpected element '" + _xmlSteam.getName() + "' in text content."; - _location.set(_xmlSteam.getLocation()); - - break; - } - eventType = _xmlSteam.next(); - } - if (error!=null) - throw new XMLStreamException(error); - } - - private void ensureBufferLength(int lengthToAdd) - { - if (_length + lengthToAdd>_buf.length) - { - char[] newBuf = new char[_length + lengthToAdd]; - if (_length>0) - System.arraycopy(_buf, 0, newBuf, 0, _length); - _buf = newBuf; - } - } - - private void fillBufferFromString(CharSequence value) - { - int textLength = value.length(); - ensureBufferLength(textLength); - - for (int i=0; inonWSStart; nonWSEnd--) - if (!XMLChar.isSpace(value.charAt(nonWSEnd-1))) - break; - if (nonWSStart==0 && nonWSEnd==length) - return value; - else - return value.subSequence(nonWSStart, nonWSEnd); - } - - throw new IllegalStateException("unknown style"); - } - - CharSequence reloadAtt(String uri, String local, int style) - throws XMLStreamException - { - _location.reset(); - _location.set(_xmlSteam.getLocation()); - String value = _xmlSteam.getAttributeValue(uri, local); - - if (value==null && _xmlSteam._defaultValue!=null) - value = _xmlSteam._defaultValue; - - _xmlSteam._defaultValue = null; - - int length = value.length(); - - if (style==XMLWHITESPACE_PRESERVE) - { - return value; - } - else if (style==XMLWHITESPACE_TRIM) - { - for (_nonWSStart=0; _nonWSStart_nonWSStart; _nonWSEnd--) - if (!XMLChar.isSpace(value.charAt(_nonWSEnd-1))) - break; - if (_nonWSStart==0 && _nonWSEnd==length) - return value; - else - return value.subSequence(_nonWSStart, _nonWSEnd); - } - throw new IllegalStateException("unknown style"); - } - - Location getLocation() - { - ExtLocation loc = new ExtLocation(); - loc.set(_location); - return loc; - } - - public int length() - { - return _nonWSEnd - _nonWSStart; - } - - public char charAt(int index) - { - // for each char, this has to be fast, using assert instead of if throw - assert (index<_nonWSEnd-_nonWSStart && -1-1 and <" + (_nonWSEnd - _nonWSStart); - - return _buf[_nonWSStart + index]; - } - - public CharSequence subSequence(int start, int end) - { - return new String(_buf, _nonWSStart + start, end - start); - } - - public String toString() - { - if (_toStringValue!=null) - return _toStringValue; - - _toStringValue = new String(_buf, _nonWSStart, _nonWSEnd - _nonWSStart); - return _toStringValue; - } - - private static class ExtLocation implements Location - { - private int _line; - private int _col; - private int _off; - private String _pid; - private String _sid; - private boolean _isSet; - - ExtLocation() - { - _isSet = false; - } - - public int getLineNumber() - { - if (_isSet) - return _line; - else - throw new IllegalStateException(); - } - - public int getColumnNumber() - { - if (_isSet) - return _col; - else - throw new IllegalStateException(); - } - - public int getCharacterOffset() - { - if (_isSet) - return _off; - else - throw new IllegalStateException(); - } - - public String getPublicId() - { - if (_isSet) - return _pid; - else - throw new IllegalStateException(); - } - - public String getSystemId() - { - if (_isSet) - return _sid; - else - throw new IllegalStateException(); - } - - void set(Location loc) - { - if (_isSet) - return; - - _isSet = true; - _line = loc.getLineNumber(); - _col = loc.getColumnNumber(); - _off = loc.getCharacterOffset(); - _pid = loc.getPublicId(); - _sid = loc.getSystemId(); - } - - void reset() - { - _isSet = false; - } - } - } - - // XMLStreamReader methods - public Object getProperty(String s) - throws IllegalArgumentException - { - return _xmlStream.getProperty(s); - } - - public int next() - throws XMLStreamException - { - return _xmlStream.next(); - } - - public void require(int i, String s, String s1) - throws XMLStreamException - { - _xmlStream.require(i, s, s1); - } - - public String getElementText() throws XMLStreamException - { - return _xmlStream.getElementText(); - } - - public int nextTag() throws XMLStreamException - { - return _xmlStream.nextTag(); - } - - public boolean hasNext() throws XMLStreamException - { - return _xmlStream.hasNext(); - } - - public void close() throws XMLStreamException - { - _xmlStream.close(); - } - - public String getNamespaceURI(String s) - { - return _xmlStream.getNamespaceURI(s); - } - - public boolean isStartElement() - { - return _xmlStream.isStartElement(); - } - - public boolean isEndElement() - { - return _xmlStream.isEndElement(); - } - - public boolean isCharacters() - { - return _xmlStream.isCharacters(); - } - - public boolean isWhiteSpace() - { - return _xmlStream.isWhiteSpace(); - } - - public String getAttributeValue(String s, String s1) - { - return _xmlStream.getAttributeValue(s, s1); - } - - public int getAttributeCount() - { - return _xmlStream.getAttributeCount(); - } - - public QName getAttributeName(int i) - { - return _xmlStream.getAttributeName(i); - } - - public String getAttributeNamespace(int i) - { - return _xmlStream.getAttributeNamespace(i); - } - - public String getAttributeLocalName(int i) - { - return _xmlStream.getAttributeLocalName(i); - } - - public String getAttributePrefix(int i) - { - return _xmlStream.getAttributePrefix(i); - } - - public String getAttributeType(int i) - { - return _xmlStream.getAttributeType(i); - } - - public String getAttributeValue(int i) - { - return _xmlStream.getAttributeValue(i); - } - - public boolean isAttributeSpecified(int i) - { - return _xmlStream.isAttributeSpecified(i); - } - - public int getNamespaceCount() - { - return _xmlStream.getNamespaceCount(); - } - - public String getNamespacePrefix(int i) - { - return _xmlStream.getNamespacePrefix(i); - } - - public String getNamespaceURI(int i) - { - return _xmlStream.getNamespaceURI(i); - } - - public NamespaceContext getNamespaceContext() - { - return _xmlStream.getNamespaceContext(); - } - - public int getEventType() - { - return _xmlStream.getEventType(); - } - - public String getText() - { - return _xmlStream.getText(); - } - - public char[] getTextCharacters() - { - return _xmlStream.getTextCharacters(); - } - - public int getTextCharacters(int i, char[] chars, int i1, int i2) - throws XMLStreamException - { - return _xmlStream.getTextCharacters(i, chars, i1, i2); - } - - public int getTextStart() - { - return _xmlStream.getTextStart(); - } - - public int getTextLength() - { - return _xmlStream.getTextLength(); - } - - public String getEncoding() - { - return _xmlStream.getEncoding(); - } - - public boolean hasText() - { - return _xmlStream.hasText(); - } - - public Location getLocation() - { - return _xmlStream.getLocation(); - } - - public QName getName() - { - return _xmlStream.getName(); - } - - public String getLocalName() - { - return _xmlStream.getLocalName(); - } - - public boolean hasName() - { - return _xmlStream.hasName(); - } - - public String getNamespaceURI() - { - return _xmlStream.getNamespaceURI(); - } - - public String getPrefix() - { - return _xmlStream.getPrefix(); - } - - public String getVersion() - { - return _xmlStream.getVersion(); - } - - public boolean isStandalone() - { - return _xmlStream.isStandalone(); - } - - public boolean standaloneSet() - { - return _xmlStream.standaloneSet(); - } - - public String getCharacterEncodingScheme() - { - return _xmlStream.getCharacterEncodingScheme(); - } - - public String getPITarget() - { - return _xmlStream.getPITarget(); - } - - public String getPIData() - { - return _xmlStream.getPIData(); - } -} diff --git a/src/repackage/repackage/EditBuildScript.java b/src/repackage/repackage/EditBuildScript.java deleted file mode 100644 index 6df16e8..0000000 --- a/src/repackage/repackage/EditBuildScript.java +++ /dev/null @@ -1,99 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repackage; - -import java.io.*; - -public class EditBuildScript -{ - // - // usgae: edit buildfile token new-value - // - - public static void main ( String[] args ) - throws Exception - { - if (args.length != 3) - throw new IllegalArgumentException( "Wrong number of arguments" ); - - args[ 0 ] = args[ 0 ].replace( '/', File.separatorChar ); - - File buildFile = new File( args[ 0 ] ); - - StringBuffer sb = readFile( buildFile ); - - String tokenStr = " 0) - System.out.println("Skipped " + _skippedFiles + " unmodified files."); - } - - private boolean fileIsUnchanged(String name) - { - File sourceFile = new File( _sourceBase, name ); - File targetFile = new File( _targetBase, name ); - return (sourceFile.lastModified() < targetFile.lastModified()); - } - - public void repackageFile ( String name ) - throws IOException - { - if (name.endsWith( ".java" )) - repackageJavaFile( name ); - else if (name.endsWith( ".xsdconfig" ) || - name.endsWith( ".xml" ) || - name.endsWith( ".g" ) ) - repackageNonJavaFile( name ); - else if (name.startsWith( "bin" + File.separatorChar )) - repackageNonJavaFile( name ); - else - moveAlongWithJavaFiles( name ); - } - - public void moveAlongWithJavaFiles( String name ) - { - _moveAlongFiles.add(name); - } - - public void finishMovingFiles ( ) - throws IOException - { - for ( Iterator i = _moveAlongFiles.iterator(); i.hasNext(); ) - { - String name = (String) i.next(); - String toName = name; - - String srcDir = Repackager.dirForPath( name ); - String toDir = (String) _movedDirs.get( srcDir ); - - if (toDir != null) - toName = new File( toDir, new File( name ).getName() ).toString(); - - if (name.endsWith( ".html" )) - repackageNonJavaFile(name, toName); - else - justMoveNonJavaFile(name, toName); - } - } - - public void repackageNonJavaFile(String name) - throws IOException - { - File sourceFile = new File( _sourceBase, name ); - File targetFile = new File( _targetBase, name ); - - if (sourceFile.lastModified() < targetFile.lastModified()) - _skippedFiles += 1; - else - writeFile( targetFile, _repackager.repackage( readFile( sourceFile ) ) ); - } - - public void repackageNonJavaFile ( String sourceName, String targetName ) - throws IOException - { - File sourceFile = new File( _sourceBase, sourceName ); - File targetFile = new File( _targetBase, targetName ); - - if (sourceFile.lastModified() < targetFile.lastModified()) - _skippedFiles += 1; - else - writeFile( targetFile, _repackager.repackage( readFile( sourceFile ) ) ); - } - - public void justMoveNonJavaFile ( String sourceName, String targetName ) - throws IOException - { - File sourceFile = new File( _sourceBase, sourceName ); - File targetFile = new File( _targetBase, targetName ); - - if (sourceFile.lastModified() < targetFile.lastModified()) - _skippedFiles += 1; - else - copyFile( sourceFile, targetFile ); - } - - public void repackageJavaFile ( String name ) - throws IOException - { - File sourceFile = new File(_sourceBase, name); - StringBuffer sb = readFile(sourceFile); - - Matcher packageMatcher = _packagePattern.matcher( sb ); - - if (packageMatcher.find()) - { - String pkg = packageMatcher.group( 1 ); - int pkgStart = packageMatcher.start( 1 ); - int pkgEnd = packageMatcher.end( 1 ); - - if (packageMatcher.find()) - throw new RuntimeException( "Two package specifications found: " + name ); - - List filePath = Repackager.splitPath( name, File.separatorChar ); - String srcDir = Repackager.dirForPath( name ); - - // Sort the repackage spec so that longer from's are first to match - // longest package first - - for ( ; ; ) - { - boolean swapped = false; - - for ( int i = 1 ; i < filePath.size() ; i++ ) - { - String spec1 = (String) filePath.get( i - 1 ); - String spec2 = (String) filePath.get( i ); - - if (spec1.indexOf( ':' ) < spec2.indexOf( ':' )) - { - filePath.set( i - 1, spec2 ); - filePath.set( i, spec1 ); - - swapped = true; - } - } - - if (!swapped) - break; - } - - List pkgPath = Repackager.splitPath( pkg, '.' ); - - int f = filePath.size() - 2; - - if (f<0 || (filePath.size()-1)< pkgPath.size()) - throw new RuntimeException("Package spec differs from file path: " + name); - - for ( int i = pkgPath.size() - 1 ; i >= 0 ; i-- ) - { - if (!pkgPath.get( i ).equals( filePath.get( f ) )) - throw new RuntimeException( "Package spec differs from file path: " + name ); - f--; - } - - List changeTo = null; - List changeFrom = null; - - from: - for ( int i = 0 ; i < _fromPackages.size() ; i ++ ) - { - List from = (List) _fromPackages.get( i ); - - if (from.size() <= pkgPath.size()) - { - for ( int j = 0 ; j < from.size() ; j++ ) - if (!from.get( j ).equals( pkgPath.get( j ))) - continue from; - - changeFrom = from; - changeTo = (List) _toPackages.get( i ); - - break; - } - } - - if (changeTo != null) - { - String newPkg = ""; - String newName = ""; - - for ( int i = 0 ; i < changeTo.size() ; i++ ) - { - if (i > 0) - { - newPkg += "."; - newName += File.separatorChar; - } - - newPkg += changeTo.get( i ); - newName += changeTo.get( i ); - } - - for ( int i = filePath.size() - pkgPath.size() - 2 ; i >= 0 ; i-- ) - newName = (String) filePath.get( i ) + File.separatorChar + newName; - - for ( int i = changeFrom.size() ; i < pkgPath.size() ; i++ ) - { - newName += File.separatorChar + (String) pkgPath.get( i ); - newPkg += '.' + (String) pkgPath.get( i ); - } - - newName += File.separatorChar + (String) filePath.get( filePath.size() - 1 ); - - sb.replace( pkgStart, pkgEnd, newPkg ); - - name = newName; - String newDir = Repackager.dirForPath( name ); - - if (!srcDir.equals(newDir)) - { - _movedDirs.put(srcDir, newDir); - } - } - } - - File targetFile = new File(_targetBase, name); // new name - - if (sourceFile.lastModified() < targetFile.lastModified()) - { - _skippedFiles += 1; - return; - } - - writeFile( new File( _targetBase, name ), _repackager.repackage( sb ) ); - } - - void writeFile ( File f, StringBuffer chars ) - throws IOException - { - f.getParentFile().mkdirs(); - - OutputStream out = new FileOutputStream( f ); - Writer w = new OutputStreamWriter( out ); - Reader r = new StringReader( chars.toString() ); - - copy( r, w ); - - r.close(); - w.close(); - out.close(); - } - - StringBuffer readFile ( File f ) - throws IOException - { - InputStream in = new FileInputStream( f ); - Reader r = new InputStreamReader( in ); - StringWriter w = new StringWriter(); - - copy( r, w ); - - w.close(); - r.close(); - in.close(); - - return w.getBuffer(); - } - - StringBuffer readInputStream ( InputStream is ) - throws IOException - { - Reader r = new InputStreamReader( is ); - StringWriter w = new StringWriter(); - - copy( r, w ); - - w.close(); - r.close(); - - return w.getBuffer(); - } - - public static void copyFile ( File from, File to ) throws IOException - { - to.getParentFile().mkdirs(); - - FileInputStream in = new FileInputStream( from ); - FileOutputStream out = new FileOutputStream( to ); - - copy( in, out ); - - out.close(); - in.close(); - } - - public static void copy ( InputStream in, OutputStream out ) throws IOException - { - byte[] buffer = new byte [ 1024 * 16 ]; - - for ( ; ; ) - { - int n = in.read( buffer, 0, buffer.length ); - - if (n < 0) - break; - - out.write( buffer, 0, n ); - } - } - - public static void copy ( Reader r, Writer w ) throws IOException - { - char[] buffer = new char [ 1024 * 16 ]; - - for ( ; ; ) - { - int n = r.read( buffer, 0, buffer.length ); - - if (n < 0) - break; - - w.write( buffer, 0, n ); - } - } - - public void fillFiles ( ArrayList files, File file ) throws IOException - { - if (!file.isDirectory()) - { - files.add( file ); - return; - } - - // Exclude the build directory - - if (file.getName().equals( "build" )) - return; - - // Exclude CVS directories - if (file.getName().equals( "CVS" )) - return; - - String[] entries = file.list(); - - for ( int i = 0 ; i < entries.length ; i++ ) - fillFiles( files, new File( file, entries[ i ] ) ); - } - - public void recursiveDelete ( File file ) throws IOException - { - if (!file.exists()) - return; - - if (file.isDirectory()) - { - String[] entries = file.list(); - - for ( int i = 0 ; i < entries.length ; i++ ) - recursiveDelete( new File( file, entries[ i ] ) ); - } - - file.delete(); - } - - private File _sourceBase; - private File _targetBase; - - private List _fromPackages; - private List _toPackages; - - private Pattern _packagePattern; - - private Repackager _repackager; - - private Map _movedDirs; - private List _moveAlongFiles; - private int _skippedFiles; -} diff --git a/src/repackage/repackage/Repackager.java b/src/repackage/repackage/Repackager.java deleted file mode 100644 index d1a815d..0000000 --- a/src/repackage/repackage/Repackager.java +++ /dev/null @@ -1,184 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repackage; - -import java.util.List; -import java.util.ArrayList; -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import java.io.File; - -public class Repackager -{ - public Repackager ( String repackageSpecs ) - { - _fromPackages = new ArrayList(); - _toPackages = new ArrayList(); - - List repackages = splitPath( repackageSpecs, ';' ); - - // Sort the repackage spec so that longer from's are first to match - // longest package first - - for ( ; ; ) - { - boolean swapped = false; - - for ( int i = 1 ; i < repackages.size() ; i++ ) - { - String spec1 = (String) repackages.get( i - 1 ); - String spec2 = (String) repackages.get( i ); - - if (spec1.indexOf( ':' ) < spec2.indexOf( ':' )) - { - repackages.set( i - 1, spec2 ); - repackages.set( i, spec1 ); - - swapped = true; - } - } - - if (!swapped) - break; - } - - for ( int i = 0 ; i < repackages.size() ; i++ ) - { - String spec = (String) repackages.get( i ); - - int j = spec.indexOf( ':' ); - - if (j < 0 || spec.indexOf( ':', j + 1 ) >= 0) - throw new RuntimeException( "Illegal repackage specification: " + spec ); - - String from = spec.substring( 0, j ); - String to = spec.substring( j + 1 ); - - _fromPackages.add( Repackager.splitPath( from, '.' ) ); - _toPackages.add( Repackager.splitPath( to, '.' ) ); - } - - _fromMatchers = new Matcher [ _fromPackages.size() * 2 ]; - _toPackageNames = new String [ _fromPackages.size() * 2 ]; - - addPatterns( '.', 0 ); - addPatterns( '/', _fromPackages.size() ); - } - - void addPatterns ( char sep, int off ) - { - for ( int i = 0 ; i < _fromPackages.size() ; i++ ) - { - List from = (List) _fromPackages.get( i ); - List to = (List) _toPackages.get( i ); - - String pattern = ""; - - for ( int j = 0 ; j < from.size() ; j++ ) - { - if (j > 0) - pattern += "\\" + sep; - - pattern += from.get( j ); - } - - String toPackage = ""; - - for ( int j = 0 ; j < to.size() ; j++ ) - { - if (j > 0) - toPackage += sep; - - toPackage += to.get( j ); - } - - _fromMatchers[ off + i ] = Pattern.compile( pattern ).matcher( "" ); - _toPackageNames[ off + i ] = toPackage; - } - } - - public StringBuffer repackage ( StringBuffer sb ) - { - StringBuffer result = null; - - for ( int i = 0 ; i < _fromMatchers.length ; i++ ) - { - Matcher m = (Matcher) _fromMatchers[ i ]; - - m.reset( sb ); - - for ( boolean found = m.find() ; found ; found = m.find() ) - { - if (result == null) - result = new StringBuffer(); - - m.appendReplacement( result, _toPackageNames[ i ] ); - } - - if (result != null) - { - m.appendTail( result ); - sb = result; - result = null; - } - } - - return sb; - } - - public List getFromPackages ( ) - { - return _fromPackages; - } - - public List getToPackages ( ) - { - return _toPackages; - } - - public static ArrayList splitPath ( String path, char separator ) - { - ArrayList components = new ArrayList(); - - for ( ; ; ) - { - int i = path.indexOf( separator ); - - if (i < 0) - break; - - components.add( path.substring( 0, i ) ); - - path = path.substring( i + 1 ); - } - - if (path.length() > 0) - components.add( path ); - - return components; - } - - public static String dirForPath ( String path ) - { - return new File(path).getParent(); - } - - private List _fromPackages; - private List _toPackages; - - private Matcher[] _fromMatchers; - private String[] _toPackageNames; -} \ No newline at end of file diff --git a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPElementFactory.java b/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPElementFactory.java deleted file mode 100644 index 492da54..0000000 --- a/src/saaj_api/org/apache/xmlbeans/impl/soap/SOAPElementFactory.java +++ /dev/null @@ -1,117 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.soap; - -/** - *

      SOAPElementFactory is a factory for XML - * fragments that will eventually end up in the SOAP part. These - * fragments can be inserted as children of the - * SOAPHeader or SOAPBody or - * SOAPEnvelope.

      - * - *

      Elements created using this factory do not have the - * properties of an element that lives inside a SOAP header - * document. These elements are copied into the XML document tree - * when they are inserted.

      - * @deprecated - Use javax.xml.soap.SOAPFactory for creating SOAPElements. - * @see SOAPFactory SOAPFactory - */ -public class SOAPElementFactory { - - /** - * Create a new SOAPElementFactory from a SOAPFactory. - * - * @param soapfactory the SOAPFactory to use - */ - private SOAPElementFactory(SOAPFactory soapfactory) { - sf = soapfactory; - } - - /** - * Create a SOAPElement object initialized with - * the given Name object. - * @param name a Name object with - * the XML name for the new element - * @return the new SOAPElement object that was - * created - * @throws SOAPException if there is an error in - * creating the SOAPElement object - * @deprecated Use javax.xml.soap.SOAPFactory.createElement(javax.xml.soap.Name) instead - * @see SOAPFactory#createElement(javax.xml.soap.Name) SOAPFactory.createElement(javax.xml.soap.Name) - */ - public SOAPElement create(Name name) throws SOAPException { - return sf.createElement(name); - } - - /** - * Create a SOAPElement object initialized with - * the given local name. - * @param localName a String giving - * the local name for the new element - * @return the new SOAPElement object that was - * created - * @throws SOAPException if there is an error in - * creating the SOAPElement object - * @deprecated Use javax.xml.soap.SOAPFactory.createElement(String localName) instead - * @see SOAPFactory#createElement(java.lang.String) SOAPFactory.createElement(java.lang.String) - */ - public SOAPElement create(String localName) throws SOAPException { - return sf.createElement(localName); - } - - /** - * Create a new SOAPElement object with the - * given local name, prefix and uri. - * @param localName a String giving - * the local name for the new element - * @param prefix the prefix for this - * SOAPElement - * @param uri a String giving the - * URI of the namespace to which the new element - * belongs - * @return the new SOAPElement object that was - * created - * @throws SOAPException if there is an error in - * creating the SOAPElement object - * @deprecated Use javax.xml.soap.SOAPFactory.createElement(String localName, String prefix, String uri) instead - * @see SOAPFactory#createElement(java.lang.String, java.lang.String, java.lang.String) SOAPFactory.createElement(java.lang.String, java.lang.String, java.lang.String) - */ - public SOAPElement create(String localName, String prefix, String uri) - throws SOAPException { - return sf.createElement(localName, prefix, uri); - } - - /** - * Creates a new instance of SOAPElementFactory. - * - * @return a new instance of a - * SOAPElementFactory - * @throws SOAPException if there was an error creating - * the default SOAPElementFactory - * @deprecated - */ - public static SOAPElementFactory newInstance() throws SOAPException { - - try { - return new SOAPElementFactory(SOAPFactory.newInstance()); - } catch (Exception exception) { - throw new SOAPException("Unable to create SOAP Element Factory: " - + exception.getMessage()); - } - } - - private SOAPFactory sf; -} diff --git a/src/store/org/apache/xmlbeans/impl/store/CharUtil.java b/src/store/org/apache/xmlbeans/impl/store/CharUtil.java deleted file mode 100755 index c3b8fa0..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/CharUtil.java +++ /dev/null @@ -1,930 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.store; - -import java.io.PrintStream; -import java.lang.ref.SoftReference; - -public final class CharUtil -{ - public CharUtil ( int charBufSize ) - { - _charBufSize = charBufSize; - } - - public CharIterator getCharIterator ( Object src, int off, int cch ) - { - _charIter.init( src, off, cch ); - return _charIter; - } - - public CharIterator getCharIterator ( Object src, int off, int cch, int start ) - { - _charIter.init( src, off, cch, start ); - return _charIter; - } - - public static CharUtil getThreadLocalCharUtil ( ) - { - SoftReference softRef = (SoftReference)tl_charUtil.get(); - CharUtil charUtil = (CharUtil) softRef.get(); - if (charUtil==null) - { - charUtil = new CharUtil( CHARUTIL_INITIAL_BUFSIZE ); - tl_charUtil.set(new SoftReference(charUtil)); - } - return charUtil; - } - - public static void getString ( StringBuffer sb, Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - - if (cch == 0) - return; - - if (src instanceof char[]) - sb.append( (char[]) src, off, cch ); - else if (src instanceof String) - { - String s = (String) src; - - if (off == 0 && cch == s.length()) - sb.append( (String) src ); - else - sb.append( s.substring( off, off + cch ) ); - } - else - ((CharJoin) src).getString( sb, off, cch ); - } - - public static void getChars ( char[] chars, int start, Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - assert chars != null && start >= 0 && start <= chars.length; - - if (cch == 0) - return; - - if (src instanceof char[]) - System.arraycopy( (char[]) src, off, chars, start, cch ); - else if (src instanceof String) - ((String) src).getChars( off, off + cch, chars, start ); - else - ((CharJoin) src).getChars( chars, start, off, cch ); - } - - public static String getString ( Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - - if (cch == 0) - return ""; - - if (src instanceof char[]) - return new String( (char[]) src, off, cch ); - - if (src instanceof String) - { - String s = (String) src; - - if (off == 0 && cch == s.length()) - return s; - - return s.substring( off, off + cch ); - } - - StringBuffer sb = new StringBuffer(); - - ((CharJoin) src).getString( sb, off, cch ); - - return sb.toString(); - } - - public static final boolean isWhiteSpace ( char ch ) - { - switch ( ch ) - { - case ' ': case '\t': case '\n': case '\r': return true; - default : return false; - } - } - - public final boolean isWhiteSpace ( Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - - if (cch <= 0) - return true; - - if (src instanceof char[]) - { - for ( char[] chars = (char[]) src ; cch > 0 ; cch-- ) - if (!isWhiteSpace( chars[ off++ ] )) - return false; - - return true; - } - - if (src instanceof String) - { - for ( String s = (String) src ; cch > 0 ; cch-- ) - if (!isWhiteSpace( s.charAt( off++ ) )) - return false; - - return true; - } - - boolean isWhite = true; - - for ( _charIter.init( src, off, cch ) ; _charIter.hasNext() ; ) - { - if (!isWhiteSpace( _charIter.next() )) - { - isWhite = false; - break; - } - } - - _charIter.release(); - - return isWhite; - } - - public Object stripLeft ( Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - - if (cch > 0) - { - if (src instanceof char[]) - { - char[] chars = (char[]) src; - - while ( cch > 0 && isWhiteSpace( chars[ off ] ) ) - { cch--; off++; } - } - else if (src instanceof String) - { - String s = (String) src; - - while ( cch > 0 && isWhiteSpace( s.charAt( off ) ) ) - { cch--; off++; } - } - else - { - int count = 0; - - for ( _charIter.init( src, off, cch ) ; _charIter.hasNext() ; count++ ) - if (!isWhiteSpace( _charIter.next() )) - break; - - _charIter.release(); - - off += count; - } - } - - if (cch == 0) - { - _offSrc = 0; - _cchSrc = 0; - - return null; - } - - _offSrc = off; - _cchSrc = cch; - - return src; - } - - public Object stripRight ( Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - - if (cch > 0) - { - for ( _charIter.init( src, off, cch, cch ) ; _charIter.hasPrev() ; cch-- ) - if (!isWhiteSpace( _charIter.prev() )) - break; - - _charIter.release(); - } - - if (cch == 0) - { - _offSrc = 0; - _cchSrc = 0; - - return null; - } - - _offSrc = off; - _cchSrc = cch; - - return src; - } - - public Object insertChars ( - int posInsert, - Object src, int off, int cch, - Object srcInsert, int offInsert, int cchInsert ) - { - assert isValid( src, off, cch ); - assert isValid( srcInsert, offInsert, cchInsert ); - assert posInsert >= 0 && posInsert <= cch; - - // TODO - at some point, instead of creating joins, I should - // normalize all the text into a single buffer to stop large - // tree's from being built when many modifications happen... - - // TODO - actually, I should see if the size of the new char - // sequence is small enough to simply allocate a new contigous - // sequence, either in a common char[] managed by the master, - // or just create a new string ... this goes for remove chars - // as well. - - if (cchInsert == 0) - { - _cchSrc = cch; - _offSrc = off; - return src; - } - - if (cch == 0) - { - _cchSrc = cchInsert; - _offSrc = offInsert; - return srcInsert; - } - - _cchSrc = cch + cchInsert; - - Object newSrc; - - if (_cchSrc <= MAX_COPY && canAllocate( _cchSrc )) - { - char[] c = allocate( _cchSrc ); - - getChars( c, _offSrc, src, off, posInsert ); - getChars( c, _offSrc + posInsert, srcInsert, offInsert, cchInsert ); - getChars( c, _offSrc + posInsert + cchInsert, src, off + posInsert, cch - posInsert ); - - newSrc = c; - } - else - { - _offSrc = 0; - - CharJoin newJoin; - - if (posInsert == 0) - newJoin = new CharJoin( srcInsert, offInsert, cchInsert, src, off ); - else if (posInsert == cch) - newJoin = new CharJoin( src, off, cch, srcInsert, offInsert ); - else - { - CharJoin j = new CharJoin( src, off, posInsert, srcInsert, offInsert ); - newJoin = new CharJoin( j, 0, posInsert + cchInsert, src, off + posInsert ); - } - - if (newJoin._depth > CharJoin.MAX_DEPTH) - newSrc = saveChars( newJoin, _offSrc, _cchSrc ); - else - newSrc = newJoin; - } - - assert isValid( newSrc, _offSrc, _cchSrc ); - - return newSrc; - } - - public Object removeChars ( int posRemove, int cchRemove, Object src, int off, int cch ) - { - assert isValid( src, off, cch ); - assert posRemove >= 0 && posRemove <= cch; - assert cchRemove >= 0 && posRemove + cchRemove <= cch; - - Object newSrc; - - _cchSrc = cch - cchRemove; - - if (_cchSrc == 0) - { - newSrc = null; - _offSrc = 0; - } - else if (posRemove == 0) - { - newSrc = src; - _offSrc = off + cchRemove; - } - else if (posRemove + cchRemove == cch) - { - newSrc = src; - _offSrc = off; - } - else - { - int cchAfter = cch - cchRemove; - - if (cchAfter <= MAX_COPY && canAllocate( cchAfter )) - { - char[] chars = allocate( cchAfter ); - - getChars( chars, _offSrc, src, off, posRemove ); - - getChars( - chars, _offSrc + posRemove, - src, off + posRemove + cchRemove, cch - posRemove - cchRemove ); - - newSrc = chars; - _offSrc = _offSrc; - } - else - { - CharJoin j = new CharJoin( src, off, posRemove, src, off + posRemove + cchRemove ); - - if (j._depth > CharJoin.MAX_DEPTH) - newSrc = saveChars( j, 0, _cchSrc ); - else - { - newSrc = j; - _offSrc = 0; - } - } - } - - assert isValid( newSrc, _offSrc, _cchSrc ); - - return newSrc; - } - - private static int sizeof ( Object src ) - { - assert src == null || src instanceof String || src instanceof char[]; - - if (src instanceof char[]) - return ((char[]) src).length; - - return src == null ? 0 : ((String) src).length(); - } - - private boolean canAllocate ( int cch ) - { - return _currentBuffer == null || _currentBuffer.length - _currentOffset >= cch; - } - - private char[] allocate ( int cch ) - { - assert _currentBuffer == null || _currentBuffer.length - _currentOffset > 0; - - if (_currentBuffer == null) - { - _currentBuffer = new char [ Math.max( cch, _charBufSize ) ]; - _currentOffset = 0; - } - - _offSrc = _currentOffset; - _cchSrc = Math.min( _currentBuffer.length - _currentOffset, cch ); - - char[] retBuf = _currentBuffer; - - assert _currentOffset + _cchSrc <= _currentBuffer.length; - - if ((_currentOffset += _cchSrc) == _currentBuffer.length) - { - _currentBuffer = null; - _currentOffset = 0; - } - - return retBuf; - } - - public Object saveChars ( Object srcSave, int offSave, int cchSave ) - { - return saveChars( srcSave, offSave, cchSave, null, 0, 0 ); - } - - public Object saveChars ( - Object srcSave, int offSave, int cchSave, - Object srcPrev, int offPrev, int cchPrev ) - { - // BUGBUG (ericvas) - // - // There is a severe degenerate situation which can deveol here. The cases is where - // there is a long strings of calls to saveChars, where the caller passes in prev text - // to be prepended. In this cases, the buffer breaks and a join is made, but because the - // join is created, subsequent calls willproduce additional joins. I need to figure - // out a way that a whole bunch of joins are not created. I really only want to create - // joins in situations where large amount of text is manipulated. - - assert isValid( srcSave, offSave, cchSave ); - assert isValid( srcPrev, offPrev, cchPrev ); - - // Allocate some space to save the text and copy it there. This may not allocate all - // the space I need. This happens when I run out of buffer space. Deal with this later. - - char[] srcAlloc = allocate( cchSave ); - int offAlloc = _offSrc; - int cchAlloc = _cchSrc; - - assert cchAlloc <= cchSave; - - getChars( srcAlloc, offAlloc, srcSave, offSave, cchAlloc ); - - Object srcNew; - int offNew; - - int cchNew = cchAlloc + cchPrev; - - // The prev arguments specify a chunk of text which the caller wants prepended to the - // text to be saved. The optimization here is to detect the case where the prev text - // and the newly allcoated and saved text are adjacent, so that I can avoid copying - // or joining the two pieces. The situation where this happens most is when a parser - // reports a big piece of text in chunks, perhaps because there are entities in the - // big chunk of text. - - CharJoin j; - - if (cchPrev == 0) - { - srcNew = srcAlloc; - offNew = offAlloc; - } - else if (srcPrev == srcAlloc && offPrev + cchPrev == offAlloc) - { - assert srcPrev instanceof char[]; - - srcNew = srcPrev; - offNew = offPrev; - } - else if (srcPrev instanceof CharJoin && (j = (CharJoin) srcPrev)._srcRight == srcAlloc && - offPrev + cchPrev - j._cchLeft + j._offRight == offAlloc) - { - assert j._srcRight instanceof char[]; - - srcNew = srcPrev; - offNew = offPrev; - } - else - { - j = new CharJoin( srcPrev, offPrev, cchPrev, srcAlloc, offAlloc ); - - srcNew = j; - offNew = 0; - srcNew = j._depth > CharJoin.MAX_DEPTH ? saveChars( j, 0, cchNew ) : j; - } - - // Now, srcNew and offNew specify the two parts of the triple which has the prev text and - // part of the text to save (if not all of it). Here I compute cchMore which is any - // remaining text which was not allocated for earlier. Effectively, this code deals with - // the case where the text to save was greater than the remaining space in the buffer and - // I need to allocate another buffer to save away the second part and then join the two. - - int cchMore = cchSave - cchAlloc; - - if (cchMore > 0) - { - // If we're here the the buffer got consumed. So, this time it must allocate a new - // buffer capable of containing all of the remaining text (no matter how large) and - // return the beginning part of it. - - srcAlloc = allocate( cchMore ); - offAlloc = _offSrc; - cchAlloc = _cchSrc; - - assert cchAlloc == cchMore; - assert offAlloc == 0; - - getChars( srcAlloc, offAlloc, srcSave, offSave + (cchSave - cchMore), cchMore ); - - j = new CharJoin( srcNew, offNew, cchNew, srcAlloc, offAlloc ); - - offNew = 0; - cchNew += cchMore; - srcNew = j._depth > CharJoin.MAX_DEPTH ? saveChars( j, 0, cchNew ) : j; - } - - _offSrc = offNew; - _cchSrc = cchNew; - - assert isValid( srcNew, _offSrc, _cchSrc ); - - return srcNew; - } - - private static void dumpText ( PrintStream o, String s ) - { - o.print( "\"" ); - - for ( int i = 0 ; i < s.length() ; i++ ) - { - char ch = s.charAt( i ); - - if (i == 36) - { - o.print( "..." ); - break; - } - - if (ch == '\n') o.print( "\\n" ); - else if (ch == '\r') o.print( "\\r" ); - else if (ch == '\t') o.print( "\\t" ); - else if (ch == '\f') o.print( "\\f" ); - else if (ch == '\f') o.print( "\\f" ); - else if (ch == '"' ) o.print( "\\\"" ); - else o.print( ch ); - } - - o.print( "\"" ); - } - - public static void dump ( Object src, int off, int cch ) - { - dumpChars( System.out, src, off, cch ); - System.out.println(); - } - - public static void dumpChars ( PrintStream p, Object src, int off, int cch ) - { - p.print( "off=" + off + ", cch=" + cch + ", " ); - - if (src == null) - p.print( "" ); - else if (src instanceof String) - { - String s = (String) src; - - p.print( "String" ); - - if (off != 0 || cch != s.length()) - { - if (off < 0 || off > s.length() || off + cch < 0 || off + cch > s.length()) - { - p.print( " (Error)" ); - return; - } - } - - //p.print( ": " ); - dumpText( p, s.substring( off, off + cch ) ); - } - else if (src instanceof char[]) - { - char[] chars = (char[]) src; - - p.print( "char[]" ); - - if (off != 0 || cch != chars.length) - { - if (off < 0 || off > chars.length || off + cch < 0 || off + cch > chars.length) - { - p.print( " (Error)" ); - return; - } - } - - //p.print( ": " ); - dumpText( p, new String( chars, off, cch ) ); - } - else if (src instanceof CharJoin) - { - p.print( "CharJoin" ); - - ((CharJoin) src).dumpChars( p, off, cch ); - } - else - { - p.print( "Unknown text source" ); - } - } - - public static boolean isValid ( Object src, int off, int cch ) - { - if (cch < 0 || off < 0) - return false; - - if (src == null) - return off == 0 && cch == 0; - - if (src instanceof char[]) - { - char[] c = (char[]) src; - return off <= c.length && off + cch <= c.length; - } - - if (src instanceof String) - { - String s = (String) src; - return off <= s.length() && off + cch <= s.length(); - } - - if (src instanceof CharJoin) - return ((CharJoin) src).isValid( off, cch ); - - return false; - } - - // - // Private stuff - // - - public static final class CharJoin - { - public CharJoin ( - Object srcLeft, int offLeft, int cchLeft, Object srcRight, int offRight ) - { - _srcLeft = srcLeft; _offLeft = offLeft; _cchLeft = cchLeft; - _srcRight = srcRight; _offRight = offRight; - - int depth = 0; - - if (srcLeft instanceof CharJoin) - depth = ((CharJoin) srcLeft)._depth; - - if (srcRight instanceof CharJoin) - { - int rightDepth = ((CharJoin) srcRight)._depth; - - if (rightDepth > depth) - depth = rightDepth; - } - - _depth = depth + 1; - - assert _depth <= MAX_DEPTH + 2; - } - - private int cchRight ( int off, int cch ) - { - return Math.max( 0, cch - _cchLeft - off ); - } - - public int depth ( ) - { - int depth = 0; - - if (_srcLeft instanceof CharJoin) - depth = ((CharJoin) _srcLeft).depth(); - - if (_srcRight instanceof CharJoin) - depth = Math.max( ((CharJoin)_srcRight).depth(), depth ); - - return depth + 1; - } - - public boolean isValid ( int off, int cch ) - { - // Deep trees cause this to take forever - - if (_depth > 2) - return true; - - assert _depth == depth(); - - if (off < 0 || cch < 0) - return false; - - if (!CharUtil.isValid( _srcLeft, _offLeft, _cchLeft )) - return false; - - if (!CharUtil.isValid( _srcRight, _offRight, cchRight( off, cch ) )) - return false; - - return true; - } - - private void getString ( StringBuffer sb, int off, int cch ) - { - assert cch > 0; - - if (off < _cchLeft) - { - int cchL = Math.min( _cchLeft - off, cch ); - - CharUtil.getString( sb, _srcLeft, _offLeft + off, cchL ); - - if (cch > cchL) - CharUtil.getString( sb, _srcRight, _offRight, cch - cchL ); - } - else - CharUtil.getString( sb, _srcRight, _offRight + off - _cchLeft, cch ); - } - - private void getChars ( char[] chars, int start, int off, int cch ) - { - assert cch > 0; - - if (off < _cchLeft) - { - int cchL = Math.min( _cchLeft - off, cch ); - - CharUtil.getChars( chars, start, _srcLeft, _offLeft + off, cchL ); - - if (cch > cchL) - CharUtil.getChars( chars, start + cchL, _srcRight, _offRight, cch - cchL ); - } - else - CharUtil.getChars( chars, start, _srcRight, _offRight + off - _cchLeft, cch ); - } - - private void dumpChars( int off, int cch ) - { - dumpChars( System.out, off, cch ); - } - - private void dumpChars( PrintStream p, int off, int cch ) - { - p.print( "( " ); - CharUtil.dumpChars( p, _srcLeft, _offLeft, _cchLeft ); - p.print( ", " ); - CharUtil.dumpChars( p, _srcRight, _offRight, cchRight( off, cch ) ); - p.print( " )" ); - } - - // - // - // - - public final Object _srcLeft; - public final int _offLeft; - public final int _cchLeft; - - public final Object _srcRight; - public final int _offRight; - - public final int _depth; - - static final int MAX_DEPTH = 64; - } - - // - // - // - - public final static class CharIterator - { - public void init ( Object src, int off, int cch ) - { - init( src, off, cch, 0 ); - } - - public void init ( Object src, int off, int cch, int startPos ) - { - assert isValid( src, off, cch ); - - release(); - - _srcRoot = src; - _offRoot = off; - _cchRoot = cch; - - _minPos = _maxPos = -1; - - movePos( startPos ); - } - - public void release ( ) - { - _srcRoot = null; - _srcLeafString = null; - _srcLeafChars = null; - } - - public boolean hasNext ( ) { return _pos < _cchRoot; } - public boolean hasPrev ( ) { return _pos > 0; } - - public char next ( ) - { - assert hasNext() ; - - char ch = currentChar(); - - movePos( _pos + 1 ); - - return ch; - } - - public char prev ( ) - { - assert hasPrev() ; - - movePos( _pos - 1 ); - - return currentChar(); - } - - public void movePos ( int newPos ) - { - assert newPos >= 0 && newPos <= _cchRoot; - - if (newPos < _minPos || newPos > _maxPos) - { - // if newPos out of cached leaf, recache new leaf - Object src = _srcRoot; - int off = _offRoot + newPos; - int cch = _cchRoot; - - for ( _offLeaf = _offRoot ; src instanceof CharJoin ; ) - { - CharJoin j = (CharJoin) src; - - if (off < j._cchLeft) - { - src = j._srcLeft; - _offLeaf = j._offLeft; - off = off + j._offLeft; - cch = j._cchLeft; - } - else - { - src = j._srcRight; - _offLeaf = j._offRight; - off = off - (j._cchLeft - j._offRight); - cch = cch - j._cchLeft; - } - } - -// _offLeaf = off - Math.min( off - _offLeaf, newPos ); - _minPos = newPos - (off - _offLeaf); -// _maxPos = newPos + Math.min( _cchRoot - newPos, sizeof( src ) - off ); - _maxPos = _minPos + cch; - - if (newPos < _cchRoot) - _maxPos--; - - // Cache the leaf src to avoid instanceof for every char - - _srcLeafChars = null; - _srcLeafString = null; - - if (src instanceof char[]) - _srcLeafChars = (char[]) src; - else - _srcLeafString = (String) src; - - assert newPos >= _minPos && newPos <= _maxPos; - } - - _pos = newPos; - } - - private char currentChar ( ) - { - int i = _offLeaf + _pos - _minPos; - - return _srcLeafChars == null ? _srcLeafString.charAt( i ) : _srcLeafChars[ i ]; - } - - private Object _srcRoot; // Original triple - private int _offRoot; - private int _cchRoot; - - private int _pos; // Current position - - private int _minPos; // Min/max poses for current cached leaf - private int _maxPos; - - private int _offLeaf; - - private String _srcLeafString; // Cached leaf - either a char[] or a string - private char[] _srcLeafChars; - } - - private static int CHARUTIL_INITIAL_BUFSIZE = 1024 * 32; - private static ThreadLocal tl_charUtil = - new ThreadLocal() { protected Object initialValue() { return new SoftReference(new CharUtil( CHARUTIL_INITIAL_BUFSIZE )); } }; - - private CharIterator _charIter = new CharIterator(); - - // TODO - 64 is kinda arbitrary. Perhaps it should be configurable. - private static final int MAX_COPY = 64; - - // Current char buffer we're allcoating new chars to - - private int _charBufSize; - private int _currentOffset; - private char[] _currentBuffer; - - // These members are used to communicate offset and character count - // information back to a caller of various methods on CharUtil. - // Usually, the methods returns the src Object, and these two hold - // the offset and the char count. - - public int _offSrc; - public int _cchSrc; -} \ No newline at end of file diff --git a/src/store/org/apache/xmlbeans/impl/store/Cur.java b/src/store/org/apache/xmlbeans/impl/store/Cur.java deleted file mode 100755 index fcb8bfe..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Cur.java +++ /dev/null @@ -1,3619 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import org.w3c.dom.Attr; -import org.w3c.dom.CDATASection; -import org.w3c.dom.CharacterData; -import org.w3c.dom.Comment; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.DocumentType; -import org.w3c.dom.DOMException; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Element; -import org.w3c.dom.EntityReference; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.DOMImplementation; - -// DOM Level 3 -import org.w3c.dom.UserDataHandler; -import org.w3c.dom.DOMConfiguration; -import org.w3c.dom.TypeInfo; - - -import javax.xml.transform.Source; - -import java.io.PrintStream; - -import java.util.Iterator; -import java.util.Map; -import java.util.ArrayList; -import java.util.List; - -import org.apache.xmlbeans.impl.soap.Detail; -import org.apache.xmlbeans.impl.soap.DetailEntry; -import org.apache.xmlbeans.impl.soap.MimeHeaders; -import org.apache.xmlbeans.impl.soap.Name; -import org.apache.xmlbeans.impl.soap.SOAPBody; -import org.apache.xmlbeans.impl.soap.SOAPBodyElement; -import org.apache.xmlbeans.impl.soap.SOAPElement; -import org.apache.xmlbeans.impl.soap.SOAPEnvelope; -import org.apache.xmlbeans.impl.soap.SOAPException; -import org.apache.xmlbeans.impl.soap.SOAPFactory; -import org.apache.xmlbeans.impl.soap.SOAPFault; -import org.apache.xmlbeans.impl.soap.SOAPFaultElement; -import org.apache.xmlbeans.impl.soap.SOAPHeader; -import org.apache.xmlbeans.impl.soap.SOAPHeaderElement; -import org.apache.xmlbeans.impl.soap.SOAPPart; -import org.apache.xmlbeans.impl.store.Xobj.Bookmark; - -import org.apache.xmlbeans.impl.store.Locale.LoadContext; - -import org.apache.xmlbeans.impl.store.DomImpl.Dom; -import org.apache.xmlbeans.impl.store.DomImpl.CharNode; -import org.apache.xmlbeans.impl.store.DomImpl.TextNode; -import org.apache.xmlbeans.impl.store.DomImpl.CdataNode; -import org.apache.xmlbeans.impl.store.DomImpl.SaajTextNode; -import org.apache.xmlbeans.impl.store.DomImpl.SaajCdataNode; - -import org.apache.xmlbeans.CDataBookmark; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlLineNumber; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import org.apache.xmlbeans.impl.values.TypeStore; -import org.apache.xmlbeans.impl.values.TypeStoreUser; -import org.apache.xmlbeans.impl.values.TypeStoreVisitor; -import org.apache.xmlbeans.impl.values.TypeStoreUserFactory; - -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.impl.common.ValidatorListener; -import org.apache.xmlbeans.impl.common.XmlLocale; -import org.apache.xmlbeans.impl.common.QNameHelper; - - -final class Cur -{ - static final int TEXT = 0; // Must be 0 - static final int ROOT = 1; - static final int ELEM = 2; - static final int ATTR = 3; - static final int COMMENT = 4; - static final int PROCINST = 5; - - static final int POOLED = 0; - static final int REGISTERED = 1; - static final int EMBEDDED = 2; - static final int DISPOSED = 3; - - static final int END_POS = -1; - static final int NO_POS = -2; - - Cur ( Locale l ) - { - _locale = l; - _pos = NO_POS; - - _tempFrame = -1; - - _state = POOLED; - - _stackTop = Locations.NULL; - _selectionFirst = -1; - _selectionN = -1; - _selectionLoc = Locations.NULL; - _selectionCount = 0; - } - - boolean isPositioned ( ) { assert isNormal(); return _xobj != null; } - - static boolean kindIsContainer ( int k ) { return k == ELEM || k == ROOT; } - static boolean kindIsFinish ( int k ) { return k == -ELEM || k == -ROOT; } - - int kind ( ) - { - assert isPositioned(); - int kind = _xobj.kind(); - return _pos == 0 ? kind : (_pos == END_POS ? - kind : TEXT); - } - - boolean isRoot ( ) { assert isPositioned(); return _pos == 0 && _xobj.kind() == ROOT; } - boolean isElem ( ) { assert isPositioned(); return _pos == 0 && _xobj.kind() == ELEM; } - boolean isAttr ( ) { assert isPositioned(); return _pos == 0 && _xobj.kind() == ATTR; } - boolean isComment ( ) { assert isPositioned(); return _pos == 0 && _xobj.kind() == COMMENT; } - boolean isProcinst ( ) { assert isPositioned(); return _pos == 0 && _xobj.kind() == PROCINST; } - boolean isText ( ) { assert isPositioned(); return _pos > 0; } - boolean isEnd ( ) { assert isPositioned(); return _pos == END_POS && _xobj.kind() ==ELEM;} - boolean isEndRoot ( ) { assert isPositioned(); return _pos == END_POS && _xobj.kind() ==ROOT;} - boolean isNode ( ) { assert isPositioned(); return _pos == 0; } - boolean isContainer ( ) { assert isPositioned(); return _pos == 0 && kindIsContainer( _xobj.kind() ); } - boolean isFinish ( ) { assert isPositioned(); return _pos == END_POS && kindIsContainer( _xobj.kind() ); } - boolean isUserNode ( ) { assert isPositioned(); int k = kind(); return k == ELEM || k == ROOT || (k == ATTR && !isXmlns()); } - - boolean isContainerOrFinish ( ) - { - assert isPositioned(); - - if (_pos!=0 && _pos!= END_POS) - return false; - - int kind = _xobj.kind(); - return kind == ELEM || kind == -ELEM || kind == ROOT || kind == -ROOT; - } - - boolean isNormalAttr ( ) { return isNode() && _xobj.isNormalAttr(); } - boolean isXmlns ( ) { return isNode() && _xobj.isXmlns(); } - - boolean isTextCData ( ) { return _xobj.hasBookmark(CDataBookmark.class, _pos); } - - QName getName ( ) { assert isNode() || isEnd(); return _xobj._name; } - String getLocal ( ) { return getName().getLocalPart(); } - String getUri ( ) { return getName().getNamespaceURI(); } - - String getXmlnsPrefix ( ) { assert isXmlns(); return _xobj.getXmlnsPrefix(); } - String getXmlnsUri ( ) { assert isXmlns(); return _xobj.getXmlnsUri(); } - - boolean isDomDocRoot ( ) { return isRoot() && _xobj.getDom() instanceof Document; } - boolean isDomFragRoot ( ) { return isRoot() && _xobj.getDom() instanceof DocumentFragment; } - - int cchRight ( ) { assert isPositioned(); return _xobj.cchRight( _pos ); } - int cchLeft ( ) { assert isPositioned(); return _xobj.cchLeft ( _pos ); } - - // - // Creation methods - // - - void createRoot ( ) - { - createDomDocFragRoot(); - } - - void createDomDocFragRoot ( ) - { - moveTo( new Xobj.DocumentFragXobj( _locale ) ); - } - - void createDomDocumentRoot ( ) - { - moveTo( createDomDocumentRootXobj( _locale ) ); - } - - void createAttr ( QName name ) - { - createHelper( new Xobj.AttrXobj( _locale, name ) ); - } - - void createComment ( ) - { - createHelper( new Xobj.CommentXobj( _locale ) ); - } - - void createProcinst ( String target ) - { - createHelper( new Xobj.ProcInstXobj( _locale, target ) ); - } - - void createElement ( QName name ) - { - createElement( name, null ); - } - - void createElement ( QName name, QName parentName ) - { - createHelper( createElementXobj( _locale, name, parentName ) ); - } - - static Xobj createDomDocumentRootXobj ( Locale l ) - { - return createDomDocumentRootXobj(l, false); - } - - static Xobj createDomDocumentRootXobj ( Locale l , boolean fragment) - { - Xobj xo; - - if (l._saaj == null) - if (fragment) - xo = new Xobj.DocumentFragXobj( l ); - else - xo = new Xobj.DocumentXobj( l ); - else - xo = new Xobj.SoapPartDocXobj( l ); - - if (l._ownerDoc == null) - l._ownerDoc = xo.getDom(); - - return xo; - } - - static Xobj createElementXobj ( Locale l, QName name, QName parentName ) - { - if (l._saaj == null) - return new Xobj.ElementXobj( l, name ); - - Class c = l._saaj.identifyElement( name, parentName ); - - if (c == SOAPElement.class) return new Xobj.SoapElementXobj ( l, name ); - if (c == SOAPBody.class) return new Xobj.SoapBodyXobj ( l, name ); - if (c == SOAPBodyElement.class) return new Xobj.SoapBodyElementXobj ( l, name ); - if (c == SOAPEnvelope.class) return new Xobj.SoapEnvelopeXobj ( l, name ); - if (c == SOAPHeader.class) return new Xobj.SoapHeaderXobj ( l, name ); - if (c == SOAPHeaderElement.class) return new Xobj.SoapHeaderElementXobj ( l, name ); - if (c == SOAPFaultElement.class) return new Xobj.SoapFaultElementXobj ( l, name ); - if (c == Detail.class) return new Xobj.DetailXobj ( l, name ); - if (c == DetailEntry.class) return new Xobj.DetailEntryXobj ( l, name ); - if (c == SOAPFault.class) return new Xobj.SoapFaultXobj ( l, name ); - - throw new IllegalStateException( "Unknown SAAJ element class: " + c ); - } - - private void createHelper ( Xobj x ) - { - assert x._locale == _locale; - - // insert the new Xobj into an exisiting tree. - - if (isPositioned()) - { - Cur from = tempCur( x, 0 ); - from.moveNode( this ); - from.release(); - } - - moveTo( x ); - } - - // - // General operations - // - - boolean isSamePos ( Cur that ) - { - assert isNormal() && (that == null || that.isNormal()); - - return _xobj == that._xobj && _pos == that._pos; - } - - // is this just after the end of that (that must be the start of a node) - - boolean isJustAfterEnd ( Cur that ) - { - assert isNormal() && that != null && that.isNormal() && that.isNode(); - - return that._xobj.isJustAfterEnd( _xobj, _pos ); - } - - boolean isJustAfterEnd ( Xobj x ) - { - return x.isJustAfterEnd( _xobj, _pos ); - } - - boolean isAtEndOf ( Cur that ) - { - assert that != null && that.isNormal() && that.isNode(); - - return _xobj == that._xobj && _pos == END_POS; - } - - boolean isInSameTree ( Cur that ) - { - assert isPositioned() && that.isPositioned(); - - return _xobj.isInSameTree( that._xobj ); - } - - // Retunr -1, 0 or 1 for relative cursor positions. Return 2 is not in sames trees. - - int comparePosition ( Cur that ) - { - assert isPositioned() && that.isPositioned(); - - // If in differnet locales, then can't comapre - - if (_locale != that._locale) - return 2; - - // No need to denormalize, but I want positions which I can compare (no END_POS) - - Xobj xThis = _xobj; - int pThis = _pos == END_POS ? xThis.posAfter() - 1 : _pos; - - Xobj xThat = that._xobj; - int pThat = that._pos == END_POS ? xThat.posAfter() - 1 : that._pos; - - // There are several cases: - // - // 1. Cursors are on the same xobj - // 2. One cursor is a child of the other - // 3. Cursors share a common parent - // 4. Cursors are not in the same trees - // - // Check for the first, trivial, case. Then, compute the depths of the nodes the - // cursors are on, checkin for case 2 - // - - if (xThis == xThat) - return pThis < pThat ? -1 : pThis == pThat ? 0 : 1; - - // Compute the depth of xThis. See if I hit xThat (case 2) - - int dThis = 0; - - for ( Xobj x = xThis._parent ; x != null ; x = x._parent ) - { - dThis++; - - if (x == xThat) - return pThat < xThat.posAfter() - 1 ? 1 : -1; - } - - // Compute the depth of xThat. See if I hit xThis (case 2) - - int dThat = 0; - - for ( Xobj x = xThat._parent ; x != null ; x = x._parent ) - { - dThat++; - - if (x == xThis) - return pThis < xThis.posAfter() - 1 ? -1 : 1; - } - - // Must be case 3 or 4 now. Find a common parent. If none, then it's case 4 - - while ( dThis > dThat ) { dThis--; xThis = xThis._parent; } - while ( dThat > dThis ) { dThat--; xThat = xThat._parent; } - - assert dThat == dThis; - - if (dThat == 0) - return 2; - - assert xThis._parent != null && xThat._parent != null; - - while ( xThis._parent != xThat._parent ) - { - if ((xThis = xThis._parent) == null) - return 2; - - xThat = xThat._parent; - } - - // Now, see where xThis and XThat are relative to eachother in the childlist. Apply - // some quick common checks before iterating. - - if (xThis._prevSibling == null || xThat._nextSibling == null) - return -1; - - if (xThis._nextSibling == null || xThat._prevSibling == null) - return 1; - - while ( xThis != null ) - if ((xThis = xThis._prevSibling) == xThat) - return 1; - - return -1; - } - - void setName ( QName newName ) - { - assert isNode() && newName != null; - - _xobj.setName( newName ); - } - - void moveTo ( Xobj x ) - { - moveTo( x, 0 ); - } - - void moveTo ( Xobj x, int p ) - { - // This cursor may not be normalized upon entry, don't assert isNormal() here - - assert x == null || _locale == x._locale; - assert x != null || p == NO_POS; - assert x == null || x.isNormal( p ) || ( x.isVacant() && x._cchValue==0 && x._user == null ); - assert _state == REGISTERED || _state == EMBEDDED; - assert _state == EMBEDDED || (_xobj == null || !isOnList( _xobj._embedded )); - assert _state == REGISTERED || (_xobj != null && isOnList( _xobj._embedded )); - - moveToNoCheck( x, p ); - - assert isNormal() || ( _xobj.isVacant() && _xobj._cchValue==0 && _xobj._user == null ); - } - - void moveToNoCheck ( Xobj x, int p ) - { - if (_state == EMBEDDED && x != _xobj) - { - _xobj._embedded = listRemove( _xobj._embedded ); - _locale._registered = listInsert( _locale._registered ); - _state = REGISTERED; - } - - _xobj = x; - _pos = p; - } - - void moveToCur ( Cur to ) - { - assert isNormal() && (to == null || to.isNormal()); - - if (to == null) - moveTo( null, NO_POS ); - else - moveTo( to._xobj, to._pos ); - } - - void moveToDom ( Dom d ) - { - assert _locale == d.locale(); - assert d instanceof Xobj || d instanceof Xobj.SoapPartDom; - - moveTo( d instanceof Xobj ? (Xobj) d : ((Xobj.SoapPartDom) d)._docXobj ); - } - - static final class Locations - { - private static final int NULL = -1; - - Locations ( Locale l ) - { - _locale = l; - - _xobjs = new Xobj [ _initialSize ]; - _poses = new int [ _initialSize ]; - _curs = new Cur [ _initialSize ]; - _next = new int [ _initialSize ]; - _prev = new int [ _initialSize ]; - _nextN = new int [ _initialSize ]; - _prevN = new int [ _initialSize ]; - - for ( int i = _initialSize - 1 ; i >= 0 ; i-- ) - { - assert _xobjs[ i ] == null; - _poses [ i ] = NO_POS; - _next [ i ] = i + 1; - _prev [ i ] = NULL; - _nextN [ i ] = NULL; - _prevN [ i ] = NULL; - } - - _next [ _initialSize - 1 ] = NULL; - - _free = 0; - _naked = NULL; - } - - boolean isSamePos ( int i, Cur c ) - { - if (_curs[ i ] == null) - return c._xobj == _xobjs[ i ] && c._pos == _poses[ i ]; - else - return c.isSamePos( _curs[ i ] ); - } - - boolean isAtEndOf ( int i, Cur c ) - { - assert _curs[ i ] != null || _poses[ i ] == 0; - assert _curs[ i ] == null || _curs[ i ].isNode(); - - if (_curs[ i ] == null) - return c._xobj == _xobjs[ i ] && c._pos == END_POS; - else - return c.isAtEndOf( _curs[ i ] ); - } - - void moveTo ( int i, Cur c ) - { - if (_curs[ i ] == null) - c.moveTo( _xobjs[ i ], _poses[ i ] ); - else - c.moveToCur( _curs[ i ] ); - } - - int insert ( int head, int before, int i ) - { - return insert( head, before, i, _next, _prev ); - } - - int remove ( int head, int i ) - { - Cur c = _curs[ i ]; - - assert c != null || _xobjs[ i ] != null; - assert c != null || _xobjs[ i ] != null; - - if (c != null) - { - _curs[ i ].release(); - _curs[ i ] = null; - - assert _xobjs[ i ] == null; - assert _poses [ i ] == NO_POS; - } - else - { - assert _xobjs[ i ] != null && _poses[ i ] != NO_POS; - - _xobjs[ i ] = null; - _poses[ i ] = NO_POS; - - _naked = remove( _naked, i, _nextN, _prevN ); - } - - head = remove( head, i, _next, _prev ); - - _next[ i ] = _free; - _free = i; - - return head; - } - - int allocate ( Cur addThis ) - { - assert addThis.isPositioned(); - - if (_free == NULL) - makeRoom(); - - int i = _free; - - _free = _next [ i ]; - - _next [ i ] = NULL; - assert _prev [ i ] == NULL; - - assert _curs [ i ] == null; - assert _xobjs[ i ] == null; - assert _poses[ i ] == NO_POS; - - _xobjs [ i ] = addThis._xobj; - _poses [ i ] = addThis._pos; - - _naked = insert( _naked, NULL, i, _nextN, _prevN ); - - return i; - } - - private static int insert ( int head, int before, int i, int[] next, int[] prev ) - { - if (head == NULL) - { - assert before == NULL; - prev[ i ] = i; - head = i; - } - else if (before != NULL) - { - prev[ i ] = prev[ before ]; - next[ i ] = before; - prev[ before ] = i; - - if (head == before) - head = i; - } - else - { - prev[ i ] = prev[ head ]; - assert next[ i ] == NULL; - next[ prev[ head ] ] = i; - prev[ head ] = i; - } - - return head; - } - - private static int remove ( int head, int i, int[] next, int[] prev ) - { - if (prev[ i ] == i) - { - assert head == i; - head = NULL; - } - else - { - if (head == i) - head = next[ i ]; - else - next[ prev [ i ] ] = next[ i ]; - - if (next[ i ] == NULL) - prev[ head ] = prev[ i ]; - else - { - prev[ next[ i ] ] = prev[ i ]; - next[ i ] = NULL; - } - } - - prev[ i ] = NULL; - assert next[ i ] == NULL; - - return head; - } - - void notifyChange ( ) - { - for ( int i ; (i = _naked) != NULL ; ) - { - assert _curs[ i ] == null && _xobjs[ i ] != null && _poses[ i ] != NO_POS; - - _naked = remove( _naked, i, _nextN, _prevN ); - - _curs[ i ] = _locale.getCur(); - _curs[ i ].moveTo( _xobjs[ i ], _poses[ i ] ); - - _xobjs[ i ] = null; - _poses[ i ] = NO_POS; - } - } - - int next ( int i ) { return _next[ i ]; } - int prev ( int i ) { return _prev[ i ]; } - - private void makeRoom ( ) - { - assert _free == NULL; - - int l = _xobjs.length; - - Xobj [] oldXobjs = _xobjs; - int [] oldPoses = _poses; - Cur [] oldCurs = _curs; - int [] oldNext = _next; - int [] oldPrev = _prev; - int [] oldNextN = _nextN; - int [] oldPrevN = _prevN; - - _xobjs = new Xobj [ l * 2 ]; - _poses = new int [ l * 2 ]; - _curs = new Cur [ l * 2 ]; - _next = new int [ l * 2 ]; - _prev = new int [ l * 2 ]; - _nextN = new int [ l * 2 ]; - _prevN = new int [ l * 2 ]; - - System.arraycopy( oldXobjs, 0, _xobjs, 0, l ); - System.arraycopy( oldPoses, 0, _poses, 0, l ); - System.arraycopy( oldCurs, 0, _curs, 0, l ); - System.arraycopy( oldNext, 0, _next, 0, l ); - System.arraycopy( oldPrev, 0, _prev, 0, l ); - System.arraycopy( oldNextN, 0, _nextN, 0, l ); - System.arraycopy( oldPrevN, 0, _prevN, 0, l ); - - for ( int i = l * 2 - 1 ; i >= l ; i-- ) - { - _next [ i ] = i + 1; - _prev [ i ] = NULL; - _nextN [ i ] = NULL; - _prevN [ i ] = NULL; - _poses [ i ] = NO_POS; - } - - _next [ l * 2 - 1 ] = NULL; - - _free = l; - } - - private static final int _initialSize = 32; - - private Locale _locale; - - private Xobj [] _xobjs; - private int [] _poses; - private Cur [] _curs; - private int [] _next; - private int [] _prev; - private int [] _nextN; - private int [] _prevN; - - private int _free; // Unused entries - private int _naked; // Entries without Curs - } - - void push ( ) - { - assert isPositioned(); - - int i = _locale._locations.allocate( this ); - _stackTop = _locale._locations.insert( _stackTop, _stackTop, i ); - } - - void pop ( boolean stay ) - { - if (stay) - popButStay(); - else - pop(); - } - - void popButStay ( ) - { - if (_stackTop != Locations.NULL) - _stackTop = _locale._locations.remove( _stackTop, _stackTop ); - } - - boolean pop ( ) - { - if (_stackTop == Locations.NULL) - return false; - - _locale._locations.moveTo( _stackTop, this ); - _stackTop = _locale._locations.remove( _stackTop, _stackTop ); - - return true; - } - - boolean isAtLastPush ( ) - { - assert _stackTop != Locations.NULL; - - return _locale._locations.isSamePos( _stackTop, this ); - } - - boolean isAtEndOfLastPush ( ) - { - assert _stackTop != Locations.NULL; - - return _locale._locations.isAtEndOf( _stackTop, this ); - } - - void addToSelection ( Cur that ) - { - assert that != null && that.isNormal(); - assert isPositioned() && that.isPositioned(); - - int i = _locale._locations.allocate( that ); - _selectionFirst = _locale._locations.insert( _selectionFirst, Locations.NULL, i ); - - _selectionCount++; - } - - void addToSelection ( ) - { - assert isPositioned(); - - int i = _locale._locations.allocate( this ); - _selectionFirst = _locale._locations.insert( _selectionFirst, Locations.NULL, i ); - - _selectionCount++; - } - - private int selectionIndex ( int i ) - { - assert _selectionN >= -1 && i >= 0 && i < _selectionCount; - - if (_selectionN == -1) - { - _selectionN = 0; - _selectionLoc = _selectionFirst; - } - - while ( _selectionN < i ) - { - _selectionLoc = _locale._locations.next( _selectionLoc ); - _selectionN++; - } - - while ( _selectionN > i ) - { - _selectionLoc = _locale._locations.prev( _selectionLoc ); - _selectionN--; - } - - return _selectionLoc; - } - - void removeSelection ( int i ) - { - assert i >= 0 && i < _selectionCount; - - int j = selectionIndex( i ); - - // Update the nth selection indices to accomodate the deletion - - if (i < _selectionN) - _selectionN--; - else if (i == _selectionN) - { - _selectionN--; - - if (i == 0) - _selectionLoc = Locations.NULL; - else - _selectionLoc = _locale._locations.prev( _selectionLoc ); - } - - _selectionFirst = _locale._locations.remove( _selectionFirst, j ); - - _selectionCount--; - } - - int selectionCount ( ) - { - return _selectionCount; - } - - void moveToSelection ( int i ) - { - assert i >= 0 && i < _selectionCount; - - _locale._locations.moveTo( selectionIndex( i ), this ); - } - - void clearSelection ( ) - { - assert _selectionCount >= 0; - - while ( _selectionCount > 0 ) - removeSelection( 0 ); - } - - boolean toParent ( ) { return toParent( false ); } - boolean toParentRaw ( ) { return toParent( true ); } - - Xobj getParent ( ) { return getParent( false ); } - Xobj getParentRaw ( ) { return getParent( true ); } - - boolean hasParent ( ) - { - assert isPositioned(); - - if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) - return true; - - assert _pos == 0 || _xobj._parent != null; - - return _xobj._parent != null; - } - - Xobj getParentNoRoot() - { - assert isPositioned(); - - if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) - return _xobj; - - assert _pos == 0 || _xobj._parent != null; - - if (_xobj._parent != null) - return _xobj._parent; - - return null; - } - - Xobj getParent ( boolean raw ) - { - assert isPositioned(); - - if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) - return _xobj; - - assert _pos == 0 || _xobj._parent != null; - - if (_xobj._parent != null) - return _xobj._parent; - - if (raw || _xobj.isRoot()) - return null; - - Cur r = _locale.tempCur(); - - r.createRoot(); - - Xobj root = r._xobj; - - r.next(); - moveNode( r ); - r.release(); - - return root; - } - - boolean toParent ( boolean raw ) - { - Xobj parent = getParent( raw ); - - if (parent == null) - return false; - - moveTo( parent ); - - return true; - } - - void toRoot () - { - Xobj xobj = _xobj; - while (!xobj.isRoot()) - { - if (xobj._parent==null) - { - Cur r = _locale.tempCur(); - - r.createRoot(); - - Xobj root = r._xobj; - - r.next(); - moveNode( r ); - r.release(); - - xobj = root; - break; - } - xobj = xobj._parent; - } - moveTo(xobj); - } - - boolean hasText ( ) - { - assert isNode(); - - return _xobj.hasTextEnsureOccupancy(); - } - - boolean hasAttrs ( ) - { - assert isNode(); - - return _xobj.hasAttrs(); - } - - boolean hasChildren ( ) - { - assert isNode(); - - return _xobj.hasChildren(); - } - - boolean toFirstChild ( ) - { - assert isNode(); - - if (!_xobj.hasChildren()) - return false; - - for ( Xobj x = _xobj._firstChild ; ; x = x._nextSibling ) - { - if (!x.isAttr()) - { - moveTo( x ); - return true; - } - } - } - - protected boolean toLastChild ( ) - { - assert isNode(); - - if (!_xobj.hasChildren()) - return false; - - moveTo( _xobj._lastChild ); - - return true; - } - - boolean toNextSibling ( ) - { - assert isNode(); - - if (_xobj.isAttr()) - { - if (_xobj._nextSibling != null && _xobj._nextSibling.isAttr()) - { - moveTo( _xobj._nextSibling ); - return true; - } - } - else if (_xobj._nextSibling != null) - { - moveTo( _xobj._nextSibling ); - return true; - } - - return false; - } - - void setValueAsQName ( QName qname ) - { - assert isNode(); - - String value = qname.getLocalPart(); - String ns = qname.getNamespaceURI(); - - String prefix = - prefixForNamespace( - ns, qname.getPrefix().length() > 0 ? qname.getPrefix() : null, true ); - - if (prefix.length() > 0) - value = prefix + ":" + value; - - setValue( value ); - } - - void setValue ( String value ) - { - assert isNode(); - - moveNodeContents( null, false ); - - next(); - - insertString( value ); - - toParent(); - } - - void removeFollowingAttrs ( ) - { - assert isAttr(); - - QName attrName = getName(); - - push(); - - if (toNextAttr()) - { - while ( isAttr() ) - { - if (getName().equals( attrName )) - moveNode( null ); - else if (!toNextAttr()) - break; - } - } - - pop(); - } - - String getAttrValue ( QName name ) - { - String s = null; - - push(); - - if (toAttr( name )) - s = getValueAsString(); - - pop(); - - return s; - } - - void setAttrValueAsQName ( QName name, QName value ) - { - assert isContainer(); - - if (value == null) - { - _xobj.removeAttr( name ); - } - else - { - if (toAttr( name )) - { - removeFollowingAttrs(); - } - else - { - next(); - createAttr( name ); - } - - setValueAsQName( value ); - - toParent(); - } - } - - boolean removeAttr ( QName name ) - { - assert isContainer(); - - return _xobj.removeAttr( name ); - } - - void setAttrValue ( QName name, String value ) - { - assert isContainer(); - - _xobj.setAttr( name, value ); - } - - boolean toAttr ( QName name ) - { - assert isNode(); - - Xobj a = _xobj.getAttr( name ); - - if (a == null) - return false; - - moveTo( a ); - - return true; - } - - boolean toFirstAttr ( ) - { - assert isNode(); - - Xobj firstAttr = _xobj.firstAttr(); - - if (firstAttr == null) - return false; - - moveTo( firstAttr ); - - return true; - } - - boolean toLastAttr ( ) - { - assert isNode(); - - if (!toFirstAttr()) - return false; - - while ( toNextAttr() ) - ; - - return true; - } - - boolean toNextAttr ( ) - { - assert isAttr() || isContainer(); - - Xobj nextAttr = _xobj.nextAttr(); - - if (nextAttr == null) - return false; - - moveTo( nextAttr ); - - return true; - } - - boolean toPrevAttr ( ) - { - if (isAttr()) - { - if (_xobj._prevSibling == null) - moveTo( _xobj.ensureParent() ); - else - moveTo( _xobj._prevSibling ); - - return true; - } - - prev(); - - if (!isContainer()) - { - next(); - return false; - } - - return toLastAttr(); - } - - boolean skipWithAttrs ( ) - { - assert isNode(); - - if (skip()) - return true; - - if (_xobj.isRoot()) - return false; - - assert _xobj.isAttr(); - - toParent(); - - next(); - - return true; - } - - boolean skip ( ) - { - assert isNode(); - - if (_xobj.isRoot()) - return false; - - if (_xobj.isAttr()) - { - if (_xobj._nextSibling == null || !_xobj._nextSibling.isAttr()) - return false; - - moveTo( _xobj._nextSibling, 0 ); - } - else - moveTo( getNormal( _xobj, _xobj.posAfter() ), _posTemp ); - - return true; - } - - void toEnd ( ) - { - assert isNode(); - - moveTo( _xobj, END_POS ); - } - - void moveToCharNode ( CharNode node ) - { - assert node.getDom() != null && node.getDom().locale() == _locale; - - moveToDom( node.getDom() ); - - CharNode n; - - _xobj.ensureOccupancy(); - - n = _xobj._charNodesValue = - updateCharNodes( _locale, _xobj, _xobj._charNodesValue, _xobj._cchValue ); - - for ( ; n != null ; n = n._next ) - { - if (node == n) - { - moveTo( getNormal( _xobj, n._off + 1 ), _posTemp ); - return; - } - } - - n = _xobj._charNodesAfter = - updateCharNodes( _locale, _xobj, _xobj._charNodesAfter, _xobj._cchAfter ); - - for ( ; n != null ; n = n._next ) - { - if (node == n) - { - moveTo( getNormal( _xobj, n._off + _xobj._cchValue + 2 ), _posTemp ); - return; - } - } - - assert false; - } - - boolean prevWithAttrs ( ) - { - if (prev()) - return true; - - if (!isAttr()) - return false; - - toParent(); - - return true; - } - - boolean prev ( ) - { - assert isPositioned(); - - if (_xobj.isRoot() && _pos == 0) - return false; - - if (_xobj.isAttr() && _pos == 0 && _xobj._prevSibling == null) - return false; - - Xobj x = getDenormal(); - int p = _posTemp; - - assert p > 0 && p != END_POS; - - int pa = x.posAfter(); - - if (p > pa) - p = pa; - else if (p == pa) - { - // Text after an attr is allowed only on the last attr, - // and that text belongs to the parent container.. - // - // If we're a thte end of the last attr, then we were just - // inside the container, and we need to skip the attrs. - - if (x.isAttr() && - (x._cchAfter > 0 || x._nextSibling == null || !x._nextSibling.isAttr())) - { - x = x.ensureParent(); - p = 0; - } - else - p = END_POS; - } - else if (p == pa - 1) - { - x.ensureOccupancy(); - p = x._cchValue > 0 ? 1 : 0; - } - else if (p > 1) - p = 1; - else - { - assert p == 1; - p = 0; - } - - moveTo( getNormal( x, p ), _posTemp ); - - return true; - } - - boolean next ( boolean withAttrs ) - { - return withAttrs ? nextWithAttrs() : next(); - } - - boolean nextWithAttrs ( ) - { - int k = kind(); - - if (kindIsContainer( k )) - { - if (toFirstAttr()) - return true; - } - else if (k == -ATTR) - { - if (next()) - return true; - - toParent(); - - if (!toParentRaw()) - return false; - } - - return next(); - } - - boolean next ( ) - { - assert isNormal(); - - Xobj x = _xobj; - int p = _pos; - - int pa = x.posAfter(); - - if (p >= pa) - p = _xobj.posMax(); - else if (p == END_POS) - { - if (x.isRoot() || (x.isAttr() && (x._nextSibling == null || !x._nextSibling.isAttr()))) - return false; - - p = pa; - } - else if (p > 0) - { - assert x._firstChild == null || !x._firstChild.isAttr(); - - if (x._firstChild != null) - { - x = x._firstChild; - p = 0; - } - else - p = END_POS; - } - else - { - assert p == 0; - - x.ensureOccupancy(); - - p = 1; - - if (x._cchValue == 0) - { - if (x._firstChild != null) - { - if (x._firstChild.isAttr()) - { - Xobj a = x._firstChild; - - while ( a._nextSibling != null && a._nextSibling.isAttr() ) - a = a._nextSibling; - - if (a._cchAfter > 0) - { - x = a; - p = a.posAfter(); - } - else if (a._nextSibling != null) - { - x = a._nextSibling; - p = 0; - } - } - else - { - x = x._firstChild; - p = 0; - } - } - } - } - - moveTo( getNormal( x, p ), _posTemp ); - - return true; - } - - int prevChars ( int cch ) - { - assert isPositioned(); - - int cchLeft = cchLeft(); - - if (cch < 0 || cch > cchLeft) - cch = cchLeft; - - // Dang, I love this stmt :-) - - if (cch != 0) - moveTo( getNormal( getDenormal(), _posTemp - cch ), _posTemp ); - - return cch; - } - - int nextChars ( int cch ) - { - assert isPositioned(); - - int cchRight = cchRight(); - - if (cchRight == 0) - return 0; - - if (cch < 0 || cch >= cchRight) - { - // Use next to not skip over children - next(); - return cchRight; - } - - moveTo( getNormal( _xobj, _pos + cch ), _posTemp ); - - return cch; - } - - void setCharNodes ( CharNode nodes ) - { - assert nodes == null || _locale == nodes.locale(); - assert isPositioned(); - - Xobj x = getDenormal(); - int p = _posTemp; - - assert !x.isRoot() || (p > 0 && p < x.posAfter()); - - if (p >= x.posAfter()) - x._charNodesAfter = nodes; - else - x._charNodesValue = nodes; - - for ( ; nodes != null ; nodes = nodes._next ) - nodes.setDom( (Dom) x ); - - // No Need to notify text change or alter version, text nodes are - // not part of the infoset - } - - CharNode getCharNodes ( ) - { - assert isPositioned(); - assert !isRoot(); - - Xobj x = getDenormal(); - - CharNode nodes; - - if (_posTemp >= x.posAfter()) - { - nodes = x._charNodesAfter = - updateCharNodes( _locale, x, x._charNodesAfter, x._cchAfter ); - } - else - { - x.ensureOccupancy(); - - nodes = x._charNodesValue = - updateCharNodes( _locale, x, x._charNodesValue, x._cchValue ); - } - - return nodes; - } - - // private - static CharNode updateCharNodes ( Locale l, Xobj x, CharNode nodes, int cch ) - { - assert nodes == null || nodes.locale() == l; - - CharNode node = nodes; - int i = 0; - - while ( node != null && cch > 0 ) - { - assert node.getDom() == x; - - if (node._cch > cch) - node._cch = cch; - - node._off = i; - i += node._cch; - cch -= node._cch; - - node = node._next; - } - - if (cch <= 0) - { - for ( ; node != null ; node = node._next ) - { - assert node.getDom() == x; - - if (node._cch != 0) - node._cch = 0; - - node._off = i; - } - } - else - { - node = l.createTextNode(); - node.setDom( (Dom) x ); - node._cch = cch; - node._off = i; - nodes = CharNode.appendNode( nodes, node ); - } - - return nodes; - } - - final QName getXsiTypeName ( ) - { - assert isNode(); - - return _xobj.getXsiTypeName(); - } - - final void setXsiType ( QName value ) - { - assert isContainer(); - - setAttrValueAsQName( Locale._xsiType, value ); - } - - final QName valueAsQName ( ) - { - throw new RuntimeException( "Not implemented" ); - } - - final String namespaceForPrefix ( String prefix, boolean defaultAlwaysMapped ) - { - return _xobj.namespaceForPrefix( prefix, defaultAlwaysMapped ); - } - - final String prefixForNamespace ( String ns, String suggestion, boolean createIfMissing ) - { - return - (isContainer() ? _xobj : getParent()). - prefixForNamespace( ns, suggestion, createIfMissing ); - } - - // Does the node at this cursor properly contain the position specified by the argument - - boolean contains ( Cur that ) - { - assert isNode(); - assert that != null && that.isPositioned(); - - return _xobj.contains( that ); - } - - void insertString ( String s ) - { - if (s != null) - insertChars( s, 0, s.length() ); - } - - void insertChars ( Object src, int off, int cch ) - { - assert isPositioned() && !isRoot(); - assert CharUtil.isValid( src, off, cch ); - - // Check for nothing to insert - - if (cch <= 0) - return; - - _locale.notifyChange(); - - // The only situation where I need to ensure occupancy is when I'm at the end of a node. - // All other positions will require occupancy. For example, if I'm at the beginning of a - // node, then I will either insert in the after text of the previous sibling, or I will - // insert in the value of the parent. In the latter case, because the parent has a child, - // it cannot be vacant. - - if (_pos == END_POS) - _xobj.ensureOccupancy(); - - // Get the denormailized Xobj and pos. This is the Xobj which will actually receive - // the new chars. Note that a denormalized position can never be <= 0. - - Xobj x = getDenormal(); - int p = _posTemp; - - assert p > 0; - - // This will move "this" cursor to be after the inserted text. No worries, I'll update its - // position after. This insertChars takes care of all the appropriate invalidations - // (passing true as last arg). - - x.insertCharsHelper( p, src, off, cch, true ); - - // Reposition the cursor to be just before the newly inserted text. It's current - // position could have been shifted, or it may have been just before the end tag, or - // normalized on another Xobj. - - moveTo( x, p ); - - _locale._versionAll++; - } - - // Move the chars just after this Cur to the "to" Cur. If no "to" Cur is specified, - // then remove the chars. - - Object moveChars ( Cur to, int cchMove ) - { - assert isPositioned(); - assert cchMove <= 0 || cchMove <= cchRight(); - assert to == null || (to.isPositioned() && !to.isRoot()); - - if (cchMove < 0) - cchMove = cchRight(); - - // If we're instructed to move 0 characters, then return the null triple. - - if (cchMove == 0) - { - _offSrc = 0; - _cchSrc = 0; - - return null; - } - - // Here I record the triple of the chars to move. I will return this. No need to save - // cch 'cause cchMove will be that value. - - Object srcMoved = getChars( cchMove ); - int offMoved = _offSrc; - - // Either I'm moving text from the value or the after text. If after, then the container - // must be occupied. If in the value, because we're just before text, it must be occupied. - - assert isText() && (_pos >= _xobj.posAfter() ? _xobj._parent : _xobj).isOccupied(); - - if (to == null) - { - // In this case, I'm removing chars vs moving them. Normally I would like to blow - // them away entirely, but if there are any references to those chars via a bookmark - // I need to keep them alive. I do this by moving these chars to a new root. Note - // that because Curs will stay behind, I don't have to check for them. - - for ( Bookmark b = _xobj._bookmarks ; b != null ; b = b._next ) - { - if (inChars( b, cchMove, false )) - { - Cur c = _locale.tempCur(); - - c.createRoot(); - c.next(); - - Object chars = moveChars( c, cchMove ); - - c.release(); - - return chars; - } - } - } - else - { - // If the target, "to", is inside or on the edge of the text to be moved, then this - // is a no-op. In this case, I still want to return the text "moved". - // - // Note how I move "to" and this cur around. I move "to" to be at the beginning of the - // chars moved and "this" to be at the end. If the text were really moving to a - // different location, then "to" would be at the beginning of the newly moved chars, - // and "this" would be at the gap left by the newly removed chars. - - if (inChars( to, cchMove, true )) - { - // BUGBUG - may want to consider shuffling the interior cursors to the right just - // like I move "this" to the right... - - to.moveToCur( this ); - nextChars( cchMove ); - - _offSrc = offMoved; - _cchSrc = cchMove; - - return srcMoved; - } - - // Copy the chars here, I'll remove the originals next - - to.insertChars( srcMoved, offMoved, cchMove ); - } - - // Notice that I can delay the general change notification to this point because any - // modifications up to this point are made by calling other high level operations which - // generate this notification themselves. Also, no need to notify of general change in - // the "to" locale because the insertion of chars above handles that. - - _locale.notifyChange(); - - // - //if ( _xobj != null ) - { - if (to == null) - _xobj.removeCharsHelper( _pos, cchMove, null, NO_POS, false, true ); - else - _xobj.removeCharsHelper( _pos, cchMove, to._xobj, to._pos, false, true ); - } - - // Need to update the position of this cursor even though it did not move anywhere. This - // needs to happen because it may not be properly normalized anymore. Note that because - // of the removal of the text, this cur may not be normal any more, thus I call moveTo - // which does not assume this. - - _locale._versionAll++; - - _offSrc = offMoved; - _cchSrc = cchMove; - - return srcMoved; - } - - void moveNode ( Cur to ) - { - assert isNode() && !isRoot(); - assert to == null || to.isPositioned(); - assert to == null || !contains( to ); - assert to == null || !to.isRoot(); - - // TODO - should assert that is an attr is being moved, it is ok there - - - // Record the node to move and skip this cur past it. This moves this cur to be after - // the move to move/remove -- it's final resting place. The only piece of information - // about the source of the move is the node itself. - - Xobj x = _xobj; - - skip(); - - // I call another function here to move the node. I do this because I don't have to - // worry about messing with "this" here given that it not should be treated like any other - // cursor after this point. - - moveNode( x, to ); - } - - // Moves text from one place to another in a low-level way, used as a helper for the higher - // level functions. Takes care of moving bookmarks and cursors. In the high level content - // manipulation functions, cursors do not follow content, but this helper moves them. The - // arguments are denormalized. The Xobj's must be different from eachother but from the same - // locale. The destination must not be not be vacant. - - private static void transferChars ( Xobj xFrom, int pFrom, Xobj xTo, int pTo, int cch ) - { - assert xFrom != xTo; - assert xFrom._locale == xTo._locale; - assert pFrom > 0 && pFrom < xFrom.posMax(); - assert pTo > 0 && pTo <= xTo .posMax(); - assert cch > 0 && cch <= xFrom.cchRight( pFrom ); - assert pTo >= xTo.posAfter() || xTo.isOccupied(); - - // Copy the chars from -> to without performing any invalidations. This will scoot curs - // and marks around appropriately. Note that I get the cars with getCharsHelper which - // does not check for normalization because the state of the tree at this moment may not - // exactly be "correct" here. - - xTo.insertCharsHelper( - pTo, xFrom.getCharsHelper( pFrom, cch ), - xFrom._locale._offSrc, xFrom._locale._cchSrc, false ); - - xFrom.removeCharsHelper( pFrom, cch, xTo, pTo, true, false ); - } - - // Moves the node x to "to", or removes it if to is null. - - static void moveNode ( Xobj x, Cur to ) - { - assert x != null && !x.isRoot(); - assert to == null || to.isPositioned(); - assert to == null || !x.contains( to ); - assert to == null || !to.isRoot(); - - if (to != null) - { - // Before I go much further, I want to make sure that if "to" is in the container of - // a vacant node, I get it occupied. I do not need to worry about the source being - // vacant. - - if (to._pos == END_POS) - to._xobj.ensureOccupancy(); - - // See if the destination is on the edge of the node to be moved (a no-op). It is - // illegal to call this fcn when to is contained within the node to be moved. Note - // that I make sure that to gets oved to the beginning of the node. The position of - // to in all operations should leave to just before the content moved/inserted. - - if ((to._pos == 0 && to._xobj == x) || to.isJustAfterEnd( x )) - { - // TODO - should shuffle contained curs to the right??? - - to.moveTo( x ); - return; - } - } - - // Notify the locale(s) about the change I am about to make. - - x._locale.notifyChange(); - - x._locale._versionAll++; - x._locale._versionSansText++; - - if (to != null && to._locale != x._locale) - { - to._locale.notifyChange(); - - to._locale._versionAll++; - to._locale._versionSansText++; - } - - // Node is going away. Invalidate the parent (the text around the node is merging). - // Also, this node may be an attribute -- invalidate special attrs ... - - if (x.isAttr()) - x.invalidateSpecialAttr( to == null ? null : to.getParentRaw() ); - else - { - if (x._parent != null) - x._parent.invalidateUser(); - - if (to != null && to.hasParent()) - to.getParent().invalidateUser(); - } - - // If there is any text after x, I move it to be before x. This frees me to extract x - // and it's contents with out this text coming along for the ride. Note that if this - // node is the last attr and there is text after it, transferText will move the text - // to a potential previous attr. This is an invalid state for a short period of time. - // I need to move this text away here so that when I walk the tree next, *all* curs - // embedded in this node or deeper will be moved off this node. - - if (x._cchAfter > 0) - transferChars( x, x.posAfter(), x.getDenormal( 0 ), x.posTemp(), x._cchAfter ); - - assert x._cchAfter == 0; - - // Walk the node tree, moving curs out, disconnecting users and relocating to a, possibly, - // new locale. I embed the cursors in this locale before itersting to just cause the - // embed to happen once. - - x._locale.embedCurs(); - - for ( Xobj y = x ; y != null ; y = y.walk( x, true ) ) - { - while ( y._embedded != null ) - y._embedded.moveTo( x.getNormal( x.posAfter() ) ); - - y.disconnectUser(); - - if (to != null) - y._locale = to._locale; - } - - // Now, actually remove the node - - x.removeXobj(); - - // Now, if there is a destination, insert the node there and shuffle the text in the - // vicinity of the destination appropriately. - - if (to != null) - { - // To know where I should insert/append the node to move, I need to see where "to" - // would be if there were no text after it. However, I need to keep "to" where it - // is when I move the text after it later. - - Xobj here = to._xobj; - boolean append = to._pos != 0; - - int cchRight = to.cchRight(); - - if (cchRight > 0) - { - to.push(); - to.next(); - here = to._xobj; - append = to._pos != 0; - to.pop(); - } - - if (append) - here.appendXobj( x ); - else - here.insertXobj( x ); - - // The only text I need to move is that to the right of "to". Even considering all - // the cases where an attribute is involed! - - if (cchRight > 0) - transferChars( to._xobj, to._pos, x, x.posAfter(), cchRight ); - - to.moveTo( x ); - } - } - - void moveNodeContents ( Cur to, boolean moveAttrs ) - { - assert _pos==0; - assert to == null || !to.isRoot(); - - // By calling this helper, I do not have to deal with this Cur any longer. Basically, - // this Cur is out of the picture, it behaves like any other cur at this point. - - moveNodeContents( _xobj, to, moveAttrs ); - } - - static void moveNodeContents ( Xobj x, Cur to, boolean moveAttrs ) - { - // TODO - should assert that is an attr is being moved, it is ok there - - assert to == null || !to.isRoot(); - - // Collect a bit of information about the contents to move first. Note that the collection - // of this info must not cause a vacant value to become occupied. - - boolean hasAttrs = x.hasAttrs(); - boolean noSubNodesToMove = !x.hasChildren() && (!moveAttrs || !hasAttrs); - - // Deal with the cases where only text is involved in the move - - if (noSubNodesToMove) - { - // If we're vacant and there is no place to move a potential value, then I can avoid - // acquiring the text from the TypeStoreUser. Otherwise, there may be text here I - // need to move somewhere else. - - if (x.isVacant() && to == null) - { - x.clearBit( Xobj.VACANT ); - - x.invalidateUser(); - x.invalidateSpecialAttr( null ); - x._locale._versionAll++; - } - else if (x.hasTextEnsureOccupancy()) - { - Cur c = x.tempCur(); - c.next(); - c.moveChars( to, -1 ); - c.release(); - } - - return; - } - - // Here I check to see if "to" is just inside x. In this case this is a no-op. Note that - // the value of x may still be vacant. - - if (to != null) - { - // Quick check of the right edge. If it is there, I need to move "to" to the left edge - // so that it is positioned at the beginning of the "moved" content. - - if (x == to._xobj && to._pos == END_POS) - { - // TODO - shuffle interior curs? - - to.moveTo( x ); - to.next( moveAttrs && hasAttrs ); - - return; - } - - // Here I need to see if to is at the left edge. I push to's current position and - // then navigate it to the left edge then compare it to the pushed position... - // Note: gotta be careful to make sure to and x are not in different locales, curs - // may not go to a different locale. - - boolean isAtLeftEdge = false; - - if (to._locale == x._locale) - { - to.push(); - to.moveTo( x ); - to.next( moveAttrs && hasAttrs ); - isAtLeftEdge = to.isAtLastPush(); - to.pop(); - } - - // TODO - shuffle interior curs? - - if (isAtLeftEdge) - return; - - // Now, after dealing with the edge condition, I can assert that to is not inside x - - assert !x.contains( to ); - - // So, at this point, I've taken case of the no-op cases and the movement of just text. - // Also, to must be occupied because I took care of the text only and nothing to move - // cases. - - assert to.getParent().isOccupied(); - } - - // TODO - did I forget to put a changeNotification here? Look more closely ... - - // Deal with the value text of x which is either on x or the last attribute of x. - // I need to get it out of the way to properly deal with the walk of the contents. - // In order to reposition "to" properly later, I need to record how many chars were moved. - - int valueMovedCch = 0; - - if (x.hasTextNoEnsureOccupancy()) - { - Cur c = x.tempCur(); - c.next(); - c.moveChars( to, -1 ); - c.release(); - - if (to != null) - to.nextChars( valueMovedCch = c._cchSrc ); - } - - // Now, walk all the contents, invalidating special attrs, reportioning cursors, - // disconnecting users and relocating to a potentially different locale. Because I moved - // the value text above, no top level attrs should have any text. - - x._locale.embedCurs(); - - Xobj firstToMove = x.walk( x, true ); - boolean sawBookmark = false; - - for ( Xobj y = firstToMove ; y != null ; y = y.walk( x, true ) ) - { - if (y._parent == x && y.isAttr()) - { - assert y._cchAfter == 0; - - if (!moveAttrs) - { - firstToMove = y._nextSibling; - continue; - } - - y.invalidateSpecialAttr( to == null ? null : to.getParent() ); - } - - for ( Cur c ; (c = y._embedded) != null ; ) - c.moveTo( x, END_POS ); - - y.disconnectUser(); - - if (to != null) - y._locale = to._locale; - - sawBookmark = sawBookmark || y._bookmarks != null; - } - - Xobj lastToMove = x._lastChild; - - // If there were any bookmarks in the tree to remove, to preserve the content that these - // bookmarks reference, move the contents to a new root. Note that I already moved the - // first piece of text above elsewhere. Note: this has the effect of keeping all of the - // contents alive even if there is one bookmark deep into the tree. I should really - // disband all the content, except for the pieces which are bookmarked. - - Cur surragateTo = null; - - if (sawBookmark && to == null) - { - surragateTo = to = x._locale.tempCur(); - to.createRoot(); - to.next(); - } - - // Perform the rest of the invalidations. If only attrs are moving, then no user - // invalidation needed. If I've move text to "to" already, no need to invalidate - // again. - - if (!lastToMove.isAttr()) - x.invalidateUser(); - - x._locale._versionAll++; - x._locale._versionSansText++; - - if (to != null && valueMovedCch == 0) - { - to.getParent().invalidateUser(); - to._locale._versionAll++; - to._locale._versionSansText++; - } - - // Remove the children and, if needed, move them - - x.removeXobjs( firstToMove, lastToMove ); - - if (to != null) - { - // To know where I should insert/append the contents to move, I need to see where "to" - // would be if there were no text after it. - - Xobj here = to._xobj; - boolean append = to._pos != 0; - - int cchRight = to.cchRight(); - - if (cchRight > 0) - { - to.push(); - to.next(); - here = to._xobj; - append = to._pos != 0; - to.pop(); - } - - // Now, I have to shuffle the text around "to" in special ways. A complication is - // the insertion of attributes. First, if I'm inserting attrs here then, logically, - // there can be no text to the left because attrs can only live after another attr - // or just inside a container. So, If attrs are being inserted and there is value - // text on the target container, I will need to move this value text to be after - // the lew last attribute. Note that this value text may already live on a current - // last attr (before the inserting). Also, I need to figure this all out before I - // move the text after "to" because this text may end up being sent to the same place - // as the containers value text when the last new node being inserted is an attr! - // Whew! - - if (firstToMove.isAttr()) - { - Xobj lastNewAttr = firstToMove; - - while ( lastNewAttr._nextSibling != null && lastNewAttr._nextSibling.isAttr() ) - lastNewAttr = lastNewAttr._nextSibling; - - // Get to's parnet now before I potentially move him with the next transfer - - Xobj y = to.getParent(); - - if (cchRight > 0) - transferChars( to._xobj, to._pos, lastNewAttr, lastNewAttr.posMax(), cchRight ); - - if (y.hasTextNoEnsureOccupancy()) - { - int p, cch; - - if (y._cchValue > 0) - { - p = 1; - cch = y._cchValue; - } - else - { - y = y.lastAttr(); - p = y.posAfter(); - cch = y._cchAfter; - } - - transferChars( y, p, lastNewAttr, lastNewAttr.posAfter(), cch ); - } - } - else if (cchRight > 0) - transferChars( to._xobj, to._pos, lastToMove, lastToMove.posMax(), cchRight ); - - // After mucking with the text, splice the new tree in - - if (append) - here.appendXobjs( firstToMove, lastToMove ); - else - here.insertXobjs( firstToMove, lastToMove ); - - // Position "to" to be at the beginning of the newly inserted contents - - to.moveTo( firstToMove ); - to.prevChars( valueMovedCch ); - } - - // If I consed up a to, release it here - - if (surragateTo != null) - surragateTo.release(); - } - - protected final Bookmark setBookmark ( Object key, Object value ) - { - assert isNormal(); - assert key != null; - - return _xobj.setBookmark( _pos, key, value ); - } - - Object getBookmark ( Object key ) - { - assert isNormal(); - assert key != null; - - for ( Bookmark b = _xobj._bookmarks ; b != null ; b = b._next ) - if (b._pos == _pos && b._key == key) - return b._value; - - return null; - } - - int firstBookmarkInChars ( Object key, int cch ) - { - assert isNormal(); - assert key != null; - assert cch > 0; - assert cch <= cchRight(); - - int d = -1; - - if (isText()) - { - for ( Bookmark b = _xobj._bookmarks ; b != null ; b = b._next ) - if (b._key == key && inChars( b, cch, false )) - d = (d == -1 || b._pos - _pos < d) ? b._pos - _pos : d; - } - - return d; - } - - int firstBookmarkInCharsLeft ( Object key, int cch ) - { - assert isNormal(); - assert key != null; - assert cch > 0; - assert cch <= cchLeft(); - - int d = -1; - - if (cchLeft() > 0) - { - Xobj x = getDenormal(); - int p = _posTemp - cch; - - for ( Bookmark b = x._bookmarks ; b != null ; b = b._next ) - if (b._key == key && x.inChars( p, b._xobj, b._pos, cch, false )) - d = (d == -1 || b._pos - p < d) ? b._pos - p : d; - } - - return d; - } - - String getCharsAsString ( int cch ) - { - assert isNormal() && _xobj != null; - - return getCharsAsString( cch, Locale.WS_PRESERVE ); - } - - String getCharsAsString ( int cch, int wsr ) - { - return _xobj.getCharsAsString( _pos, cch, wsr ); - } - - String getValueAsString ( int wsr ) - { - assert isNode(); - - return _xobj.getValueAsString( wsr ); - } - - String getValueAsString ( ) - { - assert isNode(); - assert ! hasChildren(); - - return _xobj.getValueAsString(); - } - - Object getChars ( int cch ) - { - assert isPositioned(); - - return _xobj.getChars( _pos, cch, this ); - } - - Object getFirstChars ( ) - { - assert isNode(); - - Object src = _xobj.getFirstChars(); - - _offSrc = _locale._offSrc; - _cchSrc = _locale._cchSrc; - - return src; - } - - void copyNode ( Cur to ) - { - assert to != null; - assert isNode(); - - Xobj copy = _xobj.copyNode( to._locale ); - - // TODO - in the moveNode case, I would not have to walk the tree for cursors ... optimize - - if (to.isPositioned()) - Cur.moveNode( copy, to ); - else - to.moveTo( copy ); - } - - Cur weakCur ( Object o ) - { - Cur c = _locale.weakCur( o ); - c.moveToCur( this ); - return c; - } - - Cur tempCur ( ) - { - return tempCur( null ); - } - - Cur tempCur ( String id ) - { - Cur c = _locale.tempCur( id ); - c.moveToCur( this ); - return c; - } - - private Cur tempCur ( Xobj x, int p ) - { - assert _locale == x._locale; - assert x != null || p == NO_POS; - - Cur c = _locale.tempCur(); - - if (x != null) - c.moveTo( getNormal( x, p ), _posTemp ); - - return c; - } - - // Is a cursor (c) in the chars defined by cch chars after where this Cur is positioned. - // Is inclusive on the left, and inclusive/exclusive on the right depending on the value - // of includeEnd. - - boolean inChars ( Cur c, int cch, boolean includeEnd ) - { - assert isPositioned() && isText() && cchRight() >= cch; - assert c.isNormal(); - - return _xobj.inChars( _pos, c._xobj, c._pos, cch, includeEnd ); - } - - boolean inChars ( Bookmark b, int cch, boolean includeEnd ) - { - assert isPositioned() && isText() && cchRight() >= cch; - assert b._xobj.isNormal( b._pos ); - - return _xobj.inChars( _pos, b._xobj, b._pos, cch, includeEnd ); - } - - // Can't be static because I need to communicate pos in _posTemp :-( - // I wish I had multiple return vars ... - - private Xobj getNormal ( Xobj x, int p ) - { - Xobj nx = x.getNormal( p ); - _posTemp = x._locale._posTemp; - return nx; - } - - private Xobj getDenormal ( ) - { - assert isPositioned(); - - return getDenormal( _xobj, _pos ); - } - - private Xobj getDenormal ( Xobj x, int p ) - { - Xobj dx = x.getDenormal( p ); - _posTemp = x._locale._posTemp; - return dx; - } - - // May throw IllegalArgumentException if can't change the type - - void setType ( SchemaType type ) - { - setType( type, true ); - } - - void setType ( SchemaType type, boolean complain ) - { - assert type != null; - assert isUserNode(); - - TypeStoreUser user = peekUser(); - - if (user != null && user.get_schema_type() == type) - return; - - if (isRoot()) - { - _xobj.setStableType( type ); - return; - } - - // Gotta get the parent user to make sure this type is ok here - - TypeStoreUser parentUser = _xobj.ensureParent().getUser(); - - // One may only set the type of an attribute to its 'natural' type because - // attributes cannot take advantage of the xsiType attribute. - - if (isAttr()) - { - if (complain && parentUser.get_attribute_type( getName() ) != type) - { - throw - new IllegalArgumentException( - "Can't set type of attribute to " + type.toString() ); - } - - return; - } - - assert isElem(); - - // First check to see if this type can be here sans xsi:type. - // If so, make sure there is no xsi:type - - if (parentUser.get_element_type( getName(), null ) == type) - { - removeAttr( Locale._xsiType ); - return; - } - - // If the desired type has no name, then it cannot be - // referenced via xsi:type - - QName typeName = type.getName(); - - if (typeName == null) - { - if (complain) - throw new IllegalArgumentException( "Can't set type of element, type is un-named" ); - else - return; - } - - // See if setting xsiType would result in the target type - - if (parentUser.get_element_type( getName(), typeName ) != type) - { - if (complain) - throw new IllegalArgumentException( "Can't set type of element, invalid type" ); - else - return; - } - - setAttrValueAsQName( Locale._xsiType, typeName ); - } - - void setSubstitution ( QName name, SchemaType type ) - { - setSubstitution( name, type, true ); - } - - void setSubstitution ( QName name, SchemaType type, boolean complain ) - { - assert name != null; - assert type != null; - assert isUserNode(); - - TypeStoreUser user = peekUser(); - - if (user != null && user.get_schema_type() == type && name.equals(getName())) - return; - - if (isRoot()) - { - // If this is the root node, we can't set its name, so the whole - // operation is aborted - return; - } - - // Gotta get the parent user to make sure this type is ok here - - TypeStoreUser parentUser = _xobj.ensureParent().getUser(); - - // One may only set the type of an attribute to its 'natural' type because - // attributes cannot take advantage of the xsiType attribute. - - if (isAttr()) - { - if (complain) - { - throw - new IllegalArgumentException( - "Can't use substitution with attributes"); - } - - return; - } - - assert isElem(); - - // First check to see if this type can be here sans xsi:type. - // If so, make sure there is no xsi:type - - if (parentUser.get_element_type( name, null ) == type) - { - setName( name ); - removeAttr( Locale._xsiType ); - return; - } - - // If the desired type has no name, then it cannot be - // referenced via xsi:type - - QName typeName = type.getName(); - - if (typeName == null) - { - if (complain) - throw new IllegalArgumentException( "Can't set xsi:type on element, type is un-named" ); - else - return; - } - - // See if setting xsiType would result in the target type - - if (parentUser.get_element_type( name, typeName ) != type) - { - if (complain) - throw new IllegalArgumentException( "Can't set xsi:type on element, invalid type" ); - else - return; - } - - setName( name ); - setAttrValueAsQName( Locale._xsiType, typeName ); - } - - TypeStoreUser peekUser ( ) - { - assert isUserNode(); - - return _xobj._user; - } - - XmlObject getObject ( ) - { - return isUserNode() ? (XmlObject) getUser() : null; - } - - TypeStoreUser getUser ( ) - { - assert isUserNode(); - - return _xobj.getUser(); - } - - Dom getDom ( ) - { - assert isNormal(); - assert isPositioned(); - - if (isText()) - { - int cch = cchLeft(); - - for ( CharNode cn = getCharNodes() ; ; cn = cn._next ) - if ((cch -= cn._cch) < 0) - return cn; - } - - return _xobj.getDom(); - } - - static void release ( Cur c ) - { - if (c != null) - c.release(); - } - - void release ( ) - { - if (_tempFrame >= 0) - { - if (_nextTemp != null) - _nextTemp._prevTemp = _prevTemp; - - if (_prevTemp == null) - _locale._tempFrames[ _tempFrame ] = _nextTemp; - else - _prevTemp._nextTemp = _nextTemp; - - _prevTemp = _nextTemp = null; - _tempFrame = -1; - } - - if (_state != POOLED && _state != DISPOSED) - { - // Clean up any state - - while ( _stackTop != -1 ) - popButStay(); - - clearSelection(); - - _id = null; - - // Unposition - - moveToCur( null ); - - assert isNormal(); - - assert _xobj == null; - assert _pos == NO_POS; - - // Release weak reference and attacked value - - if (_ref != null) - { - _ref.clear(); - _ref._cur = null; - } - - _ref = null; - - // Unregister and either diapose of cursor or add it back to pool - - assert _state == REGISTERED; - _locale._registered = listRemove( _locale._registered ); - - if (_locale._curPoolCount < 16) - { - _locale._curPool = listInsert( _locale._curPool ); - _state = POOLED; - _locale._curPoolCount++; - } - else - { - _locale = null; - _state = DISPOSED; - } - } - } - - boolean isOnList ( Cur head ) - { - for ( ; head != null ; head = head._next ) - if (head == this) - return true; - - return false; - } - - Cur listInsert ( Cur head ) - { - assert _next == null && _prev == null; - - if (head == null) - head = _prev = this; - else - { - _prev = head._prev; - head._prev = head._prev._next = this; - } - - return head; - } - - Cur listRemove ( Cur head ) - { - assert _prev != null && isOnList( head ); - - if (_prev == this) - head = null; - else - { - if (head == this) - head = _next; - else - _prev._next = _next; - - if (_next == null) - head._prev = _prev; - else - { - _next._prev = _prev; - _next = null; - } - } - - _prev = null; - assert _next == null; - - return head; - } - -// boolean isNormal ( Cur that ) -// { -// return isNormal() && (that == null || (_locale == that._locale && that.isNormal())); -// } - - boolean isNormal ( ) - { - if (_state == POOLED || _state == DISPOSED) - return false; - - if (_xobj == null) - return _pos == NO_POS; - - if (!_xobj.isNormal( _pos )) - return false; - - if (_state == EMBEDDED) - return isOnList( _xobj._embedded ); - - assert _state == REGISTERED; - - return isOnList( _locale._registered ); - } - - static final String LOAD_USE_LOCALE_CHAR_UTIL = "LOAD_USE_LOCALE_CHAR_UTIL"; - - static final class CurLoadContext extends LoadContext - { - CurLoadContext ( Locale l, XmlOptions options ) - { - options = XmlOptions.maskNull( options ); - - _locale = l; - - _charUtil = - options.hasOption( LOAD_USE_LOCALE_CHAR_UTIL ) - ? _locale.getCharUtil() - : CharUtil.getThreadLocalCharUtil(); - - _frontier = createDomDocumentRootXobj( _locale ); - _after = false; - - _lastXobj = _frontier; - _lastPos = 0; - - if (options.hasOption( XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT )) - { - _replaceDocElem = (QName) options.get( XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT ); - _discardDocElem = true; - } - - _stripWhitespace = options.hasOption( XmlOptions.LOAD_STRIP_WHITESPACE ); - _stripComments = options.hasOption( XmlOptions.LOAD_STRIP_COMMENTS ); - _stripProcinsts = options.hasOption( XmlOptions.LOAD_STRIP_PROCINSTS ); - - _substituteNamespaces = (Map) options.get( XmlOptions.LOAD_SUBSTITUTE_NAMESPACES ); - _additionalNamespaces = (Map) options.get( XmlOptions.LOAD_ADDITIONAL_NAMESPACES ); - - _locale._versionAll++; - _locale._versionSansText++; - } - - // - // Really primitive load context operations - // - - private void start ( Xobj xo ) - { - assert _frontier != null; - assert !_after || _frontier._parent != null; - - flushText(); - - if (_after) - { - _frontier = _frontier._parent; - _after = false; - } - - _frontier.appendXobj( xo ); - _frontier = xo; - - _lastXobj = xo; - _lastPos = 0; - } - - private void end ( ) - { - assert _frontier != null; - assert !_after || _frontier._parent != null; - - flushText(); - - if (_after) - _frontier = _frontier._parent; - else - _after = true; - - _lastXobj = _frontier; - _lastPos = END_POS; - } - - private void text ( Object src, int off, int cch ) - { - if (cch <= 0) - return; - - _lastXobj = _frontier; - _lastPos = _frontier._cchValue + 1; - - if (_after) - { - _lastPos += _frontier._cchAfter + 1; - - _frontier._srcAfter = - _charUtil.saveChars( - src, off, cch, - _frontier._srcAfter, _frontier._offAfter, _frontier._cchAfter ); - - _frontier._offAfter = _charUtil._offSrc; - _frontier._cchAfter = _charUtil._cchSrc; - - } - else - { - _frontier._srcValue = - _charUtil.saveChars( - src, off, cch, - _frontier._srcValue, _frontier._offValue, _frontier._cchValue ); - - _frontier._offValue = _charUtil._offSrc; - _frontier._cchValue = _charUtil._cchSrc; - } - } - - private void flushText ( ) - { - if (_stripWhitespace) - { - if (_after) - { - _frontier._srcAfter = - _charUtil.stripRight( - _frontier._srcAfter, _frontier._offAfter, _frontier._cchAfter ); - - _frontier._offAfter = _charUtil._offSrc; - _frontier._cchAfter = _charUtil._cchSrc; - } - else - { - _frontier._srcValue = - _charUtil.stripRight( - _frontier._srcValue, _frontier._offValue, _frontier._cchValue ); - - _frontier._offValue = _charUtil._offSrc; - _frontier._cchValue = _charUtil._cchSrc; - } - } - } - - private Xobj parent ( ) - { - return _after ? _frontier._parent : _frontier; - } - - private QName checkName ( QName name, boolean local ) - { - if (_substituteNamespaces != null && (!local || name.getNamespaceURI().length() > 0)) - { - String substituteUri = (String) _substituteNamespaces.get( name.getNamespaceURI() ); - - if (substituteUri != null) - name = _locale.makeQName( substituteUri, name.getLocalPart(), name.getPrefix()); - } - - return name; - } - - // - // - // - - protected void startDTD (String name, String publicId, String systemId ) - { - _doctypeName = name; - _doctypePublicId = publicId; - _doctypeSystemId = systemId; - } - - protected void endDTD ( ) - { - } - - protected void startElement ( QName name ) - { - start( createElementXobj( _locale, checkName( name, false ), parent()._name ) ); - _stripLeft = true; - } - - protected void endElement ( ) - { - assert parent().isElem(); - - end(); - _stripLeft = true; - } - - protected void xmlns ( String prefix, String uri ) - { - assert parent().isContainer(); - // BUGBUG - should assert there that there is no text before this attr - - // Namespace attrs are different than regular attrs -- I don't change their name, - // I change their value! - - if (_substituteNamespaces != null) - { - String substituteUri = (String) _substituteNamespaces.get( uri ); - - if (substituteUri != null) - uri = substituteUri; - } - - Xobj x = new Xobj.AttrXobj( _locale, _locale.createXmlns( prefix ) ); - - start( x ); - text( uri, 0, uri.length() ); - end(); - - _lastXobj = x; - _lastPos = 0; - } - - protected void attr ( QName name, String value ) - { - assert parent().isContainer(); - // BUGBUG - should assert there that there is no text before this attr - - QName parentName = _after? - _lastXobj._parent.getQName(): _lastXobj.getQName(); - boolean isId = isAttrOfTypeId(name, parentName); - - Xobj x = isId ? - new Xobj.AttrIdXobj(_locale, checkName(name, true)) : - new Xobj.AttrXobj(_locale, checkName(name, true)); - start(x); - text(value, 0, value.length()); - end(); - if (isId) - { - Cur c1 = x.tempCur(); - c1.toRoot(); - Xobj doc = c1._xobj; - c1.release(); - if (doc instanceof Xobj.DocumentXobj) - ((Xobj.DocumentXobj) doc).addIdElement(value, - x._parent.getDom()); - } - _lastXobj = x; - _lastPos = 0; - } - protected void attr ( String local, String uri, String prefix, String value ) - { - attr( _locale.makeQName( uri, local, prefix ), value ); - } - - protected void procInst ( String target, String value ) - { - if (!_stripProcinsts) - { - Xobj x = new Xobj.ProcInstXobj( _locale, target ); - - start( x ); - text( value, 0, value.length() ); - end(); - - _lastXobj = x; - _lastPos = 0; - } - _stripLeft = true; - } - - protected void comment ( String comment ) - { - if (!_stripComments) - comment( comment, 0, comment.length() ); - _stripLeft = true; - } - - protected void comment ( char[] chars, int off, int cch ) - { - if (!_stripComments) - { - comment( - _charUtil.saveChars( chars, off, cch ), - _charUtil._offSrc, _charUtil._cchSrc ); - } - _stripLeft = true; - } - - private void comment ( Object src, int off, int cch ) - { - Xobj x = new Xobj.CommentXobj( _locale ); - - start( x ); - text( src, off, cch ); - end(); - - _lastXobj = x; - _lastPos = 0; - } - - private boolean _stripLeft = true; - - private void stripText ( Object src, int off, int cch ) - { - if (_stripWhitespace) - { - // this is to avoid bug in cases like Procter & Gamble - if (_stripLeft) - { - src = _charUtil.stripLeft( src, off, cch ); - _stripLeft = false; - off = _charUtil._offSrc; - cch = _charUtil._cchSrc; - } - } - - text( src, off, cch ); - } - - protected void text ( String s ) - { - if (s == null) - return; - - stripText( s, 0, s.length() ); - } - - protected void text ( char[] src, int off, int cch ) - { - stripText( src, off, cch ); - } - - protected void bookmark ( XmlBookmark bm ) - { - _lastXobj.setBookmark( _lastPos, bm.getKey(), bm ); - } - - protected void bookmarkLastNonAttr ( XmlBookmark bm ) - { - if (_lastPos > 0 || !_lastXobj.isAttr()) - _lastXobj.setBookmark( _lastPos, bm.getKey(), bm ); - else - { - assert _lastXobj._parent != null; - - _lastXobj._parent.setBookmark( 0, bm.getKey(), bm ); - } - } - - protected void bookmarkLastAttr ( QName attrName, XmlBookmark bm ) - { - if (_lastPos == 0 && _lastXobj.isAttr()) - { - assert _lastXobj._parent != null; - - Xobj a = _lastXobj._parent.getAttr( attrName ); - - if (a != null) - a.setBookmark( 0, bm.getKey(), bm ); - } - } - - protected void lineNumber ( int line, int column, int offset ) - { - _lastXobj.setBookmark( - _lastPos, - XmlLineNumber.class, - new XmlLineNumber( line, column, offset ) ); - } - - protected void abort ( ) - { - _stripLeft = true; - while ( !parent().isRoot() ) - end(); - - finish().release(); - } - - protected Cur finish ( ) - { - flushText(); - - if (_after) - _frontier = _frontier._parent; - - assert _frontier != null && _frontier._parent == null && _frontier.isRoot(); - - Cur c = _frontier.tempCur(); - - if (!Locale.toFirstChildElement( c )) - return c; - - // See if the document element is a fragment - - boolean isFrag = Locale.isFragmentQName( c.getName() ); - - if (_discardDocElem || isFrag) - { - if (_replaceDocElem != null) - c.setName( _replaceDocElem ); - else - { - // Remove the content around the element to remove so that that content - // does not appear to have been the contents of the removed element. - - while ( c.toParent() ) - ; - - c.next(); - - while ( !c.isElem() ) - if (c.isText()) c.moveChars( null, -1 ); else c.moveNode( null ); - - assert c.isElem(); - c.skip(); - - while ( !c.isFinish() ) - if (c.isText()) c.moveChars( null, -1 ); else c.moveNode( null ); - - c.toParent(); - - c.next(); - - assert c.isElem(); - - Cur c2 = c.tempCur(); - - c.moveNodeContents( c, true ); - - c.moveToCur( c2 ); - - c2.release(); - - c.moveNode( null ); - } - - // Remove the fragment namespace decl - - if (isFrag) - { - c.moveTo( _frontier ); - - if (c.toFirstAttr()) - { - for ( ; ; ) - { - if (c.isXmlns() && c.getXmlnsUri().equals( Locale._openFragUri )) - { - c.moveNode( null ); - - if (!c.isAttr()) - break; - } - else if (!c.toNextAttr()) - break; - } - } - - c.moveTo(_frontier); - _frontier = createDomDocumentRootXobj( _locale, true ); - - Cur c2 = _frontier.tempCur(); - c2.next(); - c.moveNodeContents(c2, true); - c.moveTo(_frontier); - c2.release(); - } - } - - - if (_additionalNamespaces != null) - { - c.moveTo( _frontier ); - Locale.toFirstChildElement( c ); - Locale.applyNamespaces( c, _additionalNamespaces ); - } - - if (_doctypeName != null && (_doctypePublicId != null || _doctypeSystemId != null)) - { - XmlDocumentProperties props = Locale.getDocProps(c, true); - props.setDoctypeName(_doctypeName); - if (_doctypePublicId != null) - props.setDoctypePublicId(_doctypePublicId); - if (_doctypeSystemId != null) - props.setDoctypeSystemId(_doctypeSystemId); - } - - c.moveTo( _frontier ); - - assert c.isRoot(); - - return c; - } - - public void dump ( ) - { - _frontier.dump(); - } - - private Locale _locale; - private CharUtil _charUtil; - - private Xobj _frontier; - private boolean _after; - - private Xobj _lastXobj; - private int _lastPos; - - private boolean _discardDocElem; - private QName _replaceDocElem; - private boolean _stripWhitespace; - private boolean _stripComments; - private boolean _stripProcinsts; - private Map _substituteNamespaces; - private Map _additionalNamespaces; - - private String _doctypeName; - private String _doctypePublicId; - private String _doctypeSystemId; - } - - // - // - // - - static String kindName ( int kind ) - { - switch ( kind ) - { - case ROOT : return "ROOT"; - case ELEM : return "ELEM"; - case ATTR : return "ATTR"; - case COMMENT : return "COMMENT"; - case PROCINST : return "PROCINST"; - case TEXT : return "TEXT"; - default : return "<< Unknown Kind (" + kind + ") >>"; - } - } - - static void dump ( PrintStream o, Dom d, Object ref ) - { - } - - static void dump ( PrintStream o, Dom d ) - { - d.dump( o ); - } - - static void dump ( Dom d ) - { - dump( System.out, d ); - } - - static void dump ( Node n ) - { - dump( System.out, n ); - } - - static void dump ( PrintStream o, Node n ) - { - dump( o, (Dom) n ); - } - - void dump ( ) - { - dump( System.out, _xobj, this ); - } - - void dump ( PrintStream o ) - { - if (_xobj == null) - { - o.println( "Unpositioned xptr" ); - return; - } - - dump( o, _xobj, this ); - } - - public static void dump ( PrintStream o, Xobj xo, Object ref ) - { - if (ref == null) - ref = xo; - - while ( xo._parent != null ) - xo = xo._parent; - - dumpXobj( o, xo, 0, ref ); - - o.println(); - } - - private static void dumpCur ( PrintStream o, String prefix, Cur c, Object ref ) - { - o.print( " " ); - - if (ref == c) - o.print( "*:" ); - - o.print( prefix + (c._id == null ? "" : c._id) + "[" + c._pos + "]" ); - } - - private static void dumpCurs ( PrintStream o, Xobj xo, Object ref ) - { - for ( Cur c = xo._embedded ; c != null ; c = c._next ) - dumpCur( o, "E:", c, ref ); - - for ( Cur c = xo._locale._registered ; c != null ; c = c._next ) - { - if (c._xobj == xo) - dumpCur( o, "R:", c, ref ); - } - } - - private static void dumpBookmarks ( PrintStream o, Xobj xo, Object ref ) - { - for ( Bookmark b = xo._bookmarks ; b != null ; b = b._next ) - { - o.print( " " ); - - if (ref == b) - o.print( "*:" ); - - if (b._value instanceof XmlLineNumber) - { - XmlLineNumber l = (XmlLineNumber) b._value; - o.print( "" + "[" + b._pos + "]" ); - } - else - o.print( "" + "[" + b._pos + "]" ); - } - } - - private static void dumpCharNodes ( PrintStream o, CharNode nodes, Object ref ) - { - for ( CharNode n = nodes ; n != null ; n = n._next ) - { - o.print( " " ); - - if (n == ref) - o.print( "*" ); - - o.print( (n instanceof TextNode ? "TEXT" : "CDATA") + "[" + n._cch + "]" ); - } - } - - private static void dumpChars ( PrintStream o, Object src, int off, int cch ) - { -// CharUtil.dumpChars( o, src, off, cch ); - - o.print( "\"" ); - - String s = CharUtil.getString( src, off, cch ); - - for ( int i = 0 ; i < s.length(); ) - { - if (i == 36) - { - o.print( "..." ); - break; - } - - int codePoint = s.codePointAt( i ); - char[] chars = Character.toChars(codePoint); - - if ( chars.length == 1 ) { - char ch = chars[0]; - if (ch >= 32 && ch < 127) - o.print( ch ); - else if (ch == '\n') - o.print( "\\n" ); - else if (ch == '\r') - o.print( "\\r" ); - else if (ch == '\t') - o.print( "\\t" ); - else if (ch == '\"') - o.print( "\\\"" ); - else - o.print( "<#" + ((int) ch) + ">" ); - } else { - o.print( "<#" + codePoint + ">" ); - } - - i += Character.charCount(codePoint); - } - - o.print( "\"" ); - } - - private static void dumpXobj ( PrintStream o, Xobj xo, int level, Object ref ) - { - if (xo == null) - return; - - if (xo == ref) - o.print( "* " ); - else - o.print( " " ); - - for ( int i = 0 ; i < level ; i++ ) - o.print( " " ); - - o.print( kindName( xo.kind() ) ); - - if (xo._name != null) - { - o.print( " " ); - - if (xo._name.getPrefix().length() > 0) - o.print( xo._name.getPrefix() + ":" ); - - o.print( xo._name.getLocalPart() ); - - if (xo._name.getNamespaceURI().length() > 0) - o.print( "@" + xo._name.getNamespaceURI() ); - } - - if (xo._srcValue != null || xo._charNodesValue != null) - { - o.print( " Value( " ); - dumpChars( o, xo._srcValue, xo._offValue, xo._cchValue ); - dumpCharNodes( o, xo._charNodesValue, ref ); - o.print( " )" ); - } - - if (xo._user != null) - o.print( " (USER)" ); - - if (xo.isVacant()) - o.print( " (VACANT)" ); - - if (xo._srcAfter != null || xo._charNodesAfter != null) - { - o.print( " After( " ); - dumpChars( o, xo._srcAfter, xo._offAfter, xo._cchAfter ); - dumpCharNodes( o, xo._charNodesAfter, ref ); - o.print( " )" ); - } - - dumpCurs( o, xo, ref ); - dumpBookmarks( o, xo, ref ); - - String className = xo.getClass().getName(); - - int i = className.lastIndexOf( '.' ); - - if (i > 0) - { - className = className.substring( i + 1 ); - - i = className.lastIndexOf( '$' ); - - if (i > 0) - className = className.substring( i + 1 ); - } - - o.print( " (" ); - o.print( className ); - o.print( ")" ); - - o.println(); - - for ( xo = xo._firstChild ; xo != null ; xo = xo._nextSibling ) - dumpXobj( o, xo, level + 1, ref ); - } - - void setId ( String id ) - { - _id = id; - } - - // - // - // - - Locale _locale; - - Xobj _xobj; - int _pos; - - int _state; - - String _id; - - Cur _nextTemp; - Cur _prevTemp; - int _tempFrame; - - Cur _next; - Cur _prev; - - Locale.Ref _ref; - - int _stackTop; - - int _selectionFirst; - int _selectionN; - int _selectionLoc; - int _selectionCount; - - private int _posTemp; - - int _offSrc; - int _cchSrc; -} \ No newline at end of file diff --git a/src/store/org/apache/xmlbeans/impl/store/Cursor.java b/src/store/org/apache/xmlbeans/impl/store/Cursor.java deleted file mode 100755 index fc3708f..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Cursor.java +++ /dev/null @@ -1,4377 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import java.util.ArrayList; - -import java.io.PrintStream; - -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamReader; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlDocumentProperties; - -import org.apache.xmlbeans.impl.common.XMLChar; -import org.apache.xmlbeans.impl.common.GlobalLock; - -import java.util.Map; -import java.util.Collection; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.io.File; -import java.io.IOException; -import java.io.FileOutputStream; - -import org.w3c.dom.Node; - -import org.xml.sax.ContentHandler; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.SAXException; - -import org.apache.xmlbeans.impl.store.Saver.TextSaver; -import org.apache.xmlbeans.impl.store.Locale.ChangeListener; -import org.apache.xmlbeans.impl.store.Path.PathEngine; - -public final class Cursor implements XmlCursor, ChangeListener { - static final int ROOT = Cur.ROOT; - static final int ELEM = Cur.ELEM; - static final int ATTR = Cur.ATTR; - static final int COMMENT = Cur.COMMENT; - static final int PROCINST = Cur.PROCINST; - static final int TEXT = Cur.TEXT; - - Cursor(Xobj x, int p) { - _cur = x._locale.weakCur(this); - _cur.moveTo(x, p); - _currentSelection = -1; - } - - Cursor(Cur c) { - this(c._xobj, c._pos); - } - - private static boolean isValid(Cur c) { - if (c.kind() <= 0) { - c.push(); - - if (c.toParentRaw()) { - int pk = c.kind(); - - if (pk == COMMENT || pk == PROCINST || pk == ATTR) - return false; - } - - c.pop(); - } - - return true; - } - - private boolean isValid() { - return isValid(_cur); - } - - Locale locale() { - return _cur._locale; - } - - Cur tempCur() { - return _cur.tempCur(); - } - - public void dump(PrintStream o) { - _cur.dump(o); - } - - static void validateLocalName(QName name) { - if (name == null) - throw new IllegalArgumentException("QName is null"); - - validateLocalName(name.getLocalPart()); - } - - static void validateLocalName(String name) { - if (name == null) - throw new IllegalArgumentException("Name is null"); - - if (name.length() == 0) - throw new IllegalArgumentException("Name is empty"); - - if (!XMLChar.isValidNCName(name)) - throw new IllegalArgumentException("Name is not valid"); - } - - static void validatePrefix(String name) { - if (name == null) - throw new IllegalArgumentException("Prefix is null"); - - if (name.length() == 0) - throw new IllegalArgumentException("Prefix is empty"); - - if (Locale.beginsWithXml(name)) - throw new IllegalArgumentException("Prefix begins with 'xml'"); - - if (!XMLChar.isValidNCName(name)) - throw new IllegalArgumentException("Prefix is not valid"); - } - - private static void complain(String msg) { - throw new IllegalArgumentException(msg); - } - - private void checkInsertionValidity(Cur that) { - int thatKind = that.kind(); - - if (thatKind < 0) - complain("Can't move/copy/insert an end token."); - - if (thatKind == ROOT) - complain("Can't move/copy/insert a whole document."); - - int thisKind = _cur.kind(); - - if (thisKind == ROOT) - complain("Can't insert before the start of the document."); - - if (thatKind == ATTR) { - _cur.push(); - _cur.prevWithAttrs(); - int pk = _cur.kind(); - _cur.pop(); - - if (pk != ELEM && pk != ROOT && pk != -ATTR) { - complain("Can only insert attributes before other attributes or after containers."); - } - } - - if (thisKind == ATTR && thatKind != ATTR) - complain("Can only insert attributes before other attributes or after containers."); - } - - private void insertNode(Cur that, String text) { - assert !that.isRoot(); - assert that.isNode(); - assert isValid(that); - assert isValid(); - - if (text != null && text.length() > 0) { - that.next(); - that.insertString(text); - that.toParent(); - } - - checkInsertionValidity(that); - - that.moveNode(_cur); - - _cur.toEnd(); - _cur.nextWithAttrs(); - } - - // - // - // - - // TODO - deal with cursors moving to other documents upon release? - // Can I move the ref from one q to another? If not I will have to - // change from a phantom ref to a soft/weak ref so I can know what - // to do when I dequeue from the old q. - - public void _dispose() { - _cur.release(); - _cur = null; - } - - public XmlCursor _newCursor() { - return new Cursor(_cur); - } - - public QName _getName() { - // TODO - consider taking this out of the gateway - - switch (_cur.kind()) { - case ATTR: - - if (_cur.isXmlns()) { - return - _cur._locale.makeQNameNoCheck(_cur.getXmlnsUri(), _cur.getXmlnsPrefix()); - } - - // Fall thru - - case ELEM: - case PROCINST: - return _cur.getName(); - } - - return null; - } - - public void _setName(QName name) { - if (name == null) - throw new IllegalArgumentException("Name is null"); - - switch (_cur.kind()) { - case ELEM: - case ATTR: - { - validateLocalName(name.getLocalPart()); - break; - } - - case PROCINST: - { - validatePrefix(name.getLocalPart()); - - if (name.getNamespaceURI().length() > 0) - throw new IllegalArgumentException("Procinst name must have no URI"); - - if (name.getPrefix().length() > 0) - throw new IllegalArgumentException("Procinst name must have no prefix"); - - break; - } - - default : - throw - new IllegalStateException("Can set name on element, atrtribute and procinst only"); - } - - _cur.setName(name); - } - - public TokenType _currentTokenType() { - assert isValid(); - - switch (_cur.kind()) { - case ROOT: - return TokenType.STARTDOC; - case -ROOT: - return TokenType.ENDDOC; - case ELEM: - return TokenType.START; - case -ELEM: - return TokenType.END; - case TEXT: - return TokenType.TEXT; - case ATTR: - return _cur.isXmlns() ? TokenType.NAMESPACE : TokenType.ATTR; - case COMMENT: - return TokenType.COMMENT; - case PROCINST: - return TokenType.PROCINST; - - default : - throw new IllegalStateException(); - } - } - - public boolean _isStartdoc() { - //return _currentTokenType().isStartdoc(); - assert isValid(); - return _cur.isRoot(); - } - - public boolean _isEnddoc() { - //return _currentTokenType().isEnddoc(); - assert isValid(); - return _cur.isEndRoot(); - } - - public boolean _isStart() { - //return _currentTokenType().isStart(); - assert isValid(); - return _cur.isElem(); - } - - public boolean _isEnd() { - //return _currentTokenType().isEnd(); - assert isValid(); - return _cur.isEnd(); - } - - public boolean _isText() { - //return _currentTokenType().isText(); - assert isValid(); - return _cur.isText(); - } - - public boolean _isAttr() { - //return _currentTokenType().isAttr(); - assert isValid(); - return _cur.isNormalAttr(); - } - - public boolean _isNamespace() { - //return _currentTokenType().isNamespace(); - assert isValid(); - return _cur.isXmlns(); - } - - public boolean _isComment() { - //return _currentTokenType().isComment(); - assert isValid(); - return _cur.isComment(); - } - - public boolean _isProcinst() { - //return _currentTokenType().isProcinst(); - assert isValid(); - return _cur.isProcinst(); - } - - public boolean _isContainer() { - //return _currentTokenType().isContainer(); - assert isValid(); - return _cur.isContainer(); - } - - public boolean _isFinish() { - //return _currentTokenType().isFinish(); - assert isValid(); - return _cur.isFinish(); - } - - public boolean _isAnyAttr() { - //return _currentTokenType().isAnyAttr(); - assert isValid(); - return _cur.isAttr(); - } - - public TokenType _toNextToken() { - assert isValid(); - - switch (_cur.kind()) { - case ROOT: - case ELEM: - { - if (!_cur.toFirstAttr()) - _cur.next(); - - break; - } - - case ATTR: - { - if (!_cur.toNextSibling()) { - _cur.toParent(); - _cur.next(); - } - - break; - } - - case COMMENT: - case PROCINST: - { - _cur.skip(); - break; - } - - default : - { - if (!_cur.next()) - return TokenType.NONE; - - break; - } - } - - return _currentTokenType(); - } - - public TokenType _toPrevToken() { - assert isValid(); - - // This method is different than the Cur version of prev in a few ways. First, - // Cursor iterates over attrs inline with all the other content. Cur will skip attrs, or - // if the Cur in in attrs, it will not jump out of attrs. Also, if moving backwards and - // text is to the left and right, Cur will move to the beginning of that text, while - // Cursor will move further so that the token type to the right is not text. - - boolean wasText = _cur.isText(); - - if (!_cur.prev()) { - assert _cur.isRoot() || _cur.isAttr(); - - if (_cur.isRoot()) - return TokenType.NONE; - - _cur.toParent(); - } else { - int k = _cur.kind(); - - if (k < 0 && (k == -COMMENT || k == -PROCINST || k == -ATTR)) - _cur.toParent(); - else if (_cur.isContainer()) - _cur.toLastAttr(); - else if (wasText && _cur.isText()) - return _toPrevToken(); - } - - return _currentTokenType(); - } - - public Object _monitor() { - // TODO - some of these methods need not be protected by a - // gatway. This is one of them. Inline this. - - return _cur._locale; - } - - public boolean _toParent() { - Cur c = _cur.tempCur(); - - if (!c.toParent()) - return false; - - _cur.moveToCur(c); - - c.release(); - - return true; - } - - private static final class ChangeStampImpl implements ChangeStamp { - ChangeStampImpl(Locale l) { - _locale = l; - _versionStamp = _locale.version(); - } - - public boolean hasChanged() { - return _versionStamp != _locale.version(); - } - - private final Locale _locale; - private final long _versionStamp; - } - - public ChangeStamp _getDocChangeStamp() { - return new ChangeStampImpl(_cur._locale); - } - - // - // These simply delegate to the version of the method which takes XmlOptions - // - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream _newXMLInputStream() { - return _newXMLInputStream(null); - } - - public XMLStreamReader _newXMLStreamReader() { - return _newXMLStreamReader(null); - } - - public Node _newDomNode() { - return _newDomNode(null); - } - - public InputStream _newInputStream() { - return _newInputStream(null); - } - - public String _xmlText() { - return _xmlText(null); - } - - public Reader _newReader() { - return _newReader(null); - } - - public void _save(File file) throws IOException { - _save(file, null); - } - - public void _save(OutputStream os) throws IOException { - _save(os, null); - } - - public void _save(Writer w) throws IOException { - _save(w, null); - } - - public void _save(ContentHandler ch, LexicalHandler lh) throws SAXException { - _save(ch, lh, null); - } - - // - // - // - - public XmlDocumentProperties _documentProperties() { - return Locale.getDocProps(_cur, true); - } - - public XMLStreamReader _newXMLStreamReader(XmlOptions options) { - return Jsr173.newXmlStreamReader(_cur, options); - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream _newXMLInputStream(XmlOptions options) { - return new Saver.XmlInputStreamImpl(_cur, options); - } - - public String _xmlText(XmlOptions options) { - assert isValid(); - - return new TextSaver(_cur, options, null).saveToString(); - } - - public InputStream _newInputStream(XmlOptions options) { - return new Saver.InputStreamSaver(_cur, options); - } - - public Reader _newReader(XmlOptions options) { - return new Saver.TextReader(_cur, options); - } - - public void _save(ContentHandler ch, LexicalHandler lh, XmlOptions options) - throws SAXException { - new Saver.SaxSaver(_cur, options, ch, lh); - } - - public void _save(File file, XmlOptions options) throws IOException { - if (file == null) - throw new IllegalArgumentException("Null file specified"); - - OutputStream os = new FileOutputStream(file); - - try { - _save(os, options); - } finally { - os.close(); - } - } - - public void _save(OutputStream os, XmlOptions options) throws IOException { - if (os == null) - throw new IllegalArgumentException("Null OutputStream specified"); - - InputStream is = _newInputStream(options); - - try { - byte[] bytes = new byte[8192]; - - for (; ;) { - int n = is.read(bytes); - - if (n < 0) - break; - - os.write(bytes, 0, n); - } - } finally { - is.close(); - } - } - - public void _save(Writer w, XmlOptions options) throws IOException { - if (w == null) - throw new IllegalArgumentException("Null Writer specified"); - - if (options != null && options.hasOption( XmlOptions.SAVE_OPTIMIZE_FOR_SPEED )) - { - Saver.OptimizedForSpeedSaver.save(_cur, w); //ignore all other options - return; - } - - Reader r = _newReader(options); - - try { - char[] chars = new char[8192]; - - for (; ;) { - int n = r.read(chars); - - if (n < 0) - break; - - w.write(chars, 0, n); - } - } finally { - r.close(); - } - } - - public Node _getDomNode() { - return (Node) _cur.getDom(); - } - - private boolean isDomFragment() { - if (!isStartdoc()) - return true; - - boolean seenElement = false; - - XmlCursor c = newCursor(); - int token = c.toNextToken().intValue(); - - try { - LOOP: for (; ;) { - SWITCH: switch (token) { - case TokenType.INT_START: - if (seenElement) - return true; - seenElement = true; - token = c.toEndToken().intValue(); - break SWITCH; - - case TokenType.INT_TEXT: - if (!Locale.isWhiteSpace(c.getChars())) - return true; - token = c.toNextToken().intValue(); - break SWITCH; - - case TokenType.INT_NONE: - case TokenType.INT_ENDDOC: - break LOOP; - - case TokenType.INT_ATTR: - case TokenType.INT_NAMESPACE: - return true; - - case TokenType.INT_END: - case TokenType.INT_COMMENT: - case TokenType.INT_PROCINST: - token = c.toNextToken().intValue(); - break SWITCH; - - case TokenType.INT_STARTDOC: - assert false; - break LOOP; - } - } - } finally { - c.dispose(); - } - - return !seenElement; - } - - private static final class DomSaver extends Saver { - DomSaver(Cur c, boolean isFrag, XmlOptions options) { - super(c, options); - - if (c.isUserNode()) - _type = c.getUser().get_schema_type(); - - _stl = c._locale._schemaTypeLoader; - _options = options; - _isFrag = isFrag; - } - - Node saveDom() { - Locale l = Locale.getLocale(_stl, _options); - - l.enter(); - - try { - _nodeCur = l.getCur(); // Not weak or temp - - // Build the tree - - while (process()) - ; - - // Set the type - - while (!_nodeCur.isRoot()) - _nodeCur.toParent(); - - if (_type != null) - _nodeCur.setType(_type); - - Node node = (Node) _nodeCur.getDom(); - - _nodeCur.release(); - - _nodeCur = null; - - return node; - } finally { - l.exit(); - } - } - - protected boolean emitElement(SaveCur c, ArrayList attrNames, ArrayList attrValues) { - // If there was text or comments before the frag element, I will loose them -- oh well - // Also, I will lose any attributes and namesapces on the fragment -- DOM can - // have attrs in fragments - - if (Locale.isFragmentQName(c.getName())) - _nodeCur.moveTo(null, Cur.NO_POS); - - ensureDoc(); - - _nodeCur.createElement(getQualifiedName(c, c.getName())); - _nodeCur.next(); - - for (iterateMappings(); hasMapping(); nextMapping()) { - _nodeCur.createAttr(_nodeCur._locale.createXmlns(mappingPrefix())); - _nodeCur.next(); - _nodeCur.insertString(mappingUri()); - _nodeCur.toParent(); - _nodeCur.skipWithAttrs(); - } - - for (int i = 0; i < attrNames.size(); i++) { - _nodeCur.createAttr(getQualifiedName(c, (QName) attrNames.get(i))); - _nodeCur.next(); - _nodeCur.insertString((String) attrValues.get(i)); - _nodeCur.toParent(); - _nodeCur.skipWithAttrs(); - } - - return false; - } - - protected void emitFinish(SaveCur c) { - if (!Locale.isFragmentQName(c.getName())) { - assert _nodeCur.isEnd(); - _nodeCur.next(); - } - } - - protected void emitText(SaveCur c) { - ensureDoc(); - - Object src = c.getChars(); - - if (c._cchSrc > 0) { - _nodeCur.insertChars(src, c._offSrc, c._cchSrc); - _nodeCur.next(); - } - } - - protected void emitComment(SaveCur c) { - ensureDoc(); - - _nodeCur.createComment(); - emitTextValue(c); - _nodeCur.skip(); - } - - protected void emitProcinst(SaveCur c) { - ensureDoc(); - - _nodeCur.createProcinst(c.getName().getLocalPart()); - emitTextValue(c); - _nodeCur.skip(); - } - - protected void emitDocType(String docTypeName, String publicId, String systemId) { - ensureDoc(); - - XmlDocumentProperties props = Locale.getDocProps(_nodeCur, true); - props.setDoctypeName(docTypeName); - props.setDoctypePublicId(publicId); - props.setDoctypeSystemId(systemId); - } - - protected void emitStartDoc(SaveCur c) { - ensureDoc(); - } - - protected void emitEndDoc ( SaveCur c ) - { - } - - private QName getQualifiedName(SaveCur c, QName name) { - String uri = name.getNamespaceURI(); - - String prefix = uri.length() > 0 ? getUriMapping(uri) : ""; - - if (prefix.equals(name.getPrefix())) - return name; - - return _nodeCur._locale.makeQName(uri, name.getLocalPart(), prefix); - } - - private void emitTextValue(SaveCur c) { - c.push(); - c.next(); - - if (c.isText()) { - _nodeCur.next(); - _nodeCur.insertChars(c.getChars(), c._offSrc, c._cchSrc); - _nodeCur.toParent(); - } - - c.pop(); - } - - private void ensureDoc() { - if (!_nodeCur.isPositioned()) { - if (_isFrag) - _nodeCur.createDomDocFragRoot(); - else - _nodeCur.createDomDocumentRoot(); - - _nodeCur.next(); - } - } - - private Cur _nodeCur; - private SchemaType _type; - private SchemaTypeLoader _stl; - private XmlOptions _options; - private boolean _isFrag; - } - - public Node _newDomNode(XmlOptions options) { - // Must ignore inner options for compat with v1. - - if (XmlOptions.hasOption(options, XmlOptions.SAVE_INNER)) { - options = new XmlOptions(options); - options.remove(XmlOptions.SAVE_INNER); - } - - return new DomSaver(_cur, isDomFragment(), options).saveDom(); - } - - public boolean _toCursor(Cursor other) { - assert _cur._locale == other._cur._locale; - - _cur.moveToCur(other._cur); - - return true; - } - - public void _push() { - _cur.push(); - } - - public boolean _pop() { - return _cur.pop(); - } - - public void notifyChange() { - // Force any path to get exausted, cursor may be disposed, but still be on the notification - // list. - - if (_cur != null) - _getSelectionCount(); - } - - public void setNextChangeListener(ChangeListener listener) { - _nextChangeListener = listener; - } - - public ChangeListener getNextChangeListener() { - return _nextChangeListener; - } - - public void _selectPath(String path) { - _selectPath(path, null); - } - - public void _selectPath(String pathExpr, XmlOptions options) { - _clearSelections(); - - assert _pathEngine == null; - - _pathEngine = Path.getCompiledPath(pathExpr, options).execute(_cur, options); - - _cur._locale.registerForChange(this); - } - - public boolean _hasNextSelection() { - int curr = _currentSelection; - push(); - - try { - return _toNextSelection(); - } finally { - _currentSelection = curr; - pop(); - } - } - - public boolean _toNextSelection() { - return _toSelection(_currentSelection + 1); - } - - public boolean _toSelection(int i) { - if (i < 0) - return false; - - while (i >= _cur.selectionCount()) { - if (_pathEngine == null) - return false; - - if (!_pathEngine.next(_cur)) { - _pathEngine.release(); - _pathEngine = null; - - return false; - } - } - - _cur.moveToSelection(_currentSelection = i); - - return true; - } - - public int _getSelectionCount() { - // Should never get to MAX_VALUE selection index, so, state should not change - _toSelection(Integer.MAX_VALUE); - - return _cur.selectionCount(); - } - - public void _addToSelection() { - _toSelection(Integer.MAX_VALUE); - - _cur.addToSelection(); - } - - public void _clearSelections() { - if (_pathEngine != null) { - _pathEngine.release(); - _pathEngine = null; - } - - _cur.clearSelection(); - - _currentSelection = -1; - } - - public String _namespaceForPrefix(String prefix) { - if (!_cur.isContainer()) - throw new IllegalStateException("Not on a container"); - - return _cur.namespaceForPrefix(prefix, true); - } - - public String _prefixForNamespace(String ns) { - if (ns == null || ns.length() == 0) - throw new IllegalArgumentException("Must specify a namespace"); - -// Note: I loosen this requirement in v2, can call this from anywhere -// if (!_cur.isContainer()) -// throw new IllegalStateException( "Not on a container" ); - - return _cur.prefixForNamespace(ns, null, true); - } - - public void _getAllNamespaces(Map addToThis) { - if (!_cur.isContainer()) - throw new IllegalStateException("Not on a container"); - - if (addToThis != null) - Locale.getAllNamespaces(_cur, addToThis); - } - - public XmlObject _getObject() { - return _cur.getObject(); - } - - public TokenType _prevTokenType() { - _cur.push(); - - TokenType tt = _toPrevToken(); - - _cur.pop(); - - return tt; - } - - public boolean _hasNextToken() { - //return _cur.kind() != -ROOT; - return _cur._pos!=Cur.END_POS || _cur._xobj.kind()!=ROOT; - } - - public boolean _hasPrevToken() { - return _cur.kind() != ROOT; - } - - public TokenType _toFirstContentToken() { - if (!_cur.isContainer()) - return TokenType.NONE; - - _cur.next(); - - return currentTokenType(); - } - - public TokenType _toEndToken() { - if (!_cur.isContainer()) - return TokenType.NONE; - - _cur.toEnd(); - - return currentTokenType(); - } - - public boolean _toChild(String local) { - return _toChild(null, local); - } - - public boolean _toChild(QName name) { - return _toChild(name, 0); - } - - public boolean _toChild(int index) { - return _toChild(null, index); - } - - public boolean _toChild(String uri, String local) { - validateLocalName(local); - - return _toChild(_cur._locale.makeQName(uri, local), 0); - } - - public boolean _toChild(QName name, int index) { - return Locale.toChild(_cur, name, index); - } - - public int _toNextChar(int maxCharacterCount) { - return _cur.nextChars(maxCharacterCount); - } - - public int _toPrevChar(int maxCharacterCount) { - return _cur.prevChars(maxCharacterCount); - } - - public boolean _toPrevSibling() { - return Locale.toPrevSiblingElement(_cur); - } - - public boolean _toLastChild() { - return Locale.toLastChildElement(_cur); - } - - public boolean _toFirstChild() { - return Locale.toFirstChildElement(_cur); - } - - public boolean _toNextSibling(String name) { - return _toNextSibling(new QName(name)); - } - - public boolean _toNextSibling(String uri, String local) { - validateLocalName(local); - - return _toNextSibling(_cur._locale._qnameFactory.getQName(uri, local)); - } - - public boolean _toNextSibling(QName name) { - _cur.push(); - - while (___toNextSibling()) { - if (_cur.getName().equals(name)) { - _cur.popButStay(); - return true; - } - } - - _cur.pop(); - - return false; - } - - public boolean _toFirstAttribute() { - return _cur.isContainer() && Locale.toFirstNormalAttr(_cur); - } - - public boolean _toLastAttribute() { - if (_cur.isContainer()) { - _cur.push(); - _cur.push(); - - boolean foundAttr = false; - - while (_cur.toNextAttr()) { - if (_cur.isNormalAttr()) { - _cur.popButStay(); - _cur.push(); - foundAttr = true; - } - } - - _cur.pop(); - - if (foundAttr) { - _cur.popButStay(); - return true; - } - - _cur.pop(); - } - - return false; - } - - public boolean _toNextAttribute() { - return _cur.isAttr() && Locale.toNextNormalAttr(_cur); - } - - public boolean _toPrevAttribute() { - return _cur.isAttr() && Locale.toPrevNormalAttr(_cur); - } - - public String _getAttributeText(QName attrName) { - if (attrName == null) - throw new IllegalArgumentException("Attr name is null"); - - if (!_cur.isContainer()) - return null; - - return _cur.getAttrValue(attrName); - } - - public boolean _setAttributeText(QName attrName, String value) { - if (attrName == null) - throw new IllegalArgumentException("Attr name is null"); - - validateLocalName(attrName.getLocalPart()); - - if (!_cur.isContainer()) - return false; - - _cur.setAttrValue(attrName, value); - - return true; - } - - public boolean _removeAttribute(QName attrName) { - if (attrName == null) - throw new IllegalArgumentException("Attr name is null"); - - if (!_cur.isContainer()) - return false; - - return _cur.removeAttr(attrName); - } - - public String _getTextValue() { - if (_cur.isText()) - return _getChars(); - - if (!_cur.isNode()) { - throw new IllegalStateException("Can't get text value, current token can have no text value"); - } - - return _cur.hasChildren() ? Locale.getTextValue(_cur) : _cur.getValueAsString(); - } - - public int _getTextValue(char[] chars, int offset, int max) { - if (_cur.isText()) - return _getChars(chars, offset, max); - - if (chars == null) - throw new IllegalArgumentException("char buffer is null"); - - if (offset < 0) - throw new IllegalArgumentException("offset < 0"); - - if (offset >= chars.length) - throw new IllegalArgumentException("offset off end"); - - if (max < 0) - max = Integer.MAX_VALUE; - - if (offset + max > chars.length) - max = chars.length - offset; - - if (!_cur.isNode()) { - throw new IllegalStateException("Can't get text value, current token can have no text value"); - } - - // If there are no children (hopefully the common case), I can get the text faster. - - if (_cur.hasChildren()) - return Locale.getTextValue(_cur, Locale.WS_PRESERVE, chars, offset, max); - - // Fast way - - Object src = _cur.getFirstChars(); - - if (_cur._cchSrc > max) - _cur._cchSrc = max; - - if (_cur._cchSrc <= 0) - return 0; - - CharUtil.getChars(chars, offset, src, _cur._offSrc, _cur._cchSrc); - - return _cur._cchSrc; - } - - private void setTextValue(Object src, int off, int cch) { - if (!_cur.isNode()) { - throw new IllegalStateException("Can't set text value, current token can have no text value"); - } - - _cur.moveNodeContents(null, false); - _cur.next(); - _cur.insertChars(src, off, cch); - _cur.toParent(); - } - - public void _setTextValue(String text) { - if (text == null) - text = ""; - - setTextValue(text, 0, text.length()); - } - - public void _setTextValue(char[] sourceChars, int offset, int length) { - if (length < 0) - throw new IndexOutOfBoundsException("setTextValue: length < 0"); - - if (sourceChars == null) { - if (length > 0) - throw new IllegalArgumentException("setTextValue: sourceChars == null"); - - setTextValue(null, 0, 0); - - return; - } - - if (offset < 0 || offset >= sourceChars.length) - throw new IndexOutOfBoundsException("setTextValue: offset out of bounds"); - - if (offset + length > sourceChars.length) - length = sourceChars.length - offset; - - CharUtil cu = _cur._locale.getCharUtil(); - - setTextValue(cu.saveChars(sourceChars, offset, length), cu._offSrc, cu._cchSrc); - } - - public String _getChars() { - return _cur.getCharsAsString(-1); - } - - public int _getChars(char[] buf, int off, int cch) { - int cchRight = _cur.cchRight(); - - if (cch < 0 || cch > cchRight) - cch = cchRight; - - if (buf == null || off >= buf.length) - return 0; - - if (buf.length - off < cch) - cch = buf.length - off; - - Object src = _cur.getChars(cch); - - CharUtil.getChars(buf, off, src, _cur._offSrc, _cur._cchSrc); - - return _cur._cchSrc; - } - - public void _toStartDoc() { -// while (_cur.toParent()) -// ; - _cur.toRoot(); - } - - public void _toEndDoc() { - _toStartDoc(); - - _cur.toEnd(); - } - - public int _comparePosition(Cursor other) { - int s = _cur.comparePosition(other._cur); - - if (s == 2) - throw new IllegalArgumentException("Cursors not in same document"); - - assert s >= -1 && s <= 1; - - return s; - } - - public boolean _isLeftOf(Cursor other) { - return _comparePosition(other) < 0; - } - - public boolean _isAtSamePositionAs(Cursor other) { - return _cur.isSamePos(other._cur); - } - - public boolean _isRightOf(Cursor other) { - return _comparePosition(other) > 0; - } - - public XmlCursor _execQuery(String query) { - return _execQuery(query, null); - } - - public XmlCursor _execQuery(String query, XmlOptions options) { - checkThisCursor(); - return Query.cursorExecQuery(_cur,query,options); - - } - - - public boolean _toBookmark(XmlBookmark bookmark) { - if (bookmark == null || !(bookmark._currentMark instanceof Xobj.Bookmark)) - return false; - - Xobj.Bookmark m = (Xobj.Bookmark) bookmark._currentMark; - - if (m._xobj == null || m._xobj._locale != _cur._locale) - return false; - - _cur.moveTo(m._xobj, m._pos); - - return true; - } - - public XmlBookmark _toNextBookmark(Object key) { - if (key == null) - return null; - - int cch; - - _cur.push(); - - for (; ;) { - // Move a minimal amount. If at text, move to a potential bookmark in the text. - - if ((cch = _cur.cchRight()) > 1) { - _cur.nextChars(1); - _cur.nextChars((cch = _cur.firstBookmarkInChars(key, cch - 1)) >= 0 ? cch : -1); - } else if (_toNextToken().isNone()) { - _cur.pop(); - return null; - } - - XmlBookmark bm = getBookmark(key, _cur); - - if (bm != null) { - _cur.popButStay(); - return bm; - } - - if (_cur.kind() == -ROOT) { - _cur.pop(); - return null; - } - } - } - - public XmlBookmark _toPrevBookmark(Object key) { - if (key == null) - return null; - - int cch; - - _cur.push(); - - for (; ;) { - // Move a minimal amount. If at text, move to a potential bookmark in the text. - - if ((cch = _cur.cchLeft()) > 1) { - _cur.prevChars(1); - - _cur.prevChars((cch = _cur.firstBookmarkInCharsLeft(key, cch - 1)) >= 0 ? cch : -1); - } else if (cch == 1) { - // _toPrevToken will not skip to the beginning of the text, it will go further - // so that the token to the right is not text. I need to simply skip to - // the beginning of the text ... - - _cur.prevChars(1); - } else if (_toPrevToken().isNone()) { - _cur.pop(); - return null; - } - - XmlBookmark bm = getBookmark(key, _cur); - - if (bm != null) { - _cur.popButStay(); - return bm; - } - - if (_cur.kind() == ROOT) { - _cur.pop(); - return null; - } - } - } - - public void _setBookmark(XmlBookmark bookmark) { - if (bookmark != null) { - if (bookmark.getKey() == null) - throw new IllegalArgumentException("Annotation key is null"); - - // TODO - I Don't do weak bookmarks yet ... perhaps I'll never do them .... - - bookmark._currentMark = _cur.setBookmark(bookmark.getKey(), bookmark); - } - } - - static XmlBookmark getBookmark(Object key, Cur c) { - // TODO - I Don't do weak bookmarks yet ... - - if (key == null) - return null; - - Object bm = c.getBookmark(key); - - return bm != null && bm instanceof XmlBookmark ? (XmlBookmark) bm : null; - } - - public XmlBookmark _getBookmark(Object key) { - return key == null ? null : getBookmark(key, _cur); - } - - public void _clearBookmark(Object key) { - if (key != null) - _cur.setBookmark(key, null); - } - - public void _getAllBookmarkRefs(Collection listToFill) { - if (listToFill != null) { - for (Xobj.Bookmark b = _cur._xobj._bookmarks; b != null; b = b._next) - if (b._value instanceof XmlBookmark) - listToFill.add(b._value); - } - } - - public boolean _removeXml() { - if (_cur.isRoot()) - throw new IllegalStateException("Can't remove a whole document."); - - if (_cur.isFinish()) - return false; - - assert _cur.isText() || _cur.isNode(); - - if (_cur.isText()) - _cur.moveChars(null, -1); - else - _cur.moveNode(null); - - return true; - } - - public boolean _moveXml(Cursor to) { - to.checkInsertionValidity(_cur); - - // Check for a no-op - - if (_cur.isText()) { - int cchRight = _cur.cchRight(); - - assert cchRight > 0; - - if (_cur.inChars(to._cur, cchRight, true)) - return false; - - _cur.moveChars(to._cur, cchRight); - - to._cur.nextChars(cchRight); - - return true; - } - - if (_cur.contains(to._cur)) - return false; - - // Make a cur which will float to the right of the insertion - - Cur c = to.tempCur(); - - _cur.moveNode(to._cur); - - to._cur.moveToCur(c); - - c.release(); - - return true; - } - - public boolean _copyXml(Cursor to) { - to.checkInsertionValidity(_cur); - - assert _cur.isText() || _cur.isNode(); - - Cur c = to.tempCur(); - - if (_cur.isText()) - to._cur.insertChars(_cur.getChars(-1), _cur._offSrc, _cur._cchSrc); - else - _cur.copyNode(to._cur); - - to._cur.moveToCur(c); - - c.release(); - - return true; - } - - public boolean _removeXmlContents() { - if (!_cur.isContainer()) - return false; - - _cur.moveNodeContents(null, false); - - return true; - } - - private boolean checkContentInsertionValidity(Cursor to) { - _cur.push(); - - _cur.next(); - - if (_cur.isFinish()) { - _cur.pop(); - return false; - } - - try { - to.checkInsertionValidity(_cur); - } catch (IllegalArgumentException e) { - _cur.pop(); - throw e; - } - - _cur.pop(); - - return true; - } - - public boolean _moveXmlContents(Cursor to) { - if (!_cur.isContainer() || _cur.contains(to._cur)) - return false; - - if (!checkContentInsertionValidity(to)) - return false; - - Cur c = to.tempCur(); - - _cur.moveNodeContents(to._cur, false); - - to._cur.moveToCur(c); - - c.release(); - - return true; - } - - public boolean _copyXmlContents(Cursor to) { - if (!_cur.isContainer() || _cur.contains(to._cur)) - return false; - - if (!checkContentInsertionValidity(to)) - return false; - - // I don't have a primitive to copy contents, make a copy of the node and them move the - // contents - - Cur c = _cur._locale.tempCur(); - - _cur.copyNode(c); - - Cur c2 = to._cur.tempCur(); - - c.moveNodeContents(to._cur, false); - - c.release(); - - to._cur.moveToCur(c2); - - c2.release(); - - return true; - } - - public int _removeChars(int cch) { - int cchRight = _cur.cchRight(); - - if (cchRight == 0 || cch == 0) - return 0; - - if (cch < 0 || cch > cchRight) - cch = cchRight; - - _cur.moveChars(null, cch); - - return _cur._cchSrc; - } - - public int _moveChars(int cch, Cursor to) { - int cchRight = _cur.cchRight(); - - if (cchRight <= 0 || cch == 0) - return 0; - - if (cch < 0 || cch > cchRight) - cch = cchRight; - - to.checkInsertionValidity(_cur); - - _cur.moveChars(to._cur, cch); - - to._cur.nextChars(_cur._cchSrc); - - return _cur._cchSrc; - } - - public int _copyChars(int cch, Cursor to) { - int cchRight = _cur.cchRight(); - - if (cchRight <= 0 || cch == 0) - return 0; - - if (cch < 0 || cch > cchRight) - cch = cchRight; - - to.checkInsertionValidity(_cur); - - to._cur.insertChars(_cur.getChars(cch), _cur._offSrc, _cur._cchSrc); - - to._cur.nextChars(_cur._cchSrc); - - return _cur._cchSrc; - } - - public void _insertChars(String text) { - int l = text == null ? 0 : text.length(); - - if (l > 0) { - if (_cur.isRoot() || _cur.isAttr()) { - throw - new IllegalStateException("Can't insert before the document or an attribute."); - } - - _cur.insertChars(text, 0, l); - _cur.nextChars(l); - } - } - - // - // Inserting elements - // - - public void _beginElement(String localName) { - _insertElementWithText(localName, null, null); - _toPrevToken(); - } - - public void _beginElement(String localName, String uri) { - _insertElementWithText(localName, uri, null); - _toPrevToken(); - } - - public void _beginElement(QName name) { - _insertElementWithText(name, null); - _toPrevToken(); - } - - public void _insertElement(String localName) { - _insertElementWithText(localName, null, null); - } - - public void _insertElement(String localName, String uri) { - _insertElementWithText(localName, uri, null); - } - - public void _insertElement(QName name) { - _insertElementWithText(name, null); - } - - public void _insertElementWithText(String localName, String text) { - _insertElementWithText(localName, null, text); - } - - public void _insertElementWithText(String localName, String uri, String text) { - validateLocalName(localName); - - _insertElementWithText(_cur._locale.makeQName(uri, localName), text); - } - - public void _insertElementWithText(QName name, String text) { - validateLocalName(name.getLocalPart()); - - Cur c = _cur._locale.tempCur(); - - c.createElement(name); - - insertNode(c, text); - - c.release(); - } - - // - // - // - - public void _insertAttribute(String localName) { - _insertAttributeWithValue(localName, null); - } - - public void _insertAttribute(String localName, String uri) { - _insertAttributeWithValue(localName, uri, null); - } - - public void _insertAttribute(QName name) { - _insertAttributeWithValue(name, null); - } - - public void _insertAttributeWithValue(String localName, String value) { - _insertAttributeWithValue(localName, null, value); - } - - public void _insertAttributeWithValue(String localName, String uri, String value) { - validateLocalName(localName); - - _insertAttributeWithValue(_cur._locale.makeQName(uri, localName), value); - } - - public void _insertAttributeWithValue(QName name, String text) { - validateLocalName(name.getLocalPart()); - - Cur c = _cur._locale.tempCur(); - - c.createAttr(name); - - insertNode(c, text); - - c.release(); - } - - // - // - // - - public void _insertNamespace(String prefix, String namespace) { - _insertAttributeWithValue(_cur._locale.createXmlns(prefix), namespace); - } - - public void _insertComment(String text) { - Cur c = _cur._locale.tempCur(); - - c.createComment(); - - insertNode(c, text); - - c.release(); - } - - public void _insertProcInst(String target, String text) { - validateLocalName(target); - - if (Locale.beginsWithXml(target) && target.length() == 3) - throw new IllegalArgumentException("Target is 'xml'"); - - Cur c = _cur._locale.tempCur(); - - c.createProcinst(target); - - insertNode(c, text); - - c.release(); - } - - public void _dump() { - _cur.dump(); - } - - // - // - // - // - // - // - // - - private void checkThisCursor() { - if (_cur == null) - throw new IllegalStateException("This cursor has been disposed"); - } - - private Cursor checkCursors(XmlCursor xOther) { - checkThisCursor(); - - if (xOther == null) - throw new IllegalArgumentException("Other cursor is "); - - if (!(xOther instanceof Cursor)) - throw new IllegalArgumentException("Incompatible cursors: " + xOther); - - Cursor other = (Cursor) xOther; - - if (other._cur == null) - throw new IllegalStateException("Other cursor has been disposed"); - - return other; - } - - // - // The following operations have two cursors, and can be in different documents - // - - private static final int MOVE_XML = 0; - private static final int COPY_XML = 1; - private static final int MOVE_XML_CONTENTS = 2; - private static final int COPY_XML_CONTENTS = 3; - private static final int MOVE_CHARS = 4; - private static final int COPY_CHARS = 5; - - private int twoLocaleOp(XmlCursor xOther, int op, int arg) { - Cursor other = checkCursors(xOther); - - Locale locale = _cur._locale; - Locale otherLocale = other._cur._locale; - - if (locale == otherLocale) { - if (locale.noSync()) - return twoLocaleOp(other, op, arg); - else { - synchronized (locale) { - return twoLocaleOp(other, op, arg); - } - } - } - - if (locale.noSync()) { - if (otherLocale.noSync()) - return twoLocaleOp(other, op, arg); - else { - synchronized (otherLocale) { - return twoLocaleOp(other, op, arg); - } - } - } else if (otherLocale.noSync()) { - synchronized (locale) { - return twoLocaleOp(other, op, arg); - } - } - - boolean acquired = false; - - try { - GlobalLock.acquire(); - acquired = true; - - synchronized (locale) { - synchronized (otherLocale) { - GlobalLock.release(); - acquired = false; - - return twoLocaleOp(other, op, arg); - } - } - } catch (InterruptedException e) { - throw new RuntimeException(e.getMessage(), e); - } finally { - if (acquired) - GlobalLock.release(); - } - } - - private int twoLocaleOp(Cursor other, int op, int arg) { - Locale locale = _cur._locale; - Locale otherLocale = other._cur._locale; - - locale.enter(otherLocale); - - try { - switch (op) { - case MOVE_XML: - return _moveXml(other) ? 1 : 0; - case COPY_XML: - return _copyXml(other) ? 1 : 0; - case MOVE_XML_CONTENTS: - return _moveXmlContents(other) ? 1 : 0; - case COPY_XML_CONTENTS: - return _copyXmlContents(other) ? 1 : 0; - case MOVE_CHARS: - return _moveChars(arg, other); - case COPY_CHARS: - return _copyChars(arg, other); - - default : - throw new RuntimeException("Unknown operation: " + op); - } - } finally { - locale.exit(otherLocale); - } - } - - public boolean moveXml(XmlCursor xTo) { - return twoLocaleOp(xTo, MOVE_XML, 0) == 1; - } - - public boolean copyXml(XmlCursor xTo) { - return twoLocaleOp(xTo, COPY_XML, 0) == 1; - } - - public boolean moveXmlContents(XmlCursor xTo) { - return twoLocaleOp(xTo, MOVE_XML_CONTENTS, 0) == 1; - } - - public boolean copyXmlContents(XmlCursor xTo) { - return twoLocaleOp(xTo, COPY_XML_CONTENTS, 0) == 1; - } - - public int moveChars(int cch, XmlCursor xTo) { - return twoLocaleOp(xTo, MOVE_CHARS, cch); - } - - public int copyChars(int cch, XmlCursor xTo) { - return twoLocaleOp(xTo, COPY_CHARS, cch); - } - - // - // Special methods involving multiple cursors which can be in different locales, but do not - // require sync on both locales. - // - - public boolean toCursor(XmlCursor xOther) { - // One may only move cursors within the same locale - - Cursor other = checkCursors(xOther); - - if (_cur._locale != other._cur._locale) - return false; - - if (_cur._locale.noSync()) { - _cur._locale.enter(); - try { - return _toCursor(other); - } finally { - _cur._locale.exit(); - } - } else { - synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toCursor(other); - } finally { - _cur._locale.exit(); - } - } - } - } - - public boolean isInSameDocument(XmlCursor xOther) { - return xOther == null ? false : _cur.isInSameTree(checkCursors(xOther)._cur); - } - - // - // The following operations have two cursors, but they must be in the same document - // - - private Cursor preCheck(XmlCursor xOther) { - Cursor other = checkCursors(xOther); - - if (_cur._locale != other._cur._locale) - throw new IllegalArgumentException("Cursors not in same document"); - - return other; - } - - public int comparePosition(XmlCursor xOther) { - Cursor other = preCheck(xOther); - if (_cur._locale.noSync()) { - _cur._locale.enter(); - try { - return _comparePosition(other); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _comparePosition(other); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean isLeftOf(XmlCursor xOther) { - Cursor other = preCheck(xOther); - if (_cur._locale.noSync()) { - _cur._locale.enter(); - try { - return _isLeftOf(other); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _isLeftOf(other); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean isAtSamePositionAs(XmlCursor xOther) { - Cursor other = preCheck(xOther); - if (_cur._locale.noSync()) { - _cur._locale.enter(); - try { - return _isAtSamePositionAs(other); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _isAtSamePositionAs(other); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean isRightOf(XmlCursor xOther) { - Cursor other = preCheck(xOther); - if (_cur._locale.noSync()) { - _cur._locale.enter(); - try { - return _isRightOf(other); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _isRightOf(other); - } finally { - _cur._locale.exit(); - } - } - } - - // - // Create a cursor from an Xobj -- used for XmlBookmark.createCursor - // - - public static XmlCursor newCursor(Xobj x, int p) { - Locale l = x._locale; - if (l.noSync()) { - l.enter(); - try { - return new Cursor(x, p); - } finally { - l.exit(); - } - } else synchronized (l) { - l.enter(); - try { - return new Cursor(x, p); - } finally { - l.exit(); - } - } - } - - // - // The following operations involve only one cursor - // - - private boolean preCheck() { - checkThisCursor(); - return _cur._locale.noSync(); - } - - public void dispose() { - if (_cur != null) { - Locale l = _cur._locale; - if (preCheck()) { - l.enter(); - try { - _dispose(); - } finally { - l.exit(); - } - } else synchronized (l) { - l.enter(); - try { - _dispose(); - } finally { - l.exit(); - } - } - } - } - - public Object monitor() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _monitor(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _monitor(); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlDocumentProperties documentProperties() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _documentProperties(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _documentProperties(); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlCursor newCursor() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newCursor(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newCursor(); - } finally { - _cur._locale.exit(); - } - } - } - - public XMLStreamReader newXMLStreamReader() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newXMLStreamReader(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newXMLStreamReader(); - } finally { - _cur._locale.exit(); - } - } - } - - public XMLStreamReader newXMLStreamReader(XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newXMLStreamReader(options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newXMLStreamReader(options); - } finally { - _cur._locale.exit(); - } - } - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newXMLInputStream() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newXMLInputStream(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newXMLInputStream(); - } finally { - _cur._locale.exit(); - } - } - } - - public String xmlText() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _xmlText(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _xmlText(); - } finally { - _cur._locale.exit(); - } - } - } - - public InputStream newInputStream() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newInputStream(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newInputStream(); - } finally { - _cur._locale.exit(); - } - } - } - - public Reader newReader() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newReader(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newReader(); - } finally { - _cur._locale.exit(); - } - } - } - - public Node newDomNode() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newDomNode(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newDomNode(); - } finally { - _cur._locale.exit(); - } - } - } - - public Node getDomNode() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getDomNode(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getDomNode(); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(ContentHandler ch, LexicalHandler lh) throws SAXException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(ch, lh); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(ch, lh); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(File file) throws IOException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(file); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(file); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(OutputStream os) throws IOException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(os); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(os); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(Writer w) throws IOException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(w); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(w); - } finally { - _cur._locale.exit(); - } - } - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newXMLInputStream(XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newXMLInputStream(options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newXMLInputStream(options); - } finally { - _cur._locale.exit(); - } - } - } - - public String xmlText(XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _xmlText(options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _xmlText(options); - } finally { - _cur._locale.exit(); - } - } - } - - public InputStream newInputStream(XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newInputStream(options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newInputStream(options); - } finally { - _cur._locale.exit(); - } - } - } - - public Reader newReader(XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newReader(options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newReader(options); - } finally { - _cur._locale.exit(); - } - } - } - - public Node newDomNode(XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _newDomNode(options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _newDomNode(options); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(ch, lh, options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(ch, lh, options); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(File file, XmlOptions options) throws IOException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(file, options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(file, options); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(OutputStream os, XmlOptions options) throws IOException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(os, options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(os, options); - } finally { - _cur._locale.exit(); - } - } - } - - public void save(Writer w, XmlOptions options) throws IOException { - if (preCheck()) { - _cur._locale.enter(); - try { - _save(w, options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _save(w, options); - } finally { - _cur._locale.exit(); - } - } - } - - public void push() { - if (preCheck()) { - _cur._locale.enter(); - try { - _push(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _push(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean pop() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _pop(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _pop(); - } finally { - _cur._locale.exit(); - } - } - } - - public void selectPath(String path) { - if (preCheck()) { - _cur._locale.enter(); - try { - _selectPath(path); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _selectPath(path); - } finally { - _cur._locale.exit(); - } - } - } - - public void selectPath(String path, XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - _selectPath(path, options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _selectPath(path, options); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean hasNextSelection() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _hasNextSelection(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _hasNextSelection(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toNextSelection() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextSelection(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextSelection(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toSelection(int i) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toSelection(i); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toSelection(i); - } finally { - _cur._locale.exit(); - } - } - } - - public int getSelectionCount() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getSelectionCount(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getSelectionCount(); - } finally { - _cur._locale.exit(); - } - } - } - - public void addToSelection() { - if (preCheck()) { - _cur._locale.enter(); - try { - _addToSelection(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _addToSelection(); - } finally { - _cur._locale.exit(); - } - } - } - - public void clearSelections() { - if (preCheck()) { - _cur._locale.enter(); - try { - _clearSelections(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _clearSelections(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toBookmark(XmlBookmark bookmark) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toBookmark(bookmark); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toBookmark(bookmark); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlBookmark toNextBookmark(Object key) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextBookmark(key); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextBookmark(key); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlBookmark toPrevBookmark(Object key) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toPrevBookmark(key); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toPrevBookmark(key); - } finally { - _cur._locale.exit(); - } - } - } - - public QName getName() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getName(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getName(); - } finally { - _cur._locale.exit(); - } - } - } - - public void setName(QName name) { - if (preCheck()) { - _cur._locale.enter(); - try { - _setName(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _setName(name); - } finally { - _cur._locale.exit(); - } - } - } - - public String namespaceForPrefix(String prefix) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _namespaceForPrefix(prefix); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _namespaceForPrefix(prefix); - } finally { - _cur._locale.exit(); - } - } - } - - public String prefixForNamespace(String namespaceURI) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _prefixForNamespace(namespaceURI); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _prefixForNamespace(namespaceURI); - } finally { - _cur._locale.exit(); - } - } - } - - public void getAllNamespaces(Map addToThis) { - if (preCheck()) { - _cur._locale.enter(); - try { - _getAllNamespaces(addToThis); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _getAllNamespaces(addToThis); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlObject getObject() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getObject(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getObject(); - } finally { - _cur._locale.exit(); - } - } - } - - public TokenType currentTokenType() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _currentTokenType(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _currentTokenType(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isStartdoc() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isStartdoc(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isStartdoc(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isEnddoc() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isEnddoc(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isEnddoc(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isStart() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isStart(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isStart(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isEnd() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isEnd(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isEnd(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isText() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isText(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isText(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isAttr() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isAttr(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isAttr(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isNamespace() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isNamespace(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isNamespace(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isComment() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isComment(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isComment(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isProcinst() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isProcinst(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isProcinst(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isContainer() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isContainer(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isContainer(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isFinish() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isFinish(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isFinish(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean isAnyAttr() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _isAnyAttr(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _isAnyAttr(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public TokenType prevTokenType() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _prevTokenType(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _prevTokenType(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean hasNextToken() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _hasNextToken(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _hasNextToken(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean hasPrevToken() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _hasPrevToken(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _hasPrevToken(); - } finally { - _cur._locale.exit(); - } - } - } - - public TokenType toNextToken() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextToken(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextToken(); - } finally { - _cur._locale.exit(); - } - } - } - - public TokenType toPrevToken() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toPrevToken(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toPrevToken(); - } finally { - _cur._locale.exit(); - } - } - } - - public TokenType toFirstContentToken() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toFirstContentToken(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toFirstContentToken(); - } finally { - _cur._locale.exit(); - } - } - } - - public TokenType toEndToken() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toEndToken(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toEndToken(); - } finally { - _cur._locale.exit(); - } - } - } - - public int toNextChar(int cch) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextChar(cch); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextChar(cch); - } finally { - _cur._locale.exit(); - } - } - } - - public int toPrevChar(int cch) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toPrevChar(cch); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toPrevChar(cch); - } finally { - _cur._locale.exit(); - } - } - } - -// public boolean _toNextSibling() -// { -// return Locale.toNextSiblingElement(_cur); -// } - - public boolean ___toNextSibling() - { - if (!_cur.hasParent()) - return false; - - Xobj parent = _cur.getParentNoRoot(); - - if (parent==null) - { - _cur._locale.enter(); - try - { - parent = _cur.getParent(); - } finally { - _cur._locale.exit(); - } - } - - return Locale.toNextSiblingElement(_cur, parent); - } - - public boolean toNextSibling() - { - if (preCheck()) { - return ___toNextSibling(); - } else synchronized (_cur._locale) { - return ___toNextSibling(); - } - } - - public boolean toPrevSibling() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toPrevSibling(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toPrevSibling(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toParent() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toParent(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toParent(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toFirstChild() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _toFirstChild(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _toFirstChild(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean toLastChild() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toLastChild(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toLastChild(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toChild(String name) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toChild(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toChild(name); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toChild(String namespace, String name) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toChild(namespace, name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toChild(namespace, name); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toChild(QName name) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toChild(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toChild(name); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toChild(int index) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toChild(index); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toChild(index); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toChild(QName name, int index) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toChild(name, index); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toChild(name, index); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toNextSibling(String name) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextSibling(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextSibling(name); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toNextSibling(String namespace, String name) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextSibling(namespace, name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextSibling(namespace, name); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toNextSibling(QName name) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextSibling(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextSibling(name); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toFirstAttribute() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - return _toFirstAttribute(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - return _toFirstAttribute(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public boolean toLastAttribute() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toLastAttribute(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toLastAttribute(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toNextAttribute() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toNextAttribute(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toNextAttribute(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean toPrevAttribute() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _toPrevAttribute(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _toPrevAttribute(); - } finally { - _cur._locale.exit(); - } - } - } - - public String getAttributeText(QName attrName) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getAttributeText(attrName); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getAttributeText(attrName); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean setAttributeText(QName attrName, String value) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _setAttributeText(attrName, value); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _setAttributeText(attrName, value); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean removeAttribute(QName attrName) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _removeAttribute(attrName); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _removeAttribute(attrName); - } finally { - _cur._locale.exit(); - } - } - } - - public String getTextValue() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getTextValue(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getTextValue(); - } finally { - _cur._locale.exit(); - } - } - } - - public int getTextValue(char[] chars, int offset, int cch) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getTextValue(chars, offset, cch); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getTextValue(chars, offset, cch); - } finally { - _cur._locale.exit(); - } - } - } - - public void setTextValue(String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _setTextValue(text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _setTextValue(text); - } finally { - _cur._locale.exit(); - } - } - } - - public void setTextValue(char[] sourceChars, int offset, int length) { - if (preCheck()) { - _cur._locale.enter(); - try { - _setTextValue(sourceChars, offset, length); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _setTextValue(sourceChars, offset, length); - } finally { - _cur._locale.exit(); - } - } - } - - public String getChars() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getChars(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getChars(); - } finally { - _cur._locale.exit(); - } - } - } - - public int getChars(char[] chars, int offset, int cch) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getChars(chars, offset, cch); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getChars(chars, offset, cch); - } finally { - _cur._locale.exit(); - } - } - } - - public void toStartDoc() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - _toStartDoc(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - _toStartDoc(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public void toEndDoc() { - if (preCheck()) { -// _cur._locale.enter(); -// try { - _toEndDoc(); -// } finally { -// _cur._locale.exit(); -// } - } else synchronized (_cur._locale) { -// _cur._locale.enter(); -// try { - _toEndDoc(); -// } finally { -// _cur._locale.exit(); -// } - } - } - - public XmlCursor execQuery(String query) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _execQuery(query); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _execQuery(query); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlCursor execQuery(String query, XmlOptions options) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _execQuery(query, options); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _execQuery(query, options); - } finally { - _cur._locale.exit(); - } - } - } - - public ChangeStamp getDocChangeStamp() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getDocChangeStamp(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getDocChangeStamp(); - } finally { - _cur._locale.exit(); - } - } - } - - public void setBookmark(XmlBookmark bookmark) { - if (preCheck()) { - _cur._locale.enter(); - try { - _setBookmark(bookmark); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _setBookmark(bookmark); - } finally { - _cur._locale.exit(); - } - } - } - - public XmlBookmark getBookmark(Object key) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _getBookmark(key); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _getBookmark(key); - } finally { - _cur._locale.exit(); - } - } - } - - public void clearBookmark(Object key) { - if (preCheck()) { - _cur._locale.enter(); - try { - _clearBookmark(key); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _clearBookmark(key); - } finally { - _cur._locale.exit(); - } - } - } - - public void getAllBookmarkRefs(Collection listToFill) { - if (preCheck()) { - _cur._locale.enter(); - try { - _getAllBookmarkRefs(listToFill); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _getAllBookmarkRefs(listToFill); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean removeXml() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _removeXml(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _removeXml(); - } finally { - _cur._locale.exit(); - } - } - } - - public boolean removeXmlContents() { - if (preCheck()) { - _cur._locale.enter(); - try { - return _removeXmlContents(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _removeXmlContents(); - } finally { - _cur._locale.exit(); - } - } - } - - public int removeChars(int cch) { - if (preCheck()) { - _cur._locale.enter(); - try { - return _removeChars(cch); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - return _removeChars(cch); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertChars(String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertChars(text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertChars(text); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertElement(QName name) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertElement(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertElement(name); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertElement(String localName) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertElement(localName); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertElement(localName); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertElement(String localName, String uri) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertElement(localName, uri); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertElement(localName, uri); - } finally { - _cur._locale.exit(); - } - } - } - - public void beginElement(QName name) { - if (preCheck()) { - _cur._locale.enter(); - try { - _beginElement(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _beginElement(name); - } finally { - _cur._locale.exit(); - } - } - } - - public void beginElement(String localName) { - if (preCheck()) { - _cur._locale.enter(); - try { - _beginElement(localName); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _beginElement(localName); - } finally { - _cur._locale.exit(); - } - } - } - - public void beginElement(String localName, String uri) { - if (preCheck()) { - _cur._locale.enter(); - try { - _beginElement(localName, uri); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _beginElement(localName, uri); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertElementWithText(QName name, String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertElementWithText(name, text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertElementWithText(name, text); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertElementWithText(String localName, String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertElementWithText(localName, text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertElementWithText(localName, text); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertElementWithText(String localName, String uri, String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertElementWithText(localName, uri, text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertElementWithText(localName, uri, text); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertAttribute(String localName) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertAttribute(localName); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertAttribute(localName); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertAttribute(String localName, String uri) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertAttribute(localName, uri); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertAttribute(localName, uri); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertAttribute(QName name) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertAttribute(name); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertAttribute(name); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertAttributeWithValue(String Name, String value) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertAttributeWithValue(Name, value); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertAttributeWithValue(Name, value); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertAttributeWithValue(String name, String uri, String value) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertAttributeWithValue(name, uri, value); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertAttributeWithValue(name, uri, value); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertAttributeWithValue(QName name, String value) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertAttributeWithValue(name, value); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertAttributeWithValue(name, value); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertNamespace(String prefix, String namespace) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertNamespace(prefix, namespace); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertNamespace(prefix, namespace); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertComment(String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertComment(text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertComment(text); - } finally { - _cur._locale.exit(); - } - } - } - - public void insertProcInst(String target, String text) { - if (preCheck()) { - _cur._locale.enter(); - try { - _insertProcInst(target, text); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _insertProcInst(target, text); - } finally { - _cur._locale.exit(); - } - } - } - - public void dump() { - if (preCheck()) { - _cur._locale.enter(); - try { - _dump(); - } finally { - _cur._locale.exit(); - } - } else synchronized (_cur._locale) { - _cur._locale.enter(); - try { - _dump(); - } finally { - _cur._locale.exit(); - } - } - } - - // - // - // - - private Cur _cur; - private PathEngine _pathEngine; - private int _currentSelection; - - private ChangeListener _nextChangeListener; -} diff --git a/src/store/org/apache/xmlbeans/impl/store/DomImpl.java b/src/store/org/apache/xmlbeans/impl/store/DomImpl.java deleted file mode 100755 index a15b72c..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/DomImpl.java +++ /dev/null @@ -1,4907 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import org.w3c.dom.Attr; -import org.w3c.dom.CDATASection; -import org.w3c.dom.CharacterData; -import org.w3c.dom.Comment; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.DocumentType; -import org.w3c.dom.DOMException; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Element; -import org.w3c.dom.EntityReference; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.DOMImplementation; - -// DOM Level 3 -import org.w3c.dom.UserDataHandler; - - -import org.apache.xmlbeans.impl.common.XMLChar; -import org.apache.xmlbeans.impl.soap.Detail; -import org.apache.xmlbeans.impl.soap.DetailEntry; -import org.apache.xmlbeans.impl.soap.MimeHeaders; -import org.apache.xmlbeans.impl.soap.Name; -import org.apache.xmlbeans.impl.soap.SOAPBody; -import org.apache.xmlbeans.impl.soap.SOAPBodyElement; -import org.apache.xmlbeans.impl.soap.SOAPElement; -import org.apache.xmlbeans.impl.soap.SOAPEnvelope; -import org.apache.xmlbeans.impl.soap.SOAPException; -import org.apache.xmlbeans.impl.soap.SOAPFactory; -import org.apache.xmlbeans.impl.soap.SOAPFault; -import org.apache.xmlbeans.impl.soap.SOAPHeader; -import org.apache.xmlbeans.impl.soap.SOAPHeaderElement; -import org.apache.xmlbeans.impl.soap.SOAPPart; - -import javax.xml.stream.XMLStreamReader; - -import java.io.PrintStream; - -import java.util.ArrayList; -import java.util.Iterator; - -import javax.xml.transform.Source; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlRuntimeException; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -final class DomImpl -{ - static final int ELEMENT = Node.ELEMENT_NODE; - static final int ATTR = Node.ATTRIBUTE_NODE; - static final int TEXT = Node.TEXT_NODE; - static final int CDATA = Node.CDATA_SECTION_NODE; - static final int ENTITYREF = Node.ENTITY_REFERENCE_NODE; - static final int ENTITY = Node.ENTITY_NODE; - static final int PROCINST = Node.PROCESSING_INSTRUCTION_NODE; - static final int COMMENT = Node.COMMENT_NODE; - static final int DOCUMENT = Node.DOCUMENT_NODE; - static final int DOCTYPE = Node.DOCUMENT_TYPE_NODE; - static final int DOCFRAG = Node.DOCUMENT_FRAGMENT_NODE; - static final int NOTATION = Node.NOTATION_NODE; - - interface Dom - { - Locale locale ( ); - int nodeType ( ); - Cur tempCur ( ); - QName getQName ( ); - boolean nodeCanHavePrefixUri( ); - - void dump ( ); - void dump ( PrintStream o ); - void dump ( PrintStream o, Object ref ); - }; - - static Dom parent ( Dom d ) { return node_getParentNode ( d ); } - static Dom firstChild ( Dom d ) { return node_getFirstChild ( d ); } - static Dom nextSibling ( Dom d ) { return node_getNextSibling( d ); } - static Dom prevSibling ( Dom d ) { return node_getPreviousSibling( d ); } - - public static Dom append ( Dom n, Dom p ) - { - return node_insertBefore( p, n, null ); - } - - public static Dom insert ( Dom n, Dom b ) - { - assert b != null; - return node_insertBefore( parent( b ), n, b ); - } - - public static Dom remove ( Dom n ) - { - Dom p = parent( n ); - - if (p != null) - node_removeChild( p, n ); - - return n; - } - - // - // Handy dandy Dom exceptions - // - - static class HierarchyRequestErr extends DOMException - { - HierarchyRequestErr ( ) { this( "This node isn't allowed there" ); } - HierarchyRequestErr ( String message ) { super( HIERARCHY_REQUEST_ERR, message ); } - } - - static class WrongDocumentErr extends DOMException - { - WrongDocumentErr ( ) { this( "Nodes do not belong to the same document" ); } - WrongDocumentErr ( String message ) { super( WRONG_DOCUMENT_ERR, message ); } - } - - static class NotFoundErr extends DOMException - { - NotFoundErr ( ) { this( "Node not found" ); } - NotFoundErr ( String message ) { super( NOT_FOUND_ERR, message ); } - } - - static class NamespaceErr extends DOMException - { - NamespaceErr ( ) { this( "Namespace error" ); } - NamespaceErr ( String message ) { super( NAMESPACE_ERR, message ); } - } - - static class NoModificationAllowedErr extends DOMException - { - NoModificationAllowedErr ( ) { this( "No modification allowed error" ); } - NoModificationAllowedErr ( String message ) { super( NO_MODIFICATION_ALLOWED_ERR, message ); } - } - - static class InuseAttributeError extends DOMException - { - InuseAttributeError ( ) { this( "Attribute currently in use error" ); } - InuseAttributeError ( String message ) { super( INUSE_ATTRIBUTE_ERR, message ); } - } - - static class IndexSizeError extends DOMException - { - IndexSizeError ( ) { this( "Index Size Error" ); } - IndexSizeError ( String message ) { super( INDEX_SIZE_ERR, message ); } - } - - static class NotSupportedError extends DOMException - { - NotSupportedError ( ) { this( "This operation is not supported" ); } - NotSupportedError ( String message ) { super( NOT_SUPPORTED_ERR, message ); } - } - - static class InvalidCharacterError extends DOMException - { - InvalidCharacterError ( ) { this( "The name contains an invalid character" ); } - InvalidCharacterError ( String message ) { super( INVALID_CHARACTER_ERR, message ); } - } - - // - // Helper fcns - // - - private static final class EmptyNodeList implements NodeList - { - public int getLength ( ) { return 0; } - public Node item ( int i ) { return null; } - } - - public static NodeList _emptyNodeList = new EmptyNodeList(); - - static String nodeKindName ( int t ) - { - switch ( t ) - { - case ATTR : return "attribute"; - case CDATA : return "cdata section"; - case COMMENT : return "comment"; - case DOCFRAG : return "document fragment"; - case DOCUMENT : return "document"; - case DOCTYPE : return "document type"; - case ELEMENT : return "element"; - case ENTITY : return "entity"; - case ENTITYREF : return "entity reference"; - case NOTATION : return "notation"; - case PROCINST : return "processing instruction"; - case TEXT : return "text"; - - default : throw new RuntimeException( "Unknown node type" ); - } - } - - private static String isValidChild ( Dom parent, Dom child ) - { - int pk = parent.nodeType(); - int ck = child.nodeType(); - - switch ( pk ) - { - case DOCUMENT : - { - switch ( ck ) - { - case ELEMENT : - { - if (document_getDocumentElement( parent ) != null) - return "Documents may only have a maximum of one document element"; - - return null; - } - case DOCTYPE : - { - if (document_getDoctype( parent ) != null) - return "Documents may only have a maximum of one document type node"; - - return null; - } - case PROCINST : - case COMMENT : - return null; - } - - break; - } - - case ATTR : - { - if (ck == TEXT || ck == ENTITYREF) - return null; - - // TODO -- traverse the entity tree, making sure that there are - // only entity refs and text nodes in it. - - break; - } - - case DOCFRAG : - case ELEMENT : - case ENTITY : - case ENTITYREF : - { - switch ( ck ) - { - case ELEMENT : - case ENTITYREF: - case CDATA : - case TEXT : - case COMMENT : - case PROCINST : - return null; - } - - break; - } - - case CDATA : - case TEXT : - case COMMENT : - case PROCINST : - case DOCTYPE : - case NOTATION : - return nodeKindName( pk ) + " nodes may not have any children"; - } - - return - nodeKindName( pk ) + " nodes may not have " + - nodeKindName( ck ) + " nodes as children"; - } - - private static void validateNewChild ( Dom parent, Dom child ) - { - String msg = isValidChild( parent, child ); - - if (msg != null) - throw new HierarchyRequestErr( msg ); - - if (parent == child) - throw new HierarchyRequestErr( "New child and parent are the same node" ); - - while ( (parent = parent( parent )) != null ) - { - // TODO - use read only state on a node to know if it is under an - // entity ref - - if (child.nodeType() == ENTITYREF) - throw new NoModificationAllowedErr( "Entity reference trees may not be modified" ); - - if (child == parent) - throw new HierarchyRequestErr( "New child is an ancestor node of the parent node" ); - } - } - - private static String validatePrefix ( - String prefix, String uri, String local, boolean isAttr ) - { - validateNcName( prefix ); - - if (prefix == null) - prefix = ""; - - if (uri == null) - uri = ""; - - if (prefix.length() > 0 && uri.length() == 0) - throw new NamespaceErr( "Attempt to give a prefix for no namespace" ); - - if (prefix.equals( "xml" ) && !uri.equals( Locale._xml1998Uri )) - throw new NamespaceErr( "Invalid prefix - begins with 'xml'" ); - - if (isAttr) - { - if (prefix.length() > 0) - { - if (local.equals( "xmlns" )) - throw new NamespaceErr( "Invalid namespace - attr is default namespace already" ); - - if (Locale.beginsWithXml( local )) - throw new NamespaceErr( "Invalid namespace - attr prefix begins with 'xml'" ); - - if (prefix.equals( "xmlns" ) && !uri.equals( Locale._xmlnsUri )) - throw new NamespaceErr( "Invalid namespace - uri is not '" + Locale._xmlnsUri+";" ); - } - else - { - if (local.equals( "xmlns" ) && !uri.equals( Locale._xmlnsUri )) - throw new NamespaceErr( "Invalid namespace - uri is not '" + Locale._xmlnsUri+";" ); - } - } - else if (Locale.beginsWithXml( prefix )) - throw new NamespaceErr( "Invalid prefix - begins with 'xml'" ); - - return prefix; - } - - private static void validateName ( String name ) - { - if (name == null) - throw new IllegalArgumentException( "Name is null" ); - - if (name.length() == 0) - throw new IllegalArgumentException( "Name is empty" ); - - if (!XMLChar.isValidName( name )) - throw new InvalidCharacterError( "Name has an invalid character" ); - } - - private static void validateNcName ( String name ) - { - if (name != null && name.length() > 0 && !XMLChar.isValidNCName( name )) - throw new InvalidCharacterError(); - } - - private static void validateQualifiedName ( String name, String uri, boolean isAttr ) - { - assert name != null; - - if (uri == null) - uri = ""; - - int i = name.indexOf( ':' ); - - String local; - - if (i < 0) - { - validateNcName( local = name ); - - if (isAttr && local.equals( "xmlns" ) && !uri.equals( Locale._xmlnsUri )) - { - throw - new NamespaceErr( - "Default xmlns attribute does not have namespace: " + Locale._xmlnsUri ); - } - } - else - { - if (i == 0) - throw new NamespaceErr( "Invalid qualified name, no prefix specified" ); - - String prefix = name.substring( 0, i ); - - validateNcName( prefix ); - - if (uri.length() == 0) - throw new NamespaceErr( "Attempt to give a prefix for no namespace" ); - - local = name.substring( i + 1 ); - - if (local.indexOf( ':' ) >= 0) - throw new NamespaceErr( "Invalid qualified name, more than one colon" ); - - validateNcName( local ); - - if (prefix.equals( "xml" ) && !uri.equals( Locale._xml1998Uri )) - throw new NamespaceErr( "Invalid prefix - begins with 'xml'" ); - } - - if (local.length() == 0) - throw new NamespaceErr( "Invalid qualified name, no local part specified" ); - } - - private static void removeNode ( Dom n ) - { - assert n.nodeType() != TEXT && n.nodeType() != CDATA; - - Cur cFrom = n.tempCur(); - - cFrom.toEnd(); - - // Move any char nodes which ater after the node to remove to be before it. The call to - // Next here does two things, it tells me if I can get after the move to remove (all nodes - // but the root) and it positions me at the place where there are char nodes after. - - if (cFrom.next()) - { - CharNode fromNodes = cFrom.getCharNodes(); - - if (fromNodes != null) - { - cFrom.setCharNodes( null ); - Cur cTo = n.tempCur(); - cTo.setCharNodes( CharNode.appendNodes( cTo.getCharNodes(), fromNodes ) ); - cTo.release(); - } - } - - cFrom.release(); - - Cur.moveNode( (Xobj) n, null ); - } - - private abstract static class ElementsNodeList implements NodeList - { - ElementsNodeList ( Dom root ) - { - assert root.nodeType() == DOCUMENT || root.nodeType() == ELEMENT; - - _root = root; - _locale = _root.locale(); - _version = 0; - } - - public int getLength ( ) - { - ensureElements(); - - return _elements.size(); - } - - public Node item ( int i ) - { - ensureElements(); - - return i < 0 || i >= _elements.size() ? (Node) null : (Node) _elements.get( i ); - } - - private void ensureElements ( ) - { - if (_version == _locale.version()) - return; - - _version = _locale.version(); - - _elements = new ArrayList(); - - Locale l = _locale; - - if (l.noSync()) { l.enter(); try { addElements( _root ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { addElements( _root ); } finally { l.exit(); } } - } - - private void addElements ( Dom node ) - { - for ( Dom c = firstChild( node ) ; c != null ; c = nextSibling( c ) ) - { - if (c.nodeType() == ELEMENT) - { - if (match( c )) - _elements.add( c ); - - addElements( c ); - } - } - } - - protected abstract boolean match ( Dom element ); - - private Dom _root; - private Locale _locale; - private long _version; - private ArrayList _elements; - } - - private static class ElementsByTagNameNodeList extends ElementsNodeList - { - ElementsByTagNameNodeList ( Dom root, String name ) - { - super( root ); - - _name = name; - } - - protected boolean match ( Dom element ) - { - return _name.equals( "*" ) ? true : _node_getNodeName( element ).equals( _name ); - } - - private String _name; - } - - private static class ElementsByTagNameNSNodeList extends ElementsNodeList - { - ElementsByTagNameNSNodeList ( Dom root, String uri, String local ) - { - super( root ); - - _uri = uri == null ? "" : uri; - _local = local; - } - - protected boolean match ( Dom element ) - { - if (!(_uri.equals( "*" ) ? true : _node_getNamespaceURI( element ).equals( _uri ))) - return false; - - return _local.equals( "*" ) ? true : _node_getLocalName( element ).equals( _local ); - } - - private String _uri; - private String _local; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Document _domImplementation_createDocument ( - Locale l, String u, String n, DocumentType t ) - { - Document d; - - if (l.noSync()) { l.enter(); try { return domImplementation_createDocument( l, u, n, t ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return domImplementation_createDocument( l, u, n, t ); } finally { l.exit(); } } - } - - public static Document domImplementation_createDocument ( - Locale l, String namespaceURI, String qualifiedName, DocumentType doctype ) - { - validateQualifiedName( qualifiedName, namespaceURI, false ); - - Cur c = l.tempCur(); - - c.createDomDocumentRoot(); - - Document doc = (Document) c.getDom(); - - c.next(); - - c.createElement( l.makeQualifiedQName( namespaceURI, qualifiedName ) ); - - if (doctype != null) - throw new RuntimeException( "Not impl" ); - - c.toParent(); - - try - { - Locale.autoTypeDocument( c, null, null ); - } - catch (XmlException e ) - { - throw new XmlRuntimeException( e ); - } - - c.release(); - - return doc; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _domImplementation_hasFeature ( Locale l, String feature, String version ) - { - if (feature == null) - return false; - - if (version != null && version.length() > 0 && - !version.equals( "1.0" ) && !version.equals( "2.0" )) - { - return false; - } - - if (feature.equalsIgnoreCase( "core" )) - return true; - - if (feature.equalsIgnoreCase( "xml" )) - return true; - - return false; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Element _document_getDocumentElement ( Dom d ) - { - Locale l = d.locale(); - - Dom e; - - if (l.noSync()) { l.enter(); try { e = document_getDocumentElement( d ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { e = document_getDocumentElement( d ); } finally { l.exit(); } } - - return (Element) e; - } - - public static Dom document_getDocumentElement ( Dom d ) - { - for ( d = firstChild( d ) ; d != null ; d = nextSibling( d ) ) - { - if (d.nodeType() == ELEMENT) - return d; - } - - return null; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static DocumentFragment _document_createDocumentFragment ( Dom d ) - { - Locale l = d.locale(); - - Dom f; - - if (l.noSync()) { l.enter(); try { f = document_createDocumentFragment( d ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { f = document_createDocumentFragment( d ); } finally { l.exit(); } } - - return (DocumentFragment) f; - } - - public static Dom document_createDocumentFragment ( Dom d ) - { - Cur c = d.locale().tempCur(); - - c.createDomDocFragRoot(); - - Dom f = c.getDom(); - - c.release(); - - return f; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Element _document_createElement ( Dom d, String name ) - { - Locale l = d.locale(); - - Dom e; - - if (l.noSync()) { l.enter(); try { e = document_createElement( d, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { e = document_createElement( d, name ); } finally { l.exit(); } } - - return (Element) e; - } - - public static Dom document_createElement ( Dom d, String name ) - { - validateName( name ); - - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.createElement( l.makeQualifiedQName( "", name ) ); - - Dom e = c.getDom(); - - c.release(); - ((Xobj.ElementXobj)e)._canHavePrefixUri = false; - return e; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Element _document_createElementNS ( Dom d, String uri, String qname ) - { - Locale l = d.locale(); - - Dom e; - - if (l.noSync()) { l.enter(); try { e = document_createElementNS( d, uri, qname ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { e = document_createElementNS( d, uri, qname ); } finally { l.exit(); } } - - return (Element) e; - } - - public static Dom document_createElementNS ( Dom d, String uri, String qname ) - { - validateQualifiedName( qname, uri, false ); - - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.createElement( l.makeQualifiedQName( uri, qname ) ); - - Dom e = c.getDom(); - - c.release(); - - return e; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _document_createAttribute ( Dom d, String name ) - { - Locale l = d.locale(); - - Dom a; - - if (l.noSync()) { l.enter(); try { a = document_createAttribute( d, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { a = document_createAttribute( d, name ); } finally { l.exit(); } } - - return (Attr) a; - } - - public static Dom document_createAttribute ( Dom d, String name ) - { - validateName( name ); - - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.createAttr( l.makeQualifiedQName( "", name ) ); - - Dom e = c.getDom(); - - c.release(); - ((Xobj.AttrXobj)e)._canHavePrefixUri = false; - return e; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _document_createAttributeNS ( Dom d, String uri, String qname ) - { - Locale l = d.locale(); - - Dom a; - - if (l.noSync()) { l.enter(); try { a = document_createAttributeNS( d, uri, qname ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { a = document_createAttributeNS( d, uri, qname ); } finally { l.exit(); } } - - return (Attr) a; - } - - public static Dom document_createAttributeNS ( Dom d, String uri, String qname ) - { - validateQualifiedName( qname, uri, true ); - - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.createAttr( l.makeQualifiedQName( uri, qname ) ); - - Dom e = c.getDom(); - - c.release(); - - return e; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Comment _document_createComment ( Dom d, String data ) - { - Locale l = d.locale(); - - Dom c; - - if (l.noSync()) { l.enter(); try { c = document_createComment( d, data ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { c = document_createComment( d, data ); } finally { l.exit(); } } - - return (Comment) c; - } - - public static Dom document_createComment ( Dom d, String data ) - { - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.createComment(); - - Dom comment = c.getDom(); - - if (data != null) - { - c.next(); - c.insertString( data ); - } - - c.release(); - - return comment; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static ProcessingInstruction _document_createProcessingInstruction ( Dom d, String target, String data ) - { - Locale l = d.locale(); - - Dom pi; - - if (l.noSync()) { l.enter(); try { pi = document_createProcessingInstruction( d, target, data ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { pi = document_createProcessingInstruction( d, target, data ); } finally { l.exit(); } } - - return (ProcessingInstruction) pi; - } - - public static Dom document_createProcessingInstruction ( Dom d, String target, String data ) - { - if (target == null) - throw new IllegalArgumentException( "Target is null" ); - - if (target.length() == 0) - throw new IllegalArgumentException( "Target is empty" ); - - if (!XMLChar.isValidName( target )) - throw new InvalidCharacterError( "Target has an invalid character" ); - - if (Locale.beginsWithXml( target ) && target.length() == 3) - throw new InvalidCharacterError( "Invalid target - is 'xml'" ); - - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.createProcinst( target ); - - Dom pi = c.getDom(); - - if (data != null) - { - c.next(); - c.insertString( data ); - } - - c.release(); - - return pi; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static CDATASection _document_createCDATASection ( Dom d, String data ) - { - return (CDATASection) document_createCDATASection( d, data ); - } - - public static Dom document_createCDATASection ( Dom d, String data ) - { - TextNode t = d.locale().createCdataNode(); - - if (data == null) - data = ""; - - t.setChars( data, 0, data.length() ); - - return t; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Text _document_createTextNode ( Dom d, String data ) - { - return (Text) document_createTextNode( d, data ); - } - - public static CharNode document_createTextNode ( Dom d, String data ) - { - TextNode t = d.locale().createTextNode(); - - if (data == null) - data = ""; - - t.setChars( data, 0, data.length() ); - - return t; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static EntityReference _document_createEntityReference ( Dom d, String name ) - { - throw new RuntimeException( "Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Element _document_getElementById ( Dom d, String elementId ) - { - throw new RuntimeException( "Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static NodeList _document_getElementsByTagName ( Dom d, String name ) - { - Locale l = d.locale(); - - if (l.noSync()) { l.enter(); try { return document_getElementsByTagName( d, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return document_getElementsByTagName( d, name ); } finally { l.exit(); } } - } - - public static NodeList document_getElementsByTagName ( Dom d, String name ) - { - return new ElementsByTagNameNodeList( d, name ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static NodeList _document_getElementsByTagNameNS ( Dom d, String uri, String local ) - { - Locale l = d.locale(); - - if (l.noSync()) { l.enter(); try { return document_getElementsByTagNameNS( d, uri, local ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return document_getElementsByTagNameNS( d, uri, local ); } finally { l.exit(); } } - } - - public static NodeList document_getElementsByTagNameNS ( Dom d, String uri, String local ) - { - return new ElementsByTagNameNSNodeList( d, uri, local ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static DOMImplementation _document_getImplementation ( Dom d ) - { - return (DOMImplementation) d.locale(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _document_importNode ( Dom d, Node n, boolean deep ) - { - Locale l = d.locale(); - Dom i; - -// // TODO - need to wrap this in sync .. -// if (n instanceof Dom) -// i = node_cloneNode( (Dom) n, deep, m ); -// else -// TODO -- I'm importing my own nodes through DOM methods! -- make this faster - { - if (l.noSync()) { l.enter(); try { i = document_importNode( d, n, deep ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { i = document_importNode( d, n, deep ); } finally { l.exit(); } } - } - - return (Node) i; - } - - public static Dom document_importNode ( Dom d, Node n, boolean deep ) - { - if (n == null) - return null; - - Dom i; - - boolean copyChildren = false; - - switch ( n.getNodeType() ) - { - case DOCUMENT : - throw new NotSupportedError( "Document nodes may not be imported" ); - - case DOCTYPE : - throw new NotSupportedError( "Document type nodes may not be imported" ); - - case ELEMENT : - { - String local = n.getLocalName(); - - if (local == null || local.length() == 0) - i = document_createElement( d, n.getNodeName() ); - else - { - String prefix = n.getPrefix(); - String name = prefix == null || prefix.length() == 0 ? local : prefix + ":" + local; - String uri = n.getNamespaceURI(); - - if (uri == null || uri.length() == 0) - i = document_createElement( d, name ); - else - i = document_createElementNS( d, uri, name ); - } - - NamedNodeMap attrs = n.getAttributes(); - - for ( int a = 0 ; a < attrs.getLength() ; a++ ) - attributes_setNamedItem( i, document_importNode( d, attrs.item( a ), true ) ); - - copyChildren = deep; - - break; - } - - case ATTR : - { - String local = n.getLocalName(); - - if (local == null || local.length() == 0) - i = document_createAttribute( d, n.getNodeName() ); - else - { - String prefix = n.getPrefix(); - String name = prefix == null || prefix.length() == 0 ? local : prefix + ":" + local; - String uri = n.getNamespaceURI(); - - if (uri == null || uri.length() == 0) - i = document_createAttribute( d, name ); - else - i = document_createAttributeNS( d, uri, name ); - } - - copyChildren = true; - - break; - } - - case DOCFRAG : - { - i = document_createDocumentFragment( d ); - - copyChildren = deep; - - break; - } - - case PROCINST : - { - i = document_createProcessingInstruction( d, n.getNodeName(), n.getNodeValue() ); - break; - } - - case COMMENT : - { - i = document_createComment( d, n.getNodeValue() ); - break; - } - - case TEXT : - { - i = document_createTextNode( d, n.getNodeValue() ); - break; - } - - case CDATA : - { - i = document_createCDATASection( d, n.getNodeValue() ); - break; - } - - case ENTITYREF : - case ENTITY : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - default : throw new RuntimeException( "Unknown kind" ); - } - - if (copyChildren) - { - NodeList children = n.getChildNodes(); - - for ( int c = 0 ; c < children.getLength() ; c++ ) - node_insertBefore( i, document_importNode( d, children.item( c ), true ), null); - } - - return i; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static DocumentType _document_getDoctype ( Dom d ) - { - Locale l = d.locale(); - - Dom dt; - - if (l.noSync()) { l.enter(); try { dt = document_getDoctype( d ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { dt = document_getDoctype( d ); } finally { l.exit(); } } - - return (DocumentType) dt; - } - - public static Dom document_getDoctype ( Dom d ) - { - return null; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Document _node_getOwnerDocument ( Dom n ) - { - Locale l = n.locale(); - - Dom d; - - if (l.noSync()) { l.enter(); try { d = node_getOwnerDocument( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { d = node_getOwnerDocument( n ); } finally { l.exit(); } } - - return (Document) d; - } - - public static Dom node_getOwnerDocument ( Dom n ) - { - if (n.nodeType() == DOCUMENT) - return null; - - Locale l = n.locale(); - - if (l._ownerDoc == null) - { - Cur c = l.tempCur(); - c.createDomDocumentRoot(); - l._ownerDoc = c.getDom(); - c.release(); - } - - return l._ownerDoc; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_getParentNode ( Dom n ) - { - Locale l = n.locale(); - - Dom p; - - if (l.noSync()) { l.enter(); try { p = node_getParentNode( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { p = node_getParentNode( n ); } finally { l.exit(); } } - - return (Node) p; - } - - public static Dom node_getParentNode ( Dom n ) - { - Cur c = null; - - switch ( n.nodeType() ) - { - case DOCUMENT : - case DOCFRAG : - case ATTR : - break; - - case PROCINST : - case COMMENT : - case ELEMENT : - { - if (!(c = n.tempCur()).toParentRaw()) - { - c.release(); - c = null; - } - - break; - } - - case TEXT : - case CDATA : - { - if ((c = n.tempCur()) != null) - c.toParent(); - - break; - } - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - default : throw new RuntimeException( "Unknown kind" ); - } - - if (c == null) - return null; - - Dom d = c.getDom(); - - c.release(); - - return d; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_getFirstChild ( Dom n ) - { - Locale l = n.locale(); - - Dom fc; - assert n instanceof Xobj; - Xobj node = (Xobj)n; - if (!node.isVacant()) - { - if (node.isFirstChildPtrDomUsable()) - return (Node) node._firstChild; - Xobj lastAttr = node.lastAttr(); - if (lastAttr != null && - lastAttr.isNextSiblingPtrDomUsable()) - return (Xobj.NodeXobj) lastAttr._nextSibling; - if (node.isExistingCharNodesValueUsable()) - return node._charNodesValue; - } - if (l.noSync()) { fc = node_getFirstChild( n ); } - else synchronized ( l ) { fc = node_getFirstChild( n ); } - - return (Node) fc; - } - - public static Dom node_getFirstChild ( Dom n ) - { - Dom fc = null; - - switch ( n.nodeType() ) - { - case TEXT : - case CDATA : - case PROCINST : - case COMMENT : - break; - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - case ELEMENT : - case DOCUMENT : - case DOCFRAG : - case ATTR : - { - - Xobj node = (Xobj) n; - node.ensureOccupancy(); - if (node.isFirstChildPtrDomUsable()) - return (Xobj.NodeXobj) node._firstChild; - Xobj lastAttr = node.lastAttr(); - if (lastAttr != null) - { - if (lastAttr.isNextSiblingPtrDomUsable()) - return (Xobj.NodeXobj) lastAttr._nextSibling; - else if (lastAttr.isCharNodesAfterUsable()) - return (CharNode) lastAttr._charNodesAfter; - } - if (node.isCharNodesValueUsable()) - return node._charNodesValue; - - - break; - } - } - - // TODO - handle entity refs here ... - - return fc; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_getLastChild ( Dom n ) - { - Locale l = n.locale(); - - Dom lc; - - if (l.noSync()) { l.enter(); try { lc = node_getLastChild( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { lc = node_getLastChild( n ); } finally { l.exit(); } } - - return (Node) lc; - } - - public static Dom node_getLastChild ( Dom n ) - { - switch ( n.nodeType() ) - { - case TEXT : - case CDATA : - case PROCINST : - case COMMENT : - return null; - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - case ELEMENT : - case DOCUMENT : - case DOCFRAG : - case ATTR : - break; - } - - Dom lc = null; - CharNode nodes; - - Cur c = n.tempCur(); - - if (c.toLastChild()) - { - lc = c.getDom(); - - c.skip(); - - if ((nodes = c.getCharNodes()) != null) - lc = null; - } - else - { - c.next(); - nodes = c.getCharNodes(); - } - - if (lc == null && nodes != null) - { - while ( nodes._next != null ) - nodes = nodes._next; - - lc = nodes; - } - - c.release(); - - // TODO - handle entity refs here ... - - return lc; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_getNextSibling ( Dom n ) - { - Locale l = n.locale(); - - Dom ns; - - if (l.noSync()) { ns = node_getNextSibling( n ); } - else synchronized ( l ) { ns = node_getNextSibling( n ); } - - return (Node) ns; - } - - public static Dom node_getNextSibling ( Dom n ) - { - Dom ns = null; - - switch ( n.nodeType() ) - { - case DOCUMENT : - case DOCFRAG : - case ATTR : - break; - - case TEXT : - case CDATA : - { - CharNode cn = (CharNode) n; - //if src is attr & next is null , ret null; - //if src is container and - // a) this node is aftertext && src._nextSib = null; ret null - // b) this node is value && src._fc = null; ret null - - - if (! (cn._src instanceof Xobj) ) - return null; - Xobj src = (Xobj) cn._src; - //if src is attr this node is always value and - // next is always the next ptr of the attr - src._charNodesAfter = - Cur.updateCharNodes( src._locale, src, src._charNodesAfter, src._cchAfter ); - - src._charNodesValue = - Cur.updateCharNodes( src._locale, src, src._charNodesValue, src._cchValue ); - - if (cn._next != null) - { - ns = cn._next; - break; - } - boolean isThisNodeAfterText = cn.isNodeAftertext(); - - if (isThisNodeAfterText) - ns = (Xobj.NodeXobj) src._nextSibling; - else //srcValue or attribute source - ns = (Xobj.NodeXobj) src._firstChild; - break; - - } - - case PROCINST : - case COMMENT : - case ELEMENT : - { - assert n instanceof Xobj: "PI, Comments and Elements always backed up by Xobj"; - Xobj node = (Xobj) n; - node.ensureOccupancy(); - if (node.isNextSiblingPtrDomUsable()) - return - (Xobj.NodeXobj) node._nextSibling; - if (node.isCharNodesAfterUsable()) - return node._charNodesAfter; - break; - } - - case ENTITY : - case NOTATION : - case ENTITYREF : - case DOCTYPE : - throw new RuntimeException( "Not implemented" ); - } - - // TODO - handle entity refs here ... - - return ns; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_getPreviousSibling ( Dom n ) - { - Locale l = n.locale(); - - Dom ps; - - if (l.noSync()) { ps = node_getPreviousSibling( n ); } - else synchronized ( l ) { ps = node_getPreviousSibling( n ); } - - return (Node) ps; - } - - public static Dom node_getPreviousSibling ( Dom n ) - { - Dom prev = null; - Dom temp; - switch (n.nodeType()) - { - case TEXT: - case CDATA: - { - assert n instanceof CharNode: "Text/CData should be a CharNode"; - CharNode node = (CharNode) n; - if (!(node._src instanceof Xobj)) - return null; - Xobj src = (Xobj) node._src; - src.ensureOccupancy(); - boolean isThisNodeAfterText = node.isNodeAftertext(); - prev = node._prev; - if (prev == null) - prev = isThisNodeAfterText ? (Dom) src : - src._charNodesValue; - break; - } - default: - { - assert n instanceof Xobj; - Xobj node = (Xobj) n; - prev = (Dom) node._prevSibling; - if (prev == null && node._parent != null) - prev = (Dom) node_getFirstChild((Dom) node._parent); - } - } - temp = (Dom) prev; - while (temp != null && - (temp = node_getNextSibling(temp)) != n) - prev = temp; - return prev; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _node_hasAttributes ( Dom n ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { return node_hasAttributes( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return node_hasAttributes( n ); } finally { l.exit(); } } - } - - public static boolean node_hasAttributes ( Dom n ) - { - boolean hasAttrs = false; - - if (n.nodeType() == ELEMENT) - { - Cur c = n.tempCur(); - - hasAttrs = c.hasAttrs(); - - c.release(); - } - - return hasAttrs; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _node_isSupported ( Dom n, String feature, String version ) - { - return _domImplementation_hasFeature( n.locale(), feature, version ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _node_normalize ( Dom n ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { node_normalize( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { node_normalize( n ); } finally { l.exit(); } } - } - - public static void node_normalize ( Dom n ) - { - switch ( n.nodeType() ) - { - case TEXT : - case CDATA : - case PROCINST : - case COMMENT : - return; - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - case ELEMENT : - case DOCUMENT : - case DOCFRAG : - case ATTR : - break; - } - - Cur c = n.tempCur(); - - c.push(); - - do - { - c.nextWithAttrs(); - - CharNode cn = c.getCharNodes(); - - if (cn != null) - { - if (!c.isText()) - { - while ( cn != null ) - { - cn.setChars( null, 0, 0 ); - cn = CharNode.remove( cn, cn ); - } - } - else if (cn._next != null) - { - while ( cn._next != null ) - { - cn.setChars( null, 0, 0 ); - cn = CharNode.remove( cn, cn._next ); - } - - cn._cch = Integer.MAX_VALUE; - } - - c.setCharNodes( cn ); - } - } - while ( ! c.isAtEndOfLastPush() ); - - c.release(); - - n.locale().invalidateDomCaches(n); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _node_hasChildNodes ( Dom n ) - { - // TODO - make this faster - return _node_getFirstChild( n ) != null; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_appendChild ( Dom p, Node newChild ) - { - return _node_insertBefore( p, newChild, null ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_replaceChild ( Dom p, Node newChild, Node oldChild ) - { - Locale l = p.locale(); - - if (newChild == null) - throw new IllegalArgumentException( "Child to add is null" ); - - if (oldChild == null) - throw new NotFoundErr( "Child to replace is null" ); - - Dom nc; - - if (!(newChild instanceof Dom) || (nc = (Dom) newChild).locale() != l) - throw new WrongDocumentErr( "Child to add is from another document" ); - - Dom oc = null; - - if (!(oldChild instanceof Dom) || (oc = (Dom) oldChild).locale() != l) - throw new WrongDocumentErr( "Child to replace is from another document" ); - - Dom d; - - if (l.noSync()) { l.enter(); try { d = node_replaceChild( p, nc, oc ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { d = node_replaceChild( p, nc, oc ); } finally { l.exit(); } } - - return (Node) d; - } - - public static Dom node_replaceChild ( Dom p, Dom newChild, Dom oldChild ) - { - // Remove the old child firest to avoid a dom exception raised - // when inserting two document elements - - Dom nextNode = node_getNextSibling( oldChild ); - - node_removeChild( p, oldChild ); - - try - { - node_insertBefore( p, newChild, nextNode ); - } - catch ( DOMException e ) - { - node_insertBefore( p, oldChild, nextNode ); - - throw e; - } - - return oldChild; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_insertBefore ( Dom p, Node newChild, Node refChild ) - { - Locale l = p.locale(); - - if (newChild == null) - throw new IllegalArgumentException( "Child to add is null" ); - - Dom nc; - - if (!(newChild instanceof Dom) || (nc = (Dom) newChild).locale() != l) - throw new WrongDocumentErr( "Child to add is from another document" ); - - Dom rc = null; - - if (refChild != null) - { - if (!(refChild instanceof Dom) || (rc = (Dom) refChild).locale() != l) - throw new WrongDocumentErr( "Reference child is from another document" ); - } - - Dom d; - - if (l.noSync()) { l.enter(); try { d = node_insertBefore( p, nc, rc ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { d = node_insertBefore( p, nc, rc ); } finally { l.exit(); } } - - return (Node) d; - } - - public static Dom node_insertBefore ( Dom p, Dom nc, Dom rc ) - { - assert nc != null; - - // Inserting self before self is a no-op - - if (nc == rc) - return nc; - - if (rc != null && parent( rc ) != p) - throw new NotFoundErr( "RefChild is not a child of this node" ); - - // TODO - obey readonly status of a substree - - int nck = nc.nodeType(); - - if (nck == DOCFRAG) - { - for ( Dom c = firstChild( nc ) ; c != null ; c = nextSibling( c ) ) - validateNewChild( p, c ); - - for ( Dom c = firstChild( nc ) ; c != null ; ) - { - Dom n = nextSibling( c ); - - if (rc == null) - append( c, p ); - else - insert( c, rc ); - - c = n; - } - - return nc; - } - - // - // Make sure the new child is allowed here - // - - validateNewChild( p, nc ); - - // - // Orphan the child before establishing a new parent - // - - remove( nc ); - - int pk = p.nodeType(); - - // Only these nodes can be modifiable parents - assert pk == ATTR || pk == DOCFRAG || pk == DOCUMENT || pk == ELEMENT; - - switch ( nck ) - { - case ELEMENT : - case COMMENT : - case PROCINST : - { - if (rc == null) - { - Cur cTo = p.tempCur(); - cTo.toEnd(); - Cur.moveNode( (Xobj) nc, cTo ); - cTo.release(); - } - else - { - int rck = rc.nodeType(); - - if (rck == TEXT || rck == CDATA) - { - // Quick and dirty impl.... - - ArrayList charNodes = new ArrayList(); - - while ( rc != null && (rc.nodeType() == TEXT || rc.nodeType() == CDATA ) ) - { - Dom next = nextSibling( rc ); - charNodes.add( remove( rc ) ); - rc = next; - } - - if (rc == null) - append( nc, p ); - else - insert( nc, rc ); - - rc = nextSibling( nc ); - - for ( int i = 0 ; i < charNodes.size() ; i++ ) - { - Dom n = (Dom) charNodes.get( i ); - - if (rc == null) - append( n, p ); - else - insert( n, rc ); - } - } - else if (rck == ENTITYREF) - { - throw new RuntimeException( "Not implemented" ); - } - else - { - assert rck == ELEMENT || rck == PROCINST || rck == COMMENT; - Cur cTo = rc.tempCur(); - Cur.moveNode( (Xobj) nc, cTo ); - cTo.release(); - } - } - - break; - } - - case TEXT : - case CDATA : - { - CharNode n = (CharNode) nc; - - assert n._prev == null && n._next == null; - - CharNode refCharNode = null; - Cur c = p.tempCur(); - - if (rc == null) - c.toEnd(); - else - { - int rck = rc.nodeType(); - - if (rck == TEXT || rck == CDATA) - c.moveToCharNode( refCharNode = (CharNode) rc ); - else if (rck == ENTITYREF) - throw new RuntimeException( "Not implemented" ); - else - c.moveToDom( rc ); - } - - CharNode nodes = c.getCharNodes(); - - nodes = CharNode.insertNode( nodes, n, refCharNode ); - - c.insertChars( n._src, n._off, n._cch ); - - c.setCharNodes( nodes ); - - c.release(); - - break; - } - - case ENTITYREF : - { - throw new RuntimeException( "Not implemented" ); - } - - case DOCTYPE : - { - // TODO - don't actually insert this here, associate it with the - // doc?? Hmm .. Perhaps I should disallow insertion into the tree - // at all. - - throw new RuntimeException( "Not implemented" ); - } - - default : throw new RuntimeException( "Unexpected child node type" ); - } - - return nc; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_removeChild ( Dom p, Node child ) - { - Locale l = p.locale(); - - if (child == null) - throw new NotFoundErr( "Child to remove is null" ); - - Dom c; - - if (!(child instanceof Dom) || (c = (Dom) child).locale() != l) - throw new WrongDocumentErr( "Child to remove is from another document" ); - - Dom d; - - if (l.noSync()) { l.enter(); try { d = node_removeChild( p, c ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { d = node_removeChild( p, c ); } finally { l.exit(); } } - - return (Node) d; - } - - public static Dom node_removeChild ( Dom parent, Dom child ) - { - if (parent( child ) != parent) - throw new NotFoundErr( "Child to remove is not a child of given parent" ); - - switch ( child.nodeType() ) - { - case DOCUMENT : - case DOCFRAG : - case ATTR : - throw new IllegalStateException(); - - case ELEMENT : - case PROCINST : - case COMMENT : - removeNode( child ); - break; - - case TEXT : - case CDATA : - { - Cur c = child.tempCur(); - - CharNode nodes = c.getCharNodes(); - - CharNode cn = (CharNode) child; - - assert cn._src instanceof Dom; - - cn.setChars( c.moveChars( null, cn._cch ), c._offSrc, c._cchSrc ); - - c.setCharNodes( CharNode.remove( nodes, cn ) ); - - c.release(); - - break; - } - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - default : throw new RuntimeException( "Unknown kind" ); - } - - return child; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _node_cloneNode ( Dom n, boolean deep ) - { - Locale l = n.locale(); - - Dom c; - - if (l.noSync()) { l.enter(); try { c = node_cloneNode( n, deep ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { c = node_cloneNode( n, deep ); } finally { l.exit(); } } - - return (Node) c; - } - - public static Dom node_cloneNode ( Dom n, boolean deep ) - { - Locale l = n.locale(); - - Dom clone = null; - - if (!deep) - { - Cur shallow = null; - - switch ( n.nodeType() ) - { - case DOCUMENT : - shallow = l.tempCur(); - shallow.createDomDocumentRoot(); - break; - - case DOCFRAG : - shallow = l.tempCur(); - shallow.createDomDocFragRoot(); - break; - - case ELEMENT : - { - shallow = l.tempCur(); - shallow.createElement( n.getQName() ); - - Element elem = (Element) shallow.getDom(); - NamedNodeMap attrs = ((Element) n).getAttributes(); - - for ( int i = 0 ; i < attrs.getLength() ; i++ ) - elem.setAttributeNodeNS( (Attr) attrs.item( i ).cloneNode( true ) ); - - break; - } - - case ATTR : - shallow = l.tempCur(); - shallow.createAttr( n.getQName() ); - break; - - case PROCINST : - case COMMENT : - case TEXT : - case CDATA : - case ENTITYREF : - case ENTITY : - case DOCTYPE : - case NOTATION : - break; - } - - if (shallow != null) - { - clone = shallow.getDom(); - shallow.release(); - } - } - - if (clone == null) - { - switch ( n.nodeType() ) - { - case DOCUMENT : - case DOCFRAG : - case ATTR : - case ELEMENT : - case PROCINST : - case COMMENT : - { - Cur cClone = l.tempCur(); - Cur cSrc = n.tempCur(); - cSrc.copyNode( cClone ); - clone = cClone.getDom(); - cClone.release(); - cSrc.release(); - - break; - } - - case TEXT : - case CDATA : - { - Cur c = n.tempCur(); - - CharNode cn = n.nodeType() == TEXT ? l.createTextNode() : l.createCdataNode(); - - cn.setChars( c.getChars( ((CharNode) n)._cch ), c._offSrc, c._cchSrc ); - - clone = cn; - - c.release(); - - break; - } - - case ENTITYREF : - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - default : throw new RuntimeException( "Unknown kind" ); - } - } - - return clone; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getLocalName ( Dom n ) - { - if (! n.nodeCanHavePrefixUri() ) return null; - QName name = n.getQName(); - return name == null ? "" : name.getLocalPart(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getNamespaceURI ( Dom n ) - { - if (! n.nodeCanHavePrefixUri() ) return null; - QName name = n.getQName(); - // TODO - should return the correct namespace for xmlns ... - return name == null ? "": - //name.getNamespaceURI().equals("")? null: - name.getNamespaceURI(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _node_setPrefix ( Dom n, String prefix ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { node_setPrefix( n, prefix ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { node_setPrefix( n, prefix ); } finally { l.exit(); } } - } - - public static void node_setPrefix ( Dom n, String prefix ) - { - // TODO - make it possible to set the prefix of an xmlns - // TODO - test to make use prefix: xml maps to the predefined namespace - // if set???? hmmm ... perhaps I should not allow the setting of any - // prefixes which start with xml unless the namespace is the predefined - // one and the prefix is 'xml' all other prefixes which start with - // 'xml' should fail. - - if (n.nodeType() == ELEMENT || n.nodeType() == ATTR) - { - Cur c = n.tempCur(); - QName name = c.getName(); - String uri = name.getNamespaceURI(); - String local = name.getLocalPart(); - - prefix = validatePrefix( prefix, uri, local, n.nodeType() == ATTR ); - - c.setName( n.locale().makeQName( uri, local, prefix ) ); - - c.release(); - } - else - validatePrefix( prefix, "", "", false ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getPrefix ( Dom n ) - { - if (! n.nodeCanHavePrefixUri() ) return null; - QName name = n.getQName(); - return name == null ? "" : - name.getPrefix(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getNodeName ( Dom n ) - { - switch ( n.nodeType() ) - { - case CDATA : return "#cdata-section"; - case COMMENT : return "#comment"; - case DOCFRAG : return "#document-fragment"; - case DOCUMENT : return "#document"; - case PROCINST : return n.getQName().getLocalPart(); - case TEXT : return "#text"; - - case ATTR : - case ELEMENT : - { - QName name = n.getQName(); - String prefix = name.getPrefix(); - return prefix.length() == 0 ? name.getLocalPart() : prefix + ":" + name.getLocalPart(); - } - - case DOCTYPE : - case ENTITY : - case ENTITYREF : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - default : throw new RuntimeException( "Unknown node type" ); - } - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static short _node_getNodeType ( Dom n ) - { - return (short) n.nodeType(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _node_setNodeValue ( Dom n, String nodeValue ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { node_setNodeValue( n, nodeValue ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { node_setNodeValue( n, nodeValue ); } finally { l.exit(); } } - } - - public static void node_setNodeValue ( Dom n, String nodeValue ) - { - if (nodeValue == null) - nodeValue = ""; - - switch ( n.nodeType() ) - { - case TEXT : - case CDATA : - { - CharNode cn = (CharNode) n; - - Cur c; - - if ((c = cn.tempCur()) != null) - { - c.moveChars( null, cn._cch ); - cn._cch = nodeValue.length(); - c.insertString( nodeValue ); - c.release(); - } - else - cn.setChars( nodeValue, 0, nodeValue.length() ); - - break; - } - - case ATTR : - { - // Try to set an exisiting text node to contain the new value - - NodeList children = ((Node) n).getChildNodes(); - - while ( children.getLength() > 1 ) - node_removeChild( n, (Dom) children.item( 1 ) ); - - if (children.getLength() == 0) - { - TextNode tn = n.locale().createTextNode(); - tn.setChars( nodeValue, 0, nodeValue.length() ); - node_insertBefore( n, tn, null ); - } - else - { - assert children.getLength() == 1; - children.item( 0 ).setNodeValue( nodeValue ); - } - if (((Xobj.AttrXobj) n).isId()) - { - Dom d = DomImpl.node_getOwnerDocument(n); - String val = node_getNodeValue(n); - if (d instanceof Xobj.DocumentXobj) - { - ((Xobj.DocumentXobj) d).removeIdElement(val); - ((Xobj.DocumentXobj) d).addIdElement(nodeValue, - attr_getOwnerElement(n)); - } - } - - break; - } - - case PROCINST : - case COMMENT : - { - Cur c = n.tempCur(); - c.next(); - - c.getChars( -1 ); - c.moveChars( null, c._cchSrc ); - c.insertString( nodeValue ); - - c.release(); - - break; - } - } - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getNodeValue ( Dom n ) - { - Locale l = n.locale(); - - if (l.noSync()) { return node_getNodeValue( n ); } - else synchronized ( l ) { return node_getNodeValue( n ); } - } - - public static String node_getNodeValue ( Dom n ) - { - String s = null; - - switch ( n.nodeType() ) - { - case ATTR : - case PROCINST : - case COMMENT : - { - s = ((Xobj)n).getValueAsString(); - break; - } - - case TEXT : - case CDATA : - { - assert n instanceof CharNode: "Text/CData should be a CharNode"; - CharNode node = (CharNode) n; - if (! (node._src instanceof Xobj) ) - s = CharUtil.getString( node._src, node._off, node._cch ); - else{ - Xobj src = (Xobj) node._src; - src.ensureOccupancy(); - boolean isThisNodeAfterText = node.isNodeAftertext(); - if( isThisNodeAfterText ){ - src._charNodesAfter = - Cur.updateCharNodes( src._locale, src, src._charNodesAfter, src._cchAfter ); - s = src.getCharsAfterAsString(node._off, node._cch); - } - else{ - src._charNodesValue = - Cur.updateCharNodes( src._locale, src, src._charNodesValue, src._cchValue ); - s = src.getCharsValueAsString(node._off, node._cch); - } - - } - break; - } - } - - return s; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Object _node_getUserData ( Dom n, String key ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Object _node_setUserData ( Dom n, String key, Object data, UserDataHandler handler ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Object _node_getFeature ( Dom n, String feature, String version ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _node_isEqualNode ( Dom n, Node arg ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _node_isSameNode ( Dom n, Node arg ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_lookupNamespaceURI ( Dom n, String prefix ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _node_isDefaultNamespace ( Dom n, String namespaceURI ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_lookupPrefix ( Dom n, String namespaceURI ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _node_setTextContent ( Dom n, String textContent ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getTextContent ( Dom n ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static short _node_compareDocumentPosition ( Dom n, Node other ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _node_getBaseURI ( Dom n ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _childNodes_item ( Dom n, int i ) - { - Locale l = n.locale(); - - Dom d; - if (i == 0) return _node_getFirstChild(n); - if (l.noSync()) { d = childNodes_item( n, i ); } - else synchronized ( l ) { d = childNodes_item( n, i ); } - - return (Node) d; - } - - public static Dom childNodes_item ( Dom n, int i ) - { - if (i < 0) - return null; - - switch ( n.nodeType() ) - { - case TEXT : - case CDATA : - case PROCINST : - case COMMENT : - return null; - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - case ELEMENT : - case DOCUMENT : - case DOCFRAG : - case ATTR : - break; - } - if ( i == 0 ) - return node_getFirstChild ( n ); - return n.locale().findDomNthChild(n, i); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static int _childNodes_getLength ( Dom n ) - { - Locale l = n.locale(); - assert n instanceof Xobj; - int count; - Xobj node = (Xobj) n; - if (!node.isVacant() && - (count = node.getDomZeroOneChildren()) < 2) - return count; - if (l.noSync()) { return childNodes_getLength( n ); } - else synchronized ( l ) { return childNodes_getLength( n ); } - } - - public static int childNodes_getLength ( Dom n ) - { - switch ( n.nodeType() ) - { - case TEXT : - case CDATA : - case PROCINST : - case COMMENT : - return 0; - - case ENTITYREF : - throw new RuntimeException( "Not impl" ); - - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - case ELEMENT : - case DOCUMENT : - case DOCFRAG : - case ATTR : - break; - } - - int count; - assert n instanceof Xobj; - Xobj node = (Xobj) n; - node.ensureOccupancy(); - if ((count = node.getDomZeroOneChildren()) < 2) - return count; - return n.locale().domLength(n); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _element_getTagName ( Dom e ) - { - return _node_getNodeName( e ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _element_getAttributeNode ( Dom e, String name ) - { - return (Attr) _attributes_getNamedItem( e, name ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _element_getAttributeNodeNS ( Dom e, String uri, String local ) - { - return (Attr) _attributes_getNamedItemNS( e, uri, local ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _element_setAttributeNode ( Dom e, Attr newAttr ) - { - return (Attr) _attributes_setNamedItem( e, newAttr ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _element_setAttributeNodeNS ( Dom e, Attr newAttr ) - { - return (Attr) _attributes_setNamedItemNS( e, newAttr ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _element_getAttribute ( Dom e, String name ) - { - Node a = _attributes_getNamedItem( e, name ); - return a == null ? "" : a.getNodeValue(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _element_getAttributeNS ( Dom e, String uri, String local ) - { - Node a = _attributes_getNamedItemNS( e, uri, local ); - return a == null ? "" : a.getNodeValue(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _element_hasAttribute ( Dom e, String name ) - { - return _attributes_getNamedItem( e, name ) != null; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _element_hasAttributeNS ( Dom e, String uri, String local ) - { - return _attributes_getNamedItemNS( e, uri, local ) != null; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _element_removeAttribute ( Dom e, String name ) - { - try - { - _attributes_removeNamedItem( e, name ); - } - catch ( NotFoundErr ex ) - { - } - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _element_removeAttributeNS ( Dom e, String uri, String local ) - { - try - { - _attributes_removeNamedItemNS( e, uri, local ); - } - catch ( NotFoundErr ex ) - { - } - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Attr _element_removeAttributeNode ( Dom e, Attr oldAttr ) - { - if (oldAttr == null) - throw new NotFoundErr( "Attribute to remove is null" ); - - if (oldAttr.getOwnerElement() != e) - throw new NotFoundErr( "Attribute to remove does not belong to this element" ); - - return (Attr) _attributes_removeNamedItem( e, oldAttr.getNodeName() ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _element_setAttribute ( Dom e, String name, String value ) - { - // TODO - validate all attr/element names in all apprpraite - // methdos - - Locale l = e.locale(); - - if (l.noSync()) { l.enter(); try { element_setAttribute( e, name, value ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { element_setAttribute( e, name, value ); } finally { l.exit(); } } - } - - public static void element_setAttribute ( Dom e, String name, String value ) - { - Dom a = attributes_getNamedItem( e, name ); - - if (a == null) - { - a = document_createAttribute( node_getOwnerDocument( e ), name ); - attributes_setNamedItem( e, a ); - } - - node_setNodeValue( a, value ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _element_setAttributeNS ( Dom e, String uri, String qname, String value ) - { - Locale l = e.locale(); - - if (l.noSync()) { l.enter(); try { element_setAttributeNS( e, uri, qname, value ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { element_setAttributeNS( e, uri, qname, value ); } finally { l.exit(); } } - } - - public static void element_setAttributeNS ( Dom e, String uri, String qname, String value ) - { - validateQualifiedName( qname, uri, true ); - - QName name = e.locale().makeQualifiedQName( uri, qname ); - String local = name.getLocalPart(); - String prefix = validatePrefix( name.getPrefix(), uri, local, true ); - - Dom a = attributes_getNamedItemNS( e, uri, local ); - - if (a == null) - { - a = document_createAttributeNS( node_getOwnerDocument( e ), uri, local ); - attributes_setNamedItemNS( e, a ); - } - - node_setPrefix( a, prefix ); - node_setNodeValue( a, value ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static NodeList _element_getElementsByTagName ( Dom e, String name ) - { - Locale l = e.locale(); - - if (l.noSync()) { l.enter(); try { return element_getElementsByTagName( e, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return element_getElementsByTagName( e, name ); } finally { l.exit(); } } - - } - public static NodeList element_getElementsByTagName ( Dom e, String name ) - { - return new ElementsByTagNameNodeList( e, name ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static NodeList _element_getElementsByTagNameNS ( Dom e, String uri, String local ) - { - Locale l = e.locale(); - - if (l.noSync()) { l.enter(); try { return element_getElementsByTagNameNS( e, uri, local ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return element_getElementsByTagNameNS( e, uri, local ); } finally { l.exit(); } } - } - - public static NodeList element_getElementsByTagNameNS ( Dom e, String uri, String local ) - { - return new ElementsByTagNameNSNodeList( e, uri, local ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static int _attributes_getLength ( Dom e ) - { - Locale l = e.locale(); - - if (l.noSync()) { l.enter(); try { return attributes_getLength( e ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return attributes_getLength( e ); } finally { l.exit(); } } - } - - public static int attributes_getLength ( Dom e ) - { - int n = 0; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - n++; - - c.release(); - - return n; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_setNamedItem ( Dom e, Node attr ) - { - Locale l = e.locale(); - - if (attr == null) - throw new IllegalArgumentException( "Attr to set is null" ); - - Dom a; - - if (!(attr instanceof Dom) || (a = (Dom) attr).locale() != l) - throw new WrongDocumentErr( "Attr to set is from another document" ); - - Dom oldA; - - if (l.noSync()) { l.enter(); try { oldA = attributes_setNamedItem( e, a ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { oldA = attributes_setNamedItem( e, a ); } finally { l.exit(); } } - - return (Node) oldA; - } - - public static Dom attributes_setNamedItem ( Dom e, Dom a ) - { - if (attr_getOwnerElement( a ) != null) - throw new InuseAttributeError(); - - if (a.nodeType() != ATTR) - throw new HierarchyRequestErr( "Node is not an attribute" ); - - String name = _node_getNodeName( a ); - Dom oldAttr = null; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - { - Dom aa = c.getDom(); - - if (_node_getNodeName( aa ).equals( name )) - { - if (oldAttr == null) - oldAttr = aa; - else - { - removeNode( aa ); - c.toPrevAttr(); - } - } - } - - if (oldAttr == null) - { - c.moveToDom( e ); - c.next(); - Cur.moveNode( (Xobj) a, c ); - } - else - { - c.moveToDom( oldAttr ); - Cur.moveNode( (Xobj) a, c ); - removeNode( oldAttr ); - } - - c.release(); - - return oldAttr; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_getNamedItem ( Dom e, String name ) - { - Locale l = e.locale(); - - Dom n; - - if (l.noSync()) { l.enter(); try { n = attributes_getNamedItem( e, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { n = attributes_getNamedItem( e, name ); } finally { l.exit(); } } - - return (Node) n; - } - - public static Dom attributes_getNamedItem ( Dom e, String name ) - { - Dom a = null; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - { - Dom d = c.getDom(); - - if (_node_getNodeName( d ).equals( name )) - { - a = d; - break; - } - } - - c.release(); - - return a; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_getNamedItemNS ( Dom e, String uri, String local ) - { - Locale l = e.locale(); - - Dom n; - - if (l.noSync()) { l.enter(); try { n = attributes_getNamedItemNS( e, uri, local ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { n = attributes_getNamedItemNS( e, uri, local ); } finally { l.exit(); } } - - return (Node) n; - } - - public static Dom attributes_getNamedItemNS ( Dom e, String uri, String local ) - { - if (uri == null) - uri = ""; - - Dom a = null; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - { - Dom d = c.getDom(); - - QName n = d.getQName(); - - if (n.getNamespaceURI().equals( uri ) && n.getLocalPart().equals( local )) - { - a = d; - break; - } - } - - c.release(); - - return a; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_removeNamedItem ( Dom e, String name ) - { - Locale l = e.locale(); - - Dom n; - - if (l.noSync()) { l.enter(); try { n = attributes_removeNamedItem( e, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { n = attributes_removeNamedItem( e, name ); } finally { l.exit(); } } - - return (Node) n; - } - - public static Dom attributes_removeNamedItem ( Dom e, String name ) - { - Dom oldAttr = null; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - { - Dom aa = c.getDom(); - - if (_node_getNodeName(aa).equals(name)) - { - if (oldAttr == null) - oldAttr = aa; - - if (((Xobj.AttrXobj) aa).isId()) - { - Dom d = DomImpl.node_getOwnerDocument(aa); - String val = node_getNodeValue( aa ); - if (d instanceof Xobj.DocumentXobj) - ((Xobj.DocumentXobj) d).removeIdElement(val); - } - removeNode(aa); - c.toPrevAttr(); - } - } - - c.release(); - - if (oldAttr == null) - throw new NotFoundErr( "Named item not found: " + name ); - - return oldAttr; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_removeNamedItemNS ( Dom e, String uri, String local ) - { - Locale l = e.locale(); - - Dom n; - - if (l.noSync()) { l.enter(); try { n = attributes_removeNamedItemNS( e, uri, local ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { n = attributes_removeNamedItemNS( e, uri, local ); } finally { l.exit(); } } - - return (Node) n; - } - - public static Dom attributes_removeNamedItemNS ( Dom e, String uri, String local ) - { - if (uri == null) - uri = ""; - - Dom oldAttr = null; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - { - Dom aa = c.getDom(); - - QName qn = aa.getQName(); - - if (qn.getNamespaceURI().equals( uri ) && qn.getLocalPart().equals( local )) - { - if (oldAttr == null) - oldAttr = aa; - if (((Xobj.AttrXobj) aa).isId()) - { - Dom d = DomImpl.node_getOwnerDocument(aa); - String val = node_getNodeValue( aa ); - if (d instanceof Xobj.DocumentXobj) - ((Xobj.DocumentXobj) d).removeIdElement(val); - } - removeNode( aa ); - - c.toPrevAttr(); - } - } - - c.release(); - - if (oldAttr == null) - throw new NotFoundErr( "Named item not found: uri=" + uri + ", local=" + local ); - - return oldAttr; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_setNamedItemNS ( Dom e, Node attr ) - { - Locale l = e.locale(); - - if (attr == null) - throw new IllegalArgumentException( "Attr to set is null" ); - - Dom a; - - if (!(attr instanceof Dom) || (a = (Dom) attr).locale() != l) - throw new WrongDocumentErr( "Attr to set is from another document" ); - - Dom oldA; - - if (l.noSync()) { l.enter(); try { oldA = attributes_setNamedItemNS( e, a ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { oldA = attributes_setNamedItemNS( e, a ); } finally { l.exit(); } } - - return (Node) oldA; - } - - public static Dom attributes_setNamedItemNS ( Dom e, Dom a ) - { - Dom owner = attr_getOwnerElement( a ); - - if (owner == e) - return a; - - if (owner != null) - throw new InuseAttributeError(); - - if (a.nodeType() != ATTR) - throw new HierarchyRequestErr( "Node is not an attribute" ); - - QName name = a.getQName(); - Dom oldAttr = null; - - Cur c = e.tempCur(); - - while ( c.toNextAttr() ) - { - Dom aa = c.getDom(); - - if (aa.getQName().equals( name )) - { - if (oldAttr == null) - oldAttr = aa; - else - { - removeNode( aa ); - c.toPrevAttr(); - } - } - } - - if (oldAttr == null) - { - c.moveToDom( e ); - c.next(); - Cur.moveNode( (Xobj) a, c ); - } - else - { - c.moveToDom( oldAttr ); - Cur.moveNode( (Xobj) a, c ); - removeNode( oldAttr ); - } - - c.release(); - - return oldAttr; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Node _attributes_item ( Dom e, int index ) - { - Locale l = e.locale(); - - Dom a; - - if (l.noSync()) { l.enter(); try { a = attributes_item( e, index ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { a = attributes_item( e, index ); } finally { l.exit(); } } - - return (Node) a; - } - - public static Dom attributes_item ( Dom e, int index ) - { - if (index < 0) - return null; - - Cur c = e.tempCur(); - - Dom a = null; - - while ( c.toNextAttr() ) - { - if (index-- == 0) - { - a = c.getDom(); - break; - } - } - - c.release(); - - return a; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _processingInstruction_getData ( Dom p ) - { - return _node_getNodeValue( p ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _processingInstruction_getTarget ( Dom p ) - { - return _node_getNodeName( p ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _processingInstruction_setData ( Dom p, String data ) - { - _node_setNodeValue( p, data ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _attr_getSpecified ( Dom a ) - { - // Can't tell the difference - return true; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Element _attr_getOwnerElement ( Dom a ) - { - Locale l = a.locale(); - - Dom e; - - if (l.noSync()) { l.enter(); try { e = attr_getOwnerElement( a ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { e = attr_getOwnerElement( a ); } finally { l.exit(); } } - - return (Element) e; - } - - public static Dom attr_getOwnerElement ( Dom n ) - { - Cur c = n.tempCur(); - - if (!c.toParentRaw()) - { - c.release(); - return null; - } - - Dom p = c.getDom(); - - c.release(); - - return p; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _characterData_appendData ( Dom cd, String arg ) - { - // TODO - fix this *really* cheesy/bad/lousy perf impl - // also fix all the funcitons which follow - - if (arg != null && arg.length() != 0) - _node_setNodeValue( cd, _node_getNodeValue( cd ) + arg ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _characterData_deleteData ( Dom c, int offset, int count ) - { - String s = _characterData_getData( c ); - - if (offset < 0 || offset > s.length() || count < 0) - throw new IndexSizeError(); - - if (offset + count > s.length()) - count = s.length() - offset; - - if (count > 0) - _characterData_setData( c, s.substring( 0, offset ) + s.substring( offset + count ) ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _characterData_getData ( Dom c ) - { - return _node_getNodeValue( c ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static int _characterData_getLength ( Dom c ) - { - return _characterData_getData( c ).length(); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _characterData_insertData ( Dom c, int offset, String arg ) - { - String s = _characterData_getData( c ); - - if (offset < 0 || offset > s.length()) - throw new IndexSizeError(); - - if (arg != null && arg.length() > 0) - _characterData_setData( c, s.substring( 0, offset ) + arg + s.substring( offset ) ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _characterData_replaceData ( Dom c, int offset, int count, String arg ) - { - String s = _characterData_getData( c ); - - if (offset < 0 || offset > s.length() || count < 0) - throw new IndexSizeError(); - - if (offset + count > s.length()) - count = s.length() - offset; - - if (count > 0) - { - _characterData_setData( - c, s.substring( 0, offset ) + (arg == null ? "" : arg) - + s.substring( offset + count ) ); - } - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static void _characterData_setData ( Dom c, String data ) - { - _node_setNodeValue( c, data ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _characterData_substringData ( Dom c, int offset, int count ) - { - String s = _characterData_getData( c ); - - if (offset < 0 || offset > s.length() || count < 0) - throw new IndexSizeError(); - - if (offset + count > s.length()) - count = s.length() - offset; - - return s.substring( offset, offset + count ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Text _text_splitText ( Dom t, int offset ) - { - assert t.nodeType() == TEXT; - - String s = _characterData_getData( t ); - - if (offset < 0 || offset > s.length()) - throw new IndexSizeError(); - - _characterData_deleteData( t, offset, s.length() - offset ); - - // Don't need to pass a doc here, any node will do.. - - Dom t2 = (Dom) _document_createTextNode( t, s.substring( offset ) ); - - Dom p = (Dom) _node_getParentNode( t ); - - if (p != null) - { - _node_insertBefore( p, (Text) t2, _node_getNextSibling( t ) ); - t.locale().invalidateDomCaches(p); - } - - return (Text) t2; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static String _text_getWholeText ( Dom t ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static boolean _text_isElementContentWhitespace ( Dom t ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static Text _text_replaceWholeText ( Dom t, String content ) - { - throw new RuntimeException( "DOM Level 3 Not implemented" ); - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static XMLStreamReader _getXmlStreamReader ( Dom n ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { return getXmlStreamReader( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return getXmlStreamReader( n ); } finally { l.exit(); } } - } - - public static XMLStreamReader getXmlStreamReader ( Dom n ) - { - XMLStreamReader xs; - - switch ( n.nodeType() ) - { - case DOCUMENT : - case DOCFRAG : - case ATTR : - case ELEMENT : - case PROCINST : - case COMMENT : - { - Cur c = n.tempCur(); - xs = Jsr173.newXmlStreamReader( c, null ); - c.release(); - break; - } - - case TEXT : - case CDATA : - { - CharNode cn = (CharNode) n; - - Cur c; - - if ((c = cn.tempCur()) == null) - { - c = n.locale().tempCur(); - - xs = Jsr173.newXmlStreamReader( c, cn._src, cn._off, cn._cch ); - } - else - { - xs = - Jsr173.newXmlStreamReader( - c , c.getChars( cn._cch ), c._offSrc, c._cchSrc ); - - } - - c.release(); - - break; - } - - case ENTITYREF : - case ENTITY : - case DOCTYPE : - case NOTATION : - throw new RuntimeException( "Not impl" ); - - default : throw new RuntimeException( "Unknown kind" ); - } - - return xs; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static XmlCursor _getXmlCursor ( Dom n ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { return getXmlCursor( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return getXmlCursor( n ); } finally { l.exit(); } } - } - - public static XmlCursor getXmlCursor ( Dom n ) - { - Cur c = n.tempCur(); - - Cursor xc = new Cursor( c ); - - c.release(); - - return xc; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - public static XmlObject _getXmlObject ( Dom n ) - { - Locale l = n.locale(); - - if (l.noSync()) { l.enter(); try { return getXmlObject( n ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return getXmlObject( n ); } finally { l.exit(); } } - } - - public static XmlObject getXmlObject ( Dom n ) - { - Cur c = n.tempCur(); - - XmlObject x = c.getObject(); - - c.release(); - - return x; - } - - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////////// - - static abstract class CharNode implements Dom, Node, CharacterData - { - public CharNode ( Locale l ) - { - assert l != null; - - _locale = l; - } - - public QName getQName ( ) - { - return null; - } - - public Locale locale ( ) - { - assert isValid(); - - return _locale == null ? ((Dom) _src).locale() : _locale; - } - - public void setChars ( Object src, int off, int cch ) - { - assert CharUtil.isValid( src, off, cch ); - assert _locale != null || _src instanceof Dom; - - if (_locale == null) - _locale = ((Dom) _src).locale(); - - _src = src; - _off = off; - _cch = cch; - } - - public Dom getDom ( ) - { - assert isValid(); - - if (_src instanceof Dom) - return (Dom) _src; - - return null; - } - - public void setDom ( Dom d ) - { - assert d != null; - - _src = d; - _locale = null; - } - - public Cur tempCur ( ) - { - assert isValid(); - - if (!(_src instanceof Dom)) - return null; - - Cur c = locale().tempCur(); - c.moveToCharNode( this ); - - return c; - } - - private boolean isValid ( ) - { - if (_src instanceof Dom) - return _locale == null; - - if (_locale == null) - return false; - - return true; - } - - public static boolean isOnList ( CharNode nodes, CharNode node ) - { - assert node != null; - - for ( CharNode cn = nodes ; cn != null ; cn = cn._next ) - if (cn == node) - return true; - - return false; - } - - public static CharNode remove ( CharNode nodes, CharNode node ) - { - assert isOnList( nodes, node ); - - if (nodes == node) - nodes = node._next; - else - node._prev._next = node._next; - - if (node._next != null) - node._next._prev = node._prev; - - node._prev = node._next = null; - - return nodes; - } - - public static CharNode insertNode ( CharNode nodes, CharNode newNode, CharNode before ) - { - assert !isOnList( nodes, newNode ); - assert before == null || isOnList( nodes, before ); - assert newNode != null; - assert newNode._prev == null && newNode._next == null; - - if (nodes == null) - { - assert before == null; - nodes = newNode; - } - else if (nodes == before) - { - nodes._prev = newNode; - newNode._next = nodes; - nodes = newNode; - } - else - { - CharNode n = nodes; - - while ( n._next != before ) - n = n._next; - - if ((newNode._next = n._next) != null) - n._next._prev = newNode; - - newNode._prev = n; - n._next = newNode; - } - - return nodes; - } - - public static CharNode appendNode ( CharNode nodes, CharNode newNode ) - { - return insertNode( nodes, newNode, null ); - } - - public static CharNode appendNodes ( CharNode nodes, CharNode newNodes ) - { - assert newNodes != null; - assert newNodes._prev == null; - - if (nodes == null) - return newNodes; - - CharNode n = nodes; - - while ( n._next != null ) - n = n._next; - - n._next = newNodes; - newNodes._prev = n; - - return nodes; - } - - public static CharNode copyNodes ( CharNode nodes, Object newSrc ) - { - CharNode newNodes = null; - - for ( CharNode n = null ; nodes != null ; nodes = nodes._next ) - { - CharNode newNode; - - if (nodes instanceof TextNode) - newNode = nodes.locale().createTextNode(); - else - newNode = nodes.locale().createCdataNode(); - - // How to deal with entity refs?? - - newNode.setChars( newSrc, nodes._off, nodes._cch ); - - if (newNodes == null) - newNodes = newNode; - - if (n != null) - { - n._next = newNode; - newNode._prev = n; - } - - n = newNode; - } - - return newNodes; - } - - public boolean nodeCanHavePrefixUri() - { - return false; - } - - public boolean isNodeAftertext() - { - assert _src instanceof Xobj : - "this method is to only be used for nodes backed up by Xobjs"; - Xobj src =(Xobj) _src; - return src._charNodesValue == null ? true : - src._charNodesAfter == null ? false : - CharNode.isOnList(src._charNodesAfter, this); - } - public void dump ( PrintStream o, Object ref ) - { - if (_src instanceof Dom) - ((Dom) _src).dump( o, ref ); - else - o.println( "Lonely CharNode: \"" + CharUtil.getString( _src, _off, _cch ) + "\"" ); - } - - public void dump ( PrintStream o ) - { - dump( o, (Object) this ); - } - - public void dump ( ) - { - dump( System.out ); - } - - public Node appendChild ( Node newChild ) { return DomImpl._node_appendChild( this, newChild ); } - public Node cloneNode ( boolean deep ) { return DomImpl._node_cloneNode( this, deep ); } - public NamedNodeMap getAttributes ( ) { return null; } - public NodeList getChildNodes ( ) { return DomImpl._emptyNodeList; } - public Node getParentNode ( ) { return DomImpl._node_getParentNode( this ); } - public Node removeChild ( Node oldChild ) { return DomImpl._node_removeChild( this, oldChild ); } - public Node getFirstChild ( ) { return null; } - public Node getLastChild ( ) { return null; } - public String getLocalName ( ) { return DomImpl._node_getLocalName( this ); } - public String getNamespaceURI ( ) { return DomImpl._node_getNamespaceURI( this ); } - public Node getNextSibling ( ) { return DomImpl._node_getNextSibling( this ); } - public String getNodeName ( ) { return DomImpl._node_getNodeName( this ); } - public short getNodeType ( ) { return DomImpl._node_getNodeType( this ); } - public String getNodeValue ( ) { return DomImpl._node_getNodeValue( this ); } - public Document getOwnerDocument ( ) { return DomImpl._node_getOwnerDocument( this ); } - public String getPrefix ( ) { return DomImpl._node_getPrefix( this ); } - public Node getPreviousSibling ( ) { return DomImpl._node_getPreviousSibling( this ); } - public boolean hasAttributes ( ) { return false; } - public boolean hasChildNodes ( ) { return false; } - public Node insertBefore ( Node newChild, Node refChild ) { return DomImpl._node_insertBefore( this, newChild, refChild ); } - public boolean isSupported ( String feature, String version ) { return DomImpl._node_isSupported( this, feature, version ); } - public void normalize ( ) { DomImpl._node_normalize( this ); } - public Node replaceChild ( Node newChild, Node oldChild ) { return DomImpl._node_replaceChild( this, newChild, oldChild ); } - public void setNodeValue ( String nodeValue ) { DomImpl._node_setNodeValue( this, nodeValue ); } - public void setPrefix ( String prefix ) { DomImpl._node_setPrefix( this, prefix ); } - - // DOM Level 3 - public Object getUserData ( String key ) { return DomImpl._node_getUserData( this, key ); } - public Object setUserData ( String key, Object data, UserDataHandler handler ) { return DomImpl._node_setUserData( this, key, data, handler ); } - public Object getFeature ( String feature, String version ) { return DomImpl._node_getFeature( this, feature, version ); } - public boolean isEqualNode ( Node arg ) { return DomImpl._node_isEqualNode( this, arg ); } - public boolean isSameNode ( Node arg ) { return DomImpl._node_isSameNode( this, arg ); } - public String lookupNamespaceURI ( String prefix ) { return DomImpl._node_lookupNamespaceURI( this, prefix ); } - public String lookupPrefix ( String namespaceURI ) { return DomImpl._node_lookupPrefix( this, namespaceURI ); } - public boolean isDefaultNamespace ( String namespaceURI ) { return DomImpl._node_isDefaultNamespace( this, namespaceURI ); } - public void setTextContent ( String textContent ) { DomImpl._node_setTextContent( this, textContent ); } - public String getTextContent ( ) { return DomImpl._node_getTextContent( this ); } - public short compareDocumentPosition ( Node other ) { return DomImpl._node_compareDocumentPosition( this, other ); } - public String getBaseURI ( ) { return DomImpl._node_getBaseURI( this ); } - - public void appendData ( String arg ) { DomImpl._characterData_appendData( this, arg ); } - public void deleteData ( int offset, int count ) { DomImpl._characterData_deleteData( this, offset, count ); } - public String getData ( ) { return DomImpl._characterData_getData( this ); } - public int getLength ( ) { return DomImpl._characterData_getLength( this ); } - public void insertData ( int offset, String arg ) { DomImpl._characterData_insertData( this, offset, arg ); } - public void replaceData ( int offset, int count, String arg ) { DomImpl._characterData_replaceData( this, offset, count, arg ); } - public void setData ( String data ) { DomImpl._characterData_setData( this, data ); } - public String substringData ( int offset, int count ) { return DomImpl._characterData_substringData( this, offset, count ); } - - private Locale _locale; - - CharNode _next; - CharNode _prev; - - private Object _src; - - int _off; - int _cch; - } - - static class TextNode extends CharNode implements Text - { - TextNode ( Locale l ) - { - super( l ); - } - - public int nodeType ( ) { return DomImpl.TEXT; } - - public String name ( ) { return "#text"; } - - public Text splitText ( int offset ) { return DomImpl._text_splitText ( this, offset ); } - public String getWholeText ( ) { return DomImpl._text_getWholeText( this ); } - public boolean isElementContentWhitespace ( ) { return DomImpl._text_isElementContentWhitespace( this ); } - public Text replaceWholeText ( String content ) { return DomImpl._text_replaceWholeText( this, content ); } - } - - static class CdataNode extends TextNode implements CDATASection - { - CdataNode ( Locale l ) - { - super( l ); - } - - public int nodeType ( ) { return DomImpl.CDATA; } - - public String name ( ) { return "#cdata-section"; } - } - - static class SaajTextNode extends TextNode implements org.apache.xmlbeans.impl.soap.Text - { - SaajTextNode ( Locale l ) - { - super( l ); - } - - public boolean isComment ( ) { return DomImpl._soapText_isComment( this ); } - - public void detachNode ( ) { DomImpl._soapNode_detachNode( this ); } - public void recycleNode ( ) { DomImpl._soapNode_recycleNode( this ); } - public String getValue ( ) { return DomImpl._soapNode_getValue( this ); } - public void setValue ( String value ) { DomImpl._soapNode_setValue( this, value ); } - public SOAPElement getParentElement ( ) { return DomImpl._soapNode_getParentElement( this ); } - public void setParentElement ( SOAPElement p ) { DomImpl._soapNode_setParentElement( this, p ); } - } - - static class SaajCdataNode extends CdataNode implements org.apache.xmlbeans.impl.soap.Text - { - public SaajCdataNode ( Locale l ) - { - super( l ); - } - - public boolean isComment ( ) { return DomImpl._soapText_isComment( this ); } - - public void detachNode ( ) { DomImpl._soapNode_detachNode( this ); } - public void recycleNode ( ) { DomImpl._soapNode_recycleNode( this ); } - public String getValue ( ) { return DomImpl._soapNode_getValue( this ); } - public void setValue ( String value ) { DomImpl._soapNode_setValue( this, value ); } - public SOAPElement getParentElement ( ) { return DomImpl._soapNode_getParentElement( this ); } - public void setParentElement ( SOAPElement p ) { DomImpl._soapNode_setParentElement( this, p ); } - } - - // - // Soap Text Node - // - - public static boolean _soapText_isComment ( Dom n ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Text text = (org.apache.xmlbeans.impl.soap.Text) n; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapText_isComment( text ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapText_isComment( text ); } finally { l.exit(); } } - } - - // - // Soap Node - // - - public static void _soapNode_detachNode ( Dom n ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; - - if (l.noSync()) { l.enter(); try { l._saaj.soapNode_detachNode( node ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapNode_detachNode( node ); } finally { l.exit(); } } - } - - public static void _soapNode_recycleNode ( Dom n ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; - - if (l.noSync()) { l.enter(); try { l._saaj.soapNode_recycleNode( node ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapNode_recycleNode( node ); } finally { l.exit(); } } - } - - public static String _soapNode_getValue ( Dom n ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapNode_getValue( node ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapNode_getValue( node ); } finally { l.exit(); } } - } - - public static void _soapNode_setValue ( Dom n, String value ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; - - if (l.noSync()) { l.enter(); try { l._saaj.soapNode_setValue( node, value ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapNode_setValue( node, value ); } finally { l.exit(); } } - } - - public static SOAPElement _soapNode_getParentElement ( Dom n ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapNode_getParentElement( node ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapNode_getParentElement( node ); } finally { l.exit(); } } - } - - public static void _soapNode_setParentElement ( Dom n, SOAPElement p ) - { - Locale l = n.locale(); - - org.apache.xmlbeans.impl.soap.Node node = (org.apache.xmlbeans.impl.soap.Node) n; - - if (l.noSync()) { l.enter(); try { l._saaj.soapNode_setParentElement( node, p ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapNode_setParentElement( node, p ); } finally { l.exit(); } } - } - - // - // Soap Element - // - - public static void _soapElement_removeContents ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapElement_removeContents( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapElement_removeContents( se ); } finally { l.exit(); } } - } - - public static String _soapElement_getEncodingStyle ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getEncodingStyle( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getEncodingStyle( se ); } finally { l.exit(); } } - } - - public static void _soapElement_setEncodingStyle ( Dom d, String encodingStyle ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapElement_setEncodingStyle( se, encodingStyle ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapElement_setEncodingStyle( se, encodingStyle ); } finally { l.exit(); } } - } - - public static boolean _soapElement_removeNamespaceDeclaration ( Dom d, String prefix ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_removeNamespaceDeclaration( se, prefix ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_removeNamespaceDeclaration( se, prefix ); } finally { l.exit(); } } - } - - public static Iterator _soapElement_getAllAttributes ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getAllAttributes( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getAllAttributes( se ); } finally { l.exit(); } } - } - - public static Iterator _soapElement_getChildElements ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getChildElements( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getChildElements( se ); } finally { l.exit(); } } - } - - public static Iterator _soapElement_getNamespacePrefixes ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getNamespacePrefixes( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getNamespacePrefixes( se ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addAttribute ( Dom d, Name name, String value ) throws SOAPException - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addAttribute( se, name, value ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addAttribute( se, name, value ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addChildElement ( Dom d, SOAPElement oldChild ) throws SOAPException - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, oldChild ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, oldChild ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addChildElement ( Dom d, Name name ) throws SOAPException - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, name ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addChildElement ( Dom d, String localName ) throws SOAPException - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, localName ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, localName ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addChildElement ( Dom d, String localName, String prefix ) throws SOAPException - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, localName, prefix ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, localName, prefix ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addChildElement ( Dom d, String localName, String prefix, String uri ) throws SOAPException - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, localName, prefix, uri ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addChildElement( se, localName, prefix, uri ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addNamespaceDeclaration ( Dom d, String prefix, String uri ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addNamespaceDeclaration( se, prefix, uri ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addNamespaceDeclaration( se, prefix, uri ); } finally { l.exit(); } } - } - - public static SOAPElement _soapElement_addTextNode ( Dom d, String data ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_addTextNode( se, data ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_addTextNode( se, data ); } finally { l.exit(); } } - } - - public static String _soapElement_getAttributeValue ( Dom d, Name name ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getAttributeValue( se, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getAttributeValue( se, name ); } finally { l.exit(); } } - } - - public static Iterator _soapElement_getChildElements ( Dom d, Name name ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getChildElements( se, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getChildElements( se, name ); } finally { l.exit(); } } - } - - public static Name _soapElement_getElementName ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getElementName( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getElementName( se ); } finally { l.exit(); } } - } - - public static String _soapElement_getNamespaceURI ( Dom d, String prefix ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getNamespaceURI( se, prefix ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getNamespaceURI( se, prefix ); } finally { l.exit(); } } - } - - public static Iterator _soapElement_getVisibleNamespacePrefixes ( Dom d ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_getVisibleNamespacePrefixes( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_getVisibleNamespacePrefixes( se ); } finally { l.exit(); } } - } - - public static boolean _soapElement_removeAttribute ( Dom d, Name name ) - { - Locale l = d.locale(); - - SOAPElement se = (SOAPElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapElement_removeAttribute( se, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapElement_removeAttribute( se, name ); } finally { l.exit(); } } - } - - // - // Soap Envelope - // - - public static SOAPBody _soapEnvelope_addBody ( Dom d ) throws SOAPException - { - Locale l = d.locale(); - - SOAPEnvelope se = (SOAPEnvelope) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapEnvelope_addBody( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapEnvelope_addBody( se ); } finally { l.exit(); } } - } - - public static SOAPBody _soapEnvelope_getBody ( Dom d ) throws SOAPException - { - Locale l = d.locale(); - - SOAPEnvelope se = (SOAPEnvelope) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapEnvelope_getBody( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapEnvelope_getBody( se ); } finally { l.exit(); } } - } - - public static SOAPHeader _soapEnvelope_getHeader ( Dom d ) throws SOAPException - { - Locale l = d.locale(); - - SOAPEnvelope se = (SOAPEnvelope) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapEnvelope_getHeader( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapEnvelope_getHeader( se ); } finally { l.exit(); } } - } - - public static SOAPHeader _soapEnvelope_addHeader ( Dom d ) throws SOAPException - { - Locale l = d.locale(); - - SOAPEnvelope se = (SOAPEnvelope) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapEnvelope_addHeader( se ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapEnvelope_addHeader( se ); } finally { l.exit(); } } - } - - public static Name _soapEnvelope_createName ( Dom d, String localName ) - { - Locale l = d.locale(); - - SOAPEnvelope se = (SOAPEnvelope) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapEnvelope_createName( se, localName ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapEnvelope_createName( se, localName ); } finally { l.exit(); } } - } - - public static Name _soapEnvelope_createName ( Dom d, String localName, String prefix, String namespaceURI ) - { - Locale l = d.locale(); - - SOAPEnvelope se = (SOAPEnvelope) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapEnvelope_createName( se, localName, prefix, namespaceURI ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapEnvelope_createName( se, localName, prefix, namespaceURI ); } finally { l.exit(); } } - } - - // - // Soap Header - // - - public static Iterator soapHeader_examineAllHeaderElements ( Dom d ) - { - Locale l = d.locale(); - - SOAPHeader sh = (SOAPHeader) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeader_examineAllHeaderElements( sh ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeader_examineAllHeaderElements( sh ); } finally { l.exit(); } } - } - - public static Iterator soapHeader_extractAllHeaderElements ( Dom d ) - { - Locale l = d.locale(); - - SOAPHeader sh = (SOAPHeader) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeader_extractAllHeaderElements( sh ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeader_extractAllHeaderElements( sh ); } finally { l.exit(); } } - } - - public static Iterator soapHeader_examineHeaderElements ( Dom d, String actor ) - { - Locale l = d.locale(); - - SOAPHeader sh = (SOAPHeader) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeader_examineHeaderElements( sh, actor ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeader_examineHeaderElements( sh, actor ); } finally { l.exit(); } } - } - - public static Iterator soapHeader_examineMustUnderstandHeaderElements ( Dom d, String mustUnderstandString ) - { - Locale l = d.locale(); - - SOAPHeader sh = (SOAPHeader) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeader_examineMustUnderstandHeaderElements( sh, mustUnderstandString ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeader_examineMustUnderstandHeaderElements( sh, mustUnderstandString ); } finally { l.exit(); } } - } - - public static Iterator soapHeader_extractHeaderElements ( Dom d, String actor ) - { - Locale l = d.locale(); - - SOAPHeader sh = (SOAPHeader) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeader_extractHeaderElements( sh, actor ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeader_extractHeaderElements( sh, actor ); } finally { l.exit(); } } - } - - public static SOAPHeaderElement soapHeader_addHeaderElement ( Dom d, Name name ) - { - Locale l = d.locale(); - - SOAPHeader sh = (SOAPHeader) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeader_addHeaderElement( sh, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeader_addHeaderElement( sh, name ); } finally { l.exit(); } } - } - - // - // Soap Body - // - - public static boolean soapBody_hasFault ( Dom d ) - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_hasFault( sb ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_hasFault( sb ); } finally { l.exit(); } } - } - - public static SOAPFault soapBody_addFault ( Dom d ) throws SOAPException - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_addFault( sb ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_addFault( sb ); } finally { l.exit(); } } - } - - public static SOAPFault soapBody_getFault ( Dom d ) - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_getFault( sb ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_getFault( sb ); } finally { l.exit(); } } - } - - public static SOAPBodyElement soapBody_addBodyElement ( Dom d, Name name ) - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_addBodyElement( sb, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_addBodyElement( sb, name ); } finally { l.exit(); } } - } - - public static SOAPBodyElement soapBody_addDocument ( Dom d, Document document ) - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_addDocument( sb, document ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_addDocument( sb, document ); } finally { l.exit(); } } - } - - public static SOAPFault soapBody_addFault ( Dom d, Name name, String s ) throws SOAPException - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_addFault( sb, name, s ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_addFault( sb, name, s ); } finally { l.exit(); } } - } - - public static SOAPFault soapBody_addFault ( Dom d, Name faultCode, String faultString, java.util.Locale locale ) throws SOAPException - { - Locale l = d.locale(); - - SOAPBody sb = (SOAPBody) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapBody_addFault( sb, faultCode, faultString, locale ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapBody_addFault( sb, faultCode, faultString, locale ); } finally { l.exit(); } } - } - - // - // Soap Fault - // - - public static void soapFault_setFaultString ( Dom d, String faultString ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapFault_setFaultString( sf, faultString ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapFault_setFaultString( sf, faultString ); } finally { l.exit(); } } - } - - public static void soapFault_setFaultString ( Dom d, String faultString, java.util.Locale locale ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapFault_setFaultString( sf, faultString, locale ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapFault_setFaultString( sf, faultString, locale ); } finally { l.exit(); } } - } - - public static void soapFault_setFaultCode ( Dom d, Name faultCodeName ) throws SOAPException - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapFault_setFaultCode( sf, faultCodeName ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapFault_setFaultCode( sf, faultCodeName ); } finally { l.exit(); } } - } - - public static void soapFault_setFaultActor ( Dom d, String faultActorString ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapFault_setFaultActor( sf, faultActorString ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapFault_setFaultActor( sf, faultActorString ); } finally { l.exit(); } } - } - - public static String soapFault_getFaultActor ( Dom d ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_getFaultActor( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_getFaultActor( sf ); } finally { l.exit(); } } - } - - public static String soapFault_getFaultCode ( Dom d ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_getFaultCode( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_getFaultCode( sf ); } finally { l.exit(); } } - } - - public static void soapFault_setFaultCode ( Dom d, String faultCode ) throws SOAPException - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapFault_setFaultCode( sf, faultCode ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapFault_setFaultCode( sf, faultCode ); } finally { l.exit(); } } - } - - public static java.util.Locale soapFault_getFaultStringLocale ( Dom d ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_getFaultStringLocale( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_getFaultStringLocale( sf ); } finally { l.exit(); } } - } - - public static Name soapFault_getFaultCodeAsName ( Dom d ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_getFaultCodeAsName( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_getFaultCodeAsName( sf ); } finally { l.exit(); } } - } - - public static String soapFault_getFaultString ( Dom d ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_getFaultString( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_getFaultString( sf ); } finally { l.exit(); } } - } - - public static Detail soapFault_addDetail ( Dom d ) throws SOAPException - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_addDetail( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_addDetail( sf ); } finally { l.exit(); } } - } - - public static Detail soapFault_getDetail ( Dom d ) - { - Locale l = d.locale(); - - SOAPFault sf = (SOAPFault) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapFault_getDetail( sf ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapFault_getDetail( sf ); } finally { l.exit(); } } - } - - // - // Soap Header Element - // - - public static void soapHeaderElement_setMustUnderstand ( Dom d, boolean mustUnderstand ) - { - Locale l = d.locale(); - - SOAPHeaderElement she = (SOAPHeaderElement) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapHeaderElement_setMustUnderstand( she, mustUnderstand ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapHeaderElement_setMustUnderstand( she, mustUnderstand ); } finally { l.exit(); } } - } - - public static boolean soapHeaderElement_getMustUnderstand ( Dom d ) - { - Locale l = d.locale(); - - SOAPHeaderElement she = (SOAPHeaderElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeaderElement_getMustUnderstand( she ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeaderElement_getMustUnderstand( she ); } finally { l.exit(); } } - } - - public static void soapHeaderElement_setActor ( Dom d, String actor ) - { - Locale l = d.locale(); - - SOAPHeaderElement she = (SOAPHeaderElement) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapHeaderElement_setActor( she, actor ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapHeaderElement_setActor( she, actor ); } finally { l.exit(); } } - } - - public static String soapHeaderElement_getActor ( Dom d ) - { - Locale l = d.locale(); - - SOAPHeaderElement she = (SOAPHeaderElement) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapHeaderElement_getActor( she ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapHeaderElement_getActor( she ); } finally { l.exit(); } } - } - - // - // Soap Header Element - // - - public static DetailEntry detail_addDetailEntry ( Dom d, Name name ) - { - Locale l = d.locale(); - - Detail detail = (Detail) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.detail_addDetailEntry( detail, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.detail_addDetailEntry( detail, name ); } finally { l.exit(); } } - } - - public static Iterator detail_getDetailEntries ( Dom d ) - { - Locale l = d.locale(); - - Detail detail = (Detail) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.detail_getDetailEntries( detail ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.detail_getDetailEntries( detail ); } finally { l.exit(); } } - } - - // - // Soap Header Element - // - - public static void _soapPart_removeAllMimeHeaders ( Dom d ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapPart_removeAllMimeHeaders( sp ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapPart_removeAllMimeHeaders( sp ); } finally { l.exit(); } } - } - - public static void _soapPart_removeMimeHeader ( Dom d, String name ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapPart_removeMimeHeader( sp, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapPart_removeMimeHeader( sp, name ); } finally { l.exit(); } } - } - - public static Iterator _soapPart_getAllMimeHeaders ( Dom d ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapPart_getAllMimeHeaders( sp ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapPart_getAllMimeHeaders( sp ); } finally { l.exit(); } } - } - - public static SOAPEnvelope _soapPart_getEnvelope ( Dom d ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapPart_getEnvelope( sp ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapPart_getEnvelope( sp ); } finally { l.exit(); } } - } - - public static Source _soapPart_getContent ( Dom d ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapPart_getContent( sp ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapPart_getContent( sp ); } finally { l.exit(); } } - } - - public static void _soapPart_setContent ( Dom d, Source source ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapPart_setContent( sp, source ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapPart_setContent( sp, source ); } finally { l.exit(); } } - } - - public static String[] _soapPart_getMimeHeader ( Dom d, String name ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapPart_getMimeHeader( sp, name ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapPart_getMimeHeader( sp, name ); } finally { l.exit(); } } - } - - public static void _soapPart_addMimeHeader ( Dom d, String name, String value ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapPart_addMimeHeader( sp, name, value ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapPart_addMimeHeader( sp, name, value ); } finally { l.exit(); } } - } - - public static void _soapPart_setMimeHeader ( Dom d, String name, String value ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { l._saaj.soapPart_setMimeHeader( sp, name, value ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { l._saaj.soapPart_setMimeHeader( sp, name, value ); } finally { l.exit(); } } - } - - public static Iterator _soapPart_getMatchingMimeHeaders ( Dom d, String[] names ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapPart_getMatchingMimeHeaders( sp, names ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapPart_getMatchingMimeHeaders( sp, names ); } finally { l.exit(); } } - } - - public static Iterator _soapPart_getNonMatchingMimeHeaders ( Dom d, String[] names ) - { - Locale l = d.locale(); - - SOAPPart sp = (SOAPPart) d; - - if (l.noSync()) { l.enter(); try { return l._saaj.soapPart_getNonMatchingMimeHeaders( sp, names ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return l._saaj.soapPart_getNonMatchingMimeHeaders( sp, names ); } finally { l.exit(); } } - } - - // - // Saaj callback - // - - private static class SaajData - { - Object _obj; - } - - public static void saajCallback_setSaajData ( Dom d, Object o ) - { - Locale l = d.locale(); - - if (l.noSync()) { l.enter(); try { impl_saajCallback_setSaajData( d, o ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { impl_saajCallback_setSaajData( d, o ); } finally { l.exit(); } } - } - - public static void impl_saajCallback_setSaajData ( Dom d, Object o ) - { - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.moveToDom( d ); - - SaajData sd = null; - - if (o != null) - { - sd = (SaajData) c.getBookmark( SaajData.class ); - - if (sd == null) - sd = new SaajData(); - - sd._obj = o; - } - - c.setBookmark( SaajData.class, sd ); - - c.release(); - } - - public static Object saajCallback_getSaajData ( Dom d ) - { - Locale l = d.locale(); - - if (l.noSync()) { l.enter(); try { return impl_saajCallback_getSaajData( d ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return impl_saajCallback_getSaajData( d ); } finally { l.exit(); } } - } - - public static Object impl_saajCallback_getSaajData ( Dom d ) - { - Locale l = d.locale(); - - Cur c = l.tempCur(); - - c.moveToDom( d ); - - SaajData sd = (SaajData) c.getBookmark( SaajData.class ); - - Object o = sd == null ? null : sd._obj; - - c.release(); - - return o; - } - - public static Element saajCallback_createSoapElement ( Dom d, QName name, QName parentName ) - { - Locale l = d.locale(); - - Dom e; - - if (l.noSync()) { l.enter(); try { e = impl_saajCallback_createSoapElement( d, name, parentName ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { e = impl_saajCallback_createSoapElement( d, name, parentName ); } finally { l.exit(); } } - - return (Element) e; - } - - public static Dom impl_saajCallback_createSoapElement ( Dom d, QName name, QName parentName ) - { - Cur c = d.locale().tempCur(); - - c.createElement( name, parentName ); - - Dom e = c.getDom(); - - c.release(); - - return e; - } - - public static Element saajCallback_importSoapElement ( - Dom d, Element elem, boolean deep, QName parentName ) - { - Locale l = d.locale(); - - Dom e; - - if (l.noSync()) { l.enter(); try { e = impl_saajCallback_importSoapElement( d, elem, deep, parentName ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { e = impl_saajCallback_importSoapElement( d, elem, deep, parentName ); } finally { l.exit(); } } - - return (Element) e; - } - - public static Dom impl_saajCallback_importSoapElement ( - Dom d, Element elem, boolean deep, QName parentName ) - { - // TODO -- need to rewrite DomImpl.document_importNode to use an Xcur - // to create the new tree. Then, I can pass the parentName to the new - // fcn and use it to create the correct root parent - - throw new RuntimeException( "Not impl" ); - } - - - public static Text saajCallback_ensureSoapTextNode ( Dom d ) - { - Locale l = d.locale(); - - if (l.noSync()) { l.enter(); try { return impl_saajCallback_ensureSoapTextNode( d ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return impl_saajCallback_ensureSoapTextNode( d ); } finally { l.exit(); } } - } - - public static Text impl_saajCallback_ensureSoapTextNode ( Dom d ) - { -// if (!(d instanceof Text)) -// { -// Xcur x = d.tempCur(); -// -// x.moveTo -// -// x.release(); -// } -// -// return (Text) d; - - return null; - } - -} - diff --git a/src/store/org/apache/xmlbeans/impl/store/Jsr173.java b/src/store/org/apache/xmlbeans/impl/store/Jsr173.java deleted file mode 100755 index 7bff79d..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Jsr173.java +++ /dev/null @@ -1,1252 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import java.io.Reader; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.ConcurrentModificationException; - -import javax.xml.namespace.NamespaceContext; -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.Location; - -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlLineNumber; -import org.apache.xmlbeans.XmlDocumentProperties; - -import org.w3c.dom.Node; - -public class Jsr173 -{ - public static Node nodeFromStream ( XMLStreamReader xs ) - { - if (!(xs instanceof Jsr173GateWay)) - return null; - - Jsr173GateWay gw = (Jsr173GateWay) xs; - - Locale l = gw._l; - - if (l.noSync()) { l.enter(); try { return nodeFromStreamImpl( gw ); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return nodeFromStreamImpl( gw ); } finally { l.exit(); } } - - } - - public static Node nodeFromStreamImpl ( Jsr173GateWay gw ) - { - Cur c = gw._xs.getStreamCur(); - - return c.isNode() ? (Node) c.getDom() : (Node) null; - } - - public static XMLStreamReader newXmlStreamReader ( Cur c, Object src, int off, int cch ) - { - XMLStreamReaderBase xs = new XMLStreamReaderForString( c, src, off, cch ); - - if (c._locale.noSync()) - return new UnsyncedJsr173( c._locale, xs ); - else - return new SyncedJsr173( c._locale, xs ); - } - - public static XMLStreamReader newXmlStreamReader ( Cur c, XmlOptions options ) - { - options = XmlOptions.maskNull( options ); - - boolean inner = - options.hasOption( XmlOptions.SAVE_INNER ) && - !options.hasOption( XmlOptions.SAVE_OUTER ); - - XMLStreamReaderBase xs; - - int k = c.kind(); - - if (k == Cur.TEXT || k < 0) - { - xs = new XMLStreamReaderForString( c, c.getChars( -1 ), c._offSrc, c._cchSrc ); - } - else if (inner) - { - if (!c.hasAttrs() && !c.hasChildren()) - xs = new XMLStreamReaderForString( c, c.getFirstChars(), c._offSrc, c._cchSrc ); - else - { - assert c.isContainer(); - xs = new XMLStreamReaderForNode( c, true ); - } - } - else - xs = new XMLStreamReaderForNode( c, false ); - - if (c._locale.noSync()) - return new UnsyncedJsr173( c._locale, xs ); - else - return new SyncedJsr173( c._locale, xs ); - } - - // - // - // - - private static final class XMLStreamReaderForNode extends XMLStreamReaderBase - { - public XMLStreamReaderForNode ( Cur c, boolean inner ) - { - super( c ); - - assert c.isContainer() || c.isComment() || c.isProcinst() || c.isAttr(); - - // Iterate over everything *between* _cur and _end. Do - // not iterate the thing to the right of _end - - if (inner) - { - assert c.isContainer(); - - _cur = c.weakCur( this ); - - if (!_cur.toFirstAttr()) - _cur.next(); - - _end = c.weakCur( this ); - _end.toEnd(); - } - else - { - _cur = c.weakCur( this ); - - if (c.isRoot()) - _wholeDoc = true; - else - { - _end = c.weakCur( this ); - - if (c.isAttr()) - { - if (!_end.toNextAttr()) - { - _end.toParent(); - _end.next(); - } - } - else - _end.skip(); - } - } - - if (!_wholeDoc) - { - // Set the _done bit properly - - _cur.push(); - - try - { - next(); - } - catch ( XMLStreamException e ) - { - throw new RuntimeException( e.getMessage(), e ); - } - - _cur.pop(); - } - - assert _wholeDoc || !_cur.isSamePos( _end ); - } - - protected Cur getStreamCur ( ) - { - return _cur; - } - - // - // - // - - public boolean hasNext ( ) throws XMLStreamException - { - checkChanged(); - - return !_done; - } - - public int getEventType ( ) - { - switch ( _cur.kind() ) - { - case Cur.ROOT : return START_DOCUMENT; - case -Cur.ROOT : return END_DOCUMENT; - case Cur.ELEM : return START_ELEMENT; - case -Cur.ELEM : return END_ELEMENT; - case Cur.ATTR : return _cur.isXmlns() ? NAMESPACE : ATTRIBUTE; - case Cur.TEXT : return CHARACTERS; - case Cur.COMMENT : return COMMENT; - case Cur.PROCINST : return PROCESSING_INSTRUCTION; - default : throw new IllegalStateException(); - } - } - - public int next ( ) throws XMLStreamException - { - checkChanged(); - - if (!hasNext()) - throw new IllegalStateException( "No next event in stream" ); - - int kind = _cur.kind(); - - if (kind == -Cur.ROOT) - { - assert _wholeDoc; - _done = true; - } - else - { - if (kind == Cur.ATTR) - { - if (!_cur.toNextAttr()) - { - _cur.toParent(); - _cur.next(); - } - } - else if (kind == Cur.COMMENT || kind == Cur.PROCINST) - _cur.skip(); - else if (kind == Cur.ROOT) - { - if (!_cur.toFirstAttr()) - _cur.next(); - } - else - _cur.next(); - - assert _wholeDoc || _end != null; - - _done = _wholeDoc ? _cur.kind() == -Cur.ROOT : _cur.isSamePos( _end ); - } - - _textFetched = false; - _srcFetched = false; - - return getEventType(); - } - - public String getText ( ) - { - checkChanged(); - - int k = _cur.kind(); - - if (k == Cur.COMMENT) - return _cur.getValueAsString(); - - if (k == Cur.TEXT) - return _cur.getCharsAsString( -1 ); - - throw new IllegalStateException(); - } - - public boolean isStartElement ( ) - { - return getEventType() == START_ELEMENT; - } - - public boolean isEndElement ( ) - { - return getEventType() == END_ELEMENT; - } - - public boolean isCharacters ( ) - { - return getEventType() == CHARACTERS; - } - - public String getElementText ( ) throws XMLStreamException - { - checkChanged(); - - if (!isStartElement()) - throw new IllegalStateException(); - - StringBuffer sb = new StringBuffer(); - - for ( ; ; ) - { - if (!hasNext()) - throw new XMLStreamException(); - - int e = next(); - - if (e == END_ELEMENT) - break; - else if (e == START_ELEMENT) - throw new XMLStreamException(); - else if (e != COMMENT && e != PROCESSING_INSTRUCTION) - sb.append( getText() ); - } - - return sb.toString(); - } - - public int nextTag ( ) throws XMLStreamException - { - checkChanged(); - - for ( ; ; ) - { - if (isStartElement() || isEndElement()) - return getEventType(); - - if (!isWhiteSpace()) - throw new XMLStreamException(); - - if (!hasNext()) - throw new XMLStreamException(); - - next(); - } - } - - private static boolean matchAttr ( Cur c, String uri, String local ) - { - assert c.isNormalAttr(); - - QName name = c.getName(); - - return - name.getLocalPart().equals( local ) && - (uri == null || name.getNamespaceURI().equals( uri )); - } - - private static Cur toAttr ( Cur c, String uri, String local ) - { - if (uri == null || local == null || local.length() == 0) - throw new IllegalArgumentException(); - - Cur ca = c.tempCur(); - boolean match = false; - - if (c.isElem()) - { - if (ca.toFirstAttr()) - { - do - { - if (ca.isNormalAttr() && matchAttr( ca, uri, local )) - { - match = true; - break; - } - } - while ( ca.toNextSibling() ); - } - } - else if (c.isNormalAttr()) - match = matchAttr( c, uri, local ); - else - throw new IllegalStateException(); - - if (!match) - { - ca.release(); - ca = null; - } - - return ca; - } - - public String getAttributeValue ( String uri, String local ) - { - Cur ca = toAttr( _cur, uri, local ); - - String value = null; - - if (ca != null) - { - value = ca.getValueAsString(); - ca.release(); - } - - return value; - } - - private static Cur toAttr ( Cur c, int i ) - { - if (i < 0) - throw new IndexOutOfBoundsException( "Attribute index is negative" ); - - Cur ca = c.tempCur(); - boolean match = false; - - if (c.isElem()) - { - if (ca.toFirstAttr()) - { - do - { - if (ca.isNormalAttr() && i-- == 0) - { - match = true; - break; - } - } - while ( ca.toNextSibling() ); - } - } - else if (c.isNormalAttr()) - match = i == 0; - else - throw new IllegalStateException(); - - if (!match) - { - ca.release(); - throw new IndexOutOfBoundsException( "Attribute index is too large" ); - } - - return ca; - } - - public int getAttributeCount ( ) - { - int n = 0; - - if (_cur.isElem()) - { - Cur ca = _cur.tempCur(); - - if (ca.toFirstAttr()) - { - do - { - if (ca.isNormalAttr()) - n++; - } - while ( ca.toNextSibling() ); - } - - ca.release(); - } - else if (_cur.isNormalAttr()) - n++; - else - throw new IllegalStateException(); - - return n; - } - - public QName getAttributeName ( int index ) - { - Cur ca = toAttr( _cur, index ); - QName name = ca.getName(); - ca.release(); - return name; - } - - public String getAttributeNamespace ( int index ) - { - return getAttributeName( index ).getNamespaceURI(); - } - - public String getAttributeLocalName ( int index ) - { - return getAttributeName( index ).getLocalPart(); - } - - public String getAttributePrefix ( int index ) - { - return getAttributeName( index ).getPrefix(); - } - - public String getAttributeType ( int index ) - { - toAttr( _cur, index ).release(); - return "CDATA"; - } - - public String getAttributeValue ( int index ) - { - Cur ca = toAttr( _cur, index ); - - String value = null; - - if (ca != null) - { - value = ca.getValueAsString(); - ca.release(); - } - - return value; - } - - public boolean isAttributeSpecified ( int index ) - { - // Go to attr to force index check - Cur ca = toAttr( _cur, index ); - ca.release(); - - return false; - } - - public int getNamespaceCount ( ) - { - int n = 0; - - if (_cur.isElem() || _cur.kind() == -Cur.ELEM) - { - Cur ca = _cur.tempCur(); - - if (_cur.kind() == -Cur.ELEM) - ca.toParent(); - - if (ca.toFirstAttr()) - { - do - { - if (ca.isXmlns()) - n++; - } - while ( ca.toNextSibling() ); - } - - ca.release(); - } - else if (_cur.isXmlns()) - n++; - else - throw new IllegalStateException(); - - return n; - } - - private static Cur toXmlns ( Cur c, int i ) - { - if (i < 0) - throw new IndexOutOfBoundsException( "Namespace index is negative" ); - - Cur ca = c.tempCur(); - boolean match = false; - - if (c.isElem() || c.kind() == -Cur.ELEM) - { - if (c.kind() == -Cur.ELEM) - ca.toParent(); - - if (ca.toFirstAttr()) - { - do - { - if (ca.isXmlns() && i-- == 0) - { - match = true; - break; - } - } - while ( ca.toNextSibling() ); - } - } - else if (c.isXmlns()) - match = i == 0; - else - throw new IllegalStateException(); - - if (!match) - { - ca.release(); - throw new IndexOutOfBoundsException( "Namespace index is too large" ); - } - - return ca; - } - - public String getNamespacePrefix ( int index ) - { - Cur ca = toXmlns( _cur, index ); - String prefix = ca.getXmlnsPrefix(); - ca.release(); - return prefix; - } - - public String getNamespaceURI ( int index ) - { - Cur ca = toXmlns( _cur, index ); - String uri = ca.getXmlnsUri(); - ca.release(); - return uri; - } - - private void fetchChars ( ) - { - if (!_textFetched) - { - int k = _cur.kind(); - - Cur cText = null; - - if (k == Cur.COMMENT) - { - cText = _cur.tempCur(); - cText.next(); - } - else if (k == Cur.TEXT) - cText = _cur; - else - throw new IllegalStateException(); - - Object src = cText.getChars( -1 ); - - ensureCharBufLen( cText._cchSrc ); - - CharUtil.getChars( - _chars, _offChars = 0, src, cText._offSrc, _cchChars = cText._cchSrc ); - - if (cText != _cur) - cText.release(); - - _textFetched = true; - } - } - - private void ensureCharBufLen ( int cch ) - { - if (_chars == null || _chars.length < cch) - { - int l = 256; - - while ( l < cch ) - l *= 2; - - _chars = new char [ l ]; - } - } - - public char[] getTextCharacters ( ) - { - checkChanged(); - - fetchChars(); - - return _chars; - } - - public int getTextStart ( ) - { - checkChanged(); - - fetchChars(); - - return _offChars; - } - - public int getTextLength ( ) - { - checkChanged(); - - fetchChars(); - - return _cchChars; - } - - public int getTextCharacters ( - int sourceStart, char[] target, int targetStart, int length ) - throws XMLStreamException - { - if (length < 0) - throw new IndexOutOfBoundsException(); - - if (targetStart < 0 || targetStart >= target.length) - throw new IndexOutOfBoundsException(); - - if (targetStart + length > target.length) - throw new IndexOutOfBoundsException(); - - if (!_srcFetched) - { - int k = _cur.kind(); - - Cur cText = null; - - if (k == Cur.COMMENT) - { - cText = _cur.tempCur(); - cText.next(); - } - else if (k == Cur.TEXT) - cText = _cur; - else - throw new IllegalStateException(); - - _src = cText.getChars( -1 ); - _offSrc = cText._offSrc; - _cchSrc = cText._cchSrc; - - if (cText != _cur) - cText.release(); - - _srcFetched = true; - } - - if (sourceStart > _cchSrc) - throw new IndexOutOfBoundsException(); - - if (sourceStart + length > _cchSrc) - length = _cchSrc - sourceStart; - - CharUtil.getChars( target, targetStart, _src, _offSrc, length ); - - return length; - } - - public boolean hasText ( ) - { - int k = _cur.kind(); - - return k == Cur.COMMENT || k == Cur.TEXT; - } - - public boolean hasName ( ) - { - int k = _cur.kind(); - return k == Cur.ELEM || k == -Cur.ELEM; - } - - public QName getName ( ) - { - if (!hasName()) - throw new IllegalStateException(); - - return _cur.getName(); - } - - public String getNamespaceURI ( ) - { - return getName().getNamespaceURI(); - } - - public String getLocalName ( ) - { - return getName().getLocalPart(); - } - - public String getPrefix ( ) - { - return getName().getPrefix(); - } - - public String getPITarget ( ) - { - return _cur.kind() == Cur.PROCINST ? _cur.getName().getLocalPart() : null; - } - - public String getPIData ( ) - { - return _cur.kind() == Cur.PROCINST ? _cur.getValueAsString() : null; - } - - // - // - // - - private boolean _wholeDoc; - private boolean _done; - - private Cur _cur; - private Cur _end; - - private boolean _srcFetched; - private Object _src; - private int _offSrc; - private int _cchSrc; - - private boolean _textFetched; - private char[] _chars; - private int _offChars; - private int _cchChars; - } - - // - // - // - - private static abstract class XMLStreamReaderBase - implements XMLStreamReader, NamespaceContext, Location - { - XMLStreamReaderBase ( Cur c ) - { - _locale = c._locale; - _version = _locale.version(); - } - - protected final void checkChanged ( ) - { - if (_version != _locale.version()) - throw new ConcurrentModificationException( "Document changed while streaming" ); - } - - // - // XMLStreamReader methods - // - - public void close ( ) throws XMLStreamException - { - checkChanged(); - } - - public boolean isWhiteSpace ( ) - { - checkChanged(); - - // TODO - avoid creating a string here - String s = getText(); - - return _locale.getCharUtil().isWhiteSpace( s, 0, s.length() ); - } - - public Location getLocation ( ) - { - checkChanged(); - - Cur c = getStreamCur(); - - XmlLineNumber ln = (XmlLineNumber) c.getBookmark( XmlLineNumber.class ); - - // BUGBUG - put source name here - _uri = null; - - if (ln != null) - { - _line = ln.getLine(); - _column = ln.getColumn(); - _offset = ln.getOffset(); - } - else - { - _line = -1; - _column = -1; - _offset = -1; - } - - return this; - } - - - public Object getProperty ( String name ) - { - checkChanged(); - - if (name == null) - throw new IllegalArgumentException( "Property name is null" ); - - // BUGBUG - I should implement some perperties here - - return null; - } - - public String getCharacterEncodingScheme ( ) - { - checkChanged(); - - XmlDocumentProperties props = _locale.getDocProps( getStreamCur(), false ); - - return props == null ? null : props.getEncoding(); - } - - public String getEncoding ( ) - { - // BUGBUG - this should probably return the actual decoding used on the document - return null; - } - - public String getVersion ( ) - { - checkChanged(); - - XmlDocumentProperties props = _locale.getDocProps( getStreamCur(), false ); - - return props == null ? null : props.getVersion(); - } - - public boolean isStandalone ( ) - { - checkChanged(); - - XmlDocumentProperties props = _locale.getDocProps( getStreamCur(), false ); - - return props == null ? false : props.getStandalone(); - } - - public boolean standaloneSet ( ) - { - checkChanged(); - - return false; - } - - public void require ( int type, String namespaceURI, String localName ) - throws XMLStreamException - { - checkChanged(); - - if (type != getEventType()) - throw new XMLStreamException(); - - if (namespaceURI != null && !getNamespaceURI().equals( namespaceURI )) - throw new XMLStreamException(); - - if (localName != null && !getLocalName().equals( localName )) - throw new XMLStreamException(); - } - - // - // Location methods do not need a gatway - // - - public int getCharacterOffset ( ) { return _offset; } - public int getColumnNumber ( ) { return _column; } - public int getLineNumber ( ) { return _line; } - public String getLocationURI ( ) { return _uri; } - - public String getPublicId ( ) { return null; } - public String getSystemId ( ) { return null; } - - public NamespaceContext getNamespaceContext ( ) - { - throw new RuntimeException( "This version of getNamespaceContext should not be called"); - } - - public String getNamespaceURI ( String prefix ) - { - checkChanged(); - - Cur c = getStreamCur(); - - c.push(); - - if (!c.isContainer()) - c.toParent(); - - String ns = c.namespaceForPrefix( prefix, true ); - - c.pop(); - - return ns; - } - - public String getPrefix ( String namespaceURI ) - { - checkChanged(); - - Cur c = getStreamCur(); - - c.push(); - - if (!c.isContainer()) - c.toParent(); - - String prefix = c.prefixForNamespace( namespaceURI, null, false ); - - c.pop(); - - return prefix; - } - - public Iterator getPrefixes ( String namespaceURI ) - { - checkChanged(); - - // BUGBUG - get only one for now ... - - HashMap map = new HashMap(); - - map.put( namespaceURI, getPrefix( namespaceURI ) ); - - return map.values().iterator(); - } - - // - // - // - - protected abstract Cur getStreamCur ( ); - - // - // - // - - private Locale _locale; - private long _version; - - String _uri; - - int _line = -1; - int _column = -1; - int _offset = -1; - } - - // - // - // - - private static final class XMLStreamReaderForString extends XMLStreamReaderBase - { - XMLStreamReaderForString ( Cur c, Object src, int off, int cch ) - { - super( c ); - - _src = src; - _off = off; - _cch = cch; - - _cur = c; - } - - protected Cur getStreamCur ( ) - { - return _cur; - } - - // - // Legal stream methods - // - - public String getText ( ) - { - checkChanged(); - - return CharUtil.getString( _src, _off, _cch ); - } - - public char[] getTextCharacters ( ) - { - checkChanged(); - - char[] chars = new char [ _cch ]; - - CharUtil.getChars( chars, 0, _src, _off, _cch ); - - return chars; - } - public int getTextStart ( ) - { - checkChanged(); - - return _off; - } - public int getTextLength ( ) - { - checkChanged(); - - return _cch; - } - - public int getTextCharacters ( int sourceStart, char[] target, int targetStart, int length ) - { - checkChanged(); - - if (length < 0) - throw new IndexOutOfBoundsException(); - - if (sourceStart > _cch) - throw new IndexOutOfBoundsException(); - - if (sourceStart + length > _cch) - length = _cch - sourceStart; - - CharUtil.getChars( target, targetStart, _src, _off + sourceStart, length ); - - return length; - } - - public int getEventType ( ) { checkChanged(); return CHARACTERS; } - public boolean hasName ( ) { checkChanged(); return false; } - public boolean hasNext ( ) { checkChanged(); return false; } - public boolean hasText ( ) { checkChanged(); return true; } - public boolean isCharacters ( ) { checkChanged(); return true; } - public boolean isEndElement ( ) { checkChanged(); return false; } - public boolean isStartElement ( ) { checkChanged(); return false; } - - // - // Illegal stream methods - // - - public int getAttributeCount ( ) { throw new IllegalStateException(); } - public String getAttributeLocalName ( int index ) { throw new IllegalStateException(); } - public QName getAttributeName ( int index ) { throw new IllegalStateException(); } - public String getAttributeNamespace ( int index ) { throw new IllegalStateException(); } - public String getAttributePrefix ( int index ) { throw new IllegalStateException(); } - public String getAttributeType ( int index ) { throw new IllegalStateException(); } - public String getAttributeValue ( int index ) { throw new IllegalStateException(); } - public String getAttributeValue ( String namespaceURI, String localName ) { throw new IllegalStateException(); } - public String getElementText ( ) { throw new IllegalStateException(); } - public String getLocalName ( ) { throw new IllegalStateException(); } - public QName getName ( ) { throw new IllegalStateException(); } - public int getNamespaceCount ( ) { throw new IllegalStateException(); } - public String getNamespacePrefix ( int index ) { throw new IllegalStateException(); } - public String getNamespaceURI ( int index ) { throw new IllegalStateException(); } - public String getNamespaceURI ( ) { throw new IllegalStateException(); } - public String getPIData ( ) { throw new IllegalStateException(); } - public String getPITarget ( ) { throw new IllegalStateException(); } - public String getPrefix ( ) { throw new IllegalStateException(); } - public boolean isAttributeSpecified ( int index ) { throw new IllegalStateException(); } - public int next ( ) { throw new IllegalStateException(); } - public int nextTag ( ) { throw new IllegalStateException(); } - public String getPublicId() { throw new IllegalStateException(); } - public String getSystemId() { throw new IllegalStateException(); } - - private Cur _cur; - private Object _src; - private int _off; - private int _cch; - } - - // - // - // - - private static abstract class Jsr173GateWay - { - public Jsr173GateWay ( Locale l, XMLStreamReaderBase xs ) { _l = l; _xs = xs; } - - Locale _l; - XMLStreamReaderBase _xs; - } - - private static final class SyncedJsr173 extends Jsr173GateWay implements XMLStreamReader, Location, NamespaceContext - { - public SyncedJsr173 ( Locale l, XMLStreamReaderBase xs ) { super( l, xs ); } - - public Object getProperty ( java.lang.String name ) { synchronized ( _l ) { _l.enter(); try { return _xs.getProperty( name ); } finally { _l.exit(); } } } - public int next ( ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { return _xs.next(); } finally { _l.exit(); } } } - public void require ( int type, String namespaceURI, String localName ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { _xs.require( type, namespaceURI, localName ); } finally { _l.exit(); } } } - public String getElementText ( ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { return _xs.getElementText(); } finally { _l.exit(); } } } - public int nextTag ( ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { return _xs.nextTag(); } finally { _l.exit(); } } } - public boolean hasNext ( ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { return _xs.hasNext(); } finally { _l.exit(); } } } - public void close ( ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { _xs.close(); } finally { _l.exit(); } } } - public String getNamespaceURI ( String prefix ) { synchronized ( _l ) { _l.enter(); try { return _xs.getNamespaceURI ( prefix ); } finally { _l.exit(); } } } - public boolean isStartElement ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.isStartElement(); } finally { _l.exit(); } } } - public boolean isEndElement ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.isEndElement(); } finally { _l.exit(); } } } - public boolean isCharacters ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.isCharacters(); } finally { _l.exit(); } } } - public boolean isWhiteSpace ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.isWhiteSpace(); } finally { _l.exit(); } } } - public String getAttributeValue ( String namespaceURI, String localName ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeValue ( namespaceURI, localName ); } finally { _l.exit(); } } } - public int getAttributeCount ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeCount(); } finally { _l.exit(); } } } - public QName getAttributeName ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeName ( index ); } finally { _l.exit(); } } } - public String getAttributeNamespace ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeNamespace ( index ); } finally { _l.exit(); } } } - public String getAttributeLocalName ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeLocalName ( index ); } finally { _l.exit(); } } } - public String getAttributePrefix ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributePrefix ( index ); } finally { _l.exit(); } } } - public String getAttributeType ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeType ( index ); } finally { _l.exit(); } } } - public String getAttributeValue ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getAttributeValue ( index ); } finally { _l.exit(); } } } - public boolean isAttributeSpecified ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.isAttributeSpecified ( index ); } finally { _l.exit(); } } } - public int getNamespaceCount ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getNamespaceCount(); } finally { _l.exit(); } } } - public String getNamespacePrefix ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getNamespacePrefix ( index ); } finally { _l.exit(); } } } - public String getNamespaceURI ( int index ) { synchronized ( _l ) { _l.enter(); try { return _xs.getNamespaceURI ( index ); } finally { _l.exit(); } } } - public NamespaceContext getNamespaceContext ( ) { return this; } - public int getEventType ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getEventType(); } finally { _l.exit(); } } } - public String getText ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getText(); } finally { _l.exit(); } } } - public char[] getTextCharacters ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getTextCharacters(); } finally { _l.exit(); } } } - public int getTextCharacters ( int sourceStart, char[] target, int targetStart, int length ) throws XMLStreamException { synchronized ( _l ) { _l.enter(); try { return _xs.getTextCharacters ( sourceStart, target, targetStart, length ); } finally { _l.exit(); } } } - public int getTextStart ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getTextStart(); } finally { _l.exit(); } } } - public int getTextLength ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getTextLength(); } finally { _l.exit(); } } } - public String getEncoding ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getEncoding(); } finally { _l.exit(); } } } - public boolean hasText ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.hasText(); } finally { _l.exit(); } } } - public Location getLocation ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getLocation(); } finally { _l.exit(); } } } - public QName getName ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getName(); } finally { _l.exit(); } } } - public String getLocalName ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getLocalName(); } finally { _l.exit(); } } } - public boolean hasName ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.hasName(); } finally { _l.exit(); } } } - public String getNamespaceURI ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getNamespaceURI(); } finally { _l.exit(); } } } - public String getPrefix ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getPrefix(); } finally { _l.exit(); } } } - public String getVersion ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getVersion(); } finally { _l.exit(); } } } - public boolean isStandalone ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.isStandalone(); } finally { _l.exit(); } } } - public boolean standaloneSet ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.standaloneSet(); } finally { _l.exit(); } } } - public String getCharacterEncodingScheme ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getCharacterEncodingScheme(); } finally { _l.exit(); } } } - public String getPITarget ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getPITarget(); } finally { _l.exit(); } } } - public String getPIData ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getPIData(); } finally { _l.exit(); } } } - public String getPrefix ( String namespaceURI ) { synchronized ( _l ) { _l.enter(); try { return _xs.getPrefix( namespaceURI ); } finally { _l.exit(); } } } - public Iterator getPrefixes ( String namespaceURI ) { synchronized ( _l ) { _l.enter(); try { return _xs.getPrefixes( namespaceURI ); } finally { _l.exit(); } } } - public int getCharacterOffset ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getCharacterOffset(); } finally { _l.exit(); } } } - public int getColumnNumber ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getColumnNumber(); } finally { _l.exit(); } } } - public int getLineNumber ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getLineNumber(); } finally { _l.exit(); } } } - public String getLocationURI ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getLocationURI(); } finally { _l.exit(); } } } - public String getPublicId() { synchronized ( _l ) { _l.enter(); try { return _xs.getPublicId(); } finally { _l.exit(); } } } - public String getSystemId() { synchronized ( _l ) { _l.enter(); try { return _xs.getSystemId(); } finally { _l.exit(); } } } - } - - private static final class UnsyncedJsr173 extends Jsr173GateWay implements XMLStreamReader, Location, NamespaceContext - { - public UnsyncedJsr173 ( Locale l, XMLStreamReaderBase xs ) { super( l, xs ); } - - public Object getProperty ( java.lang.String name ) { try { _l.enter(); return _xs.getProperty( name ); } finally { _l.exit(); } } - public int next ( ) throws XMLStreamException { try { _l.enter(); return _xs.next(); } finally { _l.exit(); } } - public void require ( int type, String namespaceURI, String localName ) throws XMLStreamException { try { _l.enter(); _xs.require( type, namespaceURI, localName ); } finally { _l.exit(); } } - public String getElementText ( ) throws XMLStreamException { try { _l.enter(); return _xs.getElementText(); } finally { _l.exit(); } } - public int nextTag ( ) throws XMLStreamException { try { _l.enter(); return _xs.nextTag(); } finally { _l.exit(); } } - public boolean hasNext ( ) throws XMLStreamException { try { _l.enter(); return _xs.hasNext(); } finally { _l.exit(); } } - public void close ( ) throws XMLStreamException { try { _l.enter(); _xs.close(); } finally { _l.exit(); } } - public String getNamespaceURI ( String prefix ) { try { _l.enter(); return _xs.getNamespaceURI ( prefix ); } finally { _l.exit(); } } - public boolean isStartElement ( ) { try { _l.enter(); return _xs.isStartElement(); } finally { _l.exit(); } } - public boolean isEndElement ( ) { try { _l.enter(); return _xs.isEndElement(); } finally { _l.exit(); } } - public boolean isCharacters ( ) { try { _l.enter(); return _xs.isCharacters(); } finally { _l.exit(); } } - public boolean isWhiteSpace ( ) { try { _l.enter(); return _xs.isWhiteSpace(); } finally { _l.exit(); } } - public String getAttributeValue ( String namespaceURI, String localName ) { try { _l.enter(); return _xs.getAttributeValue ( namespaceURI, localName ); } finally { _l.exit(); } } - public int getAttributeCount ( ) { try { _l.enter(); return _xs.getAttributeCount(); } finally { _l.exit(); } } - public QName getAttributeName ( int index ) { try { _l.enter(); return _xs.getAttributeName ( index ); } finally { _l.exit(); } } - public String getAttributeNamespace ( int index ) { try { _l.enter(); return _xs.getAttributeNamespace ( index ); } finally { _l.exit(); } } - public String getAttributeLocalName ( int index ) { try { _l.enter(); return _xs.getAttributeLocalName ( index ); } finally { _l.exit(); } } - public String getAttributePrefix ( int index ) { try { _l.enter(); return _xs.getAttributePrefix ( index ); } finally { _l.exit(); } } - public String getAttributeType ( int index ) { try { _l.enter(); return _xs.getAttributeType ( index ); } finally { _l.exit(); } } - public String getAttributeValue ( int index ) { try { _l.enter(); return _xs.getAttributeValue ( index ); } finally { _l.exit(); } } - public boolean isAttributeSpecified ( int index ) { try { _l.enter(); return _xs.isAttributeSpecified ( index ); } finally { _l.exit(); } } - public int getNamespaceCount ( ) { try { _l.enter(); return _xs.getNamespaceCount(); } finally { _l.exit(); } } - public String getNamespacePrefix ( int index ) { try { _l.enter(); return _xs.getNamespacePrefix ( index ); } finally { _l.exit(); } } - public String getNamespaceURI ( int index ) { try { _l.enter(); return _xs.getNamespaceURI ( index ); } finally { _l.exit(); } } - public NamespaceContext getNamespaceContext ( ) { return this; } - public int getEventType ( ) { try { _l.enter(); return _xs.getEventType(); } finally { _l.exit(); } } - public String getText ( ) { try { _l.enter(); return _xs.getText(); } finally { _l.exit(); } } - public char[] getTextCharacters ( ) { try { _l.enter(); return _xs.getTextCharacters(); } finally { _l.exit(); } } - public int getTextCharacters ( int sourceStart, char[] target, int targetStart, int length ) throws XMLStreamException { try { _l.enter(); return _xs.getTextCharacters ( sourceStart, target, targetStart, length ); } finally { _l.exit(); } } - public int getTextStart ( ) { try { _l.enter(); return _xs.getTextStart(); } finally { _l.exit(); } } - public int getTextLength ( ) { try { _l.enter(); return _xs.getTextLength(); } finally { _l.exit(); } } - public String getEncoding ( ) { try { _l.enter(); return _xs.getEncoding(); } finally { _l.exit(); } } - public boolean hasText ( ) { try { _l.enter(); return _xs.hasText(); } finally { _l.exit(); } } - public Location getLocation ( ) { try { _l.enter(); return _xs.getLocation(); } finally { _l.exit(); } } - public QName getName ( ) { try { _l.enter(); return _xs.getName(); } finally { _l.exit(); } } - public String getLocalName ( ) { try { _l.enter(); return _xs.getLocalName(); } finally { _l.exit(); } } - public boolean hasName ( ) { try { _l.enter(); return _xs.hasName(); } finally { _l.exit(); } } - public String getNamespaceURI ( ) { try { _l.enter(); return _xs.getNamespaceURI(); } finally { _l.exit(); } } - public String getPrefix ( ) { try { _l.enter(); return _xs.getPrefix(); } finally { _l.exit(); } } - public String getVersion ( ) { try { _l.enter(); return _xs.getVersion(); } finally { _l.exit(); } } - public boolean isStandalone ( ) { try { _l.enter(); return _xs.isStandalone(); } finally { _l.exit(); } } - public boolean standaloneSet ( ) { try { _l.enter(); return _xs.standaloneSet(); } finally { _l.exit(); } } - public String getCharacterEncodingScheme ( ) { try { _l.enter(); return _xs.getCharacterEncodingScheme(); } finally { _l.exit(); } } - public String getPITarget ( ) { try { _l.enter(); return _xs.getPITarget(); } finally { _l.exit(); } } - public String getPIData ( ) { try { _l.enter(); return _xs.getPIData(); } finally { _l.exit(); } } - public String getPrefix ( String namespaceURI ) { try { _l.enter(); return _xs.getPrefix( namespaceURI ); } finally { _l.exit(); } } - public Iterator getPrefixes ( String namespaceURI ) { try { _l.enter(); return _xs.getPrefixes( namespaceURI ); } finally { _l.exit(); } } - public int getCharacterOffset ( ) { try { _l.enter(); return _xs.getCharacterOffset(); } finally { _l.exit(); } } - public int getColumnNumber ( ) { try { _l.enter(); return _xs.getColumnNumber(); } finally { _l.exit(); } } - public int getLineNumber ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getLineNumber(); } finally { _l.exit(); } } } - public String getLocationURI ( ) { synchronized ( _l ) { _l.enter(); try { return _xs.getLocationURI(); } finally { _l.exit(); } } } - public String getPublicId() { synchronized ( _l ) { _l.enter(); try { return _xs.getPublicId(); } finally { _l.exit(); } } } - public String getSystemId() { synchronized ( _l ) { _l.enter(); try { return _xs.getSystemId(); } finally { _l.exit(); } } } - } -} - - \ No newline at end of file diff --git a/src/store/org/apache/xmlbeans/impl/store/Locale.java b/src/store/org/apache/xmlbeans/impl/store/Locale.java deleted file mode 100755 index 7e559c6..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Locale.java +++ /dev/null @@ -1,3758 +0,0 @@ -/* Copyright 2004-2018 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import org.xml.sax.Locator; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.ext.DeclHandler; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; -import org.xml.sax.SAXException; -import org.xml.sax.DTDHandler; - -import java.util.HashMap; -import java.util.Map; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.Reference; -import java.lang.ref.PhantomReference; -import java.lang.ref.SoftReference; - -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.IOException; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamException; - -import org.apache.xmlbeans.xml.stream.Attribute; -import org.apache.xmlbeans.xml.stream.AttributeIterator; -import org.apache.xmlbeans.xml.stream.CharacterData; -import org.apache.xmlbeans.xml.stream.ProcessingInstruction; -import org.apache.xmlbeans.xml.stream.Space; -import org.apache.xmlbeans.xml.stream.StartDocument; -import org.apache.xmlbeans.xml.stream.StartElement; -import org.apache.xmlbeans.xml.stream.XMLEvent; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLName; - -import org.apache.xmlbeans.impl.common.SAXHelper; -import org.apache.xmlbeans.impl.common.XMLNameHelper; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.XmlLocale; -import org.apache.xmlbeans.impl.common.ResolverUtil; -import org.apache.xmlbeans.impl.common.SystemCache; - -import org.apache.xmlbeans.impl.store.Saaj.SaajCallback; - -import org.apache.xmlbeans.impl.store.DomImpl.Dom; -import org.apache.xmlbeans.impl.store.DomImpl.TextNode; -import org.apache.xmlbeans.impl.store.DomImpl.CdataNode; -import org.apache.xmlbeans.impl.store.DomImpl.SaajTextNode; -import org.apache.xmlbeans.impl.store.DomImpl.SaajCdataNode; - -import org.apache.xmlbeans.impl.store.Cur.Locations; - -import org.apache.xmlbeans.CDataBookmark; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlLineNumber; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlOptionsBean; -import org.apache.xmlbeans.XmlSaxHandler; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlTokenSource; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.QNameCache; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlRuntimeException; -import org.apache.xmlbeans.XmlDocumentProperties; - -import org.apache.xmlbeans.impl.values.TypeStore; -import org.apache.xmlbeans.impl.values.TypeStoreUser; -import org.apache.xmlbeans.impl.values.TypeStoreUserFactory; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.w3c.dom.Node; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Element; - -public final class Locale - implements DOMImplementation, SaajCallback, XmlLocale -{ - static final int ROOT = Cur.ROOT; - static final int ELEM = Cur.ELEM; - static final int ATTR = Cur.ATTR; - static final int COMMENT = Cur.COMMENT; - static final int PROCINST = Cur.PROCINST; - static final int TEXT = Cur.TEXT; - - static final int WS_UNSPECIFIED = TypeStore.WS_UNSPECIFIED; - static final int WS_PRESERVE = TypeStore.WS_PRESERVE; - static final int WS_REPLACE = TypeStore.WS_REPLACE; - static final int WS_COLLAPSE = TypeStore.WS_COLLAPSE; - - static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance"; - static final String _schema = "http://www.w3.org/2001/XMLSchema"; - static final String _openFragUri = "http://www.openuri.org/fragment"; - static final String _xml1998Uri = "http://www.w3.org/XML/1998/namespace"; - static final String _xmlnsUri = "http://www.w3.org/2000/xmlns/"; - - static final QName _xsiNil = new QName(_xsi, "nil", "xsi"); - static final QName _xsiType = new QName(_xsi, "type", "xsi"); - static final QName _xsiLoc = new QName(_xsi, "schemaLocation", "xsi"); - static final QName _xsiNoLoc = new QName(_xsi, "noNamespaceSchemaLocation", - "xsi"); - static final QName _openuriFragment = new QName(_openFragUri, "fragment", - "frag"); - static final QName _xmlFragment = new QName("xml-fragment"); - - private Locale(SchemaTypeLoader stl, XmlOptions options) - { - options = XmlOptions.maskNull(options); - - // - // - // - - // TODO - add option for no=sync, or make it all thread safe - // - // Also - have a thread local setting for thread safety? .. Perhaps something - // in the type loader which defines whether ot not sync is on???? - - _noSync = options.hasOption(XmlOptions.UNSYNCHRONIZED); - - _tempFrames = new Cur[_numTempFramesLeft = 8]; - - // BUGBUG - this cannot be thread local .... - // BUGBUG - this cannot be thread local .... - // BUGBUG - this cannot be thread local .... uhh what, again? - // - // Lazy create this (loading up a locale should use the thread locale one) - // same goes for the qname factory .. use thread local for hte most part when loading - - _qnameFactory = new DefaultQNameFactory(); //new LocalDocumentQNameFactory(); - - _locations = new Locations(this); - - _schemaTypeLoader = stl; - - _validateOnSet = options.hasOption(XmlOptions.VALIDATE_ON_SET); - - // - // Check for Saaj implementation request - // - - Object saajObj = options.get(Saaj.SAAJ_IMPL); - - if (saajObj != null) - { - if (!(saajObj instanceof Saaj)) - throw new IllegalStateException( - "Saaj impl not correct type: " + saajObj); - - _saaj = (Saaj) saajObj; - - _saaj.setCallback(this); - } - } - - // - // - // - - public static final String USE_SAME_LOCALE = "USE_SAME_LOCALE"; - /** - * This option is checked in XmlObjectBase._copy(XmlOptions), the locale is used as the synchronization domain. - * useNewLocale = true: copy will use a new locale, false: copy will use the same locale as the source - * @deprecated Replace usages with CopyUseNewSynchronizationDomain option - * @see org.apache.xmlbeans.XmlOptions#setCopyUseNewSynchronizationDomain(boolean) - */ - public static final String COPY_USE_NEW_LOCALE = "COPY_USE_NEW_LOCALE"; - - static Locale getLocale(SchemaTypeLoader stl, XmlOptions options) - { - if (stl == null) - stl = XmlBeans.getContextTypeLoader(); - - options = XmlOptions.maskNull(options); - - Locale l = null; - - if (options.hasOption(USE_SAME_LOCALE)) - { - Object source = options.get(USE_SAME_LOCALE); - - if (source instanceof Locale) - l = (Locale) source; - else if (source instanceof XmlTokenSource) - l = (Locale) ((XmlTokenSource) source).monitor(); - else - throw new IllegalArgumentException( - "Source locale not understood: " + source); - - if (l._schemaTypeLoader != stl) - throw new IllegalArgumentException( - "Source locale does not support same schema type loader"); - - if (l._saaj != null && l._saaj != options.get(Saaj.SAAJ_IMPL)) - throw new IllegalArgumentException( - "Source locale does not support same saaj"); - - if (l._validateOnSet && - !options.hasOption(XmlOptions.VALIDATE_ON_SET)) - throw new IllegalArgumentException( - "Source locale does not support same validate on set"); - - // TODO - other things to check? - } - else - l = new Locale(stl, options); - - return l; - } - - // - // - // - - static void associateSourceName(Cur c, XmlOptions options) - { - String sourceName = (String) XmlOptions.safeGet(options, - XmlOptions.DOCUMENT_SOURCE_NAME); - - if (sourceName != null) - getDocProps(c, true).setSourceName(sourceName); - } - - // - // - // - - static void autoTypeDocument(Cur c, SchemaType requestedType, - XmlOptions options) - throws XmlException - { - assert c.isRoot(); - - // The type in the options overrides all sniffing - - options = XmlOptions.maskNull(options); - - SchemaType optionType = (SchemaType) options.get( - XmlOptions.DOCUMENT_TYPE); - - if (optionType != null) - { - c.setType(optionType); - return; - } - - SchemaType type = null; - - // An xsi:type can be used to pick a type out of the loader, or used to refine - // a type with a name. - - if (requestedType == null || requestedType.getName() != null) - { - QName xsiTypeName = c.getXsiTypeName(); - - SchemaType xsiSchemaType = - xsiTypeName == null ? - null : c._locale._schemaTypeLoader.findType(xsiTypeName); - - if (requestedType == null || - requestedType.isAssignableFrom(xsiSchemaType)) - type = xsiSchemaType; - } - - // Look for a document element to establish type - - if (type == null && - (requestedType == null || requestedType.isDocumentType())) - { - assert c.isRoot(); - - c.push(); - - QName docElemName = - !c.hasAttrs() && Locale.toFirstChildElement(c) && - !Locale.toNextSiblingElement(c) - ? c.getName() : null; - - c.pop(); - - if (docElemName != null) - { - type = - c._locale._schemaTypeLoader.findDocumentType(docElemName); - - if (type != null && requestedType != null) - { - QName requesteddocElemNameName = requestedType.getDocumentElementName(); - - if (!requesteddocElemNameName.equals(docElemName) && - !requestedType.isValidSubstitution(docElemName)) - { - throw - new XmlException("Element " + - QNameHelper.pretty(docElemName) + - " is not a valid " + - QNameHelper.pretty(requesteddocElemNameName) + - " document or a valid substitution."); - } - } - } - } - - if (type == null && requestedType == null) - { - c.push(); - - type = - Locale.toFirstNormalAttr(c) && !Locale.toNextNormalAttr(c) - ? - c._locale._schemaTypeLoader.findAttributeType(c.getName()) : - null; - - c.pop(); - } - - if (type == null) - type = requestedType; - - if (type == null) - type = XmlBeans.NO_TYPE; - - c.setType(type); - - if (requestedType != null) - { - if (type.isDocumentType()) - verifyDocumentType(c, type.getDocumentElementName()); - else if (type.isAttributeType()) - verifyAttributeType(c, type.getAttributeTypeAttributeName()); - } - } - - private static boolean namespacesSame(QName n1, QName n2) - { - if (n1 == n2) - return true; - - if (n1 == null || n2 == null) - return false; - - if (n1.getNamespaceURI() == n2.getNamespaceURI()) - return true; - - if (n1.getNamespaceURI() == null || n2.getNamespaceURI() == null) - return false; - - return n1.getNamespaceURI().equals(n2.getNamespaceURI()); - } - - private static void addNamespace(StringBuffer sb, QName name) - { - if (name.getNamespaceURI() == null) - sb.append(""); - else - { - sb.append("\""); - sb.append(name.getNamespaceURI()); - sb.append("\""); - } - } - - private static void verifyDocumentType(Cur c, QName docElemName) - throws XmlException - { - assert c.isRoot(); - - c.push(); - - try - { - StringBuffer sb = null; - - if (!Locale.toFirstChildElement(c) || - Locale.toNextSiblingElement(c)) - { - sb = new StringBuffer(); - - sb.append("The document is not a "); - sb.append(QNameHelper.pretty(docElemName)); - sb.append( - c.isRoot() ? - ": no document element" : ": multiple document elements"); - } - else - { - QName name = c.getName(); - - if (!name.equals(docElemName)) - { - sb = new StringBuffer(); - - sb.append("The document is not a "); - sb.append(QNameHelper.pretty(docElemName)); - - if (docElemName.getLocalPart().equals(name.getLocalPart())) - { - sb.append(": document element namespace mismatch "); - sb.append("expected "); - addNamespace(sb, docElemName); - sb.append(" got "); - addNamespace(sb, name); - } - else if (namespacesSame(docElemName, name)) - { - sb.append(": document element local name mismatch "); - sb.append("expected " + docElemName.getLocalPart()); - sb.append(" got " + name.getLocalPart()); - } - else - { - sb.append(": document element mismatch "); - sb.append("got "); - sb.append(QNameHelper.pretty(name)); - } - } - } - - if (sb != null) - { - XmlError err = XmlError.forCursor(sb.toString(), - new Cursor(c)); - throw new XmlException(err.toString(), null, err); - } - } - finally - { - c.pop(); - } - } - - private static void verifyAttributeType(Cur c, QName attrName) - throws XmlException - { - assert c.isRoot(); - - c.push(); - - try - { - StringBuffer sb = null; - - if (!Locale.toFirstNormalAttr(c) || Locale.toNextNormalAttr(c)) - { - sb = new StringBuffer(); - - sb.append("The document is not a "); - sb.append(QNameHelper.pretty(attrName)); - sb.append( - c.isRoot() ? ": no attributes" : ": multiple attributes"); - } - else - { - QName name = c.getName(); - - if (!name.equals(attrName)) - { - sb = new StringBuffer(); - - sb.append("The document is not a "); - sb.append(QNameHelper.pretty(attrName)); - - if (attrName.getLocalPart().equals(name.getLocalPart())) - { - sb.append(": attribute namespace mismatch "); - sb.append("expected "); - addNamespace(sb, attrName); - sb.append(" got "); - addNamespace(sb, name); - } - else if (namespacesSame(attrName, name)) - { - sb.append(": attribute local name mismatch "); - sb.append("expected " + attrName.getLocalPart()); - sb.append(" got " + name.getLocalPart()); - } - else - { - sb.append(": attribute element mismatch "); - sb.append("got "); - sb.append(QNameHelper.pretty(name)); - } - } - } - - if (sb != null) - { - XmlError err = XmlError.forCursor(sb.toString(), - new Cursor(c)); - throw new XmlException(err.toString(), null, err); - } - } - finally - { - c.pop(); - } - } - - static boolean isFragmentQName(QName name) - { - return name.equals(Locale._openuriFragment) || - name.equals(Locale._xmlFragment); - } - - static boolean isFragment(Cur start, Cur end) - { - assert !end.isAttr(); - - start.push(); - end.push(); - - int numDocElems = 0; - boolean isFrag = false; - - while (!start.isSamePos(end)) - { - int k = start.kind(); - - if (k == ATTR) - break; - - if (k == TEXT && !isWhiteSpace(start.getCharsAsString(-1))) - { - isFrag = true; - break; - } - - if (k == ELEM && ++numDocElems > 1) - { - isFrag = true; - break; - } - - // Move to next token - - assert k != ATTR; - - if (k != TEXT) - start.toEnd(); - - start.next(); - } - - start.pop(); - end.pop(); - - return isFrag || numDocElems != 1; - } - - // - // - // - - public static XmlObject newInstance(SchemaTypeLoader stl, SchemaType type, - XmlOptions options) - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.newInstance(type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.newInstance(type, options); - } - finally - { - l.exit(); - } - } - } - - private XmlObject newInstance(SchemaType type, XmlOptions options) - { - options = XmlOptions.maskNull(options); - - Cur c = tempCur(); - - - SchemaType sType = (SchemaType) options.get(XmlOptions.DOCUMENT_TYPE); - - if (sType == null) - sType = type == null ? XmlObject.type : type; - if (sType.isDocumentType()) - c.createDomDocumentRoot(); - else - c.createRoot(); - c.setType(sType); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - // - // - // - - public static DOMImplementation newDomImplementation(SchemaTypeLoader stl, - XmlOptions options) - { - return (DOMImplementation) getLocale(stl, options); - } - - // - // - // - - public static XmlObject parseToXmlObject(SchemaTypeLoader stl, - String xmlText, SchemaType type, XmlOptions options) - throws XmlException - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.parseToXmlObject(xmlText, type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.parseToXmlObject(xmlText, type, options); - } - finally - { - l.exit(); - } - } - } - - private XmlObject parseToXmlObject(String xmlText, SchemaType type, - XmlOptions options) - throws XmlException - { - Cur c = parse(xmlText, type, options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - Cur parse(String s, SchemaType type, XmlOptions options) - throws XmlException - { - Reader r = new StringReader(s); - - try - { - Cur c = getSaxLoader(options).load(this, new InputSource(r), - options); - - autoTypeDocument(c, type, options); - - return c; - } - catch (IOException e) - { - assert false: "StringReader should not throw IOException"; - - throw new XmlException(e.getMessage(), e); - } - finally - { - try - { - r.close(); - } - catch (IOException e) - { - } - } - } - - // - // - // - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlObject parseToXmlObject(SchemaTypeLoader stl, - XMLInputStream xis, SchemaType type, XmlOptions options) - throws XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.parseToXmlObject(xis, type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.parseToXmlObject(xis, type, options); - } - finally - { - l.exit(); - } - } - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XmlObject parseToXmlObject(XMLInputStream xis, SchemaType type, - XmlOptions options) - throws XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException - { - Cur c; - - try - { - c = loadXMLInputStream(xis, options); - } - catch (org.apache.xmlbeans.xml.stream.XMLStreamException e) - { - throw new XmlException(e.getMessage(), e); - } - - autoTypeDocument(c, type, options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - // - // - // - - public static XmlObject parseToXmlObject(SchemaTypeLoader stl, - XMLStreamReader xsr, SchemaType type, XmlOptions options) - throws XmlException - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.parseToXmlObject(xsr, type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.parseToXmlObject(xsr, type, options); - } - finally - { - l.exit(); - } - } - } - - public XmlObject parseToXmlObject(XMLStreamReader xsr, SchemaType type, - XmlOptions options) - throws XmlException - { - Cur c; - - try - { - c = loadXMLStreamReader(xsr, options); - } - catch (XMLStreamException e) - { - throw new XmlException(e.getMessage(), e); - } - - autoTypeDocument(c, type, options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - private static void lineNumber(XMLEvent xe, LoadContext context) - { - org.apache.xmlbeans.xml.stream.Location loc = xe.getLocation(); - - if (loc != null) - context.lineNumber(loc.getLineNumber(), loc.getColumnNumber(), -1); - } - - private static void lineNumber(XMLStreamReader xsr, LoadContext context) - { - javax.xml.stream.Location loc = xsr.getLocation(); - - if (loc != null) - { - context.lineNumber(loc.getLineNumber(), loc.getColumnNumber(), - loc.getCharacterOffset()); - } - } - - private void doAttributes(XMLStreamReader xsr, LoadContext context) - { - int n = xsr.getAttributeCount(); - - for (int a = 0; a < n; a++) - { - context.attr(xsr.getAttributeLocalName(a), - xsr.getAttributeNamespace(a), - xsr.getAttributePrefix(a), - xsr.getAttributeValue(a)); - } - } - - private void doNamespaces(XMLStreamReader xsr, LoadContext context) - { - int n = xsr.getNamespaceCount(); - - for (int a = 0; a < n; a++) - { - String prefix = xsr.getNamespacePrefix(a); - - if (prefix == null || prefix.length() == 0) - context.attr("xmlns", _xmlnsUri, null, - xsr.getNamespaceURI(a)); - else - context.attr(prefix, _xmlnsUri, "xmlns", - xsr.getNamespaceURI(a)); - } - - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - private Cur loadXMLInputStream(XMLInputStream xis, XmlOptions options) - throws org.apache.xmlbeans.xml.stream.XMLStreamException - { - options = XmlOptions.maskNull(options); - - boolean lineNums = options.hasOption(XmlOptions.LOAD_LINE_NUMBERS); - - XMLEvent x = xis.peek(); - - if (x != null && x.getType() == XMLEvent.START_ELEMENT) - { - Map nsMap = ((StartElement) x).getNamespaceMap(); - - if (nsMap != null && nsMap.size() > 0) - { - Map namespaces = new HashMap(); - - namespaces.putAll(nsMap); - - options = new XmlOptions(options); - - options.put(XmlOptions.LOAD_ADDITIONAL_NAMESPACES, namespaces); - } - } - - String systemId = null; - String encoding = null; - String version = null; - boolean standAlone = true; - - LoadContext context = new Cur.CurLoadContext(this, options); - - events: - for (XMLEvent xe = xis.next(); xe != null; xe = xis.next()) - { - switch (xe.getType()) - { - case XMLEvent.START_DOCUMENT: - StartDocument doc = (StartDocument) xe; - - systemId = doc.getSystemId(); - encoding = doc.getCharacterEncodingScheme(); - version = doc.getVersion(); - standAlone = doc.isStandalone(); - standAlone = doc.isStandalone(); - - if (lineNums) - lineNumber(xe, context); - - break; - - case XMLEvent.END_DOCUMENT: - if (lineNums) - lineNumber(xe, context); - - break events; - - case XMLEvent.NULL_ELEMENT: - if (!xis.hasNext()) - break events; - break; - - case XMLEvent.START_ELEMENT: - context.startElement(XMLNameHelper.getQName(xe.getName())); - - if (lineNums) - lineNumber(xe, context); - - for (AttributeIterator ai = ((StartElement) xe).getAttributes(); - ai.hasNext();) - { - Attribute attr = ai.next(); - - context.attr(XMLNameHelper.getQName(attr.getName()), - attr.getValue()); - } - - for (AttributeIterator ai = ((StartElement) xe).getNamespaces() - ; ai.hasNext();) - { - Attribute attr = ai.next(); - - XMLName name = attr.getName(); - String local = name.getLocalName(); - - if (name.getPrefix() == null && local.equals("xmlns")) - local = ""; - - context.xmlns(local, attr.getValue()); - } - - break; - - case XMLEvent.END_ELEMENT: - context.endElement(); - - if (lineNums) - lineNumber(xe, context); - - break; - - case XMLEvent.SPACE: - if (((Space) xe).ignorable()) - break; - - // Fall through - - case XMLEvent.CHARACTER_DATA: - CharacterData cd = (CharacterData) xe; - - if (cd.hasContent()) - { - context.text(cd.getContent()); - - if (lineNums) - lineNumber(xe, context); - } - - break; - - case XMLEvent.COMMENT: - org.apache.xmlbeans.xml.stream.Comment comment = - (org.apache.xmlbeans.xml.stream.Comment) xe; - - if (comment.hasContent()) - { - context.comment(comment.getContent()); - - if (lineNums) - lineNumber(xe, context); - } - - break; - - case XMLEvent.PROCESSING_INSTRUCTION: - ProcessingInstruction procInstr = (ProcessingInstruction) xe; - - context.procInst(procInstr.getTarget(), procInstr.getData()); - - if (lineNums) - lineNumber(xe, context); - - break; - - // These are ignored - case XMLEvent.ENTITY_REFERENCE: - case XMLEvent.START_PREFIX_MAPPING: - case XMLEvent.END_PREFIX_MAPPING: - case XMLEvent.CHANGE_PREFIX_MAPPING: - case XMLEvent.XML_EVENT: - break; - - default : - throw new RuntimeException( - "Unhandled xml event type: " + xe.getTypeAsString()); - } - } - - Cur c = context.finish(); - - associateSourceName(c, options); - - XmlDocumentProperties props = getDocProps(c, true); - - props.setDoctypeSystemId(systemId); - props.setEncoding(encoding); - props.setVersion(version); - props.setStandalone(standAlone); - - return c; - } - - private Cur loadXMLStreamReader(XMLStreamReader xsr, XmlOptions options) - throws XMLStreamException - { - options = XmlOptions.maskNull(options); - - boolean lineNums = options.hasOption(XmlOptions.LOAD_LINE_NUMBERS); - - String encoding = null, version = null; - boolean standAlone = false; - - LoadContext context = new Cur.CurLoadContext(this, options); - int depth = 0; - - events: - for (int eventType = xsr.getEventType(); ; eventType = xsr.next()) - { - switch (eventType) - { - case XMLStreamReader.START_DOCUMENT: - { - depth++; - - encoding = xsr.getCharacterEncodingScheme(); - version = xsr.getVersion(); - standAlone = xsr.isStandalone(); - - if (lineNums) - lineNumber(xsr, context); - - break; - } - - case XMLStreamReader.END_DOCUMENT: - { - depth--; - - if (lineNums) - lineNumber(xsr, context); - - break events; - } - - case XMLStreamReader.START_ELEMENT: - { - depth++; - context.startElement(xsr.getName()); - - if (lineNums) - lineNumber(xsr, context); - - doAttributes(xsr, context); - doNamespaces(xsr, context); - - break; - } - - case XMLStreamReader.END_ELEMENT: - { - depth--; - context.endElement(); - - if (lineNums) - lineNumber(xsr, context); - - break; - } - - case XMLStreamReader.CHARACTERS: - case XMLStreamReader.CDATA: - { - context.text(xsr.getTextCharacters(), xsr.getTextStart(), - xsr.getTextLength()); - - if (lineNums) - lineNumber(xsr, context); - - break; - } - - case XMLStreamReader.COMMENT: - { - String comment = xsr.getText(); - - context.comment(comment); - - if (lineNums) - lineNumber(xsr, context); - - break; - } - - case XMLStreamReader.PROCESSING_INSTRUCTION: - { - context.procInst(xsr.getPITarget(), xsr.getPIData()); - - if (lineNums) - lineNumber(xsr, context); - - break; - } - - case XMLStreamReader.ATTRIBUTE: - { - doAttributes(xsr, context); - break; - } - - case XMLStreamReader.NAMESPACE: - { - doNamespaces(xsr, context); - break; - } - - case XMLStreamReader.ENTITY_REFERENCE: - { - context.text(xsr.getText()); - break; - } - - case XMLStreamReader.SPACE: - case XMLStreamReader.DTD: - break; - - default : - throw new RuntimeException( - "Unhandled xml event type: " + eventType); - } - - if (!xsr.hasNext() || depth <= 0) - break; - } - - Cur c = context.finish(); - - associateSourceName(c, options); - - XmlDocumentProperties props = getDocProps(c, true); - - props.setEncoding(encoding); - props.setVersion(version); - props.setStandalone(standAlone); - - return c; - } - - // - // - // - - public static XmlObject parseToXmlObject(SchemaTypeLoader stl, - InputStream is, SchemaType type, XmlOptions options) - throws XmlException, IOException - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.parseToXmlObject(is, type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.parseToXmlObject(is, type, options); - } - finally - { - l.exit(); - } - } - } - - private XmlObject parseToXmlObject(InputStream is, SchemaType type, - XmlOptions options) - throws XmlException, IOException - { - Cur c = getSaxLoader(options).load(this, new InputSource(is), - options); - - autoTypeDocument(c, type, options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - // - // - // - - public static XmlObject parseToXmlObject(SchemaTypeLoader stl, - Reader reader, SchemaType type, XmlOptions options) - throws XmlException, IOException - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.parseToXmlObject(reader, type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.parseToXmlObject(reader, type, options); - } - finally - { - l.exit(); - } - } - } - - private XmlObject parseToXmlObject(Reader reader, SchemaType type, - XmlOptions options) - throws XmlException, IOException - { - Cur c = getSaxLoader(options).load(this, new InputSource(reader), - options); - - autoTypeDocument(c, type, options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - // - // - // - - public static XmlObject parseToXmlObject(SchemaTypeLoader stl, Node node, - SchemaType type, XmlOptions options) - throws XmlException - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.parseToXmlObject(node, type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.parseToXmlObject(node, type, options); - } - finally - { - l.exit(); - } - } - } - - public XmlObject parseToXmlObject(Node node, SchemaType type, - XmlOptions options) - throws XmlException - { - LoadContext context = new Cur.CurLoadContext(this, options); - - loadNode(node, context); - - Cur c = context.finish(); - - associateSourceName(c, options); - - autoTypeDocument(c, type, options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - return x; - } - - private void loadNodeChildren(Node n, LoadContext context) - { - for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling()) - loadNode(c, context); - } - - void loadNode(Node n, LoadContext context) - { - switch (n.getNodeType()) - { - case Node.DOCUMENT_NODE: - case Node.DOCUMENT_FRAGMENT_NODE: - case Node.ENTITY_REFERENCE_NODE: - { - loadNodeChildren(n, context); - - break; - } - case Node.ELEMENT_NODE: - { - context.startElement( - makeQualifiedQName(n.getNamespaceURI(), n.getNodeName())); - - NamedNodeMap attrs = n.getAttributes(); - - for (int i = 0; i < attrs.getLength(); i++) - { - Node a = attrs.item(i); - - String attrName = a.getNodeName(); - String attrValue = a.getNodeValue(); - - if (attrName.toLowerCase().startsWith("xmlns")) - { - if (attrName.length() == 5) - context.xmlns(null, attrValue); - else - context.xmlns(attrName.substring(6), attrValue); - } - else - context.attr( - makeQualifiedQName(a.getNamespaceURI(), attrName), - attrValue); - } - - loadNodeChildren(n, context); - - context.endElement(); - - break; - } - case Node.TEXT_NODE: - case Node.CDATA_SECTION_NODE: - { - context.text(n.getNodeValue()); - break; - } - case Node.COMMENT_NODE: - { - context.comment(n.getNodeValue()); - break; - } - case Node.PROCESSING_INSTRUCTION_NODE: - { - context.procInst(n.getNodeName(), n.getNodeValue()); - break; - } - case Node.DOCUMENT_TYPE_NODE: - case Node.ENTITY_NODE: - case Node.NOTATION_NODE: - case Node.ATTRIBUTE_NODE: - { - throw new RuntimeException("Unexpected node"); - } - } - } - - // - // - // - - private class XmlSaxHandlerImpl - extends SaxHandler - implements XmlSaxHandler - { - XmlSaxHandlerImpl(Locale l, SchemaType type, XmlOptions options) - { - super(null); - - _options = options; - _type = type; - - // Because SAX loading is not atomic with respect to XmlBeans, I can't use the default - // thread local CharUtil. Instruct the SaxHandler (and the LoadContext, eventually) - // to use the Locale specific CharUtil. - - XmlOptions saxHandlerOptions = new XmlOptions(options); - saxHandlerOptions.put(Cur.LOAD_USE_LOCALE_CHAR_UTIL); - - initSaxHandler(l, saxHandlerOptions); - } - - public ContentHandler getContentHandler() - { - return _context == null ? null : this; - } - - public LexicalHandler getLexicalHandler() - { - return _context == null ? null : this; - } - - public void bookmarkLastEvent(XmlBookmark mark) - { - _context.bookmarkLastNonAttr(mark); - } - - public void bookmarkLastAttr(QName attrName, XmlBookmark mark) - { - _context.bookmarkLastAttr(attrName, mark); - } - - public XmlObject getObject() - throws XmlException - { - if (_context == null) - return null; - - _locale.enter(); - - try - { - Cur c = _context.finish(); - - autoTypeDocument(c, _type, _options); - - XmlObject x = (XmlObject) c.getUser(); - - c.release(); - - _context = null; - - return x; - } - finally - { - _locale.exit(); - } - } - - private SchemaType _type; - private XmlOptions _options; - } - - public static XmlSaxHandler newSaxHandler(SchemaTypeLoader stl, - SchemaType type, XmlOptions options) - { - Locale l = getLocale(stl, options); - - if (l.noSync()) - { - l.enter(); - try - { - return l.newSaxHandler(type, options); - } - finally - { - l.exit(); - } - } - else - synchronized (l) - { - l.enter(); - try - { - return l.newSaxHandler(type, options); - } - finally - { - l.exit(); - } - } - } - - public XmlSaxHandler newSaxHandler(SchemaType type, XmlOptions options) - { - return new XmlSaxHandlerImpl(this, type, options); - } - - // TODO (ericvas ) - have a qname factory here so that the same factory may be - // used by the parser. This factory would probably come from my - // high speed parser. Otherwise, use a thread local on - - QName makeQName(String uri, String localPart) - { - assert localPart != null && localPart.length() > 0; - // TODO - make sure name is a well formed name? - - return _qnameFactory.getQName(uri, localPart); - } - - QName makeQNameNoCheck(String uri, String localPart) - { - return _qnameFactory.getQName(uri, localPart); - } - - QName makeQName(String uri, String local, String prefix) - { - return _qnameFactory.getQName(uri, local, prefix == null ? "" : prefix); - } - - QName makeQualifiedQName(String uri, String qname) - { - if (qname == null) - qname = ""; - - int i = qname.indexOf(':'); - - return i < 0 - ? - _qnameFactory.getQName(uri, qname) - : - _qnameFactory.getQName(uri, qname.substring(i + 1), - qname.substring(0, i)); - } - - static private class DocProps - extends XmlDocumentProperties - { - private HashMap _map = new HashMap(); - - public Object put(Object key, Object value) - { - return _map.put(key, value); - } - - public Object get(Object key) - { - return _map.get(key); - } - - public Object remove(Object key) - { - return _map.remove(key); - } - } - - static XmlDocumentProperties getDocProps(Cur c, boolean ensure) - { - c.push(); - - while (c.toParent()) - ; - - DocProps props = (DocProps) c.getBookmark(DocProps.class); - - if (props == null && ensure) - c.setBookmark(DocProps.class, props = new DocProps()); - - c.pop(); - - return props; - } - - interface ChangeListener - { - void notifyChange(); - - void setNextChangeListener(ChangeListener listener); - - ChangeListener getNextChangeListener(); - } - - void registerForChange(ChangeListener listener) - { - if (listener.getNextChangeListener() == null) - { - if (_changeListeners == null) - listener.setNextChangeListener(listener); - else - listener.setNextChangeListener(_changeListeners); - - _changeListeners = listener; - } - } - - void notifyChange() - { - // First, notify the registered listeners ... - - while (_changeListeners != null) - { - _changeListeners.notifyChange(); - - if (_changeListeners.getNextChangeListener() == _changeListeners) - _changeListeners.setNextChangeListener(null); - - ChangeListener next = _changeListeners.getNextChangeListener(); - - _changeListeners.setNextChangeListener(null); - - _changeListeners = next; - } - - // Then, prepare for the change in a locale specific way. Need to create real Curs for - // 'virtual' Curs in Locations - - _locations.notifyChange(); - } - - // - // Cursor helpers - // - - static String getTextValue(Cur c) - { - assert c.isNode(); - - if (!c.hasChildren()) - return c.getValueAsString(); - - StringBuffer sb = new StringBuffer(); - - c.push(); - - for (c.next(); !c.isAtEndOfLastPush(); c.next()) - if (c.isText()) - { - if ( (c._xobj.isComment() || c._xobj.isProcinst() ) && c._pos maxCch) - n = maxCch; - - if (n <= 0) - return 0; - - s.getChars(0, n, chars, off); - - return n; - } - - static String applyWhiteSpaceRule(String s, int wsr) - { - int l = s == null ? 0 : s.length(); - - if (l == 0 || wsr == WS_PRESERVE) - return s; - - char ch; - - if (wsr == WS_REPLACE) - { - for (int i = 0; i < l; i++) - if ((ch = s.charAt(i)) == '\n' || ch == '\r' || ch == '\t') - return processWhiteSpaceRule(s, wsr); - } - else if (wsr == Locale.WS_COLLAPSE) - { - if (CharUtil.isWhiteSpace(s.charAt(0)) || - CharUtil.isWhiteSpace(s.charAt(l - 1))) - return processWhiteSpaceRule(s, wsr); - - boolean lastWasWhite = false; - - for (int i = 1; i < l; i++) - { - boolean isWhite = CharUtil.isWhiteSpace(s.charAt(i)); - - if (isWhite && lastWasWhite) - return processWhiteSpaceRule(s, wsr); - - lastWasWhite = isWhite; - } - } - - return s; - } - - static String processWhiteSpaceRule(String s, int wsr) - { - ScrubBuffer sb = getScrubBuffer(wsr); - - sb.scrub(s, 0, s.length()); - - return sb.getResultAsString(); - } - - static final class ScrubBuffer - { - ScrubBuffer() - { - _sb = new StringBuffer(); - } - - void init(int wsr) - { - _sb.delete(0, _sb.length()); - - _wsr = wsr; - _state = START_STATE; - } - - void scrub(Object src, int off, int cch) - { - if (cch == 0) - return; - - if (_wsr == Locale.WS_PRESERVE) - { - CharUtil.getString(_sb, src, off, cch); - return; - } - - char[] chars; - - if (src instanceof char[]) - chars = (char[]) src; - else - { - if (cch <= _srcBuf.length) - chars = _srcBuf; - else if (cch <= 16384) - chars = _srcBuf = new char[16384]; - else - chars = new char[cch]; - - CharUtil.getChars(chars, 0, src, off, cch); - off = 0; - } - - int start = 0; - - for (int i = 0; i < cch; i++) - { - char ch = chars[off + i]; - - if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') - { - _sb.append(chars, off + start, i - start); - - start = i + 1; - - if (_wsr == Locale.WS_REPLACE) - _sb.append(' '); - else if (_state == NOSPACE_STATE) - _state = SPACE_SEEN_STATE; - } - else - { - if (_state == SPACE_SEEN_STATE) - _sb.append(' '); - - _state = NOSPACE_STATE; - } - } - - _sb.append(chars, off + start, cch - start); - } - - String getResultAsString() - { - return _sb.toString(); - } - - private static final int START_STATE = 0; - private static final int SPACE_SEEN_STATE = 1; - private static final int NOSPACE_STATE = 2; - - private int _state; - - private int _wsr; - - private char[] _srcBuf = new char[1024]; - private StringBuffer _sb; - } - - private static ThreadLocal tl_scrubBuffer = - new ThreadLocal() - { - protected Object initialValue() - { - return new SoftReference(new ScrubBuffer()); - } - }; - - static ScrubBuffer getScrubBuffer(int wsr) - { - SoftReference softRef = (SoftReference) tl_scrubBuffer.get(); - ScrubBuffer scrubBuffer = (ScrubBuffer) (softRef).get(); - if (scrubBuffer == null) - { - scrubBuffer = new ScrubBuffer(); - tl_scrubBuffer.set(new SoftReference(scrubBuffer)); - } - - scrubBuffer.init(wsr); - return scrubBuffer; - } - - static boolean pushToContainer(Cur c) - { - c.push(); - - for (; ;) - { - switch (c.kind()) - { - case ROOT: - case ELEM: - return true; - case -ROOT: - case -ELEM: - c.pop(); - return false; - case COMMENT: - case PROCINST: - c.skip(); - break; - default : - c.nextWithAttrs(); - break; - } - } - } - - static boolean toFirstNormalAttr(Cur c) - { - c.push(); - - if (c.toFirstAttr()) - { - do - { - if (!c.isXmlns()) - { - c.popButStay(); - return true; - } - } - while (c.toNextAttr()); - } - - c.pop(); - - return false; - } - - static boolean toPrevNormalAttr(Cur c) - { - if (c.isAttr()) - { - c.push(); - - for (; ;) - { - assert c.isAttr(); - - // See if I can move backward. If I'm at the first attr, prev must return - // false and not move. - - if (!c.prev()) - break; - - // Skip past the text value or attr begin - - c.prev(); - - // I might have skipped over text above - - if (!c.isAttr()) - c.prev(); - - if (c.isNormalAttr()) - { - c.popButStay(); - return true; - } - } - - c.pop(); - } - - return false; - } - - static boolean toNextNormalAttr(Cur c) - { - c.push(); - - while (c.toNextAttr()) - { - if (!c.isXmlns()) - { - c.popButStay(); - return true; - } - } - - c.pop(); - - return false; - } - - Xobj findNthChildElem(Xobj parent, QName name, QNameSet set, int n) - { - // only one of (set or name) is not null - // or both are null for a wildcard - assert (name == null || set == null); - assert n >= 0; - - if (parent == null) - return null; - - int da = _nthCache_A.distance(parent, name, set, n); - int db = _nthCache_B.distance(parent, name, set, n); - - Xobj x = - da <= db - ? _nthCache_A.fetch(parent, name, set, n) - : _nthCache_B.fetch(parent, name, set, n); - - if (da == db) - { - nthCache temp = _nthCache_A; - _nthCache_A = _nthCache_B; - _nthCache_B = temp; - } - - return x; - } - - int count(Xobj parent, QName name, QNameSet set) - { - int n = 0; - - for (Xobj x = findNthChildElem(parent, name, set, 0); - x != null; x = x._nextSibling) - { - if (x.isElem()) - { - if (set == null) - { - if (x._name.equals(name)) - n++; - } - else if (set.contains(x._name)) - n++; - } - } - - return n; - } - - static boolean toChild(Cur c, QName name, int n) - { - if (n >= 0 && pushToContainer(c)) - { - Xobj x = c._locale.findNthChildElem(c._xobj, name, null, n); - - c.pop(); - - if (x != null) - { - c.moveTo(x); - return true; - } - } - - return false; - } - - static boolean toFirstChildElement(Cur c) - { -// if (!pushToContainer(c)) -// return false; -// -// if (!c.toFirstChild() || (!c.isElem() && !toNextSiblingElement(c))) -// { -// c.pop(); -// return false; -// } -// -// c.popButStay(); -// -// return true; - - Xobj originalXobj = c._xobj; - int originalPos = c._pos; - - loop: - for (; ;) - { - switch (c.kind()) - { - case ROOT: - case ELEM: - break loop; - case -ROOT: - case -ELEM: - c.moveTo(originalXobj, originalPos); - return false; - case COMMENT: - case PROCINST: - c.skip(); - break; - default: - c.nextWithAttrs(); - break; - } - } - - if (!c.toFirstChild() || (!c.isElem() && !toNextSiblingElement(c))) - { - c.moveTo(originalXobj, originalPos); - return false; - } - - return true; - } - - static boolean toLastChildElement(Cur c) - { - if (!pushToContainer(c)) - return false; - - if (!c.toLastChild() || (!c.isElem() && !toPrevSiblingElement(c))) - { - c.pop(); - return false; - } - - c.popButStay(); - - return true; - } - - static boolean toPrevSiblingElement(Cur cur) - { - if (!cur.hasParent()) - return false; - - Cur c = cur.tempCur(); - - boolean moved = false; - - int k = c.kind(); - - if (k != ATTR) - { - for (; ;) - { - if (!c.prev()) - break; - - k = c.kind(); - - if (k == ROOT || k == ELEM) - break; - - if (c.kind() == -ELEM) - { - c.toParent(); - - cur.moveToCur(c); - moved = true; - - break; - } - } - } - - c.release(); - - return moved; - } - - static boolean toNextSiblingElement(Cur c) - { - if (!c.hasParent()) - return false; - - c.push(); - - int k = c.kind(); - - if (k == ATTR) - { - c.toParent(); - c.next(); - } - else if (k == ELEM) - c.skip(); - - while ((k = c.kind()) >= 0) - { - if (k == ELEM) - { - c.popButStay(); - return true; - } - - if (k > 0) - c.toEnd(); - - c.next(); - } - - c.pop(); - - return false; - } - - static boolean toNextSiblingElement(Cur c, Xobj parent) - { - Xobj originalXobj = c._xobj; - int originalPos = c._pos; - - int k = c.kind(); - - if (k == ATTR) - { - c.moveTo(parent); - c.next(); - } - else if (k == ELEM) - c.skip(); - - while ((k = c.kind()) >= 0) - { - if (k == ELEM) - { - return true; - } - - if (k > 0) - c.toEnd(); - - c.next(); - } - - c.moveTo(originalXobj, originalPos); - - return false; - } - - static void applyNamespaces(Cur c, Map namespaces) - { - assert c.isContainer(); - - java.util.Iterator i = namespaces.keySet().iterator(); - - while (i.hasNext()) - { - String prefix = (String) i.next(); - - // Usually, this is the predefined xml namespace - if (!prefix.toLowerCase().startsWith("xml")) - { - if (c.namespaceForPrefix(prefix, false) == null) - { - c.push(); - - c.next(); - c.createAttr(c._locale.createXmlns(prefix)); - c.next(); - - c.insertString((String) namespaces.get(prefix)); - - c.pop(); - } - } - } - } - - static Map getAllNamespaces(Cur c, Map filleMe) - { - assert c.isNode(); - - c.push(); - - if (!c.isContainer()) - c.toParent(); - - assert c.isContainer(); - - do - { - QName cName = c.getName(); - - while (c.toNextAttr()) - { - if (c.isXmlns()) - { - String prefix = c.getXmlnsPrefix(); - String uri = c.getXmlnsUri(); - - if (filleMe == null) - filleMe = new HashMap(); - - if (!filleMe.containsKey(prefix)) - filleMe.put(prefix, uri); - } - } - - if (!c.isContainer()) - c.toParentRaw(); - } - while (c.toParentRaw()); - - c.pop(); - - return filleMe; - } - - class nthCache - { - private boolean namesSame(QName pattern, QName name) - { - return pattern == null || pattern.equals(name); - } - - private boolean setsSame(QNameSet patternSet, QNameSet set) - { - // value equality is probably too expensive. Since the use case - // involves QNameSets that are generated by the compiler, we - // can use identity comparison. - - return patternSet != null && patternSet == set; - } - - private boolean nameHit(QName namePattern, QNameSet setPattern, - QName name) - { - return - setPattern == null - ? namesSame(namePattern, name) - : setPattern.contains(name); - } - - private boolean cacheSame(QName namePattern, QNameSet setPattern) - { - return - setPattern == null - ? namesSame(namePattern, _name) - : setsSame(setPattern, _set); - } - - int distance(Xobj parent, QName name, QNameSet set, int n) - { - assert n >= 0; - - if (_version != Locale.this.version()) - return Integer.MAX_VALUE - 1; - - if (parent != _parent || !cacheSame(name, set)) - return Integer.MAX_VALUE; - - return n > _n ? n - _n : _n - n; - } - - Xobj fetch(Xobj parent, QName name, QNameSet set, int n) - { - assert n >= 0; - - if (_version != Locale.this.version() || _parent != parent || - !cacheSame(name, set) || n == 0) - { - _version = Locale.this.version(); - _parent = parent; - _name = name; - _child = null; - _n = -1; - - loop: - for (Xobj x = parent._firstChild; - x != null; x = x._nextSibling) - { - if (x.isElem() && nameHit(name, set, x._name)) - { - _child = x; - _n = 0; - - break loop; - } - } - } - - if (_n < 0) - return null; - - if (n > _n) - { - while (n > _n) - { - for (Xobj x = _child._nextSibling; ; x = x._nextSibling) - { - if (x == null) - return null; - - if (x.isElem() && nameHit(name, set, x._name)) - { - _child = x; - _n++; - - break; - } - } - } - } - else if (n < _n) - { - while (n < _n) - { - for (Xobj x = _child._prevSibling; ; x = x._prevSibling) - { - if (x == null) - return null; - - if (x.isElem() && nameHit(name, set, x._name)) - { - _child = x; - _n--; - - break; - } - } - } - } - - return _child; - } - - private long _version; - private Xobj _parent; - private QName _name; - private QNameSet _set; - private Xobj _child; - private int _n; - } - - // - // - // - - Dom findDomNthChild ( Dom parent, int n ) - { - assert n >= 0; - - if (parent == null) - return null; - - int da = _domNthCache_A.distance(parent, n); - int db = _domNthCache_B.distance(parent, n); - - - // the "better" cache should never walk more than 1/2 len - Dom x = null; - boolean bInvalidate = (db - _domNthCache_B._len / 2 > 0) && - (db - _domNthCache_B._len / 2 - domNthCache.BLITZ_BOUNDARY > 0); - boolean aInvalidate = (da - _domNthCache_A._len / 2 > 0) && - (da - _domNthCache_A._len / 2 - domNthCache.BLITZ_BOUNDARY > 0); - if (da <= db) - if (!aInvalidate) - x = _domNthCache_A.fetch(parent, n); - else - { - _domNthCache_B._version = -1;//blitz the cache - x = _domNthCache_B.fetch(parent, n); - } - else if (!bInvalidate) - x = _domNthCache_B.fetch(parent, n); - else - { - _domNthCache_A._version = -1;//blitz the cache - x = _domNthCache_A.fetch(parent, n); - } - - if (da == db) - { - domNthCache temp = _domNthCache_A; - _domNthCache_A = _domNthCache_B; - _domNthCache_B = temp; - } - - return x; - } - - int domLength ( Dom parent ) - { - if (parent == null) - return 0; - - int da = _domNthCache_A.distance( parent, 0 ); - int db = _domNthCache_B.distance( parent, 0 ); - - int len = - da <= db - ? _domNthCache_A.length( parent ) - : _domNthCache_B.length( parent ); - - if (da == db) - { - domNthCache temp = _domNthCache_A; - _domNthCache_A = _domNthCache_B; - _domNthCache_B = temp; - } - - return len; - } - - void invalidateDomCaches ( Dom d ) - { - if (_domNthCache_A._parent == d) - _domNthCache_A._version = -1; - if (_domNthCache_B._parent == d) - _domNthCache_B._version = -1; - } - - boolean isDomCached ( Dom d ) - { - return _domNthCache_A._parent == d || _domNthCache_B._parent == d; - } - - class domNthCache - { - - int distance ( Dom parent, int n ) - { - assert n >= 0; - - if (_version != Locale.this.version()) - return Integer.MAX_VALUE - 1; - - if (parent != _parent) - return Integer.MAX_VALUE; - - return n > _n ? n - _n : _n - n; - } - - int length ( Dom parent ) - { - if (_version != Locale.this.version() || _parent != parent) - { - _parent = parent; - _version = Locale.this.version(); - _child = null; - _n = -1; - _len = -1; - } - - if (_len == -1) - { - Dom x = null; - - if (_child != null && _n != -1) - { - x = _child; - _len = _n; - } - else - { - x = DomImpl.firstChild(_parent); - _len = 0; - - // cache the 0th child - _child = x; - _n = 0; - } - - for (; x != null; x = DomImpl.nextSibling(x) ) - { - _len++; - } - } - - - return _len; - } - - Dom fetch ( Dom parent, int n ) - { - assert n >= 0; - - if (_version != Locale.this.version() || _parent != parent) - { - _parent = parent; - _version = Locale.this.version(); - _child = null; - _n = -1; - _len = -1; - - for (Dom x = DomImpl.firstChild(_parent); x != null; x = DomImpl.nextSibling(x) ) - { - _n++; - if (_child == null && n == _n ) - { - _child = x; - break; - } - } - - return _child; - } - - if (_n < 0) - return null; - - if (n > _n) - { - while ( n > _n ) - { - for (Dom x = DomImpl.nextSibling(_child); ; x = DomImpl.nextSibling(x) ) - { - if (x == null) - return null; - - _child = x; - _n++; - - break; - } - } - } - else if (n < _n) - { - while ( n < _n ) - { - for (Dom x = DomImpl.prevSibling(_child); ; x = DomImpl.prevSibling(x) ) - { - if (x == null) - return null; - - _child = x; - _n--; - - break; - } - } - } - - return _child; - } - - public static final int BLITZ_BOUNDARY = 40; //walk small lists - private long _version; - private Dom _parent; - private Dom _child; - private int _n; - private int _len; - } - - // - // - // - - CharUtil getCharUtil() - { - if (_charUtil == null) - _charUtil = new CharUtil(1024); - - return _charUtil; - } - - long version() - { - return _versionAll; - } - - Cur weakCur(Object o) - { - assert o != null && !(o instanceof Ref); - - Cur c = getCur(); - - assert c._tempFrame == -1; - assert c._ref == null; - - c._ref = new Ref(c, o); - - return c; - } - - final ReferenceQueue refQueue() - { - if (_refQueue == null) - _refQueue = new ReferenceQueue(); - - return _refQueue; - } - - final static class Ref - extends PhantomReference - { - Ref(Cur c, Object obj) - { - super(obj, c._locale.refQueue()); - - _cur = c; - } - - Cur _cur; - } - - Cur tempCur() - { - return tempCur(null); - } - - Cur tempCur(String id) - { - Cur c = getCur(); - - assert c._tempFrame == -1; - - assert _numTempFramesLeft < _tempFrames.length : "Temp frame not pushed"; - - int frame = _tempFrames.length - _numTempFramesLeft - 1; - - assert frame >= 0 && frame < _tempFrames.length; - - Cur next = _tempFrames[frame]; - - c._nextTemp = next; - assert c._prevTemp == null; - - if (next != null) - { - assert next._prevTemp == null; - next._prevTemp = c; - } - - _tempFrames[frame] = c; - c._tempFrame = frame; - - c._id = id; - - return c; - } - - Cur getCur() - { - assert _curPool == null || _curPoolCount > 0; - - Cur c; - - if (_curPool == null) - c = new Cur(this); - else - { - _curPool = _curPool.listRemove(c = _curPool); - _curPoolCount--; - } - - assert c._state == Cur.POOLED; - assert c._prev == null && c._next == null; - assert c._xobj == null && c._pos == Cur.NO_POS; - assert c._ref == null; - - _registered = c.listInsert(_registered); - c._state = Cur.REGISTERED; - - return c; - } - - void embedCurs() - { - for (Cur c; (c = _registered) != null;) - { - assert c._xobj != null; - - _registered = c.listRemove(_registered); - c._xobj._embedded = c.listInsert(c._xobj._embedded); - c._state = Cur.EMBEDDED; - } - } - - TextNode createTextNode() - { - return _saaj == null ? new TextNode(this) : new SaajTextNode(this); - } - - CdataNode createCdataNode() - { - return _saaj == null ? - new CdataNode(this) : new SaajCdataNode(this); - } - - boolean entered() - { - return _tempFrames.length - _numTempFramesLeft > 0; - } - - public void enter(Locale otherLocale) - { - enter(); - - if (otherLocale != this) - otherLocale.enter(); - } - - public void enter() - { - assert _numTempFramesLeft >= 0; - - if (--_numTempFramesLeft <= 0) - { - Cur[] newTempFrames = new Cur[_tempFrames.length * 2]; - //move this assignment down so if array allocation fails, error is not masked - _numTempFramesLeft = _tempFrames.length; - System.arraycopy(_tempFrames, 0, newTempFrames, 0, - _tempFrames.length); - _tempFrames = newTempFrames; - } - - if (++_entryCount > 1000) - { - pollQueue(); - _entryCount = 0; - } - } - - private void pollQueue() - { - if (_refQueue != null) - { - for (; ;) - { - Ref ref = (Ref) _refQueue.poll(); - - if (ref == null) - break; - - if (ref._cur != null) - ref._cur.release(); - } - } - } - - public void exit(Locale otherLocale) - { - exit(); - - if (otherLocale != this) - otherLocale.exit(); - } - - public void exit() - { - // assert _numTempFramesLeft >= 0; - //asserts computed frame fits between 0 and _tempFrames.length - assert _numTempFramesLeft >= 0 && - (_numTempFramesLeft <= _tempFrames.length - 1): - " Temp frames mismanaged. Impossible stack frame. Unsynchronized: " + - noSync(); - - int frame = _tempFrames.length - ++_numTempFramesLeft; - - while (_tempFrames[frame] != null) - _tempFrames[frame].release(); - } - - // - // - // - - public boolean noSync() - { - return _noSync; - } - - public boolean sync() - { - return !_noSync; - } - - static final boolean isWhiteSpace(String s) - { - int l = s.length(); - - while (l-- > 0) - if (!CharUtil.isWhiteSpace(s.charAt(l))) - return false; - - return true; - } - - static final boolean isWhiteSpace(StringBuffer sb) - { - int l = sb.length(); - - while (l-- > 0) - if (!CharUtil.isWhiteSpace(sb.charAt(l))) - return false; - - return true; - } - - static boolean beginsWithXml(String name) - { - if (name.length() < 3) - return false; - - char ch; - - if (((ch = name.charAt(0)) == 'x' || ch == 'X') && - ((ch = name.charAt(1)) == 'm' || ch == 'M') && - ((ch = name.charAt(2)) == 'l' || ch == 'L')) - { - return true; - } - - return false; - } - - static boolean isXmlns(QName name) - { - String prefix = name.getPrefix(); - - if (prefix.equals("xmlns")) - return true; - - return prefix.length() == 0 && name.getLocalPart().equals("xmlns"); - } - - QName createXmlns(String prefix) - { - if (prefix == null) - prefix = ""; - - return - prefix.length() == 0 - ? makeQName(_xmlnsUri, "xmlns", "") - : makeQName(_xmlnsUri, prefix, "xmlns"); - } - - static String xmlnsPrefix(QName name) - { - return name.getPrefix().equals("xmlns") ? name.getLocalPart() : ""; - } - - // - // Loading/parsing - // - - static abstract class LoadContext - { - protected abstract void startDTD(String name, String publicId, - String systemId); - - protected abstract void endDTD(); - - protected abstract void startElement(QName name); - - protected abstract void endElement(); - - protected abstract void attr(QName name, String value); - - protected abstract void attr(String local, String uri, String prefix, - String value); - - protected abstract void xmlns(String prefix, String uri); - - protected abstract void comment(char[] buff, int off, int cch); - - protected abstract void comment(String comment); - - protected abstract void procInst(String target, String value); - - protected abstract void text(char[] buff, int off, int cch); - - protected abstract void text(String s); - - protected abstract Cur finish(); - - protected abstract void abort(); - - protected abstract void bookmark(XmlBookmark bm); - - protected abstract void bookmarkLastNonAttr(XmlBookmark bm); - - protected abstract void bookmarkLastAttr(QName attrName, - XmlBookmark bm); - - protected abstract void lineNumber(int line, int column, int offset); - - protected void addIdAttr(String eName, String aName){ - if ( _idAttrs == null ) - _idAttrs = new java.util.Hashtable(); - _idAttrs.put(aName,eName); - } - - protected boolean isAttrOfTypeId(QName aqn, QName eqn){ - if (_idAttrs == null) - return false; - String pre = aqn.getPrefix(); - String lName = aqn.getLocalPart(); - String urnName = "".equals(pre)?lName:pre + ":" + lName; - String eName = (String) _idAttrs.get(urnName); - if (eName == null ) return false; - //get the name of the parent elt - pre = eqn.getPrefix(); - lName = eqn.getLocalPart(); - lName = eqn.getLocalPart(); - urnName = "".equals(pre)?lName:pre + ":" + lName; - return eName.equals(urnName); - } - private java.util.Hashtable _idAttrs; - } - - private static class DefaultEntityResolver - implements EntityResolver - { - public InputSource resolveEntity(String publicId, String systemId) - { - return new InputSource(new StringReader("")); - } - } - - private static SaxLoader getSaxLoader(XmlOptions options) throws XmlException - { - options = XmlOptions.maskNull(options); - - EntityResolver er = null; - - if (!options.hasOption(XmlOptions.LOAD_USE_DEFAULT_RESOLVER)) - { - er = (EntityResolver) options.get(XmlOptions.ENTITY_RESOLVER); - - if (er == null) - er = ResolverUtil.getGlobalEntityResolver(); - - if (er == null) - er = new DefaultEntityResolver(); - } - - XMLReader xr = (XMLReader) options.get( - XmlOptions.LOAD_USE_XMLREADER); - - if (xr == null) { - try { - xr = SAXHelper.newXMLReader(new XmlOptionsBean(options)); - } catch(Exception e) { - throw new XmlException("Problem creating XMLReader", e); - } - } - - SaxLoader sl = new XmlReaderSaxLoader(xr); - - // I've noticed that most XMLReaders don't like a null EntityResolver... - - if (er != null) - xr.setEntityResolver(er); - - return sl; - } - - private static class XmlReaderSaxLoader - extends SaxLoader - { - XmlReaderSaxLoader(XMLReader xr) - { - super(xr, null); - } - } - - private static abstract class SaxHandler - implements ContentHandler, LexicalHandler , DeclHandler, DTDHandler - { - SaxHandler(Locator startLocator) - { - _startLocator = startLocator; - } - - SaxHandler() - { - this(null); - } - - void initSaxHandler(Locale l, XmlOptions options) - { - _locale = l; - - options = XmlOptions.maskNull(options); - - _context = new Cur.CurLoadContext(_locale, options); - - _wantLineNumbers = - _startLocator != null && - options.hasOption(XmlOptions.LOAD_LINE_NUMBERS); - _wantLineNumbersAtEndElt = - _startLocator != null && - options.hasOption(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT); - _wantCdataBookmarks = - _startLocator != null && - options.hasOption(XmlOptions.LOAD_SAVE_CDATA_BOOKMARKS); - - if (options.hasOption(XmlOptions.LOAD_ENTITY_BYTES_LIMIT)) - _entityBytesLimit = ((Integer)(options.get(XmlOptions.LOAD_ENTITY_BYTES_LIMIT))).intValue(); - } - - public void startDocument() - throws SAXException - { - // Do nothing ... start of document is implicit - } - - public void endDocument() - throws SAXException - { - // Do nothing ... end of document is implicit - } - - public void startElement(String uri, String local, String qName, - Attributes atts) - throws SAXException - { - if (local.length() == 0) - local = qName; - - // Out current parser does not error when a - // namespace is used and not defined. Check for these here - - if (qName.indexOf(':') >= 0 && uri.length() == 0) - { - XmlError err = - XmlError.forMessage("Use of undefined namespace prefix: " + - qName.substring(0, qName.indexOf(':'))); - - throw new XmlRuntimeException(err.toString(), null, err); - } - - _context.startElement(_locale.makeQualifiedQName(uri, qName)); - - if (_wantLineNumbers) - { - _context.bookmark( - new XmlLineNumber(_startLocator.getLineNumber(), - _startLocator.getColumnNumber() - 1, -1)); - } - - for (int i = 0, len = atts.getLength(); i < len; i++) - { - String aqn = atts.getQName(i); - - if (aqn.equals("xmlns")) - { - _context.xmlns("", atts.getValue(i)); - } - else if (aqn.startsWith("xmlns:")) - { - String prefix = aqn.substring(6); - - if (prefix.length() == 0) - { - XmlError err = - XmlError.forMessage("Prefix not specified", - XmlError.SEVERITY_ERROR); - - throw new XmlRuntimeException(err.toString(), null, - err); - } - - String attrUri = atts.getValue(i); - - if (attrUri.length() == 0) - { - XmlError err = - XmlError.forMessage( - "Prefix can't be mapped to no namespace: " + - prefix, - XmlError.SEVERITY_ERROR); - - throw new XmlRuntimeException(err.toString(), null, - err); - } - - _context.xmlns(prefix, attrUri); - } - else - { - int colon = aqn.indexOf(':'); - - if (colon < 0) - _context.attr(aqn, atts.getURI(i), null, - atts.getValue(i)); - else - { - _context.attr(aqn.substring(colon + 1), atts.getURI(i), aqn.substring( - 0, colon), - atts.getValue(i)); - } - } - } - } - - public void endElement(String namespaceURI, String localName, - String qName) - throws SAXException - { - _context.endElement(); - if (_wantLineNumbersAtEndElt) - { - _context.bookmark( - new XmlLineNumber(_startLocator.getLineNumber(), - _startLocator.getColumnNumber() - 1, -1)); - } - } - - public void characters(char ch[], int start, int length) - throws SAXException - { - _context.text(ch, start, length); - - if (_wantCdataBookmarks && _insideCDATA) - _context.bookmarkLastNonAttr(CDataBookmark.CDATA_BOOKMARK); - - if (_insideEntity!=0) - { - if ((_entityBytes += length) > _entityBytesLimit) - { - XmlError err = XmlError.forMessage(XmlErrorCodes.EXCEPTION_EXCEEDED_ENTITY_BYTES, - new Integer[]{ new Integer(_entityBytesLimit) }); - - throw new SAXException(err.getMessage()); - } - } - } - - public void ignorableWhitespace(char ch[], int start, int length) - throws SAXException - { - } - - public void comment(char ch[], int start, int length) - throws SAXException - { - _context.comment(ch, start, length); - } - - public void processingInstruction(String target, String data) - throws SAXException - { - _context.procInst(target, data); - } - - public void startDTD(String name, String publicId, String systemId) - throws SAXException - { - _context.startDTD(name, publicId, systemId); - } - - public void endDTD() - throws SAXException - { - _context.endDTD(); - } - - public void startPrefixMapping(String prefix, String uri) - throws SAXException - { - if (beginsWithXml(prefix) && - !("xml".equals(prefix) && _xml1998Uri.equals(uri))) - { - XmlError err = - XmlError.forMessage( - "Prefix can't begin with XML: " + prefix, - XmlError.SEVERITY_ERROR); - - throw new XmlRuntimeException(err.toString(), null, err); - } - } - - public void endPrefixMapping(String prefix) - throws SAXException - { - } - - public void skippedEntity(String name) - throws SAXException - { -// throw new RuntimeException( "Not impl: skippedEntity" ); - } - - public void startCDATA() - throws SAXException - { - _insideCDATA = true; - } - - public void endCDATA() - throws SAXException - { - _insideCDATA = false; - } - - public void startEntity(String name) - throws SAXException - { - _insideEntity++; - } - - public void endEntity(String name) - throws SAXException - { - _insideEntity--; - assert _insideEntity>=0; - - if (_insideEntity==0) - { - _entityBytes=0; - } - } - - public void setDocumentLocator(Locator locator) - { - // TODO - for non-Piccolo use cases, use a locator to get line numbers - } - //DeclHandler - public void attributeDecl(String eName, String aName, String type, String valueDefault, String value){ - if (type.equals("ID")){ - _context.addIdAttr(eName,aName); - } - } - public void elementDecl(String name, String model){ - } - public void externalEntityDecl(String name, String publicId, String systemId){ - } - public void internalEntityDecl(String name, String value){ - } - - //DTDHandler - public void notationDecl(String name, String publicId, String systemId){ - } - public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName){ - } - protected Locale _locale; - - protected LoadContext _context; - - private boolean _wantLineNumbers; - private boolean _wantLineNumbersAtEndElt; - private boolean _wantCdataBookmarks; - private Locator _startLocator; - private boolean _insideCDATA = false; - private int _entityBytesLimit = 10240; - private int _entityBytes = 0; - private int _insideEntity = 0; - } - - private static abstract class SaxLoader - extends SaxHandler - implements ErrorHandler - { - SaxLoader(XMLReader xr, Locator startLocator) - { - super(startLocator); - - _xr = xr; - - try - { - _xr.setFeature( - "http://xml.org/sax/features/namespace-prefixes", true); - _xr.setFeature("http://xml.org/sax/features/namespaces", true); - _xr.setFeature("http://xml.org/sax/features/validation", false); - _xr.setProperty( - "http://xml.org/sax/properties/lexical-handler", this); - _xr.setContentHandler(this); - _xr.setProperty("http://xml.org/sax/properties/declaration-handler", this); - _xr.setDTDHandler(this); - _xr.setErrorHandler(this); - } - catch (Throwable e) - { - throw new RuntimeException(e.getMessage(), e); - } - } - - void setEntityResolver(EntityResolver er) - { - _xr.setEntityResolver(er); - } - - void postLoad(Cur c) - { - // fix garbage collection of Locale -> Xobj -> STL - _locale = null; - _context = null; - } - - public Cur load(Locale l, InputSource is, XmlOptions options) - throws XmlException, IOException - { - is.setSystemId("file://"); - - initSaxHandler(l, options); - - try - { - _xr.parse(is); - - Cur c = _context.finish(); - - associateSourceName(c, options); - - postLoad(c); - - return c; - } - catch (XmlRuntimeException e) - { - _context.abort(); - - throw new XmlException(e); - } - catch (SAXParseException e) - { - _context.abort(); - - XmlError err = - XmlError.forLocation(e.getMessage(), - (String) XmlOptions.safeGet(options, - XmlOptions.DOCUMENT_SOURCE_NAME), - e.getLineNumber(), e.getColumnNumber(), -1); - - throw new XmlException(err.toString(), e, err); - } - catch (SAXException e) - { - _context.abort(); - - XmlError err = XmlError.forMessage(e.getMessage()); - - throw new XmlException(err.toString(), e, err); - } - catch (RuntimeException e) - { - _context.abort(); - - throw e; - } - } - - public void fatalError(SAXParseException e) - throws SAXException - { - throw e; - } - - public void error(SAXParseException e) - throws SAXException - { - throw e; - } - - public void warning(SAXParseException e) - throws SAXException - { - throw e; - } - - private XMLReader _xr; - } - - private Dom load(InputSource is, XmlOptions options) - throws XmlException, IOException - { - return getSaxLoader(options).load(this, is, options).getDom(); - } - - public Dom load(Reader r) - throws XmlException, IOException - { - return load(r, null); - } - - public Dom load(Reader r, XmlOptions options) - throws XmlException, IOException - { - return load(new InputSource(r), options); - } - - public Dom load(InputStream in) - throws XmlException, IOException - { - return load(in, null); - } - - public Dom load(InputStream in, XmlOptions options) - throws XmlException, IOException - { - return load(new InputSource(in), options); - } - - public Dom load(String s) - throws XmlException - { - return load(s, null); - } - - public Dom load(String s, XmlOptions options) - throws XmlException - { - Reader r = new StringReader(s); - - try - { - return load(r, options); - } - catch (IOException e) - { - assert false: "StringReader should not throw IOException"; - - throw new XmlException(e.getMessage(), e); - } - finally - { - try - { - r.close(); - } - catch (IOException e) - { - } - } - } - - // - // DOMImplementation methods - // - - public Document createDocument(String uri, String qname, - DocumentType doctype) - { - return DomImpl._domImplementation_createDocument(this, uri, qname, - doctype); - } - - public DocumentType createDocumentType(String qname, String publicId, - String systemId) - { - throw new RuntimeException("Not implemented"); -// return DomImpl._domImplementation_createDocumentType( this, qname, publicId, systemId ); - } - - public boolean hasFeature(String feature, String version) - { - return DomImpl._domImplementation_hasFeature(this, feature, version); - } - - public Object getFeature(String feature, String version) - { - throw new RuntimeException("DOM Level 3 Not implemented"); - } - - // - // Dom methods - // - - private static Dom checkNode(Node n) - { - if (n == null) - throw new IllegalArgumentException("Node is null"); - - if (!(n instanceof Dom)) - throw new IllegalArgumentException("Node is not an XmlBeans node"); - - return (Dom) n; - } - - public static XmlCursor nodeToCursor(Node n) - { - return DomImpl._getXmlCursor(checkNode(n)); - } - - public static XmlObject nodeToXmlObject(Node n) - { - return DomImpl._getXmlObject(checkNode(n)); - } - - public static XMLStreamReader nodeToXmlStream(Node n) - { - return DomImpl._getXmlStreamReader(checkNode(n)); - } - - public static Node streamToNode(XMLStreamReader xs) - { - return Jsr173.nodeFromStream(xs); - } - - // - // SaajCallback methods - // - - public void setSaajData(Node n, Object o) - { - assert n instanceof Dom; - - DomImpl.saajCallback_setSaajData((Dom) n, o); - } - - public Object getSaajData(Node n) - { - assert n instanceof Dom; - - return DomImpl.saajCallback_getSaajData((Dom) n); - } - - public Element createSoapElement(QName name, QName parentName) - { - assert _ownerDoc != null; - - return DomImpl.saajCallback_createSoapElement(_ownerDoc, name, - parentName); - } - - public Element importSoapElement(Document doc, Element elem, boolean deep, - QName parentName) - { - assert doc instanceof Dom; - - return DomImpl.saajCallback_importSoapElement((Dom) doc, elem, deep, - parentName); - } - - - private static final class DefaultQNameFactory - implements QNameFactory - { - private QNameCache _cache = XmlBeans.getQNameCache(); - - public QName getQName(String uri, String local) - { - return _cache.getName(uri, local, ""); - } - - public QName getQName(String uri, String local, String prefix) - { - return _cache.getName(uri, local, prefix); - } - - public QName getQName(char[] uriSrc, int uriPos, int uriCch, - char[] localSrc, int localPos, int localCch) - { - return - _cache.getName(new String(uriSrc, uriPos, uriCch), - new String(localSrc, localPos, localCch), - ""); - } - - public QName getQName(char[] uriSrc, int uriPos, int uriCch, - char[] localSrc, int localPos, int localCch, - char[] prefixSrc, int prefixPos, int prefixCch) - { - return - _cache.getName(new String(uriSrc, uriPos, uriCch), - new String(localSrc, localPos, localCch), - new String(prefixSrc, prefixPos, prefixCch)); - } - } - - - private static final class LocalDocumentQNameFactory - implements QNameFactory - { - private QNameCache _cache = new QNameCache( 32 ); - - public QName getQName(String uri, String local) - { - return _cache.getName(uri, local, ""); - } - - public QName getQName(String uri, String local, String prefix) - { - return _cache.getName(uri, local, prefix); - } - - public QName getQName(char[] uriSrc, int uriPos, int uriCch, - char[] localSrc, int localPos, int localCch) - { - return - _cache.getName(new String(uriSrc, uriPos, uriCch), - new String(localSrc, localPos, localCch), - ""); - } - - public QName getQName(char[] uriSrc, int uriPos, int uriCch, - char[] localSrc, int localPos, int localCch, - char[] prefixSrc, int prefixPos, int prefixCch) - { - return - _cache.getName(new String(uriSrc, uriPos, uriCch), - new String(localSrc, localPos, localCch), - new String(prefixSrc, prefixPos, prefixCch)); - } - } - - // - // - // - - boolean _noSync; - - SchemaTypeLoader _schemaTypeLoader; - - private ReferenceQueue _refQueue; - private int _entryCount; - - int _numTempFramesLeft; - Cur[] _tempFrames; - - Cur _curPool; - int _curPoolCount; - - Cur _registered; - - ChangeListener _changeListeners; - - long _versionAll; - long _versionSansText; - - Locations _locations; - - private CharUtil _charUtil; - - int _offSrc; - int _cchSrc; - - Saaj _saaj; - - Dom _ownerDoc; - - QNameFactory _qnameFactory; - - boolean _validateOnSet; - - int _posTemp; - - nthCache _nthCache_A = new nthCache(); - nthCache _nthCache_B = new nthCache(); - - domNthCache _domNthCache_A = new domNthCache(); - domNthCache _domNthCache_B = new domNthCache(); -} diff --git a/src/store/org/apache/xmlbeans/impl/store/Path.java b/src/store/org/apache/xmlbeans/impl/store/Path.java deleted file mode 100755 index 015eea6..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Path.java +++ /dev/null @@ -1,714 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import java.io.*; -import java.util.*; - -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.lang.ref.WeakReference; -import java.math.BigDecimal; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.apache.xmlbeans.impl.common.XPath; -import org.apache.xmlbeans.impl.common.XPath.XPathCompileException; -import org.apache.xmlbeans.impl.common.XPath.ExecutionContext; - -import org.apache.xmlbeans.*; -import org.w3c.dom.Node; - - -// TODO - This class handled query *and* path ... rename it? - -public abstract class Path -{ - public static final String PATH_DELEGATE_INTERFACE = "PATH_DELEGATE_INTERFACE"; - public static String _useDelegateForXpath = "use delegate for xpath"; - public static String _useXdkForXpath = "use xdk for xpath"; - public static String _useXqrlForXpath = "use xqrl for xpath"; - public static String _useXbeanForXpath = "use xbean for xpath"; - public static String _forceXqrl2002ForXpathXQuery = "use xqrl-2002 for xpath"; - - private static final int USE_XBEAN = 0x01; - private static final int USE_XQRL = 0x02; - private static final int USE_DELEGATE = 0x04; - private static final int USE_XQRL2002 = 0x08; - private static final int USE_XDK = 0x10; - - private static Map _xbeanPathCache = new WeakHashMap(); - private static Map _xdkPathCache = new WeakHashMap(); - private static Map _xqrlPathCache = new WeakHashMap(); - private static Map _xqrl2002PathCache = new WeakHashMap(); - - private static Method _xdkCompilePath; - private static Method _xqrlCompilePath; - private static Method _xqrl2002CompilePath; - - private static boolean _xdkAvailable = true; - private static boolean _xqrlAvailable = true; - private static boolean _xqrl2002Available = true; - - private static String _delIntfName; - private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - static - { - String id = "META-INF/services/org.apache.xmlbeans.impl.store.PathDelegate.SelectPathInterface"; - InputStream in = Path.class.getResourceAsStream(id); - try - { - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - _delIntfName = br.readLine().trim(); - br.close(); - } - catch (Exception e) - { - _delIntfName = null; - } - } - - protected final String _pathKey; - - Path(String key) - { - _pathKey = key; - } - - - interface PathEngine - { - void release(); - - boolean next(Cur c); - } - - abstract PathEngine execute(Cur c, XmlOptions options); - - // - // - // - - static String getCurrentNodeVar(XmlOptions options) - { - String currentNodeVar = "this"; - - options = XmlOptions.maskNull(options); - - if (options.hasOption(XmlOptions.XQUERY_CURRENT_NODE_VAR)) { - currentNodeVar = (String) options.get(XmlOptions.XQUERY_CURRENT_NODE_VAR); - - if (currentNodeVar.startsWith("$")) { - throw new IllegalArgumentException("Omit the '$' prefix for the current node variable"); - } - } - - return currentNodeVar; - } - - public static Path getCompiledPath(String pathExpr, XmlOptions options) - { - options = XmlOptions.maskNull(options); - - int force = - options.hasOption(_useDelegateForXpath) ? USE_DELEGATE - : options.hasOption(_useXqrlForXpath) ? USE_XQRL - : options.hasOption(_useXdkForXpath) ? USE_XDK - : options.hasOption(_useXbeanForXpath) ? USE_XBEAN - : options.hasOption(_forceXqrl2002ForXpathXQuery) ? USE_XQRL2002 - : USE_XBEAN|USE_XQRL|USE_XDK|USE_DELEGATE; //set all bits except XQRL2002 - String delIntfName = - options.hasOption(PATH_DELEGATE_INTERFACE) ? - (String)options.get(PATH_DELEGATE_INTERFACE) : _delIntfName; - - return getCompiledPath(pathExpr, force, getCurrentNodeVar(options), delIntfName); - } - - static Path getCompiledPath(String pathExpr, int force, - String currentVar, String delIntfName) - { - Path path = null; - WeakReference pathWeakRef = null; - Map namespaces = (force & USE_DELEGATE) != 0 ? new HashMap() : null; - lock.readLock().lock(); - try { - if ((force & USE_XBEAN) != 0) - pathWeakRef = (WeakReference)_xbeanPathCache.get(pathExpr); - if (pathWeakRef == null && (force & USE_XQRL) != 0) - pathWeakRef = (WeakReference)_xqrlPathCache.get(pathExpr); - if (pathWeakRef == null && (force & USE_XDK) != 0) - pathWeakRef = (WeakReference)_xdkPathCache.get(pathExpr); - if (pathWeakRef == null && (force & USE_XQRL2002) != 0) - pathWeakRef = (WeakReference)_xqrl2002PathCache.get(pathExpr); - - if (pathWeakRef!=null) - path = (Path)pathWeakRef.get(); - if (path != null) - return path; - } finally { - lock.readLock().unlock(); - } - lock.writeLock().lock(); - try { - if ((force & USE_XBEAN) != 0) { - pathWeakRef = (WeakReference)_xbeanPathCache.get(pathExpr); - if (pathWeakRef != null) - path = (Path)pathWeakRef.get(); - if (path==null) - path = getCompiledPathXbean(pathExpr, currentVar, namespaces); - } - if (path == null && (force & USE_XQRL) != 0) { - pathWeakRef = (WeakReference)_xqrlPathCache.get(pathExpr); - if (pathWeakRef != null) - path = (Path)pathWeakRef.get(); - if (path==null) - path = getCompiledPathXqrl(pathExpr, currentVar); - } - if (path == null && (force & USE_XDK) != 0) { - pathWeakRef = (WeakReference)_xdkPathCache.get(pathExpr); - if (pathWeakRef != null) - path = (Path)pathWeakRef.get(); - if (path==null) - path = getCompiledPathXdk(pathExpr, currentVar); - } - if (path == null && (force & USE_DELEGATE) != 0) { - path = getCompiledPathDelegate(pathExpr, currentVar, namespaces, delIntfName); - } - if (path == null && (force & USE_XQRL2002) != 0) { - pathWeakRef = (WeakReference)_xqrl2002PathCache.get(pathExpr); - if (pathWeakRef != null) - path = (Path)pathWeakRef.get(); - if (path==null) - path = getCompiledPathXqrl2002(pathExpr, currentVar); - } - if (path == null) - { - StringBuffer errMessage = new StringBuffer(); - if ((force & USE_XBEAN) != 0) - errMessage.append(" Trying XBeans path engine..."); - if ((force & USE_XQRL) != 0) - errMessage.append(" Trying XQRL..."); - if ((force & USE_XDK) != 0) - errMessage.append(" Trying XDK..."); - if ((force & USE_DELEGATE) != 0) - errMessage.append(" Trying delegated path engine..."); - if ((force & USE_XQRL2002) != 0) - errMessage.append(" Trying XQRL2002..."); - - throw new RuntimeException(errMessage.toString() + " FAILED on " + pathExpr); - } - } finally { - lock.writeLock().unlock(); - } - return path; - } - - static private Path getCompiledPathXdk(String pathExpr, String currentVar) - { - Path path = createXdkCompiledPath(pathExpr, currentVar); - if (path != null) - _xdkPathCache.put(path._pathKey, new WeakReference(path)); - - return path; - } - - static private Path getCompiledPathXqrl(String pathExpr, String currentVar) - { - Path path = createXqrlCompiledPath(pathExpr, currentVar); - if (path != null) - _xqrlPathCache.put(path._pathKey, new WeakReference(path)); - - return path; - } - - static private Path getCompiledPathXqrl2002(String pathExpr, String currentVar) - { - Path path = createXqrl2002CompiledPath(pathExpr, currentVar); - if (path != null) - _xqrl2002PathCache.put(path._pathKey, new WeakReference(path)); - - return path; - } - - static private Path getCompiledPathXbean(String pathExpr, - String currentVar, Map namespaces) - { - Path path = XbeanPath.create(pathExpr, currentVar, namespaces); - if (path != null) - _xbeanPathCache.put(path._pathKey, new WeakReference(path)); - - return path; - } - - static private Path getCompiledPathDelegate(String pathExpr, String currentVar, Map namespaces, String delIntfName) - { - Path path = null; - if ( namespaces == null ) - namespaces = new HashMap(); - - try - { - XPath.compileXPath(pathExpr, currentVar, namespaces); - } - catch (XPath.XPathCompileException e) - { - //do nothing, this function is only called to populate the namespaces map - } - - int offset = - namespaces.get(XPath._NS_BOUNDARY) == null ? - 0 : - ((Integer) namespaces.get(XPath._NS_BOUNDARY)).intValue(); - namespaces.remove(XPath._NS_BOUNDARY); - path = DelegatePathImpl.create(delIntfName, - pathExpr.substring(offset), - currentVar, - namespaces); - - return path; - } - - - public static String compilePath(String pathExpr, XmlOptions options) - { - return getCompiledPath(pathExpr, options)._pathKey; - } - - // - // Xbean store specific implementation of compiled path - // - - private static final class XbeanPath extends Path - { - static Path create(String pathExpr, String currentVar, Map namespaces) - { - try - { - return new XbeanPath(pathExpr, currentVar, - XPath.compileXPath(pathExpr, currentVar, namespaces)); - } - catch (XPathCompileException e) { - return null; - } - } - - private XbeanPath(String pathExpr, String currentVar, XPath xpath) - { - super(pathExpr); - - _currentVar = currentVar; - _compiledPath = xpath; - } - - PathEngine execute(Cur c, XmlOptions options) - { - options = XmlOptions.maskNull(options); - String delIntfName = - options.hasOption(PATH_DELEGATE_INTERFACE) ? - (String)options.get(PATH_DELEGATE_INTERFACE) : _delIntfName; - - // The builtin XPath engine works only on containers. Delegate to - // xqrl otherwise. Also, if the path had a //. at the end, the - // simple xpath engine can't do the generate case, it only handles - // attrs and elements. - - if (!c.isContainer() || _compiledPath.sawDeepDot()) - { - int force = USE_DELEGATE | USE_XQRL | USE_XDK; - return getCompiledPath(_pathKey, force, _currentVar, delIntfName).execute(c, options); - } - return new XbeanPathEngine(_compiledPath, c); - } - - private final String _currentVar; - private final XPath _compiledPath; - public Map namespaces; - } - - private static Path createXdkCompiledPath(String pathExpr, String currentVar) - { - if (!_xdkAvailable) - return null; - - if (_xdkCompilePath == null) - { - try - { - Class xdkImpl = Class.forName("org.apache.xmlbeans.impl.store.OXQXBXqrlImpl"); - - _xdkCompilePath = - xdkImpl.getDeclaredMethod("compilePath", - new Class[]{String.class, String.class, Boolean.class}); - } - catch (ClassNotFoundException e) - { - _xdkAvailable = false; - return null; - } - catch (Exception e) - { - _xdkAvailable = false; - throw new RuntimeException(e.getMessage(), e); - } - } - - Object[] args = new Object[]{pathExpr, currentVar, new Boolean(true)}; - - try { - return (Path) _xdkCompilePath.invoke(null, args); - } - catch (InvocationTargetException e) { - Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static Path createXqrlCompiledPath(String pathExpr, String currentVar) - { - if (!_xqrlAvailable) - return null; - - if (_xqrlCompilePath == null) - { - try - { - Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.XqrlImpl"); - - _xqrlCompilePath = - xqrlImpl.getDeclaredMethod("compilePath", - new Class[]{String.class, String.class, Boolean.class}); - } - catch (ClassNotFoundException e) - { - _xqrlAvailable = false; - return null; - } - catch (Exception e) - { - _xqrlAvailable = false; - throw new RuntimeException(e.getMessage(), e); - } - } - - Object[] args = new Object[]{pathExpr, currentVar, new Boolean(true)}; - - try { - return (Path) _xqrlCompilePath.invoke(null, args); - } - catch (InvocationTargetException e) { - Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static Path createXqrl2002CompiledPath(String pathExpr, String currentVar) - { - if (!_xqrl2002Available) - return null; - - if (_xqrl2002CompilePath == null) - { - try - { - Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.Xqrl2002Impl"); - - _xqrl2002CompilePath = - xqrlImpl.getDeclaredMethod("compilePath", - new Class[]{String.class, String.class, Boolean.class}); - } - catch (ClassNotFoundException e) - { - _xqrl2002Available = false; - return null; - } - catch (Exception e) - { - _xqrl2002Available = false; - throw new RuntimeException(e.getMessage(), e); - } - } - - Object[] args = new Object[]{pathExpr, currentVar, new Boolean(true)}; - - try - { - return (Path) _xqrl2002CompilePath.invoke(null, args); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static final class XbeanPathEngine - extends ExecutionContext - implements PathEngine - { - XbeanPathEngine(XPath xpath, Cur c) - { - assert c.isContainer(); - - _version = c._locale.version(); - _cur = c.weakCur(this); - - _cur.push(); - - init(xpath); - - int ret = start(); - - if ((ret & HIT) != 0) - c.addToSelection(); - - doAttrs(ret, c); - - if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur)) - release(); - } - - private void advance(Cur c) - { - assert _cur != null; - - if (_cur.isFinish()) - { - if (_cur.isAtEndOfLastPush()) - release(); - else { - end(); - _cur.next(); - } - } - else if (_cur.isElem()) - { - int ret = element(_cur.getName()); - - if ((ret & HIT) != 0) - c.addToSelection(_cur); - - doAttrs(ret, c); - - if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur)) - { - end(); - _cur.skip(); - } - } - else - { - do - { - _cur.next(); - } - while(!_cur.isContainerOrFinish()); - } - } - - private void doAttrs(int ret, Cur c) - { - assert _cur.isContainer(); - - if ((ret & ATTRS) != 0) { - if (_cur.toFirstAttr()) { - do { - if (attr(_cur.getName())) - c.addToSelection(_cur); - } - while (_cur.toNextAttr()); - - _cur.toParent(); - } - } - } - - public boolean next(Cur c) - { - if (_cur != null && _version != _cur._locale.version()) - throw new ConcurrentModificationException("Document changed during select"); - - int startCount = c.selectionCount(); - - while (_cur != null) { - advance(c); - - if (startCount != c.selectionCount()) - return true; - } - - return false; - } - - public void release() - { - if (_cur != null) { - _cur.release(); - _cur = null; - } - } - - private final long _version; - private Cur _cur; - } - - private static final class DelegatePathImpl - extends Path - { - private PathDelegate.SelectPathInterface _xpathImpl; - - static Path create(String implClassName, String pathExpr, String currentNodeVar, Map namespaceMap) - { - assert !currentNodeVar.startsWith("$"); // cezar review with ericvas - - PathDelegate.SelectPathInterface impl = - PathDelegate.createInstance(implClassName, pathExpr, currentNodeVar, namespaceMap); - if (impl == null) - return null; - - return new DelegatePathImpl(impl, pathExpr); - } - - - private DelegatePathImpl(PathDelegate.SelectPathInterface xpathImpl, - String pathExpr) - { - super(pathExpr); - _xpathImpl = xpathImpl; - } - - protected PathEngine execute(Cur c, XmlOptions options) - { - return new DelegatePathEngine(_xpathImpl, c); - } - - private static class DelegatePathEngine - extends XPath.ExecutionContext - implements PathEngine - { - - DelegatePathEngine(PathDelegate.SelectPathInterface xpathImpl, - Cur c) - { - _engine = xpathImpl; - _version = c._locale.version(); - _cur = c.weakCur(this); - } - - public boolean next(Cur c) - { - if (!_firstCall) - return false; - - _firstCall = false; - - if (_cur != null && _version != _cur._locale.version()) - throw new ConcurrentModificationException("Document changed during select"); - - List resultsList; - Object context_node; - - context_node = _cur.getDom(); - resultsList = _engine.selectPath(context_node); - - int i; - for (i = 0; i < resultsList.size(); i++) { - //simple type function results - Object node = resultsList.get(i); - Cur pos = null; - if (!(node instanceof Node)) { - String value; - - value = resultsList.get(i).toString(); - - //we cannot leave the cursor's locale, as - //everything is done in the selections of this cursor - - Locale l = c._locale; - try { - pos = l.load("").tempCur(); - pos.setValue(value); - SchemaType type = getType(node); - Locale.autoTypeDocument(pos, type, null); - //move the cur to the actual text - pos.next(); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - else { - assert (node instanceof DomImpl.Dom): - "New object created in XPATH!"; - pos = ((DomImpl.Dom) node).tempCur(); - - } - c.addToSelection(pos); - pos.release(); - } - release(); - _engine = null; - return true; - } - - private SchemaType getType(Object node) - { - SchemaType type; - if (node instanceof Integer) - type = XmlInteger.type; - else if (node instanceof Double) - type = XmlDouble.type; - else if (node instanceof Long) - type = XmlLong.type; - else if (node instanceof Float) - type = XmlFloat.type; - else if (node instanceof BigDecimal) - type = XmlDecimal.type; - else if (node instanceof Boolean) - type = XmlBoolean.type; - else if (node instanceof String) - type = XmlString.type; - else if (node instanceof Date) - type = XmlDate.type; - else - type = XmlAnySimpleType.type; - return type; - } - - public void release() - { - if (_cur != null) { - _cur.release(); - _cur = null; - } - } - - private Cur _cur; - private PathDelegate.SelectPathInterface _engine; - private boolean _firstCall = true; - private long _version; - } - } -} diff --git a/src/store/org/apache/xmlbeans/impl/store/PathDelegate.java b/src/store/org/apache/xmlbeans/impl/store/PathDelegate.java deleted file mode 100644 index f25a14d..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/PathDelegate.java +++ /dev/null @@ -1,94 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.store; - -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.lang.reflect.Constructor; - -import org.apache.xmlbeans.impl.common.XPath; - -public final class PathDelegate -{ - private static HashMap _constructors = new HashMap(); - - private PathDelegate() - {} - - private static synchronized void init(String implClassName) - { - // default to Saxon - if (implClassName == null) - implClassName = "org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath"; - Class selectPathInterfaceImpl = null; - boolean engineAvailable = true; - try - { - selectPathInterfaceImpl = Class.forName(implClassName); - } - catch (ClassNotFoundException e) - { - engineAvailable = false; - } - catch (NoClassDefFoundError e) - { - engineAvailable = false; - } - - if (engineAvailable) - { - try - { - Constructor constructor = selectPathInterfaceImpl.getConstructor( - new Class[] {String.class, String.class, Map.class, String.class}); - _constructors.put(implClassName, constructor); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - } - - public static synchronized SelectPathInterface createInstance(String implClassName, - String xpath, String contextVar, Map namespaceMap) - { - if (_constructors.get(implClassName) == null) - init(implClassName); - - if (_constructors.get(implClassName) == null) - return null; - - Constructor constructor = (Constructor)_constructors.get(implClassName); - try - { - Object defaultNS = namespaceMap.get(XPath._DEFAULT_ELT_NS); - if (defaultNS != null) - namespaceMap.remove(XPath._DEFAULT_ELT_NS); - return (SelectPathInterface)constructor.newInstance( - new Object[] {xpath, contextVar, namespaceMap, (String)defaultNS}); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - public static interface SelectPathInterface - { - public List selectPath(Object node); - } -} diff --git a/src/store/org/apache/xmlbeans/impl/store/Query.java b/src/store/org/apache/xmlbeans/impl/store/Query.java deleted file mode 100644 index 0b8accc..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Query.java +++ /dev/null @@ -1,524 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.common.XPath; -import org.w3c.dom.*; - -import javax.xml.namespace.QName; -import java.io.*; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Date; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.math.BigDecimal; - -public abstract class Query -{ - public static final String QUERY_DELEGATE_INTERFACE = "QUERY_DELEGATE_INTERFACE"; - public static String _useDelegateForXQuery = "use delegate for xquery"; - public static String _useXdkForXQuery = "use xdk for xquery"; - - private static String _delIntfName; - //private static HashMap _delegateQueryCache = new HashMap(); - - private static HashMap _xdkQueryCache = new HashMap(); - private static Method _xdkCompileQuery; - private static boolean _xdkAvailable = true; // at the beginning assume is available - - private static HashMap _xqrlQueryCache = new HashMap(); //todo check for memory leaks - private static Method _xqrlCompileQuery; - private static boolean _xqrlAvailable = true; // at the beginning assume is available - - private static HashMap _xqrl2002QueryCache = new HashMap(); - private static Method _xqrl2002CompileQuery; - private static boolean _xqrl2002Available = true; // at the beginning assume is available - - static - { - String id = "META-INF/services/org.apache.xmlbeans.impl.store.QueryDelegate.QueryInterface"; - InputStream in = Query.class.getResourceAsStream(id); - try - { - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - _delIntfName = br.readLine().trim(); - br.close(); - } - catch (Exception e) - { - _delIntfName = null; - } - } - - abstract XmlObject[] objectExecute(Cur c, XmlOptions options); - - abstract XmlCursor cursorExecute(Cur c, XmlOptions options); - - // - // Xqrl store specific implementation of compiled path/query - // - - static XmlObject[] objectExecQuery(Cur c, String queryExpr, XmlOptions options) - { - return getCompiledQuery(queryExpr, options).objectExecute(c, options); - } - - static XmlCursor cursorExecQuery(Cur c, String queryExpr, XmlOptions options) - { - return getCompiledQuery(queryExpr, options).cursorExecute(c, options); - } - - public static synchronized Query getCompiledQuery(String queryExpr, XmlOptions options) - { - return getCompiledQuery(queryExpr, Path.getCurrentNodeVar(options), options); - } - - static synchronized Query getCompiledQuery(String queryExpr, String currentVar, XmlOptions options) - { - assert queryExpr != null; - options = XmlOptions.maskNull(options); - Query query; - - if (options.hasOption(Path._forceXqrl2002ForXpathXQuery)) - { - query = (Query)_xqrl2002QueryCache.get(queryExpr); - if (query!=null) - return query; - - query = getXqrl2002CompiledQuery(queryExpr, currentVar); - if (query!=null) - { - _xqrl2002QueryCache.put(queryExpr, query); - return query; - } - throw new RuntimeException("No 2002 query engine found."); - } - - //Parse the query via XBeans: need to figure out end of prolog - //in order to bind $this...not good but... - Map boundary = new HashMap(); - int boundaryVal = 0; - try - { - XPath.compileXPath(queryExpr, currentVar, boundary); - } - catch (XPath.XPathCompileException e) - { - //don't care if it fails, just care about boundary - } - finally - { - boundaryVal = boundary.get(XPath._NS_BOUNDARY) == null ? 0 : - ((Integer) boundary.get(XPath._NS_BOUNDARY)).intValue(); - } - - if (options.hasOption(_useXdkForXQuery)) - { - //try XDK - query = (Query) _xdkQueryCache.get(queryExpr); - if (query != null) - return query; - - query = createXdkCompiledQuery(queryExpr, currentVar); - if (query != null) - { - _xdkQueryCache.put(queryExpr, query); - return query; - } - } - - if (!options.hasOption(_useDelegateForXQuery)) - { - //try XQRL - query = (Query) _xqrlQueryCache.get(queryExpr); - if (query != null) - return query; - - query = createXqrlCompiledQuery(queryExpr, currentVar); - if (query != null) - { - _xqrlQueryCache.put(queryExpr, query); - return query; - } - } - - //otherwise (if _useDelegateForXQuery option is set), - //or if xqrl is not found, try delegate - //query = (Query) _delegateQueryCache.get(queryExpr); - - //if (query != null) - // return query; - - String delIntfName = - options.hasOption(QUERY_DELEGATE_INTERFACE) ? - (String)options.get(QUERY_DELEGATE_INTERFACE) : _delIntfName; - query = DelegateQueryImpl.createDelegateCompiledQuery(delIntfName, queryExpr, currentVar, boundaryVal); - - if (query != null) - { - //_delegateQueryCache.put(queryExpr, query); - return query; - } - - throw new RuntimeException("No query engine found"); - } - - public static synchronized String compileQuery(String queryExpr, XmlOptions options) - { - getCompiledQuery(queryExpr, options); - return queryExpr; - } - - private static Query createXdkCompiledQuery(String queryExpr, String currentVar) - { - //if the XDK engine has been determined unavailable, return null - if ( !_xdkAvailable ) return null; - if ( _xdkCompileQuery == null) - { - try - { - Class xdkImpl = Class.forName("org.apache.xmlbeans.impl.store.OXQXBXqrlImpl"); - - _xdkCompileQuery = - xdkImpl.getDeclaredMethod("compileQuery", - new Class[]{String.class, String.class, Boolean.class}); - } - catch (ClassNotFoundException e) - { - _xdkAvailable = false; - return null; - } - catch (Exception e) - { - _xdkAvailable = false; - throw new RuntimeException(e.getMessage(), e); - } - } - - Object[] args = new Object[]{queryExpr, currentVar, new Boolean(true)}; - - try - { - return (Query) _xdkCompileQuery.invoke(null, args); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static Query createXqrlCompiledQuery(String queryExpr, String currentVar) - { - //if the XQRL engine has been determined unavailable, return null - if ( !_xqrlAvailable ) return null; - if ( _xqrlCompileQuery == null) - { - try - { - Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.XqrlImpl"); - - _xqrlCompileQuery = - xqrlImpl.getDeclaredMethod("compileQuery", - new Class[]{String.class, String.class, Boolean.class}); - } - catch (ClassNotFoundException e) - { - _xqrlAvailable = false; - return null; - } - catch (Exception e) - { - _xqrlAvailable = false; - throw new RuntimeException(e.getMessage(), e); - } - } - - Object[] args = new Object[]{queryExpr, currentVar, new Boolean(true)}; - - try - { - return (Query) _xqrlCompileQuery.invoke(null, args); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static Query getXqrl2002CompiledQuery(String queryExpr, String currentVar) - { - if (_xqrl2002Available && _xqrl2002CompileQuery == null) - { - try - { - Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.Xqrl2002Impl"); - - _xqrl2002CompileQuery = - xqrlImpl.getDeclaredMethod("compileQuery", - new Class[]{String.class, String.class, Boolean.class}); - } - catch (ClassNotFoundException e) - { - _xqrl2002Available = false; - return null; - } - catch (Exception e) - { - _xqrl2002Available = false; - throw new RuntimeException(e.getMessage(), e); - } - } - - Object[] args = new Object[]{queryExpr, currentVar, new Boolean(true)}; - - try - { - return (Query) _xqrl2002CompileQuery.invoke(null, args); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static final class DelegateQueryImpl extends Query - { - private DelegateQueryImpl(QueryDelegate.QueryInterface xqueryImpl) - { - _xqueryImpl = xqueryImpl; - } - - public static Query createDelegateCompiledQuery(String delIntfName, - String queryExpr, - String currentVar, - int boundary) - { - assert !(currentVar.startsWith(".") || currentVar.startsWith("..")); - QueryDelegate.QueryInterface impl = - QueryDelegate.createInstance(delIntfName, queryExpr, - currentVar, boundary); - if (impl == null) - return null; - - return new DelegateQueryImpl(impl); - } - - XmlObject[] objectExecute(Cur c, XmlOptions options) - { - return new DelegateQueryEngine(_xqueryImpl, c, options).objectExecute(); - } - - XmlCursor cursorExecute(Cur c, XmlOptions options) - { - return new DelegateQueryEngine(_xqueryImpl, c, options).cursorExecute(); - } - - - private static class DelegateQueryEngine - { - public DelegateQueryEngine(QueryDelegate.QueryInterface xqImpl, - Cur c, XmlOptions opt) - { - - _engine = xqImpl; - _version = c._locale.version(); - _cur = c.weakCur(this); - _options = opt; - - } - - public XmlObject[] objectExecute() - { - if (_cur != null && _version != _cur._locale.version()) - //throw new ConcurrentModificationException - // ("Document changed during select") - ; - - Map bindings = (Map) XmlOptions.maskNull(_options). - get(XmlOptions.XQUERY_VARIABLE_MAP); - List resultsList; - resultsList = _engine.execQuery(_cur.getDom(), bindings); - - assert resultsList.size() > -1; - - XmlObject[] result = new XmlObject[resultsList.size()]; - int i; - for (i = 0; i < resultsList.size(); i++) { - //copy objects into the locale - Locale l = Locale.getLocale(_cur._locale._schemaTypeLoader, - _options); - - l.enter(); - Object node = resultsList.get(i); - Cur res = null; - try { - //typed function results of XQuery - if (!(node instanceof Node)) { - //TODO: exact same code as Path.java - //make a common super-class and pull this--what to name that - //superclass??? - res = l.load("").tempCur(); - res.setValue(node.toString()); - SchemaType type=getType(node); - Locale.autoTypeDocument(res, type, null); - result[i] = res.getObject(); - } - else - res = loadNode(l, (Node) node); - result[i] = res.getObject(); - } - catch (XmlException e) { - throw new RuntimeException(e); - } - finally { - l.exit(); - } - res.release(); - } - release(); - _engine = null; - return result; - } - private SchemaType getType(Object node) - { - SchemaType type; - if (node instanceof Integer) - type = XmlInteger.type; - else if (node instanceof Double) - type = XmlDouble.type; - else if (node instanceof Long) - type = XmlLong.type; - else if (node instanceof Float) - type = XmlFloat.type; - else if (node instanceof BigDecimal) - type = XmlDecimal.type; - else if (node instanceof Boolean) - type = XmlBoolean.type; - else if (node instanceof String) - type = XmlString.type; - else if (node instanceof Date) - type = XmlDate.type; - else - type = XmlAnySimpleType.type; - return type; - } - public XmlCursor cursorExecute() - { - if (_cur != null && _version != _cur._locale.version()) - //throw new ConcurrentModificationException - // ("Document changed during select") - ; - - Map bindings = (Map) XmlOptions.maskNull(_options). - get(XmlOptions.XQUERY_VARIABLE_MAP); - List resultsList; - resultsList = _engine.execQuery(_cur.getDom(), bindings); - - assert resultsList.size() > -1; - - int i; - _engine = null; - - Locale locale = Locale.getLocale(_cur._locale._schemaTypeLoader, _options); - locale.enter(); - Locale.LoadContext _context = new Cur.CurLoadContext(locale, _options); - Cursor resultCur = null; - try { - for (i = 0; i < resultsList.size(); i++) { - loadNodeHelper(locale, (Node) resultsList.get(i), _context); - } - Cur c = _context.finish(); - Locale.associateSourceName(c, _options); - Locale.autoTypeDocument(c, null, _options); - resultCur = new Cursor(c); - } - catch (Exception e) { - } - finally { - locale.exit(); - } - release(); - return resultCur; - } - - - public void release() - { - if (_cur != null) { - _cur.release(); - _cur = null; - } - } - - - private Cur loadNode(Locale locale, Node node) - { - Locale.LoadContext context = new Cur.CurLoadContext(locale, _options); - - try { - loadNodeHelper(locale, node, context); - Cur c = context.finish(); - Locale.associateSourceName(c, _options); - Locale.autoTypeDocument(c, null, _options); - return c; - } - catch (Exception e) { - throw new XmlRuntimeException(e.getMessage(), e); - } - } - - private void loadNodeHelper(Locale locale, Node node, Locale.LoadContext context) - { - if (node.getNodeType() == Node.ATTRIBUTE_NODE) { - QName attName = new QName(node.getNamespaceURI(), - node.getLocalName(), - node.getPrefix()); - context.attr(attName, node.getNodeValue()); - } - else - locale.loadNode(node, context); - - } - - - private Cur _cur; - private QueryDelegate.QueryInterface _engine; - private long _version; - private XmlOptions _options; - } - - private QueryDelegate.QueryInterface _xqueryImpl; - } - -} diff --git a/src/store/org/apache/xmlbeans/impl/store/QueryDelegate.java b/src/store/org/apache/xmlbeans/impl/store/QueryDelegate.java deleted file mode 100644 index fc8db1d..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/QueryDelegate.java +++ /dev/null @@ -1,89 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.store; - -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.lang.reflect.Constructor; - -public final class QueryDelegate -{ - private static HashMap _constructors = new HashMap(); - - private QueryDelegate() - {} - - private static synchronized void init(String implClassName) - { - // default to Saxon - if (implClassName == null) - implClassName = "org.apache.xmlbeans.impl.xquery.saxon.XBeansXQuery"; - Class queryInterfaceImpl = null; - boolean engineAvailable = true; - try - { - queryInterfaceImpl = Class.forName(implClassName); - } - catch (ClassNotFoundException e) - { - engineAvailable = false; - } - catch (NoClassDefFoundError e) - { - engineAvailable = false; - } - - if (engineAvailable) - { - try - { - Constructor constructor = queryInterfaceImpl.getConstructor( - new Class[] {String.class, String.class, Integer.class}); - _constructors.put(implClassName, constructor); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - } - - public static synchronized QueryInterface createInstance(String implClassName, - String query, String contextVar, int boundary) - { - if (_constructors.get(implClassName) == null) - init(implClassName); - - if (_constructors.get(implClassName) == null) - return null; - - Constructor constructor = (Constructor)_constructors.get(implClassName); - try - { - return (QueryInterface)constructor.newInstance( - new Object[] {query, contextVar, new Integer(boundary)}); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - - public static interface QueryInterface - { - public List execQuery(Object node, Map variableBindings); - } -} diff --git a/src/store/org/apache/xmlbeans/impl/store/Saver.java b/src/store/org/apache/xmlbeans/impl/store/Saver.java deleted file mode 100755 index c7832aa..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Saver.java +++ /dev/null @@ -1,4419 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlOptionCharEscapeMap; -import org.apache.xmlbeans.xml.stream.*; - -import org.apache.xmlbeans.impl.common.*; - -import java.io.Writer; -import java.io.Reader; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; - -import org.xml.sax.ContentHandler; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.SAXException; - -import org.xml.sax.helpers.AttributesImpl; - -import java.util.Iterator; -import java.util.ArrayList; -import java.util.List; -import java.util.HashMap; -import java.util.Map; -import java.util.LinkedHashMap; -import java.util.ConcurrentModificationException; - -abstract class Saver -{ - static final int ROOT = Cur.ROOT; - static final int ELEM = Cur.ELEM; - static final int ATTR = Cur.ATTR; - static final int COMMENT = Cur.COMMENT; - static final int PROCINST = Cur.PROCINST; - static final int TEXT = Cur.TEXT; - - protected abstract boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues ); - protected abstract void emitFinish ( SaveCur c ); - protected abstract void emitText ( SaveCur c ); - protected abstract void emitComment ( SaveCur c ); - protected abstract void emitProcinst ( SaveCur c ); - protected abstract void emitDocType ( String docTypeName, String publicId, String systemId ); - protected abstract void emitStartDoc ( SaveCur c ); - protected abstract void emitEndDoc ( SaveCur c ); - - protected void syntheticNamespace ( String prefix, String uri, boolean considerDefault ) { } - - Saver ( Cur c, XmlOptions options ) - { - assert c._locale.entered(); - - options = XmlOptions.maskNull( options ); - - _cur = createSaveCur( c, options ); - - _locale = c._locale; - _version = _locale.version(); - - _namespaceStack = new ArrayList(); - _uriMap = new HashMap(); - _prefixMap = new HashMap(); - - _attrNames = new ArrayList(); - _attrValues = new ArrayList (); - - // Define implicit xml prefixed namespace - - addMapping( "xml", Locale._xml1998Uri ); - - if (options.hasOption( XmlOptions.SAVE_IMPLICIT_NAMESPACES )) - { - Map m = (Map) options.get( XmlOptions.SAVE_IMPLICIT_NAMESPACES ); - - for ( Iterator i = m.keySet().iterator() ; i.hasNext() ; ) - { - String prefix = (String) i.next(); - addMapping( prefix, (String) m.get( prefix ) ); - } - } - - // define character map for escaped replacements - if (options.hasOption( XmlOptions.SAVE_SUBSTITUTE_CHARACTERS )) - { - _replaceChar = (XmlOptionCharEscapeMap) - options.get( XmlOptions.SAVE_SUBSTITUTE_CHARACTERS); - } - - // If the default prefix has not been mapped, do so now - - if (getNamespaceForPrefix( "" ) == null) - { - _initialDefaultUri = new String( "" ); - addMapping( "", _initialDefaultUri ); - } - - if (options.hasOption( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES ) && - !(this instanceof SynthNamespaceSaver)) - { - SynthNamespaceSaver saver = new SynthNamespaceSaver( c, options ); - - while ( saver.process() ) - ; - - if (!saver._synthNamespaces.isEmpty()) - _preComputedNamespaces = saver._synthNamespaces; - } - - _useDefaultNamespace = - options.hasOption( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE ); - - _saveNamespacesFirst = options.hasOption( XmlOptions.SAVE_NAMESPACES_FIRST ); - - if (options.hasOption( XmlOptions.SAVE_SUGGESTED_PREFIXES )) - _suggestedPrefixes = (Map) options.get( XmlOptions.SAVE_SUGGESTED_PREFIXES); - - _ancestorNamespaces = _cur.getAncestorNamespaces(); - } - - private static SaveCur createSaveCur ( Cur c, XmlOptions options ) - { - QName synthName = (QName) options.get( XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT ); - - QName fragName = synthName; - - if (fragName == null) - { - fragName = - options.hasOption( XmlOptions.SAVE_USE_OPEN_FRAGMENT ) - ? Locale._openuriFragment - : Locale._xmlFragment; - } - - boolean saveInner = - options.hasOption( XmlOptions.SAVE_INNER ) && - !options.hasOption( XmlOptions.SAVE_OUTER ); - - Cur start = c.tempCur(); - Cur end = c.tempCur(); - - SaveCur cur = null; - - int k = c.kind(); - - switch ( k ) - { - case ROOT : - { - positionToInner( c, start, end ); - - if (Locale.isFragment( start, end )) - cur = new FragSaveCur( start, end, fragName ); - else if (synthName != null) - cur = new FragSaveCur( start, end, synthName ); - else - cur = new DocSaveCur( c ); - - break; - } - - case ELEM : - { - if (saveInner) - { - positionToInner( c, start, end ); - - cur = - new FragSaveCur( - start, end, Locale.isFragment( start, end ) ? fragName : synthName ); - } - else if (synthName != null) - { - positionToInner( c, start, end ); - - cur = new FragSaveCur( start, end, synthName ); - } - else - { - start.moveToCur( c ); - end.moveToCur( c ); - end.skip(); - - cur = new FragSaveCur( start, end, null ); - } - - break; - } - } - - if (cur == null) - { - assert k < 0 || k == ATTR || k == COMMENT || k == PROCINST || k == TEXT; - - if (k < 0) - { - // Save out "" - start.moveToCur( c ); - end.moveToCur( c ); - } - else if (k == TEXT) - { - start.moveToCur( c ); - end.moveToCur( c ); - end.next(); - } - else if (saveInner) - { - start.moveToCur( c ); - start.next(); - - end.moveToCur( c ); - end.toEnd(); - } - else if (k == ATTR) - { - start.moveToCur( c ); - end.moveToCur( c ); - } - else - { - assert k == COMMENT || k == PROCINST; - - start.moveToCur( c ); - end.moveToCur( c ); - end.skip(); - } - - cur = new FragSaveCur( start, end, fragName ); - } - - String filterPI = (String) options.get( XmlOptions.SAVE_FILTER_PROCINST ); - - if (filterPI != null) - cur = new FilterPiSaveCur( cur, filterPI ); - - if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT )) - cur = new PrettySaveCur( cur, options ); - - start.release(); - end.release(); - - return cur; - } - - private static void positionToInner ( Cur c, Cur start, Cur end ) - { - assert c.isContainer(); - - start.moveToCur( c ); - - if (!start.toFirstAttr()) - start.next(); - - end.moveToCur( c ); - end.toEnd(); - } - - /** - * Test if a character is valid in xml character content. See - * http://www.w3.org/TR/REC-xml#NT-Char - */ - static boolean isBadChar ( char ch ) - { - return ! ( - Character.isHighSurrogate(ch) || - Character.isLowSurrogate(ch) || - (ch >= 0x20 && ch <= 0xD7FF ) || - (ch >= 0xE000 && ch <= 0xFFFD) || - (ch >= 0x10000 && ch <= 0x10FFFF) || - (ch == 0x9) || (ch == 0xA) || (ch == 0xD) - ); - } - - protected boolean saveNamespacesFirst ( ) - { - return _saveNamespacesFirst; - } - - protected void enterLocale() - { - _locale.enter(); - } - - protected void exitLocale() - { - _locale.exit(); - } - - protected final boolean process ( ) - { - assert _locale.entered(); - - if (_cur == null) - return false; - - if (_version != _locale.version()) - throw new ConcurrentModificationException( "Document changed during save" ); - - switch ( _cur.kind() ) - { - case ROOT : { processRoot(); break; } - case ELEM : { processElement(); break; } - case - ELEM : { processFinish (); break; } - case TEXT : { emitText ( _cur ); break; } - - case COMMENT : { emitComment ( _cur ); _cur.toEnd(); break; } - case PROCINST : { emitProcinst ( _cur ); _cur.toEnd(); break; } - - case - ROOT : - { - emitEndDoc(_cur); - _cur.release(); - _cur = null; - - return true; - } - - default : throw new RuntimeException( "Unexpected kind" ); - } - - _cur.next(); - - return true; - } - - private final void processFinish ( ) - { - emitFinish( _cur ); - popMappings(); - } - - private final void processRoot ( ) - { - assert _cur.isRoot(); - - XmlDocumentProperties props = _cur.getDocProps(); - String systemId = null; - String docTypeName = null; - if (props != null) - { - systemId = props.getDoctypeSystemId(); - docTypeName = props.getDoctypeName(); - } - - if (systemId != null || docTypeName != null) - { - if (docTypeName == null) - { - _cur.push(); - while (!_cur.isElem() && _cur.next()) - ; - if (_cur.isElem()) - docTypeName = _cur.getName().getLocalPart(); - _cur.pop(); - } - - String publicId = props.getDoctypePublicId(); - - if (docTypeName != null) - { - QName rootElemName = _cur.getName(); - - if ( rootElemName == null ) - { - _cur.push(); - while ( !_cur.isFinish() ) - { - if (_cur.isElem()) - { - rootElemName = _cur.getName(); - break; - } - _cur.next(); - } - _cur.pop(); - } - - if ( rootElemName!=null && docTypeName.equals(rootElemName.getLocalPart()) ) - { - emitDocType( docTypeName, publicId, systemId ); - return; - } - } - } - - emitStartDoc(_cur); - } - - private final void processElement ( ) - { - assert _cur.isElem() && _cur.getName() != null; - - QName name = _cur.getName(); - - // Add a new entry to the frontier. If this element has a name - // which has no namespace, then we must make sure that pushing - // the mappings causes the default namespace to be empty - - boolean ensureDefaultEmpty = name.getNamespaceURI().length() == 0; - - pushMappings( _cur, ensureDefaultEmpty ); - - // - // There are four things which use mappings: - // - // 1) The element name - // 2) The element value (qname based) - // 3) Attribute names - // 4) The attribute values (qname based) - // - - // 1) The element name (not for starts) - - ensureMapping( name.getNamespaceURI(), name.getPrefix(), !ensureDefaultEmpty, false ); - - // - // - // - - _attrNames.clear(); - _attrValues.clear(); - - _cur.push(); - - attrs: - for ( boolean A = _cur.toFirstAttr() ; A ; A = _cur.toNextAttr() ) - { - if (_cur.isNormalAttr()) - { - QName attrName = _cur.getName(); - - _attrNames.add( attrName ); - - for ( int i = _attrNames.size() - 2 ; i >= 0 ; i-- ) - { - if (_attrNames.get( i ).equals( attrName )) - { - _attrNames.remove( _attrNames.size() - 1 ); - continue attrs; - } - } - - _attrValues.add( _cur.getAttrValue() ); - - ensureMapping( attrName.getNamespaceURI(), attrName.getPrefix(), false, true ); - } - } - - _cur.pop(); - - // If I am doing aggressive namespaces and we're emitting a - // container which can contain content, add the namespaces - // we've computed. Basically, I'm making sure the pre-computed - // namespaces are mapped on the first container which has a name. - - if (_preComputedNamespaces != null) - { - for ( Iterator i = _preComputedNamespaces.keySet().iterator() ; i.hasNext() ; ) - { - String uri = (String) i.next(); - String prefix = (String) _preComputedNamespaces.get( uri ); - boolean considerDefault = prefix.length() == 0 && !ensureDefaultEmpty; - - ensureMapping( uri, prefix, considerDefault, false ); - } - - // Set to null so we do this once at the top - _preComputedNamespaces = null; - } - - if (emitElement( _cur, _attrNames, _attrValues )) - { - popMappings(); - _cur.toEnd(); - } - } - - // - // Layout of namespace stack: - // - // URI Undo - // URI Rename - // Prefix Undo - // Mapping - // - - boolean hasMappings ( ) - { - int i = _namespaceStack.size(); - - return i > 0 && _namespaceStack.get( i - 1 ) != null; - } - - void iterateMappings ( ) - { - _currentMapping = _namespaceStack.size(); - - while ( _currentMapping > 0 && _namespaceStack.get( _currentMapping - 1 ) != null ) - _currentMapping -= 8; - } - - boolean hasMapping ( ) - { - return _currentMapping < _namespaceStack.size(); - } - - void nextMapping ( ) - { - _currentMapping += 8; - } - - String mappingPrefix ( ) - { - assert hasMapping(); - return (String) _namespaceStack.get( _currentMapping + 6 ); - } - - String mappingUri ( ) - { - assert hasMapping(); - return (String) _namespaceStack.get( _currentMapping + 7 ); - } - - private final void pushMappings ( SaveCur c, boolean ensureDefaultEmpty ) - { - assert c.isContainer(); - - _namespaceStack.add( null ); - - c.push(); - - namespaces: - for ( boolean A = c.toFirstAttr() ; A ; A = c.toNextAttr() ) - if (c.isXmlns()) - addNewFrameMapping( c.getXmlnsPrefix(), c.getXmlnsUri(), ensureDefaultEmpty ); - - c.pop(); - - if (_ancestorNamespaces != null) - { - for ( int i = 0 ; i < _ancestorNamespaces.size() ; i += 2 ) - { - String prefix = (String) _ancestorNamespaces.get( i ); - String uri = (String) _ancestorNamespaces.get( i + 1 ); - - addNewFrameMapping( prefix, uri, ensureDefaultEmpty ); - } - - _ancestorNamespaces = null; - } - - if (ensureDefaultEmpty) - { - String defaultUri = (String) _prefixMap.get( "" ); - - // I map the default to "" at the very beginning - assert defaultUri != null; - - if (defaultUri.length() > 0) - addMapping( "", "" ); - } - } - - private final void addNewFrameMapping ( String prefix, String uri, boolean ensureDefaultEmpty ) - { - // If the prefix maps to "", this don't include this mapping 'cause it's not well formed. - // Also, if we want to make sure that the default namespace is always "", then check that - // here as well. - - if ((prefix.length() == 0 || uri.length() > 0) && - (!ensureDefaultEmpty || prefix.length() > 0 || uri.length() == 0)) - { - // Make sure the prefix is not already mapped in this frame - - for ( iterateMappings() ; hasMapping() ; nextMapping() ) - if (mappingPrefix().equals( prefix )) - return; - - // Also make sure that the prefix declaration is not redundant - // This has the side-effect of making it impossible to set a - // redundant prefix declaration, but seems that it's better - // to just never issue a duplicate prefix declaration. - if (uri.equals(getNamespaceForPrefix(prefix))) - return; - - addMapping( prefix, uri ); - } - } - - private final void addMapping ( String prefix, String uri ) - { - assert uri != null; - assert prefix != null; - - // If the prefix being mapped here is already mapped to a uri, - // that uri will either go out of scope or be mapped to another - // prefix. - - String renameUri = (String) _prefixMap.get( prefix ); - String renamePrefix = null; - - if (renameUri != null) - { - // See if this prefix is already mapped to this uri. If - // so, then add to the stack, but there is nothing to rename - - if (renameUri.equals( uri )) - renameUri = null; - else - { - int i = _namespaceStack.size(); - - while ( i > 0 ) - { - if (_namespaceStack.get( i - 1 ) == null) - { - i--; - continue; - } - - if (_namespaceStack.get( i - 7 ).equals( renameUri )) - { - renamePrefix = (String) _namespaceStack.get( i - 8 ); - - if (renamePrefix == null || !renamePrefix.equals( prefix )) - break; - } - - i -= 8; - } - - assert i > 0; - } - } - - _namespaceStack.add( _uriMap.get( uri ) ); - _namespaceStack.add( uri ); - - if (renameUri != null) - { - _namespaceStack.add( _uriMap.get( renameUri ) ); - _namespaceStack.add( renameUri ); - } - else - { - _namespaceStack.add( null ); - _namespaceStack.add( null ); - } - - _namespaceStack.add( prefix ); - _namespaceStack.add( _prefixMap.get( prefix ) ); - - _namespaceStack.add( prefix ); - _namespaceStack.add( uri ); - - _uriMap.put( uri, prefix ); - _prefixMap.put( prefix, uri ); - - if (renameUri != null) - _uriMap.put( renameUri, renamePrefix ); - } - - private final void popMappings ( ) - { - for ( ; ; ) - { - int i = _namespaceStack.size(); - - if (i == 0) - break; - - if (_namespaceStack.get( i - 1 ) == null) - { - _namespaceStack.remove( i - 1 ); - break; - } - - Object oldUri = _namespaceStack.get( i - 7 ); - Object oldPrefix = _namespaceStack.get( i - 8 ); - - if (oldPrefix == null) - _uriMap.remove( oldUri ); - else - _uriMap.put( oldUri, oldPrefix ); - - oldPrefix = _namespaceStack.get( i - 4 ); - oldUri = _namespaceStack.get( i - 3 ); - - if (oldUri == null) - _prefixMap.remove( oldPrefix ); - else - _prefixMap.put( oldPrefix, oldUri ); - - String uri = (String) _namespaceStack.get( i - 5 ); - - if (uri != null) - _uriMap.put( uri, _namespaceStack.get( i - 6 ) ); - - // Hahahahahaha -- :-( - _namespaceStack.remove( i - 1 ); - _namespaceStack.remove( i - 2 ); - _namespaceStack.remove( i - 3 ); - _namespaceStack.remove( i - 4 ); - _namespaceStack.remove( i - 5 ); - _namespaceStack.remove( i - 6 ); - _namespaceStack.remove( i - 7 ); - _namespaceStack.remove( i - 8 ); - } - } - - private final void dumpMappings ( ) - { - for ( int i = _namespaceStack.size() ; i > 0 ; ) - { - if (_namespaceStack.get( i - 1 ) == null) - { - System.out.println( "----------------" ); - i--; - continue; - } - - System.out.print( "Mapping: " ); - System.out.print( _namespaceStack.get( i - 2 ) ); - System.out.print( " -> " ); - System.out.print( _namespaceStack.get( i - 1 ) ); - System.out.println(); - - System.out.print( "Prefix Undo: " ); - System.out.print( _namespaceStack.get( i - 4 ) ); - System.out.print( " -> " ); - System.out.print( _namespaceStack.get( i - 3 ) ); - System.out.println(); - - System.out.print( "Uri Rename: " ); - System.out.print( _namespaceStack.get( i - 5 ) ); - System.out.print( " -> " ); - System.out.print( _namespaceStack.get( i - 6 ) ); - System.out.println(); - - System.out.print( "UriUndo: " ); - System.out.print( _namespaceStack.get( i - 7 ) ); - System.out.print( " -> " ); - System.out.print( _namespaceStack.get( i - 8 ) ); - System.out.println(); - - System.out.println(); - - i -= 8; - } - } - - private final String ensureMapping ( - String uri, String candidatePrefix, - boolean considerCreatingDefault, boolean mustHavePrefix ) - { - assert uri != null; - - // Can be called for no-namespaced things - - if (uri.length() == 0) - return null; - - String prefix = (String) _uriMap.get( uri ); - - if (prefix != null && (prefix.length() > 0 || !mustHavePrefix)) - return prefix; - - // - // I try prefixes from a number of places, in order: - // - // 1) What was passed in - // 2) The optional suggestions (for uri's) - // 3) The default mapping is allowed - // 4) ns#++ - // - - if (candidatePrefix != null && candidatePrefix.length() == 0) - candidatePrefix = null; - - if (candidatePrefix == null || !tryPrefix( candidatePrefix )) - { - if (_suggestedPrefixes != null && - _suggestedPrefixes.containsKey( uri ) && - tryPrefix( (String) _suggestedPrefixes.get( uri ) )) - { - candidatePrefix = (String) _suggestedPrefixes.get( uri ); - } - else if (considerCreatingDefault && _useDefaultNamespace && tryPrefix( "" )) - candidatePrefix = ""; - else - { - String basePrefix = QNameHelper.suggestPrefix( uri ); - candidatePrefix = basePrefix; - - for ( int i = 1 ; ; i++ ) - { - if (tryPrefix( candidatePrefix )) - break; - - candidatePrefix = basePrefix + i; - } - } - } - - assert candidatePrefix != null; - - syntheticNamespace( candidatePrefix, uri, considerCreatingDefault ); - - addMapping( candidatePrefix, uri ); - - return candidatePrefix; - } - - protected final String getUriMapping ( String uri ) - { - assert _uriMap.get( uri ) != null; - return (String) _uriMap.get( uri ); - } - - String getNonDefaultUriMapping ( String uri ) - { - String prefix = (String) _uriMap.get( uri ); - - if (prefix != null && prefix.length() > 0) - return prefix; - - for ( Iterator keys = _prefixMap.keySet().iterator() ; keys.hasNext() ; ) - { - prefix = (String) keys.next(); - - if (prefix.length() > 0 && _prefixMap.get( prefix ).equals( uri )) - return prefix; - } - - assert false : "Could not find non-default mapping"; - - return null; - } - - private final boolean tryPrefix ( String prefix ) - { - if (prefix == null || Locale.beginsWithXml( prefix )) - return false; - - String existingUri = (String) _prefixMap.get( prefix ); - - // If the prefix is currently mapped, then try another prefix. A - // special case is that of trying to map the default prefix (""). - // Here, there always exists a default mapping. If this is the - // mapping we found, then remap it anyways. I use != to compare - // strings because I want to test for the specific initial default - // uri I added when I initialized the saver. - - if (existingUri != null && (prefix.length() > 0 || existingUri != _initialDefaultUri)) - return false; - - return true; - } - - public final String getNamespaceForPrefix ( String prefix ) - { - assert !prefix.equals( "xml" ) || _prefixMap.get( prefix ).equals( Locale._xml1998Uri ); - - return (String) _prefixMap.get( prefix ); - } - - protected Map getPrefixMap() - { - return _prefixMap; - } - - // - // - // - - static final class SynthNamespaceSaver extends Saver - { - LinkedHashMap _synthNamespaces = new LinkedHashMap(); - - SynthNamespaceSaver ( Cur c, XmlOptions options ) - { - super( c, options ); - } - - protected void syntheticNamespace ( - String prefix, String uri, boolean considerCreatingDefault ) - { - _synthNamespaces.put( uri, considerCreatingDefault ? "" : prefix ); - } - - protected boolean emitElement ( - SaveCur c, ArrayList attrNames, ArrayList attrValues ) { return false; } - - protected void emitFinish ( SaveCur c ) { } - protected void emitText ( SaveCur c ) { } - protected void emitComment ( SaveCur c ) { } - protected void emitProcinst ( SaveCur c ) { } - protected void emitDocType ( String docTypeName, String publicId, String systemId ) { } - protected void emitStartDoc ( SaveCur c ) { } - protected void emitEndDoc ( SaveCur c ) { } - } - - // - // - // - - static final class TextSaver extends Saver - { - TextSaver ( Cur c, XmlOptions options, String encoding ) - { - super( c, options ); - - boolean noSaveDecl = - options != null && options.hasOption( XmlOptions.SAVE_NO_XML_DECL ); - - if (options != null && options.hasOption(XmlOptions.SAVE_CDATA_LENGTH_THRESHOLD)) - _cdataLengthThreshold = ((Integer)options.get(XmlOptions.SAVE_CDATA_LENGTH_THRESHOLD)).intValue(); - - if (options != null && options.hasOption(XmlOptions.SAVE_CDATA_ENTITY_COUNT_THRESHOLD)) - _cdataEntityCountThreshold = ((Integer)options.get(XmlOptions.SAVE_CDATA_ENTITY_COUNT_THRESHOLD)).intValue(); - - if (options != null && options.hasOption(XmlOptions.LOAD_SAVE_CDATA_BOOKMARKS) ) - _useCDataBookmarks = true; - - if (options != null && options.hasOption(XmlOptions.SAVE_PRETTY_PRINT) ) - _isPrettyPrint = true; - - _in = _out = 0; - _free = 0; - - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - if (encoding != null && !noSaveDecl) - { - XmlDocumentProperties props = Locale.getDocProps( c, false ); - - String version = props == null ? null : props.getVersion(); - - if (version == null) - version = "1.0"; - - emit( "" + _newLine ); - } - } - - protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues ) - { - assert c.isElem(); - - emit( '<' ); - emitName( c.getName(), false ); - - if (saveNamespacesFirst()) - emitNamespacesHelper(); - - for ( int i = 0 ; i < attrNames.size() ; i++ ) - emitAttrHelper( (QName) attrNames.get( i ), (String) attrValues.get( i ) ); - - if (!saveNamespacesFirst()) - emitNamespacesHelper(); - - if (!c.hasChildren() && !c.hasText()) - { - emit( '/', '>' ); - return true; - } - else - { - emit( '>' ); - return false; - } - } - - protected void emitFinish ( SaveCur c ) - { - emit( '<', '/' ); - emitName( c.getName(), false ); - emit( '>' ); - } - - protected void emitXmlns ( String prefix, String uri ) - { - assert prefix != null; - assert uri != null; - - emit( "xmlns" ); - - if (prefix.length() > 0) - { - emit( ':' ); - emit( prefix ); - } - - emit( '=', '\"' ); - - // TODO - must encode uri properly - - emit( uri ); - entitizeAttrValue(false); - - emit( '"' ); - } - - private void emitNamespacesHelper ( ) - { - for ( iterateMappings() ; hasMapping() ; nextMapping() ) - { - emit( ' ' ); - emitXmlns( mappingPrefix(), mappingUri() ); - } - } - - private void emitAttrHelper ( QName attrName, String attrValue ) - { - emit( ' ' ); - emitName( attrName, true ); - emit( '=', '\"' ); - emit( attrValue ); - entitizeAttrValue(true); - emit( '"' ); - } - - protected void emitText ( SaveCur c ) - { - assert c.isText(); - - // c.isTextCData() is expensive do it only if useCDataBookmarks option is enabled - boolean forceCData = _useCDataBookmarks && c.isTextCData(); - - emit( c ); - - entitizeContent( forceCData ); - } - - protected void emitComment ( SaveCur c ) - { - assert c.isComment(); - - emit( "" ); - } - - protected void emitProcinst ( SaveCur c ) - { - assert c.isProcinst(); - - emit( "" ); - } - - private void emitLiteral ( String literal ) - { - // TODO: systemId production http://www.w3.org/TR/REC-xml/#NT-SystemLiteral - // TODO: publicId production http://www.w3.org/TR/REC-xml/#NT-PubidLiteral - if (literal.indexOf( "\"" ) < 0) - { - emit( '\"' ); - emit( literal ); - emit( '\"' ); - } - else - { - emit( '\'' ); - emit( literal ); - emit( '\'' ); - } - } - - protected void emitDocType ( String docTypeName, String publicId, String systemId ) - { - assert docTypeName != null; - - emit( "" ); - emit( _newLine ); - } - - protected void emitStartDoc ( SaveCur c ) - { - } - - protected void emitEndDoc ( SaveCur c ) - { - } - - // - // - // - - private void emitName ( QName name, boolean needsPrefix ) - { - assert name != null; - - String uri = name.getNamespaceURI(); - - assert uri != null; - - if (uri.length() != 0) - { - String prefix = name.getPrefix(); - String mappedUri = getNamespaceForPrefix( prefix ); - - if (mappedUri == null || !mappedUri.equals( uri )) - prefix = getUriMapping( uri ); - - // Attrs need a prefix. If I have not found one, then there must be a default - // prefix obscuring the prefix needed for this attr. Find it manually. - - // NOTE - Consider keeping the currently mapped default URI separate fromn the - // _urpMap and _prefixMap. This way, I would not have to look it up manually - // here - - if (needsPrefix && prefix.length() == 0) - prefix = getNonDefaultUriMapping( uri ); - - if (prefix.length() > 0) - { - emit( prefix ); - emit( ':' ); - } - } - - assert name.getLocalPart().length() > 0; - - emit( name.getLocalPart() ); - } - - private void emit ( char ch ) - { - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - preEmit( 1 ); - - _buf[ _in ] = ch; - - _in = (_in + 1) % _buf.length; - - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - } - - private void emit ( char ch1, char ch2 ) - { - if( preEmit( 2 ) ) - return; - - _buf[ _in ] = ch1; - _in = (_in + 1) % _buf.length; - - _buf[ _in ] = ch2; - _in = (_in + 1) % _buf.length; - - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - } - - private void emit ( String s ) - { - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - int cch = s == null ? 0 : s.length(); - - if (preEmit( cch )) - return; - - int chunk; - - if (_in <= _out || cch < (chunk = _buf.length - _in)) - { - s.getChars( 0, cch, _buf, _in ); - _in += cch; - } - else - { - s.getChars( 0, chunk, _buf, _in ); - s.getChars( chunk, cch, _buf, 0 ); - _in = (_in + cch) % _buf.length; - } - - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - } - - private void emit ( SaveCur c ) - { - if (c.isText()) - { - Object src = c.getChars(); - int cch = c._cchSrc; - - if (preEmit( cch )) - return; - - int chunk; - - if (_in <= _out || cch < (chunk = _buf.length - _in)) - { - CharUtil.getChars( _buf, _in, src, c._offSrc, cch ); - _in += cch; - } - else - { - CharUtil.getChars( _buf, _in, src, c._offSrc, chunk ); - CharUtil.getChars( _buf, 0, src, c._offSrc + chunk, cch - chunk ); - _in = (_in + cch) % _buf.length; - } - } - else - preEmit( 0 ); - } - - private boolean preEmit ( int cch ) - { - assert cch >= 0; - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - _lastEmitCch = cch; - - if (cch == 0) - return true; - - if (_free <= cch) - resize( cch, -1 ); - - assert cch <= _free; - - int used = getAvailable(); - - // if we are about to emit and there is noting in the buffer, reset - // the buffer to be at the beginning so as to not grow it anymore - // than needed. - - if (used == 0) - { - assert _in == _out; - assert _free == _buf.length; - _in = _out = 0; - } - - _lastEmitIn = _in; - - _free -= cch; - - assert _free >= 0; - assert _buf==null || _free == (_in>=_out ? _buf.length - (_in - _out) : _out - _in ) - cch : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) - cch) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in - cch ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length - cch) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - return false; - } - - private void entitizeContent ( boolean forceCData ) - { - assert _free >=0; - - if (_lastEmitCch == 0) - return; - - int i = _lastEmitIn; - final int n = _buf.length; - - boolean hasCharToBeReplaced = false; - - int count = 0; - char prevChar = 0; - char prevPrevChar = 0; - for ( int cch = _lastEmitCch ; cch > 0 ; cch-- ) - { - char ch = _buf[ i ]; - - if (ch == '<' || ch == '&') - count++; - else if (prevPrevChar == ']' && prevChar == ']' && ch == '>' ) - hasCharToBeReplaced = true; - else if (isBadChar( ch ) || isEscapedChar( ch ) || (!_isPrettyPrint && ch == '\r') ) - hasCharToBeReplaced = true; - - if (++i == n) - i = 0; - - prevPrevChar = prevChar; - prevChar = ch; - } - - if (!forceCData && count == 0 && !hasCharToBeReplaced && count<_cdataEntityCountThreshold) - return; - - i = _lastEmitIn; - - // - // Heuristic for knowing when to save out stuff as a CDATA. - // - if (forceCData || (_lastEmitCch > _cdataLengthThreshold && count > _cdataEntityCountThreshold) ) - { - boolean lastWasBracket = _buf[ i ] == ']'; - - i = replace( i, " 0 ; cch-- ) - { - char ch = _buf[ i ]; - - if (ch == '>' && secondToLastWasBracket && lastWasBracket) - i = replace( i, "]]>>" ); - } - else - { - char ch = 0, ch_1 = 0, ch_2; - for ( int cch = _lastEmitCch ; cch > 0 ; cch-- ) - { - ch_2 = ch_1; - ch_1 = ch; - ch = _buf[ i ]; - - if (ch == '<') - i = replace( i, "<" ); - else if (ch == '&') - i = replace( i, "&" ); - else if (ch == '>' && ch_1 == ']' && ch_2 == ']') - i = replace( i, ">" ); - else if (isBadChar( ch )) - i = replace( i, "?" ); - else if (!_isPrettyPrint && ch == '\r') - i = replace( i, " " ); - else if (isEscapedChar( ch )) - i = replace( i, _replaceChar.getEscapedString( ch ) ); - else - i++; - - if (i == _buf.length) - i = 0; - } - } - } - - private void entitizeAttrValue ( boolean replaceEscapedChar ) - { - if (_lastEmitCch == 0) - return; - - int i = _lastEmitIn; - - for ( int cch = _lastEmitCch ; cch > 0 ; cch-- ) - { - char ch = _buf[ i ]; - - if (ch == '<') - i = replace( i, "<" ); - else if (ch == '&') - i = replace( i, "&" ); - else if (ch == '"') - i = replace( i, """ ); - else if (isEscapedChar( ch )) - { - if (replaceEscapedChar) - i = replace( i, _replaceChar.getEscapedString( ch ) ); - } - else - i++; - - if (i == _buf.length) - i = 0; - } - } - - private void entitizeComment ( ) - { - if (_lastEmitCch == 0) - return; - - int i = _lastEmitIn; - - boolean lastWasDash = false; - - for ( int cch = _lastEmitCch ; cch > 0 ; cch-- ) - { - char ch = _buf[ i ]; - - if (isBadChar( ch )) - i = replace( i, "?" ); - else if (ch == '-') - { - if (lastWasDash) - { - // Replace "--" with "- " to make well formed - i = replace( i, " " ); - lastWasDash = false; - } - else - { - lastWasDash = true; - i++; - } - } - else - { - lastWasDash = false; - i++; - } - - if (i == _buf.length) - i = 0; - } - - // Because I have only replaced chars with single chars, - // _lastEmitIn will still be ok - - int offset = (_lastEmitIn + _lastEmitCch - 1) % _buf.length; - if (_buf[ offset ] == '-') - i = replace( offset, " " ); - } - - private void entitizeProcinst ( ) - { - if (_lastEmitCch == 0) - return; - - int i = _lastEmitIn; - - boolean lastWasQuestion = false; - - for ( int cch = _lastEmitCch ; cch > 0 ; cch-- ) - { - char ch = _buf[ i ]; - - if (isBadChar( ch )) - i = replace( i, "?" ); - - if (ch == '>') - { - // TODO - Had to convert to a space here ... imples not well formed XML - if (lastWasQuestion) - i = replace( i, " " ); - else - i++; - - lastWasQuestion = false; - } - else - { - lastWasQuestion = ch == '?'; - i++; - } - - if (i == _buf.length) - i = 0; - } - } - - /** - * Test if a character is to be replaced with an escaped value - */ - private boolean isEscapedChar ( char ch ) - { - return ( null != _replaceChar && _replaceChar.containsChar( ch ) ); - } - - private int replace ( int i, String replacement ) - { - assert replacement.length() > 0; - - int dCch = replacement.length() - 1; - - if (dCch == 0) - { - _buf[ i ] = replacement.charAt( 0 ); - return i + 1; - } - - assert _free >= 0; - - if (dCch > _free) - i = resize( dCch, i ); - - assert _free >= 0; - - assert _free >= dCch; - assert getAvailable() > 0; - - int charsToCopy = dCch + 1; - - if (_out > _in && i >= _out) - { - System.arraycopy( _buf, _out, _buf, _out - dCch, i - _out ); - _out -= dCch; - i -= dCch; - } - else - { - assert i < _in; - int availableEndChunk = _buf.length - _in; - if ( dCch <= availableEndChunk ) - { - System.arraycopy( _buf, i, _buf, i + dCch, _in - i ); - _in = ( _in + dCch) % _buf.length; - } - else if ( dCch <= availableEndChunk + _in - i - 1 ) - { - int numToCopyToStart = dCch - availableEndChunk; - System.arraycopy( _buf, _in-numToCopyToStart, _buf, 0, numToCopyToStart ); - System.arraycopy( _buf, i+1, _buf, i+1+dCch, _in-i-1-numToCopyToStart); - - _in = numToCopyToStart; - } - else - { - int numToCopyToStart = _in - i - 1; - charsToCopy = availableEndChunk + _in - i; - - System.arraycopy( _buf, _in-numToCopyToStart, _buf, dCch-charsToCopy+1, numToCopyToStart ); - replacement.getChars( charsToCopy, dCch + 1, _buf, 0); - - _in = numToCopyToStart + dCch - charsToCopy + 1; - } - } - - replacement.getChars( 0, charsToCopy, _buf, i ); - - _free -= dCch; - - assert _free >= 0; - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - return (i + dCch + 1) % _buf.length; - } - // - // - // - - private int ensure ( int cch ) - { - // Even if we're asked to ensure nothing, still try to ensure - // atleast one character so we can determine if we're at the - // end of the stream. - - if (cch <= 0) - cch = 1; - - int available = getAvailable(); - - for ( ; available < cch ; available = getAvailable() ) - if (!process()) - break; - - assert available == getAvailable(); - -// if (available == 0) -// return 0; - - return available; - } - - int getAvailable ( ) - { - return _buf == null ? 0 : _buf.length - _free; - } - - private int resize ( int cch, int i ) - { - assert _free >= 0; - assert cch > 0; - assert cch >= _free; - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - int newLen = _buf == null ? _initialBufSize : _buf.length * 2; - int used = getAvailable(); - - while ( newLen - used < cch ) - newLen *= 2; - - char[] newBuf = new char [ newLen ]; - - if (used > 0) - { - if (_in > _out) - { - assert i == -1 || (i >= _out && i < _in); - System.arraycopy( _buf, _out, newBuf, 0, used ); - i -= _out; - } - else - { - assert i == -1 || (i >= _out || i < _in); - System.arraycopy( _buf, _out, newBuf, 0, used - _in ); - System.arraycopy( _buf, 0, newBuf, used - _in, _in ); - i = i >= _out ? i - _out : i + _out; - } - - _out = 0; - _in = used; - _free += newBuf.length - _buf.length; - } - else - { - _free = newBuf.length; - assert _in == 0 && _out == 0; - assert i == -1; - } - - _buf = newBuf; - - assert _free >= 0; - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - return i; - } - - public int read ( ) - { - if (ensure( 1 ) == 0) - return -1; - - assert getAvailable() > 0; - - int ch = _buf[ _out ]; - - _out = (_out + 1) % _buf.length; - _free++; - - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - return ch; - } - - public int read ( char[] cbuf, int off, int len ) - { - // Check for end of stream even if there is no way to return - // characters because the Reader doc says to return -1 at end of - // stream. - - int n; - - if ((n = ensure( len )) == 0) - return -1; - - if (cbuf == null || len <= 0) - return 0; - - if (n < len) - len = n; - - if (_out < _in) - { - System.arraycopy( _buf, _out, cbuf, off, len ); - } - else - { - int chunk = _buf.length - _out; - - if (chunk >= len) - System.arraycopy( _buf, _out, cbuf, off, len ); - else - { - System.arraycopy( _buf, _out, cbuf, off, chunk ); - System.arraycopy( _buf, 0, cbuf, off + chunk, len - chunk ); - } - } - - _out = (_out + len) % _buf.length; - _free += len; - - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - assert _free >= 0; - - return len; - } - - public int write ( Writer writer, int cchMin ) - { - while ( getAvailable() < cchMin) - { - if (!process()) - break; - } - - int charsAvailable = getAvailable(); - - if (charsAvailable > 0) - { - // I don't want to deal with the circular cases - - assert _out == 0; - assert _in >= _out : "_in:" + _in + " < _out:" + _out; - assert _free == _buf.length - _in; - - try - { -//System.out.println("-------------\nWriting in corverter: TextSaver.write():1703 " + charsAvailable + " chars\n" + new String(_buf, 0, charsAvailable)); - writer.write( _buf, 0, charsAvailable ); - writer.flush(); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - - _free += charsAvailable; - - assert _free >= 0; - - _in = 0; - } - assert _buf==null || - (_out<_in && _free == _buf.length - ( _in - _out ) ) || // data in the middle, free on the edges - (_out>_in && _free == _out - _in ) || // data on the edges, free in the middle - (_out==_in && _free == _buf.length) || // no data, all buffer free - (_out==_in && _free == 0) // buffer full - : "_buf.length:" + _buf.length + " _in:" + _in + " _out:" + _out + " _free:" + _free; - - return charsAvailable; - } - - public String saveToString ( ) - { - // We're gonna build a string. Instead of using StringBuffer, may - // as well use my buffer here. Fill the whole sucker up and - // create a String! - - while ( process() ) - ; - - assert _out == 0; - - int available = getAvailable(); - - return available == 0 ? "" : new String( _buf, _out, available ); - } - - // - // - // - - private static final int _initialBufSize = 4096; - private int _cdataLengthThreshold = 32; - private int _cdataEntityCountThreshold = 5; - private boolean _useCDataBookmarks = false; - private boolean _isPrettyPrint = false; - - private int _lastEmitIn; - private int _lastEmitCch; - - private int _free; - private int _in; - private int _out; - private char[] _buf; - /* - _buf is a circular buffer, useful data is before _in up to _out, there are 2 posible configurations: - 1: _in<=_out |data|_in empty _out|data| - 2: _out<_in |empty _out|data|_in empty| - _free is used to keep around the remaining empty space in the bufer so assert _buf==null || _free == (_in>=_out ? _buf.length - (_in - _out) : _out - _in ) ; - */ - } - - static final class OptimizedForSpeedSaver - extends Saver - { - Writer _w; - private char[] _buf = new char[1024]; - - - static private class SaverIOException - extends RuntimeException - { - SaverIOException(IOException e) - { - super(e); - } - } - - - OptimizedForSpeedSaver(Cur cur, Writer writer) - { - super(cur, XmlOptions.maskNull(null)); - _w = writer; - } - - static void save(Cur cur, Writer writer) - throws IOException - { - try - { - Saver saver = new OptimizedForSpeedSaver(cur, writer); - while(saver.process()) - {} - } - catch (SaverIOException e) - { - throw (IOException)e.getCause(); - } - } - - private void emit(String s) - { - try - { - _w.write(s); - } - catch (IOException e) - { - throw new SaverIOException(e); - } - } - - private void emit(char c) - { - try - { - _buf[0] = c; - _w.write(_buf, 0, 1); - } - catch (IOException e) - { - throw new SaverIOException(e); - } - } - - private void emit(char c1, char c2) - { - try - { - _buf[0] = c1; - _buf[1] = c2; - _w.write(_buf, 0 , 2); - } - catch (IOException e) - { - throw new SaverIOException(e); - } - } - - private void emit(char[] buf, int start, int len) - { - try - { - _w.write(buf, start, len); - } - catch (IOException e) - { - throw new SaverIOException(e); - } - } - - protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues ) - { - assert c.isElem(); - - emit( '<' ); - emitName( c.getName(), false ); - - for ( int i = 0 ; i < attrNames.size() ; i++ ) - emitAttrHelper( (QName) attrNames.get( i ), (String) attrValues.get( i ) ); - - if (!saveNamespacesFirst()) - emitNamespacesHelper(); - - if (!c.hasChildren() && !c.hasText()) - { - emit( '/', '>' ); - return true; - } - else - { - emit( '>' ); - return false; - } - } - - protected void emitFinish ( SaveCur c ) - { - emit( '<', '/' ); - emitName( c.getName(), false ); - emit( '>' ); - } - - protected void emitXmlns ( String prefix, String uri ) - { - assert prefix != null; - assert uri != null; - - emit( "xmlns" ); - - if (prefix.length() > 0) - { - emit( ':' ); - emit( prefix ); - } - - emit( '=', '\"' ); - - // TODO - must encode uri properly - emitAttrValue(uri); - - emit( '"' ); - } - - private void emitNamespacesHelper ( ) - { - for ( iterateMappings() ; hasMapping() ; nextMapping() ) - { - emit( ' ' ); - emitXmlns( mappingPrefix(), mappingUri() ); - } - } - - private void emitAttrHelper ( QName attrName, String attrValue ) - { - emit( ' ' ); - emitName( attrName, true ); - emit( '=', '\"' ); - emitAttrValue(attrValue); - - emit( '"' ); - } - - protected void emitComment ( SaveCur c ) - { - assert c.isComment(); - - emit( "" ); - } - - protected void emitProcinst ( SaveCur c ) - { - assert c.isProcinst(); - - emit( "" ); - } - - protected void emitDocType ( String docTypeName, String publicId, String systemId ) - { - assert docTypeName != null; - - emit( "' ); - emit( _newLine ); - } - - protected void emitStartDoc ( SaveCur c ) - { - } - - protected void emitEndDoc ( SaveCur c ) - { - } - - // - // - // - - private void emitName ( QName name, boolean needsPrefix ) - { - assert name != null; - - String uri = name.getNamespaceURI(); - - assert uri != null; - - if (uri.length() != 0) - { - String prefix = name.getPrefix(); - String mappedUri = getNamespaceForPrefix( prefix ); - - if (mappedUri == null || !mappedUri.equals( uri )) - prefix = getUriMapping( uri ); - - // Attrs need a prefix. If I have not found one, then there must be a default - // prefix obscuring the prefix needed for this attr. Find it manually. - - // NOTE - Consider keeping the currently mapped default URI separate fromn the - // _urpMap and _prefixMap. This way, I would not have to look it up manually - // here - - if (needsPrefix && prefix.length() == 0) - prefix = getNonDefaultUriMapping( uri ); - - if (prefix.length() > 0) - { - emit( prefix ); - emit( ':' ); - } - } - - assert name.getLocalPart().length() > 0; - - emit( name.getLocalPart() ); - } - - private void emitAttrValue ( CharSequence attVal) - { - int len = attVal.length(); - - for ( int i = 0; i cch ? cch : index + 512; - CharUtil.getChars( _buf, 0, src, off+index, indexLimit-index ); - entitizeAndWriteText(indexLimit-index); - index = indexLimit; - } - } - - protected void emitPiText ( SaveCur c ) - { - assert c.isText(); - - Object src = c.getChars(); - int cch = c._cchSrc; - int off = c._offSrc; - int index = 0; - int indexLimit = 0; - while( index cch ? cch : 512; - CharUtil.getChars( _buf, 0, src, off+index, indexLimit ); - entitizeAndWritePIText(indexLimit-index); - index = indexLimit; - } - } - - protected void emitCommentText ( SaveCur c ) - { - assert c.isText(); - - Object src = c.getChars(); - int cch = c._cchSrc; - int off = c._offSrc; - int index = 0; - int indexLimit = 0; - while( index cch ? cch : 512; - CharUtil.getChars( _buf, 0, src, off+index, indexLimit ); - entitizeAndWriteCommentText(indexLimit-index); - index = indexLimit; - } - } - - private void entitizeAndWriteText(int bufLimit) - { - int index = 0; - for (int i = 0; i < bufLimit; i++) - { - char c = _buf[i]; - switch(c) - { - case '<': - emit(_buf, index, i-index); - emit("<"); - index = i+1; - break; - case '&': - emit(_buf, index, i-index); - emit("&"); - index = i+1; - break; - } - } - emit(_buf, index, bufLimit-index); - } - - private void entitizeAndWriteCommentText ( int bufLimit ) - { - boolean lastWasDash = false; - - for ( int i=0 ; i') - { - // Had to convert to a space here ... imples not well formed XML - if (lastWasQuestion) - _buf[i] = ' '; - - lastWasQuestion = false; - } - else - { - lastWasQuestion = ch == '?'; - } - } - emit(_buf, 0, bufLimit); - } - } - - static final class TextReader extends Reader - { - TextReader ( Cur c, XmlOptions options ) - { - _textSaver = new TextSaver( c, options, null ); - _locale = c._locale; - _closed = false; - } - - public void close ( ) throws IOException { _closed = true; } - - public boolean ready ( ) throws IOException { return !_closed; } - - public int read ( ) throws IOException - { - checkClosed(); - - if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read(); } finally { _locale.exit(); } } - else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read(); } finally { _locale.exit(); } } - } - - public int read ( char[] cbuf ) throws IOException - { - checkClosed(); - - if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read( cbuf, 0, cbuf == null ? 0 : cbuf.length ); } finally { _locale.exit(); } } - else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read( cbuf, 0, cbuf == null ? 0 : cbuf.length ); } finally { _locale.exit(); } } - } - - public int read ( char[] cbuf, int off, int len ) throws IOException - { - checkClosed(); - - if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read( cbuf, off, len ); } finally { _locale.exit(); } } - else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read( cbuf, off, len ); } finally { _locale.exit(); } } - } - - private void checkClosed ( ) throws IOException - { - if (_closed) - throw new IOException( "Reader has been closed" ); - } - - private Locale _locale; - private TextSaver _textSaver; - private boolean _closed; - } - - static final class InputStreamSaver extends InputStream - { - InputStreamSaver ( Cur c, XmlOptions options ) - { - _locale = c._locale; - - _closed = false; - - assert _locale.entered(); - - options = XmlOptions.maskNull( options ); - - _outStreamImpl = new OutputStreamImpl(); - - String encoding = null; - - XmlDocumentProperties props = Locale.getDocProps( c, false ); - - if (props != null && props.getEncoding() != null) - encoding = EncodingMap.getIANA2JavaMapping( props.getEncoding() ); - - if (options.hasOption( XmlOptions.CHARACTER_ENCODING )) - encoding = (String) options.get( XmlOptions.CHARACTER_ENCODING ); - - if (encoding != null) - { - String ianaEncoding = EncodingMap.getJava2IANAMapping( encoding ); - - if (ianaEncoding != null) - encoding = ianaEncoding; - } - - if (encoding == null) - encoding = EncodingMap.getJava2IANAMapping( "UTF8" ); - - String javaEncoding = EncodingMap.getIANA2JavaMapping( encoding ); - - if (javaEncoding == null) - throw new IllegalStateException( "Unknown encoding: " + encoding ); - - try - { - _converter = new OutputStreamWriter( _outStreamImpl, javaEncoding ); - } - catch ( UnsupportedEncodingException e ) - { - throw new RuntimeException( e ); - } - - _textSaver = new TextSaver( c, options, encoding ); - } - - public void close ( ) throws IOException - { - _closed = true; - } - - private void checkClosed ( ) throws IOException - { - if (_closed) - throw new IOException( "Stream closed" ); - } - - // Having the gateway here is kinda slow for the single character case. It may be possible - // to only enter the gate when there are no chars in the buffer. - - public int read ( ) throws IOException - { - checkClosed(); - - if (_locale.noSync()) { _locale.enter(); try { return _outStreamImpl.read(); } finally { _locale.exit(); } } - else synchronized ( _locale ) { _locale.enter(); try { return _outStreamImpl.read(); } finally { _locale.exit(); } } - } - - public int read ( byte[] bbuf, int off, int len ) throws IOException - { - checkClosed(); - - if (bbuf == null) - throw new NullPointerException( "buf to read into is null" ); - - if (off < 0 || off > bbuf.length) - throw new IndexOutOfBoundsException( "Offset is not within buf" ); - - if (_locale.noSync()) { _locale.enter(); try { return _outStreamImpl.read( bbuf, off, len ); } finally { _locale.exit(); } } - else synchronized ( _locale ) { _locale.enter(); try { return _outStreamImpl.read( bbuf, off, len ); } finally { _locale.exit(); } } - } - - private int ensure ( int cbyte ) - { - // Even if we're asked to ensure nothing, still try to ensure - // atleast one byte so we can determine if we're at the - // end of the stream. - - if (cbyte <= 0) - cbyte = 1; - - int bytesAvailable = _outStreamImpl.getAvailable(); - - for ( ; bytesAvailable < cbyte ; - bytesAvailable = _outStreamImpl.getAvailable() ) - { - if (_textSaver.write( _converter, 2048 ) < 2048) - break; - } - - bytesAvailable = _outStreamImpl.getAvailable(); - -// if (bytesAvailable == 0) -// return 0; - - return bytesAvailable; - } - - public int available() - throws IOException - { - if (_locale.noSync()) - { _locale.enter(); try { - return ensure(1024); - } finally { _locale.exit(); } } - else - synchronized ( _locale ) - { _locale.enter(); try { return ensure(1024); } finally { _locale.exit(); } } - } - - private final class OutputStreamImpl extends OutputStream - { - int read ( ) - { - if (InputStreamSaver.this.ensure( 1 ) == 0) - return -1; - - assert getAvailable() > 0; - - int bite = _buf[ _out ]; - - _out = (_out + 1) % _buf.length; - _free++; - - return bite; - } - - int read ( byte[] bbuf, int off, int len ) - { - // Check for end of stream even if there is no way to return - // characters because the Reader doc says to return -1 at end of - // stream. - - int n; - - if ((n = ensure( len )) == 0) - return -1; - - if (bbuf == null || len <= 0) - return 0; - - if (n < len) - len = n; - - if (_out < _in) - { - System.arraycopy( _buf, _out, bbuf, off, len ); - } - else - { - int chunk = _buf.length - _out; - - if (chunk >= len) - System.arraycopy( _buf, _out, bbuf, off, len ); - else - { - System.arraycopy( _buf, _out, bbuf, off, chunk ); - - System.arraycopy( - _buf, 0, bbuf, off + chunk, len - chunk ); - } - } - _out = (_out + len) % _buf.length; - _free += len; - -//System.out.println("------------------------\nRead out of queue: Saver:2440 InputStreamSaver.read() bbuf " + len + " bytes :\n" + new String(bbuf, off, len)); - return len; - } - - int getAvailable ( ) - { - return _buf == null ? 0 : _buf.length - _free; - } - - public void write ( int bite ) - { - if (_free == 0) - resize( 1 ); - - assert _free > 0; - - _buf[ _in ] = (byte) bite; - - _in = (_in + 1) % _buf.length; - _free--; - } - - public void write ( byte[] buf, int off, int cbyte ) - { - assert cbyte >= 0; -//System.out.println("---------\nAfter converter, write in queue: OutputStreamImpl.write():Saver:2469 " + cbyte + " bytes \n" + new String(buf, off, cbyte)); - if (cbyte == 0) - return; - - if (_free < cbyte) - resize( cbyte ); - - if (_in == _out) - { - assert getAvailable() == 0; - assert _free == _buf.length - getAvailable(); - _in = _out = 0; - } - - int chunk = _buf.length - _in; - - if (_in <= _out || cbyte < chunk) - { - System.arraycopy( buf, off, _buf, _in, cbyte ); - _in += cbyte; - } - else - { - System.arraycopy( buf, off, _buf, _in, chunk ); - - System.arraycopy( - buf, off + chunk, _buf, 0, cbyte - chunk ); - - _in = (_in + cbyte) % _buf.length; - } - - _free -= cbyte; - } - - void resize ( int cbyte ) - { - assert cbyte > _free : cbyte + " !> " + _free; - - int newLen = _buf == null ? _initialBufSize : _buf.length * 2; - int used = getAvailable(); - - while ( newLen - used < cbyte ) - newLen *= 2; - - byte[] newBuf = new byte [ newLen ]; - - if (used > 0) - { - if (_in > _out) - System.arraycopy( _buf, _out, newBuf, 0, used ); - else - { - System.arraycopy( - _buf, _out, newBuf, 0, used - _in ); - - System.arraycopy( - _buf, 0, newBuf, used - _in, _in ); - } - - _out = 0; - _in = used; - _free += newBuf.length - _buf.length; - } - else - { - _free = newBuf.length; - assert _in == _out; - } - - _buf = newBuf; - } - - private static final int _initialBufSize = 4096; - - private int _free; - private int _in; - private int _out; - private byte[] _buf; - } - - private Locale _locale; - private boolean _closed; - private OutputStreamImpl _outStreamImpl; - private TextSaver _textSaver; - private OutputStreamWriter _converter; - } - - static final class XmlInputStreamSaver extends Saver - { - XmlInputStreamSaver ( Cur c, XmlOptions options ) - { - super( c, options ); - } - - protected boolean emitElement(SaveCur c, ArrayList attrNames, ArrayList attrValues) - { - assert c.isElem(); - - for ( iterateMappings() ; hasMapping() ; nextMapping() ) - { - enqueue( new StartPrefixMappingImpl( mappingPrefix(), mappingUri() ) ); - } - - StartElementImpl.AttributeImpl lastAttr = null; - StartElementImpl.AttributeImpl attributes = null; - StartElementImpl.AttributeImpl namespaces = null; - - for ( int i=0; i 0; - - String prefix = null; - - if (uri!=null && uri.length() != 0) - { - prefix = name.getPrefix(); - String mappedUri = saver.getNamespaceForPrefix( prefix ); - - if (mappedUri == null || !mappedUri.equals( uri )) - prefix = saver.getUriMapping( uri ); - - // Attrs need a prefix. If I have not found one, then there must be a default - // prefix obscuring the prefix needed for this attr. Find it manually. - - // NOTE - Consider keeping the currently mapped default URI separate fromn the - // _urpMap and _prefixMap. This way, I would not have to look it up manually - // here - - if (needsPrefix && prefix.length() == 0) - prefix = saver.getNonDefaultUriMapping( uri ); - - } - - return new XmlNameImpl( uri, local, prefix ); - } - - private static abstract class XmlEventImpl extends XmlEventBase - { - XmlEventImpl ( int type ) - { - super( type ); - } - - public XMLName getName ( ) - { - return null; - } - - public XMLName getSchemaType ( ) - { - throw new RuntimeException( "NYI" ); - } - - public boolean hasName ( ) - { - return false; - } - - public final Location getLocation ( ) - { - // (orig v1 comment)TODO - perhaps I can save a location goober sometimes? - return null; - } - - XmlEventImpl _next; - } - - private static class StartDocumentImpl - extends XmlEventImpl implements StartDocument - { - StartDocumentImpl ( String systemID, String encoding, boolean isStandAlone, String version ) - { - super( XMLEvent.START_DOCUMENT ); - _systemID = systemID; - _encoding = encoding; - _standAlone = isStandAlone; - _version = version; - } - - public String getSystemId ( ) - { - return _systemID; - } - - public String getCharacterEncodingScheme ( ) - { - return _encoding; - } - - public boolean isStandalone ( ) - { - return _standAlone; - } - - public String getVersion ( ) - { - return _version; - } - - String _systemID; - String _encoding; - boolean _standAlone; - String _version; - } - - private static class StartElementImpl - extends XmlEventImpl implements StartElement - { - StartElementImpl ( XMLName name, AttributeImpl attributes, AttributeImpl namespaces, Map prefixMap ) - { - super( XMLEvent.START_ELEMENT ); - - _name = name; - _attributes = attributes; - _namespaces = namespaces; - _prefixMap = prefixMap; - } - - public boolean hasName() - { - return true; - } - - public XMLName getName ( ) - { - return _name; - } - - public AttributeIterator getAttributes ( ) - { - return new AttributeIteratorImpl( _attributes, null ); - } - - public AttributeIterator getNamespaces ( ) - { - return new AttributeIteratorImpl( null, _namespaces ); - } - - public AttributeIterator getAttributesAndNamespaces ( ) - { - return new AttributeIteratorImpl( _attributes, _namespaces ); - } - - public Attribute getAttributeByName ( XMLName xmlName ) - { - for ( AttributeImpl a = _attributes ; a != null ; a = a._next ) - { - if (xmlName.equals( a.getName() )) - return a; - } - - return null; - } - - public String getNamespaceUri ( String prefix ) - { - return (String) _prefixMap.get( prefix == null ? "" : prefix ); - } - - public Map getNamespaceMap ( ) - { - return _prefixMap; - } - - private static class AttributeIteratorImpl - implements AttributeIterator - { - AttributeIteratorImpl( AttributeImpl attributes, AttributeImpl namespaces ) - { - _attributes = attributes; - _namespaces = namespaces; - } - - public Object monitor() - { - return this; - } - - public Attribute next ( ) - { - synchronized (monitor()) - { - checkVersion(); - - AttributeImpl attr = null; - - if (_attributes != null) - { - attr = _attributes; - _attributes = attr._next; - } - else if (_namespaces != null) - { - attr = _namespaces; - _namespaces = attr._next; - } - - return attr; - } - } - - public boolean hasNext ( ) - { - synchronized (monitor()) - { - checkVersion(); - - return _attributes != null || _namespaces != null; - } - } - - public Attribute peek ( ) - { - synchronized (monitor()) - { - checkVersion(); - - if (_attributes != null) - return _attributes; - else if (_namespaces != null) - return _namespaces; - - return null; - } - } - - public void skip ( ) - { - synchronized (monitor()) - { - checkVersion(); - - if (_attributes != null) - _attributes = _attributes._next; - else if (_namespaces != null) - _namespaces = _namespaces._next; - } - } - - private final void checkVersion ( ) - { -// if (_version != _root.getVersion()) -// throw new IllegalStateException( "Document changed" ); - } - -// private long _version; - private AttributeImpl _attributes; - private AttributeImpl _namespaces; - } - - private static abstract class AttributeImpl implements Attribute - { - /** - * Don't forget to set _name - */ - AttributeImpl () - { - } - - public XMLName getName ( ) - { - return _name; - } - - public String getType ( ) - { - // (from v1 impl) TODO - Make sure throwing away this DTD info is ok. - // (from v1 impl) Is there schema info which can return more useful info? - return "CDATA"; - } - - public XMLName getSchemaType ( ) - { - // (from v1 impl) TODO - Can I return something reasonable here? - return null; - } - - AttributeImpl _next; - - protected XMLName _name; - } - - private static class XmlnsAttributeImpl extends AttributeImpl - { - XmlnsAttributeImpl ( String prefix, String uri ) - { - super(); - _uri = uri; - - String local; - - if (prefix.length() == 0) - { - prefix = null; - local = "xmlns"; - } - else - { - local = prefix; - prefix = "xmlns"; - } - - _name = new XmlNameImpl( null, local, prefix ); - } - - public String getValue ( ) - { - return _uri; - } - - private String _uri; - } - - private static class NormalAttributeImpl extends AttributeImpl - { - NormalAttributeImpl (XMLName name, String value) - { - _name = name; - _value = value; - } - - public String getValue ( ) - { - return _value; - } - - private String _value; // If invalid in the store - } - - private XMLName _name; - private Map _prefixMap; - - private AttributeImpl _attributes; - private AttributeImpl _namespaces; - } - - private static class StartPrefixMappingImpl - extends XmlEventImpl implements StartPrefixMapping - { - StartPrefixMappingImpl ( String prefix, String uri ) - { - super( XMLEvent.START_PREFIX_MAPPING ); - - _prefix = prefix; - _uri = uri; - } - - public String getNamespaceUri ( ) - { - return _uri; - } - - public String getPrefix ( ) - { - return _prefix; - } - - private String _prefix, _uri; - } - - private static class ChangePrefixMappingImpl - extends XmlEventImpl implements ChangePrefixMapping - { - ChangePrefixMappingImpl ( String prefix, String oldUri, String newUri ) - { - super( XMLEvent.CHANGE_PREFIX_MAPPING ); - - _oldUri = oldUri; - _newUri = newUri; - _prefix = prefix; - } - - public String getOldNamespaceUri ( ) - { - return _oldUri; - } - - public String getNewNamespaceUri ( ) - { - return _newUri; - } - - public String getPrefix ( ) - { - return _prefix; - } - - private String _oldUri, _newUri, _prefix; - } - - private static class EndPrefixMappingImpl - extends XmlEventImpl implements EndPrefixMapping - { - EndPrefixMappingImpl ( String prefix ) - { - super( XMLEvent.END_PREFIX_MAPPING ); - _prefix = prefix; - } - - public String getPrefix ( ) - { - return _prefix; - } - - private String _prefix; - } - - private static class EndElementImpl - extends XmlEventImpl implements EndElement - { - EndElementImpl ( XMLName name ) - { - super( XMLEvent.END_ELEMENT ); - - _name = name; - } - - public boolean hasName ( ) - { - return true; - } - - public XMLName getName ( ) - { - return _name; - } - - private XMLName _name; - } - - private static class EndDocumentImpl - extends XmlEventImpl implements EndDocument - { - EndDocumentImpl ( ) - { - super( XMLEvent.END_DOCUMENT ); - } - } - - private static class TripletEventImpl - extends XmlEventImpl implements CharacterData - { - TripletEventImpl ( int eventType, Object obj, int cch, int off ) - { - super(eventType); - _obj = obj; - _cch = cch; - _off = off; - } - - public String getContent ( ) - { - return CharUtil.getString(_obj, _off, _cch); - } - - public boolean hasContent ( ) - { - return _cch > 0; - } - - private Object _obj; - private int _cch; - private int _off; - } - - private static class CharacterDataImpl - extends TripletEventImpl implements CharacterData - { - CharacterDataImpl ( Object obj, int cch, int off ) - { - super(XMLEvent.CHARACTER_DATA, obj, cch, off); - } - } - - private static class CommentImpl - extends TripletEventImpl implements Comment - { - CommentImpl ( Object obj, int cch, int off ) - { - super( XMLEvent.COMMENT, obj, cch, off); - } - } - - private static class ProcessingInstructionImpl - extends TripletEventImpl implements ProcessingInstruction - { - ProcessingInstructionImpl ( String target, Object obj, int cch, int off) - { - super( XMLEvent.PROCESSING_INSTRUCTION, obj, cch, off); - _target = target; - } - - public String getTarget ( ) - { - return _target; - } - - public String getData ( ) - { - return getContent(); - } - - private String _target; - } - - private XmlEventImpl _in, _out; - } - - static final class XmlInputStreamImpl extends GenericXmlInputStream - { - XmlInputStreamImpl ( Cur cur, XmlOptions options ) - { - _xmlInputStreamSaver = - new XmlInputStreamSaver( cur, options ); - - // Make the saver grind away just a bit to throw any exceptions - // related to the inability to create a stream on this xml - - _xmlInputStreamSaver.process(); - } - - protected XMLEvent nextEvent ( ) throws XMLStreamException - { - return _xmlInputStreamSaver.dequeue(); - } - - private XmlInputStreamSaver _xmlInputStreamSaver; - } - - static final class SaxSaver extends Saver - { - SaxSaver ( Cur c, XmlOptions options, ContentHandler ch, LexicalHandler lh ) - throws SAXException - { - super( c, options ); - - _contentHandler = ch; - _lexicalHandler = lh; - - _attributes = new AttributesImpl(); - _nsAsAttrs = !options.hasOption( XmlOptions.SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES ); - - _contentHandler.startDocument(); - - try - { - while ( process() ) - ; - } - catch ( SaverSAXException e ) - { - throw e._saxException; - } - - _contentHandler.endDocument(); - } - - private class SaverSAXException extends RuntimeException - { - SaverSAXException ( SAXException e ) - { - _saxException = e; - } - - SAXException _saxException; - } - - private String getPrefixedName ( QName name ) - { - String uri = name.getNamespaceURI(); - String local = name.getLocalPart(); - - if (uri.length() == 0) - return local; - - String prefix = getUriMapping( uri ); - - if (prefix.length() == 0) - return local; - - return prefix + ":" + local; - } - - private void emitNamespacesHelper ( ) - { - for ( iterateMappings() ; hasMapping() ; nextMapping() ) - { - String prefix = mappingPrefix(); - String uri = mappingUri(); - - try - { - _contentHandler.startPrefixMapping( prefix, uri ); - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - - if (_nsAsAttrs) - if (prefix == null || prefix.length() == 0) - _attributes.addAttribute( "http://www.w3.org/2000/xmlns/", "xmlns", "xmlns", "CDATA", uri ); - else - _attributes.addAttribute( "http://www.w3.org/2000/xmlns/", prefix, "xmlns:" + prefix, "CDATA", uri ); - } - } - - protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues ) - { - _attributes.clear(); - - if (saveNamespacesFirst()) - emitNamespacesHelper(); - - for ( int i = 0 ; i < attrNames.size() ; i++ ) - { - QName name = (QName) attrNames.get( i ); - - _attributes.addAttribute( - name.getNamespaceURI(), name.getLocalPart(), getPrefixedName( name ), - "CDATA", (String) attrValues.get( i ) ); - } - - if (!saveNamespacesFirst()) - emitNamespacesHelper(); - - QName elemName = c.getName(); - - try - { - _contentHandler.startElement( - elemName.getNamespaceURI(), elemName.getLocalPart(), - getPrefixedName( elemName ), _attributes ); - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - - return false; - } - - protected void emitFinish ( SaveCur c ) - { - QName name = c.getName(); - - try - { - _contentHandler.endElement( - name.getNamespaceURI(), name.getLocalPart(), getPrefixedName( name ) ); - - for ( iterateMappings() ; hasMapping() ; nextMapping() ) - _contentHandler.endPrefixMapping( mappingPrefix() ); - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - } - - protected void emitText ( SaveCur c ) - { - assert c.isText(); - - Object src = c.getChars(); - - try - { - if (src instanceof char[]) - { - // Pray the user does not modify the buffer .... - _contentHandler.characters( (char[]) src, c._offSrc, c._cchSrc ); - } - else - { - if (_buf == null) - _buf = new char [ 1024 ]; - - while ( c._cchSrc > 0 ) - { - int cch = java.lang.Math.min( _buf.length, c._cchSrc ); - - CharUtil.getChars( _buf, 0, src, c._offSrc, cch ); - - _contentHandler.characters( _buf, 0, cch ); - - c._offSrc += cch; - c._cchSrc -= cch; - } - } - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - } - - protected void emitComment ( SaveCur c ) - { - if (_lexicalHandler != null) - { - c.push(); - - c.next(); - - try - { - if (!c.isText()) - _lexicalHandler.comment( null, 0, 0 ); - else - { - Object src = c.getChars(); - - if (src instanceof char[]) - { - // Pray the user does not modify the buffer .... - _lexicalHandler.comment( (char[]) src, c._offSrc, c._cchSrc ); - } - else - { - if (_buf == null || _buf.length < c._cchSrc) - _buf = new char [ java.lang.Math.max( 1024, c._cchSrc ) ]; - - CharUtil.getChars( _buf, 0, src, c._offSrc, c._cchSrc ); - - _lexicalHandler.comment( _buf, 0, c._cchSrc ); - } - } - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - - c.pop(); - } - } - - protected void emitProcinst ( SaveCur c ) - { - String target = c.getName().getLocalPart(); - - c.push(); - - c.next(); - - String value = CharUtil.getString( c.getChars(), c._offSrc, c._cchSrc ); - - c.pop(); - - try - { - _contentHandler.processingInstruction( c.getName().getLocalPart(), value ); - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - } - - protected void emitDocType ( String docTypeName, String publicId, String systemId ) - { - if (_lexicalHandler != null) - { - try - { - _lexicalHandler.startDTD( docTypeName, publicId, systemId ); - _lexicalHandler.endDTD(); - } - catch ( SAXException e ) - { - throw new SaverSAXException( e ); - } - } - } - - protected void emitStartDoc ( SaveCur c ) - { - } - - protected void emitEndDoc ( SaveCur c ) - { - } - - private ContentHandler _contentHandler; - private LexicalHandler _lexicalHandler; - - private AttributesImpl _attributes; - - private char[] _buf; - private boolean _nsAsAttrs; - } - - // - // - // - - static abstract class SaveCur - { - final boolean isRoot ( ) { return kind() == ROOT; } - final boolean isElem ( ) { return kind() == ELEM; } - final boolean isAttr ( ) { return kind() == ATTR; } - final boolean isText ( ) { return kind() == TEXT; } - final boolean isComment ( ) { return kind() == COMMENT; } - final boolean isProcinst ( ) { return kind() == PROCINST; } - final boolean isFinish ( ) { return Cur.kindIsFinish( kind() ); } - final boolean isContainer ( ) { return Cur.kindIsContainer( kind() ); } - final boolean isNormalAttr ( ) { return kind() == ATTR && !isXmlns(); } - - final boolean skip ( ) { toEnd(); return next(); } - - abstract void release ( ); - - abstract int kind ( ); - - abstract QName getName ( ); - abstract String getXmlnsPrefix ( ); - abstract String getXmlnsUri ( ); - - abstract boolean isXmlns ( ); - - abstract boolean hasChildren ( ); - abstract boolean hasText ( ); - abstract boolean isTextCData ( ); - - abstract boolean toFirstAttr ( ); - abstract boolean toNextAttr ( ); - abstract String getAttrValue ( ); - - abstract boolean next ( ); - abstract void toEnd ( ); - - abstract void push ( ); - abstract void pop ( ); - - abstract Object getChars ( ); - abstract List getAncestorNamespaces ( ); - abstract XmlDocumentProperties getDocProps ( ); - - int _offSrc; - int _cchSrc; - } - - // TODO - saving a fragment need to take namesapces from root and - // reflect them on the document element - - private static final class DocSaveCur extends SaveCur - { - DocSaveCur ( Cur c ) - { - assert c.isRoot(); - _cur = c.weakCur( this ); - } - - void release ( ) - { - _cur.release(); - _cur = null; - } - - int kind ( ) { return _cur.kind(); } - - QName getName ( ) { return _cur.getName(); } - String getXmlnsPrefix ( ) { return _cur.getXmlnsPrefix(); } - String getXmlnsUri ( ) { return _cur.getXmlnsUri(); } - - boolean isXmlns ( ) { return _cur.isXmlns(); } - - boolean hasChildren ( ) { return _cur.hasChildren(); } - boolean hasText ( ) { return _cur.hasText(); } - boolean isTextCData ( ) { return _cur.isTextCData(); } - - boolean toFirstAttr ( ) { return _cur.toFirstAttr(); } - boolean toNextAttr ( ) { return _cur.toNextAttr(); } - String getAttrValue ( ) { assert _cur.isAttr(); return _cur.getValueAsString(); } - - void toEnd ( ) { _cur.toEnd(); } - boolean next ( ) { return _cur.next(); } - - void push ( ) { _cur.push(); } - void pop ( ) { _cur.pop(); } - - List getAncestorNamespaces ( ) { return null; } - - Object getChars ( ) - { - Object o = _cur.getChars( -1 ); - - _offSrc = _cur._offSrc; - _cchSrc = _cur._cchSrc; - - return o; - } - - XmlDocumentProperties getDocProps ( ) { return Locale.getDocProps(_cur, false); } - - private Cur _cur; - } - - private static abstract class FilterSaveCur extends SaveCur - { - FilterSaveCur ( SaveCur c ) - { - assert c.isRoot(); - _cur = c; - } - - // Can filter anything by root and attributes and text - protected abstract boolean filter ( ); - - void release ( ) - { - _cur.release(); - _cur = null; - } - - int kind ( ) { return _cur.kind(); } - - QName getName ( ) { return _cur.getName(); } - String getXmlnsPrefix ( ) { return _cur.getXmlnsPrefix(); } - String getXmlnsUri ( ) { return _cur.getXmlnsUri(); } - - boolean isXmlns ( ) { return _cur.isXmlns(); } - - boolean hasChildren ( ) { return _cur.hasChildren(); } - boolean hasText ( ) { return _cur.hasText(); } - boolean isTextCData ( ) { return _cur.isTextCData(); } - - boolean toFirstAttr ( ) { return _cur.toFirstAttr(); } - boolean toNextAttr ( ) { return _cur.toNextAttr(); } - String getAttrValue ( ) { return _cur.getAttrValue(); } - - void toEnd ( ) { _cur.toEnd(); } - - boolean next ( ) - { - if (!_cur.next()) - return false; - - if (!filter()) - return true; - - assert !isRoot() && !isText() && !isAttr(); - - toEnd(); - - return next(); - } - - void push ( ) { _cur.push(); } - void pop ( ) { _cur.pop(); } - - List getAncestorNamespaces ( ) { return _cur.getAncestorNamespaces(); } - - Object getChars ( ) - { - Object o = _cur.getChars(); - - _offSrc = _cur._offSrc; - _cchSrc = _cur._cchSrc; - - return o; - } - - XmlDocumentProperties getDocProps ( ) { return _cur.getDocProps(); } - - private SaveCur _cur; - } - - private static final class FilterPiSaveCur extends FilterSaveCur - { - FilterPiSaveCur ( SaveCur c, String target ) - { - super( c ); - - _piTarget = target; - } - - protected boolean filter ( ) - { - return kind() == PROCINST && getName().getLocalPart().equals( _piTarget ); - } - - private String _piTarget; - } - - private static final class FragSaveCur extends SaveCur - { - FragSaveCur ( Cur start, Cur end, QName synthElem ) - { - _saveAttr = start.isAttr() && start.isSamePos( end ); - - _cur = start.weakCur( this ); - _end = end.weakCur( this ); - - _elem = synthElem; - - _state = ROOT_START; - - _stateStack = new int [ 8 ]; - - start.push(); - computeAncestorNamespaces( start ); - start.pop(); - } - - List getAncestorNamespaces ( ) - { - return _ancestorNamespaces; - } - - private void computeAncestorNamespaces ( Cur c ) - { - _ancestorNamespaces = new ArrayList(); - - while ( c.toParentRaw() ) - { - if (c.toFirstAttr()) - { - do - { - if (c.isXmlns()) - { - String prefix = c.getXmlnsPrefix(); - String uri = c.getXmlnsUri(); - - // Don't let xmlns:foo="" get used - - if (uri.length() > 0 || prefix.length() == 0) - { - _ancestorNamespaces.add( c.getXmlnsPrefix() ); - _ancestorNamespaces.add( c.getXmlnsUri() ); - } - } - } - while ( c.toNextAttr() ); - - c.toParent(); - } - } - } - - // - // - // - - void release ( ) - { - _cur.release(); - _cur = null; - - _end.release(); - _end = null; - } - - int kind ( ) - { - switch ( _state ) - { - case ROOT_START : return ROOT; - case ELEM_START : return ELEM; - case ELEM_END : return -ELEM; - case ROOT_END : return -ROOT; - } - - assert _state == CUR; - - return _cur.kind(); - } - - QName getName ( ) - { - switch ( _state ) - { - case ROOT_START : - case ROOT_END : return null; - case ELEM_START : - case ELEM_END : return _elem; - } - - assert _state == CUR; - - return _cur.getName(); - } - - String getXmlnsPrefix ( ) - { - assert _state == CUR && _cur.isAttr(); - return _cur.getXmlnsPrefix(); - } - - String getXmlnsUri ( ) - { - assert _state == CUR && _cur.isAttr(); - return _cur.getXmlnsUri(); - } - - boolean isXmlns ( ) - { - assert _state == CUR && _cur.isAttr(); - return _cur.isXmlns(); - } - - boolean hasChildren ( ) - { - boolean hasChildren = false; - - if (isContainer()) - { // is there a faster way to do this? - push(); - next(); - - if (!isText() && !isFinish()) - hasChildren = true; - - pop(); - } - - return hasChildren; - } - - boolean hasText ( ) - { - boolean hasText = false; - - if (isContainer()) - { - push(); - next(); - - if (isText()) - hasText = true; - - pop(); - } - - return hasText; - } - - boolean isTextCData ( ) - { - return _cur.isTextCData(); - } - - Object getChars ( ) - { - assert _state == CUR && _cur.isText(); - - Object src = _cur.getChars( -1 ); - - _offSrc = _cur._offSrc; - _cchSrc = _cur._cchSrc; - - return src; - } - - boolean next ( ) - { - switch ( _state ) - { - case ROOT_START : - { - _state = _elem == null ? CUR : ELEM_START; - break; - } - - case ELEM_START : - { - if (_saveAttr) - _state = ELEM_END; - else - { - if (_cur.isAttr()) - { - _cur.toParent(); - _cur.next(); - } - - if (_cur.isSamePos( _end )) - _state = ELEM_END; - else - _state = CUR; - } - - break; - } - - case CUR : - { - assert !_cur.isAttr(); - - _cur.next(); - - if (_cur.isSamePos( _end )) - _state = _elem == null ? ROOT_END : ELEM_END; - - break; - } - - case ELEM_END : - { - _state = ROOT_END; - break; - } - case ROOT_END : - return false; - } - - return true; - } - - void toEnd ( ) - { - switch ( _state ) - { - case ROOT_START : _state = ROOT_END; return; - case ELEM_START : _state = ELEM_END; return; - case ROOT_END : - case ELEM_END : return; - } - - assert _state == CUR && !_cur.isAttr() && !_cur.isText(); - - _cur.toEnd(); - } - - boolean toFirstAttr ( ) - { - switch ( _state ) - { - case ROOT_END : - case ELEM_END : - case ROOT_START : return false; - case CUR : return _cur.toFirstAttr(); - } - - assert _state == ELEM_START; - - if (!_cur.isAttr()) - return false; - - _state = CUR; - - return true; - } - - boolean toNextAttr ( ) - { - assert _state == CUR; - return !_saveAttr && _cur.toNextAttr(); - } - - String getAttrValue ( ) - { - assert _state == CUR && _cur.isAttr(); - return _cur.getValueAsString(); - } - - void push ( ) - { - if (_stateStackSize == _stateStack.length) - { - int[] newStateStack = new int [ _stateStackSize * 2 ]; - System.arraycopy( _stateStack, 0, newStateStack, 0, _stateStackSize ); - _stateStack = newStateStack; - } - - _stateStack [ _stateStackSize++ ] = _state; - _cur.push(); - } - - void pop () - { - _cur.pop(); - _state = _stateStack [ --_stateStackSize ]; - } - - XmlDocumentProperties getDocProps ( ) { return Locale.getDocProps(_cur, false); } - - // - // - // - - private Cur _cur; - private Cur _end; - - private ArrayList _ancestorNamespaces; - - private QName _elem; - - private boolean _saveAttr; - - private static final int ROOT_START = 1; - private static final int ELEM_START = 2; - private static final int ROOT_END = 3; - private static final int ELEM_END = 4; - private static final int CUR = 5; - - private int _state; - - private int[] _stateStack; - private int _stateStackSize; - } - - private static final class PrettySaveCur extends SaveCur - { - PrettySaveCur ( SaveCur c, XmlOptions options ) - { - _sb = new StringBuffer(); - _stack = new ArrayList(); - - _cur = c; - - assert options != null; - - _prettyIndent = 2; - - if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT_INDENT )) - { - _prettyIndent = - ((Integer) options.get( XmlOptions.SAVE_PRETTY_PRINT_INDENT )).intValue(); - } - - if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT_OFFSET )) - { - _prettyOffset = - ((Integer) options.get( XmlOptions.SAVE_PRETTY_PRINT_OFFSET )).intValue(); - } - - if (options.hasOption( XmlOptions.LOAD_SAVE_CDATA_BOOKMARKS )) - { - _useCDataBookmarks = true; - } - } - - List getAncestorNamespaces ( ) { return _cur.getAncestorNamespaces(); } - - void release ( ) { _cur.release(); } - - int kind ( ) { return _txt == null ? _cur.kind() : TEXT; } - - QName getName ( ) { assert _txt == null; return _cur.getName(); } - String getXmlnsPrefix ( ) { assert _txt == null; return _cur.getXmlnsPrefix(); } - String getXmlnsUri ( ) { assert _txt == null; return _cur.getXmlnsUri(); } - - boolean isXmlns ( ) { return _txt == null ? _cur.isXmlns() : false; } - - boolean hasChildren ( ) { return _txt == null ? _cur.hasChildren() : false; } - boolean hasText ( ) { return _txt == null ? _cur.hasText() : false; } - - // _cur.isTextCData() is expensive do it only if useCDataBookmarks option is enabled - boolean isTextCData ( ) { return _txt == null ? (_useCDataBookmarks && _cur.isTextCData()) - : _isTextCData; } - - boolean toFirstAttr ( ) { assert _txt == null; return _cur.toFirstAttr(); } - boolean toNextAttr ( ) { assert _txt == null; return _cur.toNextAttr(); } - String getAttrValue ( ) { assert _txt == null; return _cur.getAttrValue(); } - - void toEnd ( ) - { - assert _txt == null; - _cur.toEnd(); - - if (_cur.kind() == -ELEM) - _depth--; - } - - boolean next ( ) - { - int k; - - if (_txt != null) - { - assert _txt.length() > 0; - assert !_cur.isText(); - _txt = null; - _isTextCData = false; - k = _cur.kind(); - } - else - { - int prevKind = k = _cur.kind(); - - if (!_cur.next()) - return false; - - _sb.delete( 0, _sb.length() ); - - assert _txt == null; - - // place any text encountered in the buffer - if (_cur.isText()) - { - // _cur.isTextCData() is expensive do it only if useCDataBookmarks option is enabled - _isTextCData = _useCDataBookmarks && _cur.isTextCData(); - CharUtil.getString( _sb, _cur.getChars(), _cur._offSrc, _cur._cchSrc ); - _cur.next(); - trim( _sb ); - } - - k = _cur.kind(); - - // Check for non leaf, _prettyIndent < 0 means that the save is all on one line - - if (_prettyIndent >= 0 && - prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM)) -// if (prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM)) - { - if (_sb.length() > 0) - { - _sb.insert( 0, _newLine ); - spaces( _sb, _newLine.length(), _prettyOffset + _prettyIndent * _depth ); - } - - if (k != -ROOT) - { - if (prevKind != ROOT) - _sb.append( _newLine ); - - int d = k < 0 ? _depth - 1 : _depth; - spaces( _sb, _sb.length(), _prettyOffset + _prettyIndent * d ); - } - } - - if (_sb.length() > 0) - { - _txt = _sb.toString(); - k = TEXT; - } - } - - if (k == ELEM) - _depth++; - else if (k == -ELEM) - _depth--; - - return true; - } - - void push ( ) - { - _cur.push(); - _stack.add( _txt ); - _stack.add( new Integer( _depth ) ); - _isTextCData = false; - } - - void pop ( ) - { - _cur.pop(); - _depth = ((Integer) _stack.remove( _stack.size() - 1 )).intValue(); - _txt = (String) _stack.remove( _stack.size() - 1 ); - _isTextCData = false; - } - - Object getChars ( ) - { - if (_txt != null) - { - _offSrc = 0; - _cchSrc = _txt.length(); - return _txt; - } - - Object o = _cur.getChars(); - - _offSrc = _cur._offSrc; - _cchSrc = _cur._cchSrc; - - return o; - } - - XmlDocumentProperties getDocProps ( ) { return _cur.getDocProps(); } - - static void spaces ( StringBuffer sb, int offset, int count ) - { - while ( count-- > 0 ) - sb.insert( offset, ' ' ); - } - - static void trim ( StringBuffer sb ) - { - int i; - - for ( i = 0 ; i < sb.length() ; i++ ) - if (!CharUtil.isWhiteSpace( sb.charAt( i ) )) - break; - - sb.delete( 0, i ); - - for ( i = sb.length() ; i > 0 ; i-- ) - if (!CharUtil.isWhiteSpace( sb.charAt( i - 1 ) )) - break; - - sb.delete( i, sb.length() ); - } - - private SaveCur _cur; - - private int _prettyIndent; - private int _prettyOffset; - - private String _txt; - private StringBuffer _sb; - - private int _depth; - - private ArrayList _stack; - private boolean _isTextCData = false; - private boolean _useCDataBookmarks = false; - } - - - // - // - // - - private final Locale _locale; - private final long _version; - - private SaveCur _cur; - - private List _ancestorNamespaces; - private Map _suggestedPrefixes; - protected XmlOptionCharEscapeMap _replaceChar; - private boolean _useDefaultNamespace; - private Map _preComputedNamespaces; - private boolean _saveNamespacesFirst; - - private ArrayList _attrNames; - private ArrayList _attrValues; - - private ArrayList _namespaceStack; - private int _currentMapping; - private HashMap _uriMap; - private HashMap _prefixMap; - private String _initialDefaultUri; - - static final String _newLine = - SystemProperties.getProperty( "line.separator" ) == null - ? "\n" - : SystemProperties.getProperty( "line.separator" ); -} diff --git a/src/store/org/apache/xmlbeans/impl/store/Xobj.java b/src/store/org/apache/xmlbeans/impl/store/Xobj.java deleted file mode 100644 index 6cbfa84..0000000 --- a/src/store/org/apache/xmlbeans/impl/store/Xobj.java +++ /dev/null @@ -1,3251 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.store; - -import org.apache.xmlbeans.CDataBookmark; -import org.w3c.dom.Attr; -import org.w3c.dom.CDATASection; -import org.w3c.dom.CharacterData; -import org.w3c.dom.Comment; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.DocumentType; -import org.w3c.dom.DOMException; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Element; -import org.w3c.dom.EntityReference; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.DOMImplementation; - -// DOM Level 3 -import org.w3c.dom.UserDataHandler; -import org.w3c.dom.DOMConfiguration; -import org.w3c.dom.TypeInfo; - - -import javax.xml.transform.Source; - -import java.io.PrintStream; - -import java.util.Iterator; -import java.util.Map; -import java.util.ArrayList; -import java.util.List; -import java.util.Vector; - -import org.apache.xmlbeans.impl.soap.Detail; -import org.apache.xmlbeans.impl.soap.DetailEntry; -import org.apache.xmlbeans.impl.soap.MimeHeaders; -import org.apache.xmlbeans.impl.soap.Name; -import org.apache.xmlbeans.impl.soap.SOAPBody; -import org.apache.xmlbeans.impl.soap.SOAPBodyElement; -import org.apache.xmlbeans.impl.soap.SOAPElement; -import org.apache.xmlbeans.impl.soap.SOAPEnvelope; -import org.apache.xmlbeans.impl.soap.SOAPException; -import org.apache.xmlbeans.impl.soap.SOAPFactory; -import org.apache.xmlbeans.impl.soap.SOAPFault; -import org.apache.xmlbeans.impl.soap.SOAPFaultElement; -import org.apache.xmlbeans.impl.soap.SOAPHeader; -import org.apache.xmlbeans.impl.soap.SOAPHeaderElement; -import org.apache.xmlbeans.impl.soap.SOAPPart; -import org.apache.xmlbeans.impl.store.Locale.LoadContext; - -import org.apache.xmlbeans.impl.store.DomImpl.Dom; -import org.apache.xmlbeans.impl.store.DomImpl.CharNode; -import org.apache.xmlbeans.impl.store.DomImpl.TextNode; -import org.apache.xmlbeans.impl.store.DomImpl.CdataNode; -import org.apache.xmlbeans.impl.store.DomImpl.SaajTextNode; -import org.apache.xmlbeans.impl.store.DomImpl.SaajCdataNode; - -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.XmlMark; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.QNameSet; - -import org.apache.xmlbeans.impl.values.TypeStore; -import org.apache.xmlbeans.impl.values.TypeStoreUser; -import org.apache.xmlbeans.impl.values.TypeStoreVisitor; -import org.apache.xmlbeans.impl.values.TypeStoreUserFactory; - -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.impl.common.ValidatorListener; -import org.apache.xmlbeans.impl.common.XmlLocale; -import org.apache.xmlbeans.impl.common.QNameHelper; - -abstract class Xobj implements TypeStore -{ - static final int TEXT = Cur.TEXT; - static final int ROOT = Cur.ROOT; - static final int ELEM = Cur.ELEM; - static final int ATTR = Cur.ATTR; - static final int COMMENT = Cur.COMMENT; - static final int PROCINST = Cur.PROCINST; - - static final int END_POS = Cur.END_POS; - static final int NO_POS = Cur.NO_POS; - - Xobj ( Locale l, int kind, int domType ) - { - assert kind == ROOT || kind == ELEM || kind == ATTR || kind == COMMENT || kind == PROCINST; - - _locale = l; - _bits = (domType << 4) + kind; - } - - final boolean entered ( ) { return _locale.entered(); } - - final int kind ( ) { return _bits & 0xF; } - final int domType ( ) { return (_bits & 0xF0) >> 4; } - - final boolean isRoot ( ) { return kind() == ROOT; } - final boolean isAttr ( ) { return kind() == ATTR; } - final boolean isElem ( ) { return kind() == ELEM; } - final boolean isProcinst ( ) { return kind() == PROCINST; } - final boolean isComment ( ) { return kind() == COMMENT; } - final boolean isContainer ( ) { return Cur.kindIsContainer( kind() ); } - final boolean isUserNode ( ) { int k = kind(); return k == ELEM || k == ROOT || (k == ATTR && !isXmlns()); } - - final boolean isNormalAttr ( ) { return isAttr() && !Locale.isXmlns( _name ); } - final boolean isXmlns ( ) { return isAttr() && Locale.isXmlns( _name ); } - - final int cchValue ( ) { return _cchValue; } - final int cchAfter ( ) { return _cchAfter; } - - final int posAfter ( ) { return 2 + _cchValue; } - final int posMax ( ) { return 2 + _cchValue + _cchAfter; } - - final String getXmlnsPrefix ( ) { return Locale.xmlnsPrefix( _name ); } - final String getXmlnsUri ( ) { return getValueAsString(); } - - final boolean hasTextEnsureOccupancy ( ) - { - ensureOccupancy(); - return hasTextNoEnsureOccupancy(); - } - - final boolean hasTextNoEnsureOccupancy ( ) - { - if (_cchValue > 0) - return true; - - Xobj lastAttr = lastAttr(); - - return lastAttr != null && lastAttr._cchAfter > 0; - } - - final boolean hasAttrs ( ) { return _firstChild != null && _firstChild.isAttr(); } - final boolean hasChildren ( ) { return _lastChild != null && !_lastChild .isAttr(); } - - - /** - * this method is to speed up DomImpl - * when underlying obj is an Xobj - * - * @return 0 or 1 dom children; val 2 indicates that DomImpl needs to - * compute the result itself - */ - final protected int getDomZeroOneChildren() - { - if (_firstChild == null && - _srcValue == null && - _charNodesValue == null) - return 0; - - if (_lastChild != null && - _lastChild.isAttr() && - _lastChild._charNodesAfter == null && - _lastChild._srcAfter == null && - _srcValue == null && - _charNodesValue == null - ) - return 0; - - if (_firstChild == _lastChild && - _firstChild != null && - !_firstChild.isAttr() && - _srcValue == null && - _charNodesValue == null && - _firstChild._srcAfter == null - ) - return 1; - - if (_firstChild == null && - _srcValue != null && - ( _charNodesValue == null || - (_charNodesValue._next == null && - _charNodesValue._cch == _cchValue)) - ) - return 1; - //single elem after an attr - Xobj lastAttr = lastAttr(); - Xobj node = lastAttr == null ? - null : lastAttr._nextSibling; - if (lastAttr != null && - lastAttr._srcAfter == null && - node != null && - node._srcAfter == null && - node._nextSibling == null) - return 1; - - return 2; - } - - /** - * can one use the _firstChild pointer to retrieve - * the first DOM child - * - * @return - */ - final protected boolean isFirstChildPtrDomUsable() - { - if (_firstChild == null && - _srcValue == null && - _charNodesValue == null) - return true; - - if (_firstChild != null && - !_firstChild.isAttr() && - _srcValue == null && - _charNodesValue == null) - { - assert (_firstChild instanceof Xobj.NodeXobj): - "wrong node type"; - return true; - } - return false; - } - - /** - * can one use the _nextSibling pointer to retrieve - * the next DOM sibling - * @return - */ - final protected boolean isNextSiblingPtrDomUsable() - { - if (_charNodesAfter == null && - _srcAfter == null) - { - assert (_nextSibling == null || - _nextSibling instanceof Xobj.NodeXobj): - "wrong node type"; - return true; - } - return false; - } - /** - * can one use the _charNodesValue pointer to retrieve - * the next DOM sibling - * - * @return - */ - final protected boolean isExistingCharNodesValueUsable() - { - if (_srcValue == null) return false; - if (_charNodesValue != null && _charNodesValue._next == null - && _charNodesValue._cch == _cchValue) - return true; - return false; - } - final protected boolean isCharNodesValueUsable() - { - return isExistingCharNodesValueUsable() || - (_charNodesValue = - Cur.updateCharNodes(_locale, this, - _charNodesValue, _cchValue)) != null; - } - - /** - * can one use the _charNodesAfter pointer to retrieve - * the next DOM sibling - * - * @return - */ - final protected boolean isCharNodesAfterUsable() - { - if (_srcAfter == null) return false; - if (_charNodesAfter != null && _charNodesAfter._next == null - && _charNodesAfter._cch == this._cchAfter) - return true; - return (_charNodesAfter = - Cur.updateCharNodes(_locale, this, - _charNodesAfter, _cchAfter)) != null; - } - - - final Xobj lastAttr ( ) - { - if (_firstChild == null || !_firstChild.isAttr()) - return null; - - Xobj lastAttr = _firstChild; - - while ( lastAttr._nextSibling != null && lastAttr._nextSibling.isAttr() ) - lastAttr = lastAttr._nextSibling; - - return lastAttr; - } - - abstract Dom getDom ( ); - - abstract Xobj newNode ( Locale l ); - - final int cchLeft ( int p ) - { - if (isRoot() && p == 0) - return 0; - - Xobj x = getDenormal( p ); - - p = posTemp(); - int pa = x.posAfter(); - - return p - (p < pa ? 1 : pa); - } - - final int cchRight ( int p ) - { - assert p < posMax(); - - if (p <= 0) - return 0; - - int pa = posAfter(); - - return p < pa ? pa - p - 1 : posMax() - p; - } - - // - // Dom interface - // - - public final Locale locale ( ) { return _locale; } - public final int nodeType ( ) { return domType(); } - public final QName getQName ( ) { return _name; } - - public final Cur tempCur ( ) { Cur c = _locale.tempCur(); c.moveTo( this ); return c; } - - public void dump ( PrintStream o, Object ref ) { Cur.dump( o, (Xobj) this, ref ); } - public void dump ( PrintStream o ) { Cur.dump( o, this, this ); } - public void dump ( ) { dump( System.out ); } - - // - // - // - - final Cur getEmbedded ( ) - { - _locale.embedCurs(); - - return _embedded; - } - - // Incoming p must be at text (implicitly denormalized) - - final boolean inChars ( int p, Xobj xIn, int pIn, int cch, boolean includeEnd ) - { - assert p > 0 && p < posMax() && p != posAfter() - 1 && cch > 0; - assert xIn.isNormal( pIn ); - - // No need to denormalize "in" if the right hand side is excluded. Denormalizing deals - // with the case where p is END_POS. - - int offset; - - if (includeEnd) - { - // Can't denormalize at the beginning of the document - - if (xIn.isRoot() && pIn == 0) - return false; - - xIn = xIn.getDenormal( pIn ); - pIn = xIn.posTemp(); - - offset = 1; - } - else - offset = 0; - - return xIn == this && pIn >= p && pIn < p + (cch < 0 ? cchRight( p ) : cch) + offset; - } - - // Is x/p just after the end of this - - final boolean isJustAfterEnd ( Xobj x, int p ) - { - assert x.isNormal( p ); - - // Get denormalize at the beginning of the doc - - if (x.isRoot() && p == 0) - return false; - - return - x == this - ? p == posAfter() - : x.getDenormal( p ) == this && x.posTemp() == posAfter(); - } - - final boolean isInSameTree ( Xobj x ) - { - if (_locale != x._locale) - return false; - - for ( Xobj y = this ; ; y = y._parent ) - { - if (y == x) - return true; - - if (y._parent == null) - { - for ( ; ; x = x._parent ) - { - if (x == this) - return true; - - if (x._parent == null) - return x == y; - } - } - } - } - - final boolean contains ( Cur c ) - { - assert c.isNormal(); - - return contains( c._xobj, c._pos ); - } - - final boolean contains ( Xobj x, int p ) - { - assert x.isNormal( p ); - - if (this == x) - return p == END_POS || (p > 0 && p < posAfter()); - - if (_firstChild == null) - return false; - - for ( ; x != null ; x = x._parent ) - if (x == this) - return true; - - return false; - } - - final Bookmark setBookmark ( int p, Object key, Object value ) - { - assert isNormal( p ); - - for ( Bookmark b = _bookmarks ; b != null ; b = b._next ) - { - if (p == b._pos && key == b._key) - { - if (value == null) - { - _bookmarks = b.listRemove( _bookmarks ); - return null; - } - - b._value = value; - - return b; - } - } - - if (value == null) - return null; - - Bookmark b = new Bookmark(); - - b._xobj = this; - b._pos = p; - b._key = key; - b._value = value; - - _bookmarks = b.listInsert( _bookmarks ); - - return b; - } - - final boolean hasBookmark(Object key, int pos) - { - for ( Bookmark b = _bookmarks ; b != null ; b = b._next ) - if ( b._pos == pos && key == b._key ) - { - //System.out.println("hasCDataBookmark pos: " + pos + " xobj: " + getQName() + " b._pos: " + _bookmarks._pos); - return true; - } - - return false; - } - - final Xobj findXmlnsForPrefix ( String prefix ) - { - assert isContainer() && prefix != null; - - for ( Xobj c = this ; c != null ; c = c._parent ) - for ( Xobj a = c.firstAttr() ; a != null ; a = a.nextAttr() ) - if (a.isXmlns() && a.getXmlnsPrefix().equals( prefix )) - return a; - - return null; - } - - final boolean removeAttr ( QName name ) - { - assert isContainer(); - - Xobj a = getAttr( name ); - - if (a == null) - return false; - - Cur c = a.tempCur(); - - for ( ; ; ) - { - c.moveNode( null ); - - a = getAttr( name ); - - if (a == null) - break; - - c.moveTo( a ); - } - - c.release(); - - return true; - } - - final Xobj setAttr ( QName name, String value ) - { - assert isContainer(); - - Cur c = tempCur(); - - if (c.toAttr( name )) - c.removeFollowingAttrs(); - else - { - c.next(); - c.createAttr( name ); - } - - c.setValue( value ); - - Xobj a = c._xobj; - - c.release(); - - return a; - } - - final void setName ( QName newName ) - { - assert isAttr() || isElem() || isProcinst(); - assert newName != null; - - if (!_name.equals( newName ) || !_name.getPrefix().equals( newName.getPrefix() )) - { -// TODO - this is not a structural change .... perhaps should not issue a change here? - _locale.notifyChange(); - - QName oldName = _name; - - _name = newName; - if (this instanceof Xobj.NamedNodeXobj) - { - NamedNodeXobj me = (NamedNodeXobj)this; - me._canHavePrefixUri = true; - } - - if (!isProcinst()) - { - Xobj disconnectFromHere = this; - - if (isAttr() && _parent != null) - { - if (oldName.equals( Locale._xsiType ) || newName.equals( Locale._xsiType )) - disconnectFromHere = _parent; - - if (oldName.equals( Locale._xsiNil ) || newName.equals( Locale._xsiNil )) - _parent.invalidateNil(); - } - - disconnectFromHere.disconnectNonRootUsers(); - } - - _locale._versionAll++; - _locale._versionSansText++; - } - } - - final Xobj ensureParent ( ) - { - assert _parent != null || (!isRoot() && cchAfter() == 0); - return _parent == null ? new DocumentFragXobj( _locale ).appendXobj( this ) : _parent; - } - - final Xobj firstAttr ( ) - { - return _firstChild == null || !_firstChild.isAttr() ? null : _firstChild; - } - - final Xobj nextAttr ( ) - { - if (_firstChild != null && _firstChild.isAttr()) - return _firstChild; - - if (_nextSibling != null && _nextSibling.isAttr()) - return _nextSibling; - - return null; - } - - final boolean isValid ( ) - { - if (isVacant() && (_cchValue != 0 || _user == null)) - return false; - - return true; - } - - final int posTemp ( ) - { - return _locale._posTemp; - } - - final Xobj getNormal ( int p ) - { - assert p == END_POS || (p >= 0 && p <= posMax()); - - Xobj x = this; - - if (p == x.posMax()) - { - if (x._nextSibling != null) - { - x = x._nextSibling; - p = 0; - } - else - { - x = x.ensureParent(); - p = END_POS; - } - } - else if (p == x.posAfter() - 1) - p = END_POS; - - _locale._posTemp = p; - - return x; - } - - // Can't denormalize a position at the very beginning of the document. No where to go to the - // left! - - final Xobj getDenormal ( int p ) - { - assert END_POS == -1; - assert !isRoot() || p == END_POS || p > 0; - - Xobj x = this; - - if (p == 0) - { - if (x._prevSibling == null) - { - x = x.ensureParent(); - p = x.posAfter() - 1; - } - else - { - x = x._prevSibling; - p = x.posMax(); - } - } - else if (p == END_POS) - { - if (x._lastChild == null) - p = x.posAfter() - 1; - else - { - x = x._lastChild; - p = x.posMax(); - } - } - - _locale._posTemp = p; - - return x; - } - - final boolean isNormal ( int p ) - { - if (!isValid()) - return false; - - if (p == END_POS || p == 0) - return true; - - if (p < 0 || p >= posMax()) - return false; - - if (p >= posAfter()) - { - if (isRoot()) - return false; - - if (_nextSibling != null && _nextSibling.isAttr()) - return false; - - if (_parent == null || !_parent.isContainer()) - return false; - } - - if (p == posAfter() - 1) - return false; - - return true; - } - - final Xobj walk ( Xobj root, boolean walkChildren ) - { - if (_firstChild != null && walkChildren) - return _firstChild; - - for ( Xobj x = this ; x != root ; x = x._parent ) - if (x._nextSibling != null) - return x._nextSibling; - - return null; - } - - final Xobj removeXobj ( ) - { - if (_parent != null) - { - if (_parent._firstChild == this) - _parent._firstChild = _nextSibling; - - if (_parent._lastChild == this) - _parent._lastChild = _prevSibling; - - if (_prevSibling != null) - _prevSibling._nextSibling = _nextSibling; - - if (_nextSibling != null) - _nextSibling._prevSibling = _prevSibling; - - _parent = null; - _prevSibling = null; - _nextSibling = null; - } - - return this; - } - - final Xobj insertXobj ( Xobj s ) - { - assert _locale == s._locale; - assert !s.isRoot() && !isRoot(); - assert s._parent == null; - assert s._prevSibling == null; - assert s._nextSibling == null; - - ensureParent(); - - s._parent = _parent; - s._prevSibling = _prevSibling; - s._nextSibling = this; - - if (_prevSibling != null) - _prevSibling._nextSibling = s; - else - _parent._firstChild = s; - - _prevSibling = s; - - return this; - } - - final Xobj appendXobj ( Xobj c ) - { - assert _locale == c._locale; - assert !c.isRoot(); - assert c._parent == null; - assert c._prevSibling == null; - assert c._nextSibling == null; - assert _lastChild == null || _firstChild != null; - - c._parent = this; - c._prevSibling = _lastChild; - - if (_lastChild == null) - _firstChild = c; - else - _lastChild._nextSibling = c; - - _lastChild = c; - - return this; - } - - final void removeXobjs ( Xobj first, Xobj last ) - { - assert last._locale == first._locale; - assert first._parent == this; - assert last._parent == this; - - if (_firstChild == first) - _firstChild = last._nextSibling; - - if (_lastChild == last) - _lastChild = first._prevSibling; - - if (first._prevSibling != null) - first._prevSibling._nextSibling = last._nextSibling; - - if (last._nextSibling != null) - last._nextSibling._prevSibling = first._prevSibling; - - // Leave the children linked together - - first._prevSibling = null; - last._nextSibling = null; - - for ( ; first != null ; first = first._nextSibling ) - first._parent = null; - } - - final void insertXobjs ( Xobj first, Xobj last ) - { - assert _locale == first._locale; - assert last._locale == first._locale; - assert first._parent == null && last._parent == null; - assert first._prevSibling == null; - assert last._nextSibling == null; - - first._prevSibling = _prevSibling; - last._nextSibling = this; - - if (_prevSibling != null) - _prevSibling._nextSibling = first; - else - _parent._firstChild = first; - - _prevSibling = last; - - for ( ; first != this ; first = first._nextSibling ) - first._parent = _parent; - } - - final void appendXobjs ( Xobj first, Xobj last ) - { - assert _locale == first._locale; - assert last._locale == first._locale; - assert first._parent == null && last._parent == null; - assert first._prevSibling == null; - assert last._nextSibling == null; - assert !first.isRoot(); - - first._prevSibling = _lastChild; - - if (_lastChild == null) - _firstChild = first; - else - _lastChild._nextSibling = first; - - _lastChild = last; - - for ( ; first != null ; first = first._nextSibling ) - first._parent = this; - } - - static final void disbandXobjs ( Xobj first, Xobj last ) - { - assert last._locale == first._locale; - assert first._parent == null && last._parent == null; - assert first._prevSibling == null; - assert last._nextSibling == null; - assert !first.isRoot(); - - while ( first != null ) - { - Xobj next = first._nextSibling; - first._nextSibling = first._prevSibling = null; - first = next; - } - } - - // Potential attr is going to be moved/removed, invalidate parent if it is a special attr - - final void invalidateSpecialAttr ( Xobj newParent ) - { - if (isAttr()) - { - if (_name.equals( Locale._xsiType )) - { - if (_parent != null) - _parent.disconnectNonRootUsers(); - - if (newParent != null) - newParent.disconnectNonRootUsers(); - } - - if (_name.equals( Locale._xsiNil )) - { - if (_parent != null) - _parent.invalidateNil(); - - if (newParent != null) - newParent.invalidateNil(); - } - } - } - - // Move or remove chars. Incoming p is denormalized. Incoming xTo and pTo are denormalized. - // Option to move curs with text. Option to perform invalidations. - // - // Important note: this fcn must operate under the assumption that the tree may be in an - // invalid state. Most likely, there may be text on two different nodes which should belong - // on the same node. Assertion of cursor normalization usually detects this problem. Any of - // the fcns it calls must also deal with these invalid conditions. Try not to call so many - // fcns from here. - - final void removeCharsHelper ( - int p, int cchRemove, Xobj xTo, int pTo, boolean moveCurs, boolean invalidate ) - { - assert p > 0 && p < posMax() && p != posAfter() - 1; - assert cchRemove > 0; - assert cchRight( p ) >= cchRemove; - assert !moveCurs || xTo != null; - - // Here I check the span of text to be removed for cursors. If xTo/pTo is not specified, - // then the caller wants these cursors to collapse to be after the text being removed. If - // the caller specifies moveCurs, then the caller has arranged for the text being removed - // to have been copied to xTp/pTo and wants the cursors to be moved there as well. - // Note that I call nextChars here. I do this because trying to shift the cursor to the - // end of the text to be removed with a moveTo could cause the improper placement of the - // cursor just before an end tag, instead of placing it just before the first child. Also, - // I adjust all positions of curs after the text to be removed to account for the removal. - - for ( Cur c = getEmbedded() ; c != null ; ) - { - Cur next = c._next; - - // Here I test to see if the Cur c is in the range of chars to be removed. Normally - // I would call inChars, but it can't handle the invalidity of the tree, so I heve - // inlined the inChars logic here (includeEnd is false, makes it much simpler). - // Note that I also call moveToNoCheck because the destination may have afterText - // and no parent which will cause normaliztion checks in MoveTo to fail. I don't think - // that nextChars will be called under such circumstnaces. - - assert c._xobj == this; - - if (c._pos >= p && c._pos < p + cchRemove) - { - if (moveCurs) - c.moveToNoCheck( xTo, pTo + c._pos - p ); - else - c.nextChars( cchRemove - c._pos + p ); - } - - // If c is still on this Xobj and it's to the right of the chars to remove, adjust - // it to adapt to the removal of the cars. I don't have to worry about END_POS - // here, just curs in text. - - if (c._xobj == this && c._pos >= p + cchRemove) - c._pos -= cchRemove; - - c = next; - } - - // Here I move bookmarks in this text to the span of text at xTo/pTo. The text at this/p - // is going away, but a caller of this fcn who specifies xTo/pTo has copied the text to - // xTo/pTo. The caller has to make sure that if xTo/pTo is not specified, then there are - // no bookmarks in the span of text to be removed. - - for ( Bookmark b = _bookmarks ; b != null ; ) - { - Bookmark next = b._next; - - // Similarly, as above, I can't call inChars here - - assert b._xobj == this; - - if (b._pos >= p && b._pos < p + cchRemove) - { - assert xTo != null; - b.moveTo( xTo, pTo + b._pos - p ); - } - - if (b._xobj == this && b._pos >= p + cchRemove) - b._pos -= cchRemove; - - b = b._next; - } - - // Now, remove the actual chars - - int pa = posAfter(); - CharUtil cu = _locale.getCharUtil(); - - if (p < pa) - { - _srcValue = cu.removeChars( p - 1, cchRemove, _srcValue, _offValue, _cchValue ); - _offValue = cu._offSrc; - _cchValue = cu._cchSrc; - - if (invalidate) - { - invalidateUser(); - invalidateSpecialAttr( null ); - } - } - else - { - _srcAfter = cu.removeChars( p - pa, cchRemove, _srcAfter, _offAfter, _cchAfter ); - _offAfter = cu._offSrc; - _cchAfter = cu._cchSrc; - - if (invalidate && _parent != null) - _parent.invalidateUser(); - } - } - - // Insert chars into this xobj. Incoming p is denormalized. Update bookmarks and cursors. - // This fcn does not deal with occupation of the value, this needs to be handled by the - // caller. - - final void insertCharsHelper ( int p, Object src, int off, int cch, boolean invalidate ) - { - assert p > 0; - assert p >= posAfter() || isOccupied(); - - int pa = posAfter(); - - // Here I shuffle bookmarks and cursors affected by the insertion of the new text. Because - // getting the embedded cursors is non-trivial, I avoid getting them if I don't need to. - // Basically, I need to know if p is before any text in the node as a whole. If it is, - // then there may be cursors/marks I need to shift right. - - if (p - (p < pa ? 1 : 2) < _cchValue + _cchAfter) - { - for ( Cur c = getEmbedded() ; c != null ; c = c._next ) - if (c._pos >= p) - c._pos += cch; - - for ( Bookmark b = _bookmarks ; b != null ; b = b._next ) - if (b._pos >= p) - b._pos += cch; - } - - // Now, stuff the new characters in! Also invalidate the proper container and if the - // value of an attribute is changing, check for special attr invalidation. Note that - // I do not assume that inserting after text will have a parent. There are use cases - // from moveNodesContents which excersize this. - - CharUtil cu = _locale.getCharUtil(); - - if (p < pa) - { - _srcValue = cu.insertChars( p - 1, _srcValue, _offValue, _cchValue, src, off, cch ); - _offValue = cu._offSrc; - _cchValue = cu._cchSrc; - - if (invalidate) - { - invalidateUser(); - invalidateSpecialAttr( null ); - } - } - else - { - _srcAfter = cu.insertChars( p - pa, _srcAfter, _offAfter, _cchAfter, src, off, cch ); - _offAfter = cu._offSrc; - _cchAfter = cu._cchSrc; - - if (invalidate && _parent != null) - _parent.invalidateUser(); - } - } - - Xobj copyNode ( Locale toLocale ) - { - Xobj newParent = null; - Xobj copy = null; - - for ( Xobj x = this ; ; ) - { - x.ensureOccupancy(); - - Xobj newX = x.newNode( toLocale ); - - newX._srcValue = x._srcValue; - newX._offValue = x._offValue; - newX._cchValue = x._cchValue; - - newX._srcAfter = x._srcAfter; - newX._offAfter = x._offAfter; - newX._cchAfter = x._cchAfter; - - for ( Bookmark b = x._bookmarks; b != null ; b = b._next ) - { - if ( x.hasBookmark( CDataBookmark.CDATA_BOOKMARK.getKey(), b._pos) ) - newX.setBookmark(b._pos, CDataBookmark.CDATA_BOOKMARK.getKey(), CDataBookmark.CDATA_BOOKMARK); - } - // TODO - strange to have charNode stuff inside here ..... - // newX._charNodesValue = CharNode.copyNodes( x._charNodesValue, newX._srcValue ); - // newX._charNodesAfter = CharNode.copyNodes( x._charNodesAfter, newX._srcAfter ); - - if (newParent == null) - copy = newX; - else - newParent.appendXobj( newX ); - - // Walk to the next in-order xobj. Record the current (y) to compute newParent - - Xobj y = x; - - if ((x = x.walk( this, true )) == null) - break; - - if (y == x._parent) - newParent = newX; - else - for ( ; y._parent != x._parent ; y = y._parent ) - newParent = newParent._parent; - } - - copy._srcAfter = null; - copy._offAfter = 0; - copy._cchAfter = 0; - - return copy; - } - - // Rturns all the chars, even if there is text intermixed with children - - String getCharsAsString ( int p, int cch, int wsr ) - { - if (cchRight( p ) == 0) - return ""; - - Object src = getChars( p, cch ); - - if (wsr == Locale.WS_PRESERVE) - return CharUtil.getString( src, _locale._offSrc, _locale._cchSrc ); - - Locale.ScrubBuffer scrub = Locale.getScrubBuffer( wsr ); - - scrub.scrub( src, _locale._offSrc, _locale._cchSrc ); - - return scrub.getResultAsString(); - } - String getCharsAfterAsString ( int off, int cch ) - { - int offset = off + _cchValue + 2; - if (offset == posMax()) - offset = -1; - return getCharsAsString(offset, cch, - Locale.WS_PRESERVE); - } - String getCharsValueAsString ( int off, int cch ) - { - return getCharsAsString(off + 1, cch, - Locale.WS_PRESERVE); - } - String getValueAsString ( int wsr ) - { - if (!hasChildren()) - { - Object src = getFirstChars(); - - if (wsr == Locale.WS_PRESERVE) - { - String s = CharUtil.getString( src, _locale._offSrc, _locale._cchSrc ); - - // Cache string to be able to use it later again - - int cch = s.length(); - - if (cch > 0) - { - Xobj lastAttr = lastAttr(); - - assert (lastAttr == null ? _cchValue : lastAttr._cchAfter) == cch; - - if (lastAttr != null) - { - lastAttr._srcAfter = s; - lastAttr._offAfter = 0; - } - else - { - _srcValue = s; - _offValue = 0; - } - } - - return s; - } - - Locale.ScrubBuffer scrub = Locale.getScrubBuffer( wsr ); - - scrub.scrub( src, _locale._offSrc, _locale._cchSrc ); - - return scrub.getResultAsString(); - } - - Locale.ScrubBuffer scrub = Locale.getScrubBuffer( wsr ); - - Cur c = tempCur(); - - c.push(); - - for ( c.next() ; !c.isAtEndOfLastPush() ; ) - { - if (c.isText()) - scrub.scrub( c.getChars( -1 ), c._offSrc, c._cchSrc ); - - if (c.isComment() || c.isProcinst()) - c.skip(); - else - c.next(); - } - - String s = scrub.getResultAsString(); - - c.release(); - - return s; - } - - String getValueAsString ( ) - { - return getValueAsString( Locale.WS_PRESERVE ); - } - - String getString ( int p, int cch ) - { - int cchRight = cchRight( p ); - - if (cchRight == 0) - return ""; - - if (cch < 0 || cch > cchRight) - cch = cchRight; - - int pa = posAfter(); - - assert p > 0; - - String s; - - if (p >= pa) - { - s = CharUtil.getString( _srcAfter, _offAfter + p - pa, cch ); - - if (p == pa && cch == _cchAfter) - { - _srcAfter = s; - _offAfter = 0; - } - } - else - { - s = CharUtil.getString( _srcValue, _offValue + p - 1, cch ); - - if (p == 1 && cch == _cchValue) - { - _srcValue = s; - _offValue = 0; - } - } - - return s; - } - - // Returns just chars just after the begin tag ... does not get all the text if there are - // children - - Object getFirstChars ( ) - { - ensureOccupancy(); - - if (_cchValue > 0) - return getChars( 1, -1 ); - - Xobj lastAttr = lastAttr(); - - if (lastAttr == null || lastAttr._cchAfter <= 0) - { - _locale._offSrc = 0; - _locale._cchSrc = 0; - - return null; - } - - return lastAttr.getChars( lastAttr.posAfter(), -1 ); - } - - Object getChars ( int pos, int cch, Cur c ) - { - Object src = getChars( pos, cch ); - - c._offSrc = _locale._offSrc; - c._cchSrc = _locale._cchSrc; - - return src; - } - - // These return the remainder of the char triple that getChars starts - - Object getChars ( int pos, int cch ) - { - assert isNormal( pos ); - - int cchRight = cchRight( pos ); - - if (cch < 0 || cch > cchRight) - cch = cchRight; - - if (cch == 0) - { - _locale._offSrc = 0; - _locale._cchSrc = 0; - - return null; - } - - return getCharsHelper( pos, cch ); - } - - // Assumes that there are chars to return, does not assume normal x/p - - Object getCharsHelper ( int pos, int cch ) - { - assert cch > 0 && cchRight( pos ) >= cch; - - int pa = posAfter(); - - Object src; - - if (pos >= pa) - { - src = _srcAfter; - _locale._offSrc = _offAfter + pos - pa; - } - else - { - src = _srcValue; - _locale._offSrc = _offValue + pos - 1; - } - - _locale._cchSrc = cch; - - return src; - } - - // - // - // - - final void setBit ( int mask ) { _bits |= mask; } - final void clearBit ( int mask ) { _bits &= ~mask; } - - final boolean bitIsSet ( int mask ) { return (_bits & mask) != 0; } - final boolean bitIsClear ( int mask ) { return (_bits & mask) == 0; } - - static final int VACANT = 0x100; - static final int STABLE_USER = 0x200; - static final int INHIBIT_DISCONNECT = 0x400; - - final boolean isVacant ( ) { return bitIsSet ( VACANT ); } - final boolean isOccupied ( ) { return bitIsClear ( VACANT ); } - final boolean inhibitDisconnect ( ) { return bitIsSet ( INHIBIT_DISCONNECT ); } - - final boolean isStableUser ( ) { return bitIsSet( STABLE_USER ); } - - void invalidateNil ( ) - { - if (_user != null) - _user.invalidate_nilvalue(); - } - - void setStableType ( SchemaType type ) - { - setStableUser( ((TypeStoreUserFactory) type).createTypeStoreUser() ); - } - - void setStableUser ( TypeStoreUser user ) - { - disconnectNonRootUsers(); - disconnectUser(); - - assert _user == null; - - _user = user; - - _user.attach_store( this ); - - setBit( STABLE_USER ); - } - - void disconnectUser ( ) - { - if (_user != null && !inhibitDisconnect()) - { - ensureOccupancy(); - _user.disconnect_store(); - _user = null; - } - } - - // If a node does not have a user, then I don't need to walk its descendents. NOte that - // the doconnect happens in document order. This may be a problem ... not sure ... May want - // to disconnect in a bottom up manner. - - void disconnectNonRootUsers ( ) - { - Xobj next; - - for ( Xobj x = this ; x != null ; x = next ) - { - next = x.walk( this, x._user != null ); - - if (!x.isRoot()) - x.disconnectUser(); - } - } - - void disconnectChildrenUsers ( ) - { - Xobj next; - - for ( Xobj x = walk( this, _user == null ) ; x != null ; x = next ) - { - next = x.walk( this, x._user != null ); - - x.disconnectUser(); - } - } - - /** - * Given a prefix, returns the namespace corresponding to - * the prefix at this location, or null if there is no mapping - * for this prefix. - *

      - * prefix="" indicates the absence of a prefix. A return value - * of "" indicates the no-namespace, and should not be confused - * with a return value of null, which indicates an illegal - * state, where there is no mapping for the given prefix. - *

      - * If the the default namespace is not explicitly mapped in the xml, - * the xml spec says that it should be mapped to the no-namespace. - * When the 'defaultAlwaysMapped' parameter is true, the default namepsace - * will return the no-namespace even if it is not explicity - * mapped, otherwise the default namespace will return null. - *

      - * This function intercepts the built-in prefixes "xml" and - * "xmlns" and returns their well-known namespace URIs. - * - * @param prefix The prefix to look up. - * @param defaultAlwaysMapped If true, return the no-namespace for the default namespace if not set. - * @return The mapped namespace URI ("" if no-namespace), or null if no mapping. - */ - - final String namespaceForPrefix ( String prefix, boolean defaultAlwaysMapped ) - { - if (prefix == null) - prefix = ""; - - // handle built-in prefixes - - if (prefix.equals( "xml" )) - return Locale._xml1998Uri; - - if (prefix.equals( "xmlns" )) - return Locale._xmlnsUri; - - for ( Xobj x = this ; x != null ; x = x._parent ) - for ( Xobj a = x._firstChild ; a != null && a.isAttr() ; a = a._nextSibling ) - if (a.isXmlns() && a.getXmlnsPrefix().equals( prefix )) - return a.getXmlnsUri(); - - return defaultAlwaysMapped && prefix.length() == 0 ? "" : null; - } - - final String prefixForNamespace ( String ns, String suggestion, boolean createIfMissing ) - { - if (ns == null) - ns = ""; - - // special cases - - if (ns.equals( Locale._xml1998Uri )) - return "xml"; - - if (ns.equals( Locale._xmlnsUri )) - return "xmlns"; - - // Get the closest container for the spot we're on - - Xobj base = this; - - while ( !base.isContainer() ) - base = base.ensureParent(); - - // Special handling for the no-namespace case - - if (ns.length() == 0) - { - // Search for a namespace decl which defines the default namespace - - Xobj a = base.findXmlnsForPrefix( "" ); - - // If I did not find a default decl or the decl maps to the no namespace, then - // the default namespace is mapped to "" - - if (a == null || a.getXmlnsUri().length() == 0) - return ""; - - // At this point, I've found a default namespace which is *not* the no-namespace. - // If I can't modify the document to mape the desired no-namespace, I must fail. - - if (!createIfMissing) - return null; - - // Ok, I need to make the default namespace on the nearest container map to "" - - base.setAttr( _locale.createXmlns( null ), "" ); - - return ""; - } - - // Look for an exisiting mapping for the desired uri which has a visible prefix - - for ( Xobj c = base ; c != null ; c = c._parent ) - for ( Xobj a = c.firstAttr() ; a != null ; a = a.nextAttr() ) - if (a.isXmlns() && a.getXmlnsUri().equals( ns )) - if (base.findXmlnsForPrefix( a.getXmlnsPrefix() ) == a) - return a.getXmlnsPrefix(); - - // No exisiting xmlns I can use, need to create one. See if I can first - - if (!createIfMissing) - return null; - - // Sanitize the suggestion. - - if (suggestion != null && - (suggestion.length() == 0 || suggestion.toLowerCase().startsWith( "xml" ) || - base.findXmlnsForPrefix( suggestion ) != null)) - { - suggestion = null; - } - - // If no suggestion, make one up - - if (suggestion == null) - { - String prefixBase = QNameHelper.suggestPrefix( ns ); - - suggestion = prefixBase; - - for ( int i = 1 ; ; suggestion = prefixBase + i++ ) - if (base.findXmlnsForPrefix( suggestion ) == null) - break; - } - - // Add a new namespace decl at the top elem if one exists, otherwise at root - - Xobj c = base; - - while ( !c.isRoot() && !c.ensureParent().isRoot() ) - c = c._parent; - - base.setAttr( _locale.createXmlns( suggestion ), ns ); - - return suggestion; - } - - final QName getValueAsQName ( ) - { - assert !hasChildren(); - - // TODO - - // caching the QName value in this object would prevent one from having - // to repeat all this string arithmatic over and over again. Perhaps - // when I make the store capable of handling strong simple types this - // can be done ... - - String value = getValueAsString( Locale.WS_COLLAPSE ); - - String prefix, localname; - - int firstcolon = value.indexOf( ':' ); - - if (firstcolon >= 0) - { - prefix = value.substring( 0, firstcolon ); - localname = value.substring( firstcolon + 1 ); - } - else - { - prefix = ""; - localname = value; - } - - String uri = namespaceForPrefix( prefix, true ); - - if (uri == null) - return null; // no prefix definition found - that's illegal - - return new QName( uri, localname ); - } - - final Xobj getAttr ( QName name ) - { - for ( Xobj x = _firstChild ; x != null && x.isAttr() ; x = x._nextSibling ) - if (x._name.equals( name )) - return x; - - return null; - } - - final QName getXsiTypeName ( ) - { - assert isContainer(); - - Xobj a = getAttr( Locale._xsiType ); - - return a == null ? null : a.getValueAsQName(); - } - - final XmlObject getObject ( ) - { - return isUserNode() ? (XmlObject) getUser() : null; - } - - final TypeStoreUser getUser ( ) - { - assert isUserNode(); - assert _user != null || (!isRoot() && !isStableUser()); - - if (_user == null) - { - // BUGBUG - this is recursive - - TypeStoreUser parentUser = - _parent == null - ? ((TypeStoreUserFactory) XmlBeans.NO_TYPE).createTypeStoreUser() - : _parent.getUser(); - - _user = - isElem() - ? parentUser.create_element_user( _name, getXsiTypeName() ) - : parentUser.create_attribute_user( _name ); - - _user.attach_store( this ); - } - - return _user; - } - - final void invalidateUser ( ) - { - assert isValid(); - assert _user == null || isUserNode(); - - if (_user != null) - _user.invalidate_value(); - } - - final void ensureOccupancy ( ) - { - assert isValid(); - - if (isVacant()) - { - assert isUserNode(); - - // In order to use Cur to set the value, I mark the - // value as occupied and remove the user to prohibit - // further user invalidations - - clearBit( VACANT ); - - TypeStoreUser user = _user; - _user = null; - - String value = user.build_text( this ); - - - long saveVersion = _locale._versionAll; - long saveVersionSansText = _locale._versionSansText; - - - setValue( value ); - assert saveVersionSansText == _locale._versionSansText; - - _locale._versionAll = saveVersion; - - - assert _user == null; - _user = user; - } - } - private void setValue(String val) - { - assert CharUtil.isValid(val, 0, val.length()); - - // Check for nothing to insert - - if (val.length() <= 0) - return; - - _locale.notifyChange(); - Xobj lastAttr = lastAttr(); - int startPos = 1; - Xobj charOwner = this; - if (lastAttr != null) - { - charOwner = lastAttr; - startPos = charOwner.posAfter(); - } - charOwner.insertCharsHelper(startPos, val, 0, val.length(), true); - } - // - // TypeStore - // - - public SchemaTypeLoader get_schematypeloader ( ) - { - return _locale._schemaTypeLoader; - } - - public XmlLocale get_locale ( ) - { - return _locale; - } - - // TODO - remove this when I've replaced the old store - public Object get_root_object ( ) - { - return _locale; - } - - public boolean is_attribute ( ) { assert isValid(); return isAttr(); } - public boolean validate_on_set ( ) { assert isValid(); return _locale._validateOnSet; } - - public void invalidate_text ( ) - { - _locale.enter(); - - try - { - assert isValid(); - - if (isOccupied()) - { - if (hasTextNoEnsureOccupancy() || hasChildren()) - { - TypeStoreUser user = _user; - _user = null; - - Cur c = tempCur(); - c.moveNodeContents( null, false ); - c.release(); - - assert _user == null; - _user = user; - } - - setBit( VACANT ); - } - - assert isValid(); - } - finally - { - _locale.exit(); - } - } - - public String fetch_text ( int wsr ) - { - _locale.enter(); - - try - { - assert isValid() && isOccupied(); - - return getValueAsString( wsr ); - } - finally - { - _locale.exit(); - } - } - - public XmlCursor new_cursor ( ) - { - _locale.enter(); - - try - { - Cur c = tempCur(); - XmlCursor xc = new Cursor( c ); - c.release(); - return xc; - - } - finally - { - _locale.exit(); - } - } - - public SchemaField get_schema_field ( ) - { - assert isValid(); - - if (isRoot()) - return null; - - TypeStoreUser parentUser = ensureParent().getUser(); - - if (isAttr()) - return parentUser.get_attribute_field( _name ); - - assert isElem(); - - TypeStoreVisitor visitor = parentUser.new_visitor(); - - if (visitor == null) - return null; - - for ( Xobj x = _parent._firstChild ; ; x = x._nextSibling ) - { - if (x.isElem()) - { - visitor.visit( x._name ); - - if (x == this) - return visitor.get_schema_field(); - } - } - } - - public void validate ( ValidatorListener eventSink ) - { - _locale.enter(); - - try - { - Cur c = tempCur(); - Validate validate = new Validate( c, eventSink ); - c.release(); - } - finally - { - _locale.exit(); - } - } - - public TypeStoreUser change_type ( SchemaType type ) - { - _locale.enter(); - - try - { - Cur c = tempCur(); - c.setType( type, false ); - c.release(); - } - finally - { - _locale.exit(); - } - - return getUser(); - } - - public TypeStoreUser substitute ( QName name, SchemaType type ) - { - _locale.enter(); - - try - { - Cur c = tempCur(); - c.setSubstitution( name, type, false ); - c.release(); - } - finally - { - _locale.exit(); - } - - return getUser(); - } - - public QName get_xsi_type ( ) - { - return getXsiTypeName(); - } - - public void store_text ( String text ) - { - _locale.enter(); - - TypeStoreUser user = _user; - _user = null; - - try - { - Cur c = tempCur(); - - c.moveNodeContents( null, false ); - - if (text != null && text.length() > 0) - { - c.next(); - c.insertString( text ); - } - - c.release(); - } - finally - { - assert _user == null; - _user = user; - - _locale.exit(); - } - } - - public int compute_flags ( ) - { - if (isRoot()) - return 0; - - TypeStoreUser parentUser = ensureParent().getUser(); - - if (isAttr()) - return parentUser.get_attributeflags( _name ); - - int f = parentUser.get_elementflags( _name ); - - if (f != -1) - return f; - - TypeStoreVisitor visitor = parentUser.new_visitor(); - - if (visitor == null) - return 0; - - for ( Xobj x = _parent._firstChild ; ; x = x._nextSibling ) - { - if (x.isElem()) - { - visitor.visit( x._name ); - - if (x == this) - return visitor.get_elementflags(); - } - } - } - - public String compute_default_text ( ) - { - if (isRoot()) - return null; - - TypeStoreUser parentUser = ensureParent().getUser(); - - if (isAttr()) - return parentUser.get_default_attribute_text( _name ); - - String result = parentUser.get_default_element_text( _name ); - - if (result != null) - return result; - - TypeStoreVisitor visitor = parentUser.new_visitor(); - - if (visitor == null) - return null; - - for ( Xobj x = _parent._firstChild ; ; x = x._nextSibling ) - { - if (x.isElem()) - { - visitor.visit( x._name ); - - if (x == this) - return visitor.get_default_text(); - } - } - } - - public boolean find_nil ( ) - { - if (isAttr()) - return false; - - _locale.enter(); - - try - { - Xobj a = getAttr( Locale._xsiNil ); - - if (a == null) - return false; - - String value = a.getValueAsString( Locale.WS_COLLAPSE ); - - return value.equals( "true" ) || value.equals( "1" ); - } - finally - { - _locale.exit(); - } - } - - public void invalidate_nil ( ) - { - if (isAttr()) - return; - - _locale.enter(); - - try - { - if (!_user.build_nil()) - removeAttr( Locale._xsiNil ); - else - setAttr( Locale._xsiNil, "true" ); - } - finally - { - _locale.exit(); - } - } - - public int count_elements ( QName name ) - { - return _locale.count( this, name, null ); - } - - public int count_elements ( QNameSet names ) - { - return _locale.count( this, null, names ); - } - - public TypeStoreUser find_element_user ( QName name, int i ) - { - for ( Xobj x = _firstChild ; x != null ; x = x._nextSibling ) - if (x.isElem() && x._name.equals( name ) && --i < 0) - return x.getUser(); - - return null; - } - - public TypeStoreUser find_element_user ( QNameSet names, int i ) - { - for ( Xobj x = _firstChild ; x != null ; x = x._nextSibling ) - if (x.isElem() && names.contains( x._name ) && --i < 0) - return x.getUser(); - - return null; - } - - public void find_all_element_users ( QName name, List fillMeUp ) - { - for ( Xobj x = _firstChild ; x != null ; x = x._nextSibling ) - if (x.isElem() && x._name.equals( name )) - fillMeUp.add( x.getUser() ); - } - - public void find_all_element_users ( QNameSet names, List fillMeUp ) - { - for ( Xobj x = _firstChild ; x != null ; x = x._nextSibling ) - if (x.isElem() && names.contains( x._name )) - fillMeUp.add( x.getUser() ); - } - - private static TypeStoreUser insertElement ( QName name, Xobj x, int pos ) - { - x._locale.enter(); - - try - { - Cur c = x._locale.tempCur(); - c.moveTo( x, pos ); - c.createElement( name ); - TypeStoreUser user = c.getUser(); - c.release(); - return user; - } - finally - { - x._locale.exit(); - } - } - - public TypeStoreUser insert_element_user ( QName name, int i ) - { - if (i < 0) - throw new IndexOutOfBoundsException(); - - if (!isContainer()) - throw new IllegalStateException(); - - Xobj x = _locale.findNthChildElem( this, name, null, i ); - - if (x == null) - { - if (i > _locale.count( this, name, null ) + 1) - throw new IndexOutOfBoundsException(); - - return add_element_user( name ); - } - - return insertElement( name, x, 0 ); - } - - public TypeStoreUser insert_element_user ( QNameSet names, QName name, int i ) - { - if (i < 0) - throw new IndexOutOfBoundsException(); - - if (!isContainer()) - throw new IllegalStateException(); - - Xobj x = _locale.findNthChildElem( this, null, names, i ); - - if (x == null) - { - if (i > _locale.count( this, null, names ) + 1) - throw new IndexOutOfBoundsException(); - - return add_element_user( name ); - } - - return insertElement( name, x, 0 ); - } - - public TypeStoreUser add_element_user ( QName name ) - { - if (!isContainer()) - throw new IllegalStateException(); - - QNameSet endSet = null; - boolean gotEndSet = false; - - Xobj candidate = null; - - for ( Xobj x = _lastChild ; x != null ; x = x._prevSibling ) - { - if (x.isContainer()) - { - if (x._name.equals( name )) - break; - - if (!gotEndSet) - { - endSet = _user.get_element_ending_delimiters( name ); - gotEndSet = true; - } - - if (endSet == null || endSet.contains( x._name )) - candidate = x; - } - } - - return - candidate == null - ? insertElement( name, this, END_POS ) - : insertElement( name, candidate, 0 ); - } - - private static void removeElement ( Xobj x ) - { - if (x == null) - throw new IndexOutOfBoundsException(); - - x._locale.enter(); - - try - { - Cur c = x.tempCur(); - c.moveNode( null ); - c.release(); - } - finally - { - x._locale.exit(); - } - } - - public void remove_element ( QName name, int i ) - { - if (i < 0) - throw new IndexOutOfBoundsException(); - - if (!isContainer()) - throw new IllegalStateException(); - - Xobj x; - - for ( x = _firstChild ; x != null ; x = x._nextSibling ) - if (x.isElem() && x._name.equals( name ) && --i < 0) - break; - - removeElement( x ); - } - - public void remove_element ( QNameSet names, int i ) - { - if (i < 0) - throw new IndexOutOfBoundsException(); - - if (!isContainer()) - throw new IllegalStateException(); - - Xobj x; - - for ( x = _firstChild ; x != null ; x = x._nextSibling ) - if (x.isElem() && names.contains( x._name ) && --i < 0) - break; - - removeElement( x ); - } - - public TypeStoreUser find_attribute_user ( QName name ) - { - Xobj a = getAttr( name ); - - return a == null ? null : a.getUser(); - } - - public TypeStoreUser add_attribute_user ( QName name ) - { - if (getAttr( name ) != null) - throw new IndexOutOfBoundsException(); - - _locale.enter(); - - try - { - return setAttr( name, "" ).getUser(); - } - finally - { - _locale.exit(); - } - } - - public void remove_attribute ( QName name ) - { - _locale.enter(); - - try - { - if (!removeAttr( name )) - throw new IndexOutOfBoundsException(); - } - finally - { - _locale.exit(); - } - } - - public TypeStoreUser copy_contents_from ( TypeStore source ) - { - Xobj xSrc = (Xobj) source; - - if (xSrc == this) - return getUser(); - - _locale.enter(); - - try - { - xSrc._locale.enter(); - - Cur c = tempCur(); - - try - { - Cur cSrc1 = xSrc.tempCur(); - Map sourceNamespaces = Locale.getAllNamespaces( cSrc1, null ); - cSrc1.release(); - - if (isAttr()) - { - Cur cSrc = xSrc.tempCur(); - String value = Locale.getTextValue( cSrc ); - cSrc.release(); - - c.setValue( value ); - } - else - { - // Here I save away the user of this node so that it does not get whacked - // in the following operations. - - disconnectChildrenUsers(); - - assert !inhibitDisconnect(); - - setBit( INHIBIT_DISCONNECT ); - - QName xsiType = isContainer() ? getXsiTypeName() : null; - - Xobj copy = xSrc.copyNode( _locale ); - - Cur.moveNodeContents( this, null, true ); - - c.next(); - - Cur.moveNodeContents( copy, c, true ); - - c.moveTo( this ); - - if (xsiType != null) - c.setXsiType( xsiType ); - - assert inhibitDisconnect(); - clearBit( INHIBIT_DISCONNECT ); - } - - if (sourceNamespaces != null) - { - if (!c.isContainer()) - c.toParent(); - - Locale.applyNamespaces( c, sourceNamespaces ); - } - - } - finally - { - c.release(); - - xSrc._locale.exit(); - } - } - finally - { - _locale.exit(); - } - - return getUser(); - } - - public TypeStoreUser copy(SchemaTypeLoader stl, SchemaType type, XmlOptions options) - { - //do not use a user's Factory method for copying. - //XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - Xobj destination = null; - options = XmlOptions.maskNull(options); - SchemaType sType = (SchemaType) options.get(XmlOptions.DOCUMENT_TYPE); - - if (sType == null) - sType = type == null ? XmlObject.type : type; - - Locale locale = this.locale(); - if ( Boolean.TRUE.equals(options.get(XmlOptions.COPY_USE_NEW_SYNC_DOMAIN)) ) - locale = Locale.getLocale(stl, options); - - if (sType.isDocumentType() || (sType.isNoType() && (this instanceof Xobj.DocumentXobj))) - destination = Cur.createDomDocumentRootXobj(locale, false); - else - destination = Cur.createDomDocumentRootXobj(locale, true); - - - locale.enter(); - try - { - Cur c = destination.tempCur(); - c.setType(type); - c.release(); - } - finally - { - locale.exit(); - } - - TypeStoreUser tsu = destination.copy_contents_from(this); - return tsu; - } - - public void array_setter ( XmlObject[] sources, QName elementName ) - { - _locale.enter(); - - try - { - // TODO - this is the quick and dirty implementation, make this faster - - int m = sources.length; - - ArrayList copies = new ArrayList(); - ArrayList types = new ArrayList(); - - for ( int i = 0 ; i < m ; i++ ) - { - // TODO - deal with null sources[ i ] here -- what to do? - - if (sources[ i ] == null) - throw new IllegalArgumentException( "Array element null" ); - - else if (sources[ i ].isImmutable()) - { - copies.add( null ); - types.add( null ); - } - else - { - Xobj x = ((Xobj) ((TypeStoreUser) sources[ i ]).get_store()); - - if (x._locale == _locale) - copies.add( x.copyNode( _locale ) ); - else - { - x._locale.enter(); - - try - { - copies.add( x.copyNode( _locale ) ); - } - finally - { - x._locale.exit(); - } - } - - types.add( sources[ i ].schemaType() ); - } - } - - int n = count_elements( elementName ); - - for ( ; n > m ; n-- ) - remove_element( elementName, m ); - - for ( ; m > n ; n++ ) - add_element_user( elementName ); - - assert m == n; - - ArrayList elements = new ArrayList(); - - find_all_element_users( elementName, elements ); - - for ( int i = 0 ; i < elements.size() ; i++ ) - elements.set( i, (Xobj) ((TypeStoreUser) elements.get( i )).get_store() ); - - assert elements.size() == n; - - Cur c = tempCur(); - - for ( int i = 0 ; i < n ; i++ ) - { - Xobj x = (Xobj) elements.get( i ); - - if (sources[ i ].isImmutable()) - x.getObject().set( sources[ i ] ); - else - { - Cur.moveNodeContents( x, null, true ); - - c.moveTo( x ); - c.next(); - - Cur.moveNodeContents( (Xobj) copies.get( i ), c, true ); - - x.change_type( (SchemaType) types.get( i ) ); - } - } - - c.release(); - } - finally - { - _locale.exit(); - } - } - - public void visit_elements ( TypeStoreVisitor visitor ) - { - throw new RuntimeException( "Not implemeneted" ); - } - - public XmlObject[] exec_query ( String queryExpr, XmlOptions options ) throws XmlException - { - _locale.enter(); - - try - { - Cur c = tempCur(); - - XmlObject[] result = Query.objectExecQuery( c, queryExpr, options ); - - c.release(); - - return result; - } - finally - { - _locale.exit(); - } - } - - public String find_prefix_for_nsuri ( String nsuri, String suggested_prefix ) - { - _locale.enter(); - - try - { - return prefixForNamespace( nsuri, suggested_prefix, true ); - } - finally - { - _locale.exit(); - } - } - - public String getNamespaceForPrefix ( String prefix ) - { - return namespaceForPrefix( prefix, true ); - } - - // - // - // - - abstract static class NodeXobj extends Xobj implements Dom, Node, NodeList - { - NodeXobj ( Locale l, int kind, int domType ) - { - super( l, kind, domType ); - } - - Dom getDom ( ) { return this; } - - // - // - // - - public int getLength ( ) { return DomImpl._childNodes_getLength( this ); } - public Node item ( int i ) { return DomImpl._childNodes_item( this, i ); } - - public Node appendChild ( Node newChild ) { return DomImpl._node_appendChild( this, newChild ); } - public Node cloneNode ( boolean deep ) { return DomImpl._node_cloneNode( this, deep ); } - public NamedNodeMap getAttributes ( ) { return null; } - public NodeList getChildNodes ( ) { return this; } - public Node getParentNode ( ) { return DomImpl._node_getParentNode( this ); } - public Node removeChild ( Node oldChild ) { return DomImpl._node_removeChild( this, oldChild ); } - public Node getFirstChild ( ) { return DomImpl._node_getFirstChild( this ); } - public Node getLastChild ( ) { return DomImpl._node_getLastChild( this ); } - public String getLocalName ( ) { return DomImpl._node_getLocalName( this ); } - public String getNamespaceURI ( ) { return DomImpl._node_getNamespaceURI( this ); } - public Node getNextSibling ( ) { return DomImpl._node_getNextSibling( this ); } - public String getNodeName ( ) { return DomImpl._node_getNodeName( this ); } - public short getNodeType ( ) { return DomImpl._node_getNodeType( this ); } - public String getNodeValue ( ) { return DomImpl._node_getNodeValue( this ); } - public Document getOwnerDocument ( ) { return DomImpl._node_getOwnerDocument( this ); } - public String getPrefix ( ) { return DomImpl._node_getPrefix( this ); } - public Node getPreviousSibling ( ) { return DomImpl._node_getPreviousSibling( this ); } - public boolean hasAttributes ( ) { return DomImpl._node_hasAttributes( this ); } - public boolean hasChildNodes ( ) { return DomImpl._node_hasChildNodes( this ); } - public Node insertBefore ( Node newChild, Node refChild ) { return DomImpl._node_insertBefore( this, newChild, refChild ); } - public boolean isSupported ( String feature, String version ) { return DomImpl._node_isSupported( this, feature, version ); } - public void normalize ( ) { DomImpl._node_normalize( this ); } - public Node replaceChild ( Node newChild, Node oldChild ) { return DomImpl._node_replaceChild( this, newChild, oldChild ); } - public void setNodeValue ( String nodeValue ) { DomImpl._node_setNodeValue( this, nodeValue ); } - public void setPrefix ( String prefix ) { DomImpl._node_setPrefix( this, prefix ); } - public boolean nodeCanHavePrefixUri( ){ return false; } - - // DOM Level 3 - public Object getUserData ( String key ) { return DomImpl._node_getUserData( this, key ); } - public Object setUserData ( String key, Object data, UserDataHandler handler ) { return DomImpl._node_setUserData( this, key, data, handler ); } - public Object getFeature ( String feature, String version ) { return DomImpl._node_getFeature( this, feature, version ); } - public boolean isEqualNode ( Node arg ) { return DomImpl._node_isEqualNode( this, arg ); } - public boolean isSameNode ( Node arg ) { return DomImpl._node_isSameNode( this, arg ); } - public String lookupNamespaceURI ( String prefix ) { return DomImpl._node_lookupNamespaceURI( this, prefix ); } - public String lookupPrefix ( String namespaceURI ) { return DomImpl._node_lookupPrefix( this, namespaceURI ); } - public boolean isDefaultNamespace ( String namespaceURI ) { return DomImpl._node_isDefaultNamespace( this, namespaceURI ); } - public void setTextContent ( String textContent ) { DomImpl._node_setTextContent( this, textContent ); } - public String getTextContent ( ) { return DomImpl._node_getTextContent( this ); } - public short compareDocumentPosition ( Node other ) { return DomImpl._node_compareDocumentPosition( this, other ); } - public String getBaseURI ( ) { return DomImpl._node_getBaseURI( this ); } - } - - static class DocumentXobj extends NodeXobj implements Document - { - DocumentXobj ( Locale l ) - { - super( l, ROOT, DomImpl.DOCUMENT ); - } - - Xobj newNode ( Locale l ) { return new DocumentXobj( l ); } - - // - // - // - - public Attr createAttribute ( String name ) { return DomImpl._document_createAttribute( this, name ); } - public Attr createAttributeNS ( String namespaceURI, String qualifiedName ) { return DomImpl._document_createAttributeNS( this, namespaceURI, qualifiedName ); } - public CDATASection createCDATASection ( String data ) { return DomImpl._document_createCDATASection( this, data ); } - public Comment createComment ( String data ) { return DomImpl._document_createComment( this, data ); } - public DocumentFragment createDocumentFragment ( ) { return DomImpl._document_createDocumentFragment( this ); } - public Element createElement ( String tagName ) { return DomImpl._document_createElement( this, tagName ); } - public Element createElementNS ( String namespaceURI, String qualifiedName ) { return DomImpl._document_createElementNS( this, namespaceURI, qualifiedName ); } - public EntityReference createEntityReference ( String name ) { return DomImpl._document_createEntityReference( this, name ); } - public ProcessingInstruction createProcessingInstruction ( String target, String data ) { return DomImpl._document_createProcessingInstruction( this, target, data ); } - public Text createTextNode ( String data ) { return DomImpl._document_createTextNode( this, data ); } - public DocumentType getDoctype ( ) { return DomImpl._document_getDoctype( this ); } - public Element getDocumentElement ( ) { return DomImpl._document_getDocumentElement( this ); } - public Element getElementById ( String elementId ) { - if ( _idToElement == null )return null; - Xobj o = (Xobj) _idToElement.get(elementId); - if (o == null) return null; - if (!isInSameTree(o)) - { - _idToElement.remove(elementId); - } - return (Element)o; - } - public NodeList getElementsByTagName ( String tagname ) { return DomImpl._document_getElementsByTagName( this, tagname ); } - public NodeList getElementsByTagNameNS ( String namespaceURI, String localName ) { return DomImpl._document_getElementsByTagNameNS( this, namespaceURI, localName ); } - public DOMImplementation getImplementation ( ) { return DomImpl._document_getImplementation( this ); } - public Node importNode ( Node importedNode, boolean deep ) { return DomImpl._document_importNode( this, importedNode, deep ); } - - // DOM Level 3 - public Node adoptNode ( Node source ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getDocumentURI ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public DOMConfiguration getDomConfig ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getInputEncoding ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public boolean getStrictErrorChecking ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getXmlEncoding ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public boolean getXmlStandalone ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getXmlVersion ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void normalizeDocument ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public Node renameNode ( Node n, String namespaceURI, String qualifiedName ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setDocumentURI ( String documentURI ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setStrictErrorChecking ( boolean strictErrorChecking ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setXmlStandalone ( boolean xmlStandalone ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setXmlVersion ( String xmlVersion ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - - protected void addIdElement( String idVal, Dom e){ - if ( _idToElement == null) - _idToElement = new java.util.Hashtable(); - _idToElement.put(idVal,e); - } - void removeIdElement( String idVal ){ - if (_idToElement != null) - _idToElement.remove(idVal); - } - private java.util.Hashtable _idToElement; - } - static class DocumentFragXobj extends NodeXobj implements DocumentFragment - { - DocumentFragXobj ( Locale l ) { super( l, ROOT, DomImpl.DOCFRAG ); } - - Xobj newNode ( Locale l ) { return new DocumentFragXobj( l ); } - } - - final static class ElementAttributes implements NamedNodeMap - { - ElementAttributes ( ElementXobj elementXobj ) - { - _elementXobj = elementXobj; - } - - public int getLength ( ) { return DomImpl._attributes_getLength( _elementXobj ); } - public Node getNamedItem ( String name ) { return DomImpl._attributes_getNamedItem ( _elementXobj, name ); } - public Node getNamedItemNS ( String namespaceURI, String localName ) { return DomImpl._attributes_getNamedItemNS ( _elementXobj, namespaceURI, localName ); } - public Node item ( int index ) { return DomImpl._attributes_item ( _elementXobj, index ); } - public Node removeNamedItem ( String name ) { return DomImpl._attributes_removeNamedItem ( _elementXobj, name ); } - public Node removeNamedItemNS ( String namespaceURI, String localName ) { return DomImpl._attributes_removeNamedItemNS ( _elementXobj, namespaceURI, localName ); } - public Node setNamedItem ( Node arg ) { return DomImpl._attributes_setNamedItem ( _elementXobj, arg ); } - public Node setNamedItemNS ( Node arg ) { return DomImpl._attributes_setNamedItemNS ( _elementXobj, arg ); } - - private ElementXobj _elementXobj; - } - - static abstract class NamedNodeXobj extends NodeXobj - { - NamedNodeXobj ( Locale l, int kind, int domType ) - { - super( l, kind, domType ); - _canHavePrefixUri = true; - } - - public boolean nodeCanHavePrefixUri( ){ return _canHavePrefixUri; } - - boolean _canHavePrefixUri; - } - - static class ElementXobj extends NamedNodeXobj implements Element - { - ElementXobj ( Locale l, QName name ) - { - super( l, ELEM, DomImpl.ELEMENT ); - _name = name; - } - - Xobj newNode ( Locale l ) { return new ElementXobj( l, _name ); } - - // - // - // - - public NamedNodeMap getAttributes ( ) - { - if (_attributes == null) - _attributes = new ElementAttributes( this ); - - return _attributes; - } - - public String getAttribute ( String name ) { return DomImpl._element_getAttribute( this, name ); } - public Attr getAttributeNode ( String name ) { return DomImpl._element_getAttributeNode( this, name ); } - public Attr getAttributeNodeNS ( String namespaceURI, String localName ) { return DomImpl._element_getAttributeNodeNS( this, namespaceURI, localName ); } - public String getAttributeNS ( String namespaceURI, String localName ) { return DomImpl._element_getAttributeNS( this, namespaceURI, localName ); } - public NodeList getElementsByTagName ( String name ) { return DomImpl._element_getElementsByTagName( this, name ); } - public NodeList getElementsByTagNameNS ( String namespaceURI, String localName ) { return DomImpl._element_getElementsByTagNameNS( this, namespaceURI, localName ); } - public String getTagName ( ) { return DomImpl._element_getTagName( this ); } - public boolean hasAttribute ( String name ) { return DomImpl._element_hasAttribute( this, name ); } - public boolean hasAttributeNS ( String namespaceURI, String localName ) { return DomImpl._element_hasAttributeNS( this, namespaceURI, localName ); } - public void removeAttribute ( String name ) { DomImpl._element_removeAttribute( this, name ); } - public Attr removeAttributeNode ( Attr oldAttr ) { return DomImpl._element_removeAttributeNode( this, oldAttr ); } - public void removeAttributeNS ( String namespaceURI, String localName ) { DomImpl._element_removeAttributeNS( this, namespaceURI, localName ); } - public void setAttribute ( String name, String value ) { DomImpl._element_setAttribute( this, name, value ); } - public Attr setAttributeNode ( Attr newAttr ) { return DomImpl._element_setAttributeNode( this, newAttr ); } - public Attr setAttributeNodeNS ( Attr newAttr ) { return DomImpl._element_setAttributeNodeNS( this, newAttr ); } - public void setAttributeNS ( String namespaceURI, String qualifiedName, String value ) { DomImpl._element_setAttributeNS( this, namespaceURI, qualifiedName, value ); } - - // DOM Level 3 - public TypeInfo getSchemaTypeInfo ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setIdAttribute ( String name, boolean isId ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setIdAttributeNS ( String namespaceURI, String localName, boolean isId ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setIdAttributeNode ( Attr idAttr, boolean isId ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - - private ElementAttributes _attributes; - } - - static class AttrXobj extends NamedNodeXobj implements Attr - { - AttrXobj ( Locale l, QName name ) - { - super( l, ATTR, DomImpl.ATTR ); - _name = name; - } - - Xobj newNode ( Locale l ) { return new AttrXobj( l, _name ); } - - // - public Node getNextSibling ( ) { return null; } - // - - public String getName ( ) { return DomImpl._node_getNodeName( this ); } - public Element getOwnerElement ( ) { return DomImpl._attr_getOwnerElement( this ); } - public boolean getSpecified ( ) { return DomImpl._attr_getSpecified( this ); } - public String getValue ( ) { return DomImpl._node_getNodeValue( this ); } - public void setValue ( String value ) { DomImpl._node_setNodeValue( this, value ); } - - // DOM Level 3 - public TypeInfo getSchemaTypeInfo ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public boolean isId ( ) { return false; } - } - - static class AttrIdXobj - extends AttrXobj - { - AttrIdXobj ( Locale l, QName name ) - { - super( l, name ); - } - public boolean isId() - { - return true; - } - } - static class CommentXobj extends NodeXobj implements Comment - { - CommentXobj ( Locale l ) { super( l, COMMENT, DomImpl.COMMENT ); } - - Xobj newNode ( Locale l ) { return new CommentXobj( l ); } - - public NodeList getChildNodes ( ) { return DomImpl._emptyNodeList; } - - public void appendData ( String arg ) { DomImpl._characterData_appendData( this, arg ); } - public void deleteData ( int offset, int count ) { DomImpl._characterData_deleteData( this, offset, count ); } - public String getData ( ) { return DomImpl._characterData_getData( this ); } - public int getLength ( ) { return DomImpl._characterData_getLength( this ); } - public Node getFirstChild ( ) { return null; } - public void insertData ( int offset, String arg ) { DomImpl._characterData_insertData( this, offset, arg ); } - public void replaceData ( int offset, int count, String arg ) { DomImpl._characterData_replaceData( this, offset, count, arg ); } - public void setData ( String data ) { DomImpl._characterData_setData( this, data ); } - public String substringData ( int offset, int count ) { return DomImpl._characterData_substringData( this, offset, count ); } - } - - static class ProcInstXobj extends NodeXobj implements ProcessingInstruction - { - ProcInstXobj ( Locale l, String target ) - { - super( l, PROCINST, DomImpl.PROCINST ); - _name = _locale.makeQName( null, target ); - } - - Xobj newNode ( Locale l ) { return new ProcInstXobj( l, _name.getLocalPart() ); } - - public int getLength ( ) { return 0; } - public Node getFirstChild ( ) { return null; } - - public String getData ( ) { return DomImpl._processingInstruction_getData( this ); } - public String getTarget ( ) { return DomImpl._processingInstruction_getTarget( this ); } - public void setData ( String data ) { DomImpl._processingInstruction_setData( this, data ); } - } - - // - // SAAJ objects - // - - static class SoapPartDocXobj extends DocumentXobj - { - SoapPartDocXobj ( Locale l ) - { - super(l); - //super( l, ROOT, DomImpl.DOCUMENT ); - _soapPartDom = new SoapPartDom( this ); - } - - Dom getDom ( ) { return _soapPartDom; } - - Xobj newNode ( Locale l ) { return new SoapPartDocXobj( l ); } - - SoapPartDom _soapPartDom; - } - - static class SoapPartDom extends SOAPPart implements Dom, Document, NodeList - { - SoapPartDom ( SoapPartDocXobj docXobj ) - { - _docXobj = docXobj; - } - - public int nodeType ( ) { return DomImpl.DOCUMENT; } - public Locale locale ( ) { return _docXobj._locale; } - public Cur tempCur ( ) { return _docXobj.tempCur(); } - public QName getQName ( ) { return _docXobj._name; } - - public void dump ( ) { dump( System.out ); } - public void dump ( PrintStream o ) { _docXobj.dump( o ); } - public void dump ( PrintStream o, Object ref ) { _docXobj.dump( o, ref ); } - - public String name ( ) { return "#document"; } - - public Node appendChild ( Node newChild ) { return DomImpl._node_appendChild( this, newChild ); } - public Node cloneNode ( boolean deep ) { return DomImpl._node_cloneNode( this, deep ); } - public NamedNodeMap getAttributes ( ) { return null; } - public NodeList getChildNodes ( ) { return this; } - public Node getParentNode ( ) { return DomImpl._node_getParentNode( this ); } - public Node removeChild ( Node oldChild ) { return DomImpl._node_removeChild( this, oldChild ); } - public Node getFirstChild ( ) { return DomImpl._node_getFirstChild( this ); } - public Node getLastChild ( ) { return DomImpl._node_getLastChild( this ); } - public String getLocalName ( ) { return DomImpl._node_getLocalName( this ); } - public String getNamespaceURI ( ) { return DomImpl._node_getNamespaceURI( this ); } - public Node getNextSibling ( ) { return DomImpl._node_getNextSibling( this ); } - public String getNodeName ( ) { return DomImpl._node_getNodeName( this ); } - public short getNodeType ( ) { return DomImpl._node_getNodeType( this ); } - public String getNodeValue ( ) { return DomImpl._node_getNodeValue( this ); } - public Document getOwnerDocument ( ) { return DomImpl._node_getOwnerDocument( this ); } - public String getPrefix ( ) { return DomImpl._node_getPrefix( this ); } - public Node getPreviousSibling ( ) { return DomImpl._node_getPreviousSibling( this ); } - public boolean hasAttributes ( ) { return DomImpl._node_hasAttributes( this ); } - public boolean hasChildNodes ( ) { return DomImpl._node_hasChildNodes( this ); } - public Node insertBefore ( Node newChild, Node refChild ) { return DomImpl._node_insertBefore( this, newChild, refChild ); } - public boolean isSupported ( String feature, String version ) { return DomImpl._node_isSupported( this, feature, version ); } - public void normalize ( ) { DomImpl._node_normalize( this ); } - public Node replaceChild ( Node newChild, Node oldChild ) { return DomImpl._node_replaceChild( this, newChild, oldChild ); } - public void setNodeValue ( String nodeValue ) { DomImpl._node_setNodeValue( this, nodeValue ); } - public void setPrefix ( String prefix ) { DomImpl._node_setPrefix( this, prefix ); } - - // DOM Level 3 - public Object getUserData ( String key ) { return DomImpl._node_getUserData( this, key ); } - public Object setUserData ( String key, Object data, UserDataHandler handler ) { return DomImpl._node_setUserData( this, key, data, handler ); } - public Object getFeature ( String feature, String version ) { return DomImpl._node_getFeature( this, feature, version ); } - public boolean isEqualNode ( Node arg ) { return DomImpl._node_isEqualNode( this, arg ); } - public boolean isSameNode ( Node arg ) { return DomImpl._node_isSameNode( this, arg ); } - public String lookupNamespaceURI ( String prefix ) { return DomImpl._node_lookupNamespaceURI( this, prefix ); } - public String lookupPrefix ( String namespaceURI ) { return DomImpl._node_lookupPrefix( this, namespaceURI ); } - public boolean isDefaultNamespace ( String namespaceURI ) { return DomImpl._node_isDefaultNamespace( this, namespaceURI ); } - public void setTextContent ( String textContent ) { DomImpl._node_setTextContent( this, textContent ); } - public String getTextContent ( ) { return DomImpl._node_getTextContent( this ); } - public short compareDocumentPosition ( Node other ) { return DomImpl._node_compareDocumentPosition( this, other ); } - public String getBaseURI ( ) { return DomImpl._node_getBaseURI( this ); } - public Node adoptNode ( Node source ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getDocumentURI ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public DOMConfiguration getDomConfig ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getInputEncoding ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public boolean getStrictErrorChecking ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getXmlEncoding ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public boolean getXmlStandalone ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public String getXmlVersion ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void normalizeDocument ( ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public Node renameNode ( Node n, String namespaceURI, String qualifiedName ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setDocumentURI ( String documentURI ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setStrictErrorChecking ( boolean strictErrorChecking ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setXmlStandalone ( boolean xmlStandalone ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - public void setXmlVersion ( String xmlVersion ) { throw new RuntimeException( "DOM Level 3 Not implemented" ); } - - public Attr createAttribute ( String name ) { return DomImpl._document_createAttribute( this, name ); } - public Attr createAttributeNS ( String namespaceURI, String qualifiedName ) { return DomImpl._document_createAttributeNS( this, namespaceURI, qualifiedName ); } - public CDATASection createCDATASection ( String data ) { return DomImpl._document_createCDATASection( this, data ); } - public Comment createComment ( String data ) { return DomImpl._document_createComment( this, data ); } - public DocumentFragment createDocumentFragment ( ) { return DomImpl._document_createDocumentFragment( this ); } - public Element createElement ( String tagName ) { return DomImpl._document_createElement( this, tagName ); } - public Element createElementNS ( String namespaceURI, String qualifiedName ) { return DomImpl._document_createElementNS( this, namespaceURI, qualifiedName ); } - public EntityReference createEntityReference ( String name ) { return DomImpl._document_createEntityReference( this, name ); } - public ProcessingInstruction createProcessingInstruction ( String target, String data ) { return DomImpl._document_createProcessingInstruction( this, target, data ); } - public Text createTextNode ( String data ) { return DomImpl._document_createTextNode( this, data ); } - public DocumentType getDoctype ( ) { return DomImpl._document_getDoctype( this ); } - public Element getDocumentElement ( ) { return DomImpl._document_getDocumentElement( this ); } - public Element getElementById ( String elementId ) { return DomImpl._document_getElementById( this, elementId ); } - public NodeList getElementsByTagName ( String tagname ) { return DomImpl._document_getElementsByTagName( this, tagname ); } - public NodeList getElementsByTagNameNS ( String namespaceURI, String localName ) { return DomImpl._document_getElementsByTagNameNS( this, namespaceURI, localName ); } - public DOMImplementation getImplementation ( ) { return DomImpl._document_getImplementation( this ); } - public Node importNode ( Node importedNode, boolean deep ) { return DomImpl._document_importNode( this, importedNode, deep ); } - - public int getLength ( ) { return DomImpl._childNodes_getLength( this ); } - public Node item ( int i ) { return DomImpl._childNodes_item( this, i ); } - - public void removeAllMimeHeaders ( ) { DomImpl._soapPart_removeAllMimeHeaders( this ); } - public void removeMimeHeader ( String name ) { DomImpl._soapPart_removeMimeHeader( this, name ); } - public Iterator getAllMimeHeaders ( ) { return DomImpl._soapPart_getAllMimeHeaders( this ); } - public SOAPEnvelope getEnvelope ( ) { return DomImpl._soapPart_getEnvelope( this ); } - public Source getContent ( ) { return DomImpl._soapPart_getContent( this ); } - public void setContent ( Source source ) { DomImpl._soapPart_setContent( this, source ); } - public String[] getMimeHeader ( String name ) { return DomImpl._soapPart_getMimeHeader( this, name ); } - public void addMimeHeader ( String name, String value ) { DomImpl._soapPart_addMimeHeader( this, name,value ); } - public void setMimeHeader ( String name, String value ) { DomImpl._soapPart_setMimeHeader( this, name, value ); } - public Iterator getMatchingMimeHeaders ( String[] names ) { return DomImpl._soapPart_getMatchingMimeHeaders( this, names ); } - public Iterator getNonMatchingMimeHeaders ( String[] names ) { return DomImpl._soapPart_getNonMatchingMimeHeaders( this, names ); } - - public boolean nodeCanHavePrefixUri( ){ return true; } - - SoapPartDocXobj _docXobj; - } - - static class SoapElementXobj - extends ElementXobj implements SOAPElement, org.apache.xmlbeans.impl.soap.Node - { - SoapElementXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapElementXobj( l, _name ); } - - public void detachNode ( ) { DomImpl._soapNode_detachNode( this ); } - public void recycleNode ( ) { DomImpl._soapNode_recycleNode( this ); } - public String getValue ( ) { return DomImpl._soapNode_getValue( this ); } - public void setValue ( String value ) { DomImpl._soapNode_setValue( this, value ); } - public SOAPElement getParentElement ( ) { return DomImpl._soapNode_getParentElement( this ); } - public void setParentElement ( SOAPElement p ) { DomImpl._soapNode_setParentElement( this, p ); } - - public void removeContents ( ) { DomImpl._soapElement_removeContents( this ); } - public String getEncodingStyle ( ) { return DomImpl._soapElement_getEncodingStyle( this ); } - public void setEncodingStyle ( String encodingStyle ) { DomImpl._soapElement_setEncodingStyle( this, encodingStyle ); } - public boolean removeNamespaceDeclaration ( String prefix ) { return DomImpl._soapElement_removeNamespaceDeclaration( this, prefix ); } - public Iterator getAllAttributes ( ) { return DomImpl._soapElement_getAllAttributes( this ); } - public Iterator getChildElements ( ) { return DomImpl._soapElement_getChildElements( this ); } - public Iterator getNamespacePrefixes ( ) { return DomImpl._soapElement_getNamespacePrefixes( this ); } - public SOAPElement addAttribute ( Name name, String value ) throws SOAPException { return DomImpl._soapElement_addAttribute( this, name, value ); } - public SOAPElement addChildElement ( SOAPElement oldChild ) throws SOAPException { return DomImpl._soapElement_addChildElement( this, oldChild ); } - public SOAPElement addChildElement ( Name name ) throws SOAPException { return DomImpl._soapElement_addChildElement( this, name ); } - public SOAPElement addChildElement ( String localName ) throws SOAPException { return DomImpl._soapElement_addChildElement( this, localName ); } - public SOAPElement addChildElement ( String localName, String prefix ) throws SOAPException { return DomImpl._soapElement_addChildElement( this, localName, prefix ); } - public SOAPElement addChildElement ( String localName, String prefix, String uri ) throws SOAPException { return DomImpl._soapElement_addChildElement( this, localName, prefix, uri ); } - public SOAPElement addNamespaceDeclaration ( String prefix, String uri ) { return DomImpl._soapElement_addNamespaceDeclaration( this, prefix, uri ); } - public SOAPElement addTextNode ( String data ) { return DomImpl._soapElement_addTextNode( this, data ); } - public String getAttributeValue ( Name name ) { return DomImpl._soapElement_getAttributeValue( this, name ); } - public Iterator getChildElements ( Name name ) { return DomImpl._soapElement_getChildElements( this, name ); } - public Name getElementName ( ) { return DomImpl._soapElement_getElementName( this ); } - public String getNamespaceURI ( String prefix ) { return DomImpl._soapElement_getNamespaceURI( this, prefix ); } - public Iterator getVisibleNamespacePrefixes ( ) { return DomImpl._soapElement_getVisibleNamespacePrefixes( this ); } - public boolean removeAttribute ( Name name ) { return DomImpl._soapElement_removeAttribute( this, name ); } - } - - static class SoapBodyXobj extends SoapElementXobj implements SOAPBody - { - SoapBodyXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapBodyXobj( l, _name ); } - - public boolean hasFault ( ) { return DomImpl.soapBody_hasFault( this ); } - public SOAPFault addFault ( ) throws SOAPException { return DomImpl.soapBody_addFault( this ); } - public SOAPFault getFault ( ) { return DomImpl.soapBody_getFault( this ); } - public SOAPBodyElement addBodyElement ( Name name ) { return DomImpl.soapBody_addBodyElement( this, name ); } - public SOAPBodyElement addDocument ( Document document ) { return DomImpl.soapBody_addDocument( this, document ); } - public SOAPFault addFault ( Name name, String s ) throws SOAPException { return DomImpl.soapBody_addFault( this, name, s ); } - public SOAPFault addFault ( Name faultCode, String faultString, java.util.Locale locale ) throws SOAPException { return DomImpl.soapBody_addFault( this, faultCode, faultString, locale ); } - } - - static class SoapBodyElementXobj extends SoapElementXobj implements SOAPBodyElement - { - SoapBodyElementXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapBodyElementXobj( l, _name ); } - } - - static class SoapEnvelopeXobj extends SoapElementXobj implements SOAPEnvelope - { - SoapEnvelopeXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapEnvelopeXobj( l, _name ); } - - public SOAPBody addBody ( ) throws SOAPException { return DomImpl._soapEnvelope_addBody( this ); } - public SOAPBody getBody ( ) throws SOAPException { return DomImpl._soapEnvelope_getBody( this ); } - public SOAPHeader getHeader ( ) throws SOAPException { return DomImpl._soapEnvelope_getHeader( this ); } - public SOAPHeader addHeader ( ) throws SOAPException { return DomImpl._soapEnvelope_addHeader( this ); } - public Name createName ( String localName ) { return DomImpl._soapEnvelope_createName( this, localName ); } - public Name createName ( String localName, String prefix, String namespaceURI ) { return DomImpl._soapEnvelope_createName( this, localName, prefix, namespaceURI ); } - } - - static class SoapHeaderXobj extends SoapElementXobj implements SOAPHeader - { - SoapHeaderXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapHeaderXobj( l, _name ); } - - public Iterator examineAllHeaderElements ( ) { return DomImpl.soapHeader_examineAllHeaderElements( this ); } - public Iterator extractAllHeaderElements ( ) { return DomImpl.soapHeader_extractAllHeaderElements( this ); } - public Iterator examineHeaderElements ( String actor ) { return DomImpl.soapHeader_examineHeaderElements( this, actor ); } - public Iterator examineMustUnderstandHeaderElements ( String mustUnderstandString ) { return DomImpl.soapHeader_examineMustUnderstandHeaderElements( this, mustUnderstandString ); } - public Iterator extractHeaderElements ( String actor ) { return DomImpl.soapHeader_extractHeaderElements( this, actor ); } - public SOAPHeaderElement addHeaderElement ( Name name ) { return DomImpl.soapHeader_addHeaderElement( this, name ); } - } - - static class SoapHeaderElementXobj extends SoapElementXobj implements SOAPHeaderElement - { - SoapHeaderElementXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapHeaderElementXobj( l, _name ); } - - public void setMustUnderstand ( boolean mustUnderstand ) { DomImpl.soapHeaderElement_setMustUnderstand( this, mustUnderstand ); } - public boolean getMustUnderstand ( ) { return DomImpl.soapHeaderElement_getMustUnderstand( this ); } - public void setActor ( String actor ) { DomImpl.soapHeaderElement_setActor( this, actor ); } - public String getActor ( ) { return DomImpl.soapHeaderElement_getActor( this ); } - } - - static class SoapFaultXobj extends SoapBodyElementXobj implements SOAPFault - { - SoapFaultXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapFaultXobj( l, _name ); } - - public void setFaultString ( String faultString ) { DomImpl.soapFault_setFaultString( this, faultString ); } - public void setFaultString ( String faultString, java.util.Locale locale ) { DomImpl.soapFault_setFaultString( this, faultString, locale ); } - public void setFaultCode ( Name faultCodeName ) throws SOAPException { DomImpl.soapFault_setFaultCode( this, faultCodeName ); } - public void setFaultActor ( String faultActorString ) { DomImpl.soapFault_setFaultActor( this, faultActorString ); } - public String getFaultActor ( ) { return DomImpl.soapFault_getFaultActor( this ); } - public String getFaultCode ( ) { return DomImpl.soapFault_getFaultCode( this ); } - public void setFaultCode ( String faultCode ) throws SOAPException { DomImpl.soapFault_setFaultCode( this, faultCode ); } - public java.util.Locale getFaultStringLocale ( ) { return DomImpl.soapFault_getFaultStringLocale( this ); } - public Name getFaultCodeAsName ( ) { return DomImpl.soapFault_getFaultCodeAsName( this ); } - public String getFaultString ( ) { return DomImpl.soapFault_getFaultString( this ); } - public Detail addDetail ( ) throws SOAPException { return DomImpl.soapFault_addDetail( this ); } - public Detail getDetail ( ) { return DomImpl.soapFault_getDetail( this ); } - } - - static class SoapFaultElementXobj extends SoapElementXobj implements SOAPFaultElement - { - SoapFaultElementXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new SoapFaultElementXobj( l, _name ); } - } - - static class DetailXobj extends SoapFaultElementXobj implements Detail - { - DetailXobj ( Locale l, QName name ) { super( l, name ); } - - Xobj newNode ( Locale l ) { return new DetailXobj( l, _name ); } - - public DetailEntry addDetailEntry ( Name name ) { return DomImpl.detail_addDetailEntry( this, name ); } - public Iterator getDetailEntries ( ) { return DomImpl.detail_getDetailEntries( this ); } - } - - static class DetailEntryXobj extends SoapElementXobj implements DetailEntry - { - Xobj newNode ( Locale l ) { return new DetailEntryXobj( l, _name ); } - - DetailEntryXobj ( Locale l, QName name ) { super( l, name ); } - } - - // - // - // - - static class Bookmark implements XmlMark - { - boolean isOnList ( Bookmark head ) - { - for ( ; head != null ; head = head._next ) - if (head == this) - return true; - - return false; - } - - Bookmark listInsert ( Bookmark head ) - { - assert _next == null && _prev == null; - - if (head == null) - head = _prev = this; - else - { - _prev = head._prev; - head._prev = head._prev._next = this; - } - - return head; - } - - Bookmark listRemove ( Bookmark head ) - { - assert _prev != null && isOnList( head ); - - if (_prev == this) - head = null; - else - { - if (head == this) - head = _next; - else - _prev._next = _next; - - if (_next == null) - head._prev = _prev; - else - { - _next._prev = _prev; - _next = null; - } - } - - _prev = null; - assert _next == null; - - return head; - } - - void moveTo ( Xobj x, int p ) - { - assert isOnList( _xobj._bookmarks ); - - if (_xobj != x) - { - _xobj._bookmarks = listRemove( _xobj._bookmarks ); - x._bookmarks = listInsert( x._bookmarks ); - - _xobj = x; - } - - _pos = p; - } - - // - // XmlCursor.XmlMark method - // - - public XmlCursor createCursor ( ) - { - if (_xobj == null) - { - throw new IllegalStateException( - "Attempting to create a cursor on a bookmark that " + - "has been cleared or replaced."); - } - - return Cursor.newCursor( _xobj, _pos ); - } - - // - // - // - - Xobj _xobj; - int _pos; - - Bookmark _next; - Bookmark _prev; - - Object _key; - Object _value; - } - - // - // - // - - Locale _locale; - QName _name; - - Cur _embedded; - - Bookmark _bookmarks; - - int _bits; - - Xobj _parent; - Xobj _nextSibling; - Xobj _prevSibling; - Xobj _firstChild; - Xobj _lastChild; - - Object _srcValue, _srcAfter; - int _offValue, _offAfter; - int _cchValue, _cchAfter; - - // TODO - put this in a ptr off this node - CharNode _charNodesValue; - CharNode _charNodesAfter; - - // TODO - put this in a ptr off this node - TypeStoreUser _user; -} diff --git a/test/src/ValidatingXSRTests/checkin/TestUriValidation.java b/src/test/java/ValidatingXSRTests/checkin/TestUriValidation.java similarity index 75% rename from test/src/ValidatingXSRTests/checkin/TestUriValidation.java rename to src/test/java/ValidatingXSRTests/checkin/TestUriValidation.java index 2146feb..749bffa 100644 --- a/test/src/ValidatingXSRTests/checkin/TestUriValidation.java +++ b/src/test/java/ValidatingXSRTests/checkin/TestUriValidation.java @@ -1,29 +1,33 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package ValidatingXSRTests.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Assert; -import org.apache.xmlbeans.impl.util.XsTypeConverter; import org.apache.xmlbeans.impl.common.InvalidLexicalValueException; +import org.apache.xmlbeans.impl.util.XsTypeConverter; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * Created by Cezar Andrei (cezar dot andrei at gmail dot com) * Date: Jul 23, 2009 */ -public class TestUriValidation - extends TestCase -{ - public TestUriValidation(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(TestUriValidation.class); - } - +public class TestUriValidation { + @Test public void testLexAnyUriValid() { String[] validURIs = { @@ -66,12 +70,12 @@ public void testLexAnyUriValid() catch (RuntimeException e) { System.out.println("URI should be valid: " + validURIs[i] + " " + e.getCause().getCause().getMessage()); - Assert.assertTrue("URI should be valid: " + validURIs[i], false); - throw new IllegalStateException("URI should be valid: " + validURIs[i]); + fail("URI should be valid: " + validURIs[i]); } } } + @Test public void testLexAnyUriInvalid() { // From XQTS cvshead June 2009 @@ -98,12 +102,11 @@ public void testLexAnyUriInvalid() { XsTypeConverter.lexAnyURI(invalidURIs[i]); System.out.println("URI should be invalid: " + invalidURIs[i] ); - Assert.assertTrue("URI should be invalid: " + invalidURIs[i], false); - throw new IllegalStateException("URI should be invalid: " + invalidURIs[i]); + fail("URI should be invalid: " + invalidURIs[i]); } catch (InvalidLexicalValueException e) { - Assert.assertTrue("URI should be invalid: " + invalidURIs[i] + " " + e.getCause().getCause().getMessage(), true); + assertTrue("URI should be invalid: " + invalidURIs[i] + " " + e.getCause().getCause().getMessage(), true); } } } diff --git a/test/src/ValidatingXSRTests/checkin/ValidatingXMLStreamReaderTests.java b/src/test/java/ValidatingXSRTests/checkin/ValidatingXMLStreamReaderTests.java similarity index 92% rename from test/src/ValidatingXSRTests/checkin/ValidatingXMLStreamReaderTests.java rename to src/test/java/ValidatingXSRTests/checkin/ValidatingXMLStreamReaderTests.java index 4899afc..52bf1f2 100755 --- a/test/src/ValidatingXSRTests/checkin/ValidatingXMLStreamReaderTests.java +++ b/src/test/java/ValidatingXSRTests/checkin/ValidatingXMLStreamReaderTests.java @@ -14,51 +14,35 @@ */ package ValidatingXSRTests.checkin; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.validator.ValidatingXMLStreamReader; +import org.junit.Test; +import org.openuri.testNumerals.DocDocument; +import tools.util.JarUtil; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.Location; import javax.xml.stream.events.XMLEvent; -import javax.xml.namespace.QName; -import javax.xml.namespace.NamespaceContext; -import java.io.FileNotFoundException; -import java.io.FileInputStream; import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; -import java.io.StringReader; -import java.util.Collection; import java.util.ArrayList; +import java.util.Collection; import java.util.Iterator; -import org.apache.xmlbeans.impl.validator.ValidatingXMLStreamReader; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; - -import org.openuri.testNumerals.DocDocument; - - -import tools.util.JarUtil; +import static org.junit.Assert.assertTrue; /** * */ -public class ValidatingXMLStreamReaderTests extends TestCase -{ - public ValidatingXMLStreamReaderTests(String name) { super(name); } - - public static Test suite() { return new TestSuite(ValidatingXMLStreamReaderTests.class); } - +public class ValidatingXMLStreamReaderTests { private final static String URI_NUMERALS = "http://openuri.org/testNumerals"; + @Test public void testValidateDoc() throws FileNotFoundException, XMLStreamException,Exception { File[] files = new File[] { @@ -113,9 +97,10 @@ private static void validate(ValidatingXMLStreamReader valXsr, File file) throws if (!valXsr.isValid()) System.out.println("---------------\n"); - Assert.assertTrue("File '" + file.getName() +"' is invalid.", valXsr.isValid()); + assertTrue("File '" + file.getName() +"' is invalid.", valXsr.isValid()); } + @Test public void testValidateGlobalAtt1() throws XMLStreamException { XmlObject xo = XmlObject.Factory.newInstance(); @@ -148,10 +133,11 @@ public void testValidateGlobalAtt1() throws XMLStreamException } } - Assert.assertTrue("Global attribute validation is broken.", valXsr.isValid()); + assertTrue("Global attribute validation is broken.", valXsr.isValid()); } + @Test public void testValidateGlobalAtt2() throws XMLStreamException { @@ -178,7 +164,7 @@ public void testValidateGlobalAtt2() throws XMLStreamException System.out.println(sev + " " + err.getLine() + ":" + err.getColumn() + " " + err.getMessage() + " "); } - Assert.assertTrue("Global attribute validation 2 is broken.", valXsr.isValid()); + assertTrue("Global attribute validation 2 is broken.", valXsr.isValid()); } private static class TestXSR implements XMLStreamReader @@ -437,6 +423,7 @@ public String getPIData() } + @Test public void testValidateContent1() throws XMLStreamException { XmlObject xo = XmlObject.Factory.newInstance(); @@ -470,7 +457,7 @@ public void testValidateContent1() throws XMLStreamException } valXsr.next(); } - Assert.assertTrue("Content1 validation is broken.", valXsr.isValid()); + assertTrue("Content1 validation is broken.", valXsr.isValid()); } private static void printState(XMLStreamReader vxsr) @@ -509,7 +496,7 @@ private static void printState(XMLStreamReader vxsr) } } - + @Test public void testValidateContent2() throws XMLStreamException { String doc = "57.654321"; @@ -556,6 +543,6 @@ public void testValidateContent2() throws XMLStreamException System.out.println(sev + " " + err.getLine() + ":" + err.getColumn() + " " + err.getMessage() + " "); } - Assert.assertTrue("Content2 validation is broken.", valXsr.isValid()); + assertTrue("Content2 validation is broken.", valXsr.isValid()); } } diff --git a/test/src/ValidatingXSRTests/common/TestPrefixResolver.java b/src/test/java/ValidatingXSRTests/common/TestPrefixResolver.java similarity index 100% rename from test/src/ValidatingXSRTests/common/TestPrefixResolver.java rename to src/test/java/ValidatingXSRTests/common/TestPrefixResolver.java diff --git a/src/test/java/ValidatingXSRTests/detailed/ValidatingXmlStreamReaderTests.java b/src/test/java/ValidatingXSRTests/detailed/ValidatingXmlStreamReaderTests.java new file mode 100755 index 0000000..ba3dbe3 --- /dev/null +++ b/src/test/java/ValidatingXSRTests/detailed/ValidatingXmlStreamReaderTests.java @@ -0,0 +1,486 @@ + +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ValidatingXSRTests.detailed; + +import com.foo.sample.HeadingDocument; +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.impl.validator.ValidatingXMLStreamReader; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.openuri.test.location.LocationDocument; +import org.openuri.test.mixedContent.LetterDocument; +import org.openuri.test.mixedContent.NoMixedDocument; +import org.openuri.test.person.Name; +import org.openuri.test.person.PersonDocument; +import org.openuri.test.person.PersonType; +import tools.util.JarUtil; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.events.XMLEvent; +import javax.xml.stream.util.StreamReaderDelegate; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +// Schema Imports + + +public class ValidatingXmlStreamReaderTests { + + // Base variable + static String casesLoc = "xbean/ValidatingStream/"; + + ////////////////////////////////////////////////////////////////////// + // Tests + + // NOTE: Tests that use getCasesFile are reading files + // from cases/qatest/files/xbean + // Tests that use getResourceFromJar are getting the contents of + // the file in the same location, but packaged into xmlcases.jar + // SO, any change to the xml files for these tests will not be + // reflected till they make it into xmlcases.jar. (ant build.xmlcases) + @Test + public void testDocWithNoSchema() throws Exception { + checkDocIsInvalid(getCasesFile(casesLoc + "po.xml"), null); + } + + @Test + public void testValidLocationDoc() throws Exception { + checkDocIsValid(getCasesFile(casesLoc + "location.xml"), null); + } + + @Test + public void testInvalidLocationDoc() throws Exception { + checkDocIsInvalid(getCasesFile(casesLoc + "location-inv.xml"), LocationDocument.type); + } + + @Test + public void testValidPersonDoc() throws Exception { + checkDocIsValid(getCasesFile(casesLoc + "person.xml"), PersonDocument.type); + } + + @Test + public void testInvalidPersonDoc() throws Exception { + checkDocIsInvalid(getCasesFile(casesLoc + "person-inv.xml"), PersonDocument.type); + } + + @Test + public void testValidMixedContentDoc() throws Exception { + checkDocIsValid(getCasesFile(casesLoc + "mixed-content.xml"), + LetterDocument.type); + } + + @Test + public void testInvalidNomixedContentDoc() throws Exception { + checkDocIsInvalid(getCasesFile(casesLoc + "nomixed-content-inv.xml"), + NoMixedDocument.type); + } + + @Test + public void testInvalidMissingAttributeDoc() throws Exception { + checkDocIsInvalid(getCasesFile(casesLoc + "foo-inv.xml"), + HeadingDocument.type); + } + + + @Test + public void testContentName() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-frag.xml"); + SchemaType type = Name.type; + + assertTrue("Xml-fragment is not valid:\n" + sXml, + checkContent(sXml, type, true)); + } + + + // Same as testContentName.. expect the xml has no chars before the first + // start element + @Test + public void testContentName2() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-frag2.xml"); + SchemaType type = Name.type; + + assertTrue("Xml-fragment is not valid:\n" + sXml, + checkContent(sXml, type, true)); + } + + @Test + public void testContentSibling() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-sibling.xml"); + SchemaType type = PersonType.type; + assertTrue("Xml-fragment is not valid:\n" + sXml, + checkContent(sXml, type, true)); + } + + @Test + public void testInvalidContentSibling() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-sibling-inv.xml"); + SchemaType type = PersonType.type; + assertTrue("Invalid Xml-fragment is getting validated:\n" + sXml, + !checkContent(sXml, type, true)); + } + + @Test + public void testValidXsiType() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-justname.xml"); + SchemaType type = Name.type; + assertTrue("Xml-fragment is not valid:\n" + sXml, + checkContent(sXml, type, true)); + } + + @Test + public void testInvalidXsiType() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-justname-inv.xml"); + SchemaType type = Name.type; + assertTrue("Invalid Xml-fragment is getting validated:\n" + sXml, + !checkContent(sXml, type, true)); + } + + @Test + public void testIncompatibleXsiType() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "person-xsi-inv.xml"); + SchemaType type = Name.type; + assertTrue("Invalid Xml-fragment is getting validated:\n" + sXml, + !checkContent(sXml, type, true)); + } + + @Test + public void testValidMixedContent() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "mixed-content.xml"); + SchemaType type = org.openuri.test.mixedContent.LetterType.type; + assertTrue("Xml-fragment is not valid:\n" + sXml, + checkContent(sXml, type, true)); + } + + @Test + @Ignore + public void testGlobalAttribute() throws Exception { + String sXml = JarUtil.getResourceFromJar(casesLoc + "global-attr.xml"); + + assertTrue("Global Attribute test failed:\n", + checkContent(sXml, null, true)); + } + + // Tests for increasing code-coverage metrics + @Test + public void testValXsrReuse() throws Exception { + Collection errors = new ArrayList(); + File[] xmls = new File[2]; + xmls[0] = getCasesFile(casesLoc + "person.xml"); + xmls[1] = getCasesFile(casesLoc + "person-inv.xml"); + SchemaType type = PersonDocument.type; + + boolean[] ret = runValidator(xmls, type, errors); + + String common = "Test for ValidatingXmlStreamReader reuse failed"; + assertEquals(common + "\nReturn value has more than 2 elements", 2, ret.length); + assertTrue(common + "\nExpected: true & false. Actual: " + + ret[0] + " & " + ret[1], + ret[0] && !ret[1]); + } + + + public void testIllegalEvent() throws Exception { + // Will require writing another XSR wrapper.. albeit simple + } + + /*/ + public void testWalk() throws Exception { + walkXml(getCasesFile(casesLoc + "global-attr.xml")); + System.out.println(); + walkXml(getCasesFile(casesLoc + "person-sibling.xml")); + } + // */ + ////////////////////////////////////////////////////////////////////// + // Utility Methods + private void walkXml(File xml) throws Exception { + XMLStreamReader xr = XMLInputFactory.newInstance(). + createXMLStreamReader(new FileInputStream(xml)); + + //xsr.nextTag(); + XmlContentTestXSR xsr = new XmlContentTestXSR(xr); + + while(xsr.hasNext()) + { + int type = xsr.next(); + System.out.print(type); + //* + if (type == XMLEvent.START_ELEMENT) + { + System.out.print("\n" + xsr.getLocalName() + " "); + } + if (type == XMLEvent.END_ELEMENT) + { + System.out.println("/" + xsr.getLocalName()); + } + if (type == XMLEvent.CHARACTERS) + { + char[] arr = xsr.getTextCharacters(); + String str = new String(arr); + System.out.print("Char:" + str + " "); + } + //*/ + } + } + + private boolean runValidator(File xml, + SchemaType type, + Collection errors) + throws IllegalArgumentException, Exception + { + if (errors == null) + throw new IllegalArgumentException( + "Collection object cannot be null"); + + XMLStreamReader xsr = XMLInputFactory.newInstance(). + createXMLStreamReader(new FileInputStream(xml)); + + ValidatingXMLStreamReader valXsr = new ValidatingXMLStreamReader(); + valXsr.init(xsr, + false, + type, + XmlBeans.typeLoaderForClassLoader(ValidatingXMLStreamReader.class.getClassLoader()), + null, + errors); + + // Walk through the xml + while (valXsr.hasNext()) + valXsr.next(); + + return valXsr.isValid(); + //return true; + } + + // This method is primarily for testing re-use of the ValXSR object. + // but could come in handy later.. + private boolean[] runValidator(File[] xml, + SchemaType type, + Collection errors) + throws IllegalArgumentException, Exception + { + if (errors == null) + throw new IllegalArgumentException( + "Collection object cannot be null"); + ValidatingXMLStreamReader valXsr = new ValidatingXMLStreamReader(); + boolean[] retArray = new boolean[xml.length]; + + for (int i = 0; i < xml.length; i++) + { + XMLStreamReader xsr = XMLInputFactory.newInstance(). + createXMLStreamReader(new FileInputStream(xml[i])); + + valXsr.init(xsr, + false, + type, + XmlBeans.typeLoaderForClassLoader(ValidatingXMLStreamReader.class.getClassLoader()), + null, + errors); + + // Walk through the xml + while (valXsr.hasNext()) + valXsr.next(); + + retArray[i] = valXsr.isValid(); + } + + return retArray; + } + + protected void checkDocIsValid(File file, SchemaType type) throws Exception { + Collection errors = new ArrayList(); + boolean isValid = runValidator(file, type, errors); + + tools.xml.Utils.printXMLErrors(errors); + Assert.assertTrue("File '" + file.getName() + "' is invalid.", isValid); + } + + + protected void checkDocIsInvalid(File file, SchemaType type) throws Exception { + Collection errors = new ArrayList(); + + boolean isValid = runValidator(file, type, errors); + assertTrue("File '" + file.getName() + "' is valid, but was expecting invalid.", + !isValid); + } + + + public boolean checkContent(String fragment, + SchemaType type, + boolean printErrors) throws Exception { + XMLStreamReader xsr = XMLInputFactory.newInstance(). + createXMLStreamReader(new StringReader(fragment)); + + XmlContentTestXSR cxsr = new XmlContentTestXSR(xsr); + Collection errors = new ArrayList(); + + ValidatingXMLStreamReader valXsr = new ValidatingXMLStreamReader(); + valXsr.init(cxsr, + false, + type, + XmlBeans.typeLoaderForClassLoader(ValidatingXMLStreamReader.class.getClassLoader()), + null, + errors); + + // Walk through the xml + while (valXsr.hasNext()) + valXsr.next(); + + if (!valXsr.isValid()) + { + if (printErrors) + tools.xml.Utils.printXMLErrors(errors); + return false; + } + return true; + } + + + private static File getCasesFile(String path) + throws java.io.IOException + { + if (path.length()==0) + throw new IOException("getCasesFile was called with path of len 0"); + return JarUtil.getResourceFromJarasFile(path); + //return new File(casesRoot + path); + } + + ///////////////////////////////////////////////////////////////////////// + // XmlStreamReader extension for content Validation + // will not work for Global Attribute + public class XmlContentTestXSR + extends StreamReaderDelegate + implements XMLStreamReader + { + private static final int TAGOPEN = 100; + private static final int TAGCLOSE = 101; + private static final int UNDEFINED = 99; + private static final int ATTRIBUTE = 102; + private static final int ENDCONTENT = 103; + + int state = -1; + int depth = -1; + boolean initialized = false; + int attributeCount = -1; + boolean hasAttributes = false; + + // Constructor Wrappers + public XmlContentTestXSR(XMLStreamReader xsr) + throws XMLStreamException + { + super(xsr); + } + + + public boolean hasNext() + { + if (state == UNDEFINED || state == ENDCONTENT) + return false; + + if (!initialized) // next() has not been called yet + return true; + + + + return true; + } + + public int next() + throws XMLStreamException + { + int _next; + if (!initialized) + { + // First time next() is called.. + // Scan for the first XMLEvent.START_ELEMENT + _next = UNDEFINED; + while ((super.hasNext()) && (_next != XMLEvent.START_ELEMENT)) + _next = super.next(); + + if (_next != XMLEvent.START_ELEMENT) + throw new XMLStreamException( + "Could not find a start element"); + initialized = true; + + // Now move past the first tag + state = TAGOPEN; + depth = 1; + + if ((attributeCount = super.getAttributeCount()) > 0) + { + // The first element has attributes.. this is part of + // the content. So the first event should XMLEvent.ATTRIBUTE + _next = XMLEvent.ATTRIBUTE; + } + else + { + // return super.next(); + /* + If content is then we will have returned + END_ELEMENT above, without ever generating a START_ELEMENT + In this case probably we should detect this and return a + END_DOCUMENT + */ + _next = super.next(); + if (_next == XMLEvent.END_ELEMENT) + { + _next = XMLEvent.END_DOCUMENT; + state = ENDCONTENT; + } + } + return _next; + } + + _next = super.next(); + switch (_next) + { + case XMLEvent.START_ELEMENT: + state = TAGOPEN; + depth++; + break; + + case XMLEvent.END_ELEMENT: + --depth; + if (depth < 0 && state == TAGOPEN) + { + throw new XMLStreamException( + "Illegal XML Stream state"); + } + else if (depth == 0 && state == TAGOPEN) + { + state = ENDCONTENT; + // at this point we will return ENDDOCUMENT + _next = XMLEvent.END_DOCUMENT; + } + break; + } + + return _next; + } + + } + + +} diff --git a/test/src/ValidatingXSRTests/detailed/ValidatorUtilTests.java b/src/test/java/ValidatingXSRTests/detailed/ValidatorUtilTests.java similarity index 82% rename from test/src/ValidatingXSRTests/detailed/ValidatorUtilTests.java rename to src/test/java/ValidatingXSRTests/detailed/ValidatorUtilTests.java index 4e7ad93..e63a7d5 100755 --- a/test/src/ValidatingXSRTests/detailed/ValidatorUtilTests.java +++ b/src/test/java/ValidatingXSRTests/detailed/ValidatorUtilTests.java @@ -15,31 +15,19 @@ package ValidatingXSRTests.detailed; -import junit.framework.TestCase; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.events.XMLEvent; -import java.util.Collection; -import java.util.ArrayList; - +import ValidatingXSRTests.common.TestPrefixResolver; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.impl.validator.ValidatorUtil; +import org.junit.Test; import tools.xml.Utils; -import ValidatingXSRTests.common.TestPrefixResolver; -public class ValidatorUtilTests - extends TestCase -{ - public ValidatorUtilTests(String name) - { - super(name); - } - - // Base variable - static String casesLoc = "xbean/ValidatingStream/"; +import java.util.ArrayList; +import java.util.Collection; +import static org.junit.Assert.fail; +public class ValidatorUtilTests { + @Test public void testValidQName() throws Exception { @@ -58,9 +46,8 @@ public void testValidQName() } - public void testInvalidQName() - throws Exception - { + @Test + public void testInvalidQName() { String xml = "foo:bz"; TestPrefixResolver pRes = new TestPrefixResolver("foo", "http://openuri.org/test/My"); SchemaType type = org.openuri.test.simType.QNameType.type; diff --git a/src/test/java/common/Common.java b/src/test/java/common/Common.java new file mode 100644 index 0000000..a19bbb8 --- /dev/null +++ b/src/test/java/common/Common.java @@ -0,0 +1,317 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package common; + +import org.apache.xmlbeans.*; +import org.junit.Assert; + +import javax.xml.namespace.QName; +import java.io.File; +import java.io.IOException; +import java.util.*; + +import static org.junit.Assert.assertNotNull; + +public class Common { + public static final String NEWLINE = System.getProperty("line.separator"); + public static final String P = File.separator; + + public static String FWROOT = getRootFile(); + public static String CASEROOT = getCaseLocation(); + public static String XBEAN_CASE_ROOT = getCaseLocation() + P + "xbean"; + + //location of files under "cases folder" + public static String OUTPUTROOT = FWROOT + P + "build" + P + "test" + P + "output"; + + + public final LinkedList errorList = new LinkedList(); + public final XmlOptions xmOpts = new XmlOptions(); + + public Common() { + xmOpts.setErrorListener(errorList); + } + + /** + * If System.property for 'xbean.rootdir' == null + * use '.' as basePath + * '.' should be where the build.xml file lives + * + * @return + * @throws IllegalStateException + */ + public static String getRootFile() throws IllegalStateException { + String baseDir = System.getProperty("xbean.rootdir"); + if (baseDir == null) { + return new File(".").getAbsolutePath(); + } else { + return new File(baseDir).getAbsolutePath(); + } + } + + /** + * If System.property for 'cases.location' == null + * use '.' as basePath and add src/test/resources. + * should be where the build.xml file lives + * + * @throws IllegalStateException + */ + public static String getCaseLocation() throws IllegalStateException { + String baseDir = System.getProperty("cases.location"); + if (baseDir == null) { + return new File("." + P + "src" + P + "test" + P + "resources").getAbsolutePath(); + } else { + return new File(baseDir).getAbsolutePath(); + } + } + + /** + * Gets a case file from under CASEROOT with location passed in as strPath + * + * @param strPath + * @return file Object for references location + */ + public static File xbeanCase(String strPath) { + return (new File(CASEROOT, strPath)); + } + + /** + * Creates directory under output directory as noted by strPath + * + * @param strPath + * @return File Object specified by strPath + */ + public static File xbeanOutput(String strPath) { + File result = (new File(OUTPUTROOT, strPath)); + File parentdir = result.getParentFile(); + parentdir.mkdirs(); + return result; + } + + /** + * Recursively deletes files under specified directory + * + * @param dir + */ + public static void deltree(File dir) { + if (dir.exists()) { + if (dir.isDirectory()) { + String[] list = dir.list(); + for (int i = 0; i < list.length; i++) { + deltree(new File(dir, list[i])); + } + } + if (!dir.delete()) { + System.out.println("Could not delete " + dir); + } + //throw new IllegalStateException("Could not delete " + dir); + } + } + + /** + * Convenience method for displaying errorListener contents after validation + * + * @param errors + */ + public static void listErrors(List errors) { + for (int i = 0; i < errors.size(); i++) { + XmlError error = (XmlError) errors.get(i); + if (error.getSeverity() == XmlError.SEVERITY_ERROR) { + System.out.println(error.toString()); + } + } + } + + /** + * check list of errors/warnings/msgs and print them. Return true if errors found + * + * @param errors + * @return + */ + public static boolean printOptionErrMsgs(Collection errors) { + boolean errFound = false; + if (!errors.isEmpty()) { + for (Iterator i = errors.iterator(); i.hasNext(); ) { + XmlError eacherr = (XmlError) i.next(); + int errSeverity = eacherr.getSeverity(); + if (errSeverity == XmlError.SEVERITY_ERROR) { + System.out.println("Err Msg (s) at line #" + eacherr.getLine() + ": " + eacherr.getMessage()); + errFound = true; + } else if (errSeverity == XmlError.SEVERITY_WARNING) { + System.out.println("Warning Msg (s) at line #" + eacherr.getLine() + ": " + eacherr.getMessage()); + } else if (errSeverity == XmlError.SEVERITY_INFO) { + System.out.println("Info Msg (s) at line #" + eacherr.getLine() + ": " + eacherr.getMessage()); + } + } + errors.clear(); + } + return errFound; + } + + /** + * Validate schemas to instance based on the docType + * + * @param schemas + * @param instances + * @param docType + * @throws Exception + */ + public static void validateInstance(String[] schemas, String[] instances, QName docType) throws Exception { + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + XmlOptions options = new XmlOptions(); + + if (docType != null) { + SchemaType docSchema = stl.findDocumentType(docType); + Assert.assertTrue(docSchema != null); + options.setDocumentType(docSchema); + } + + for (int i = 0; i < instances.length; i++) { + XmlObject x = + stl.parse((String) instances[i], null, options); + + //if (!startOnDocument) { + // XmlCursor c = x.newCursor(); + // c.toFirstChild(); + // x = c.getObject(); + // c.dispose(); + //} + + List xel = new ArrayList<>(); + + options.setErrorListener(xel); + + boolean isValid = x.validate(options); + + if (!isValid) { + StringBuilder errorTxt = new StringBuilder("Invalid doc, expected a valid doc: "); + errorTxt.append("Instance(" + i + "): "); + errorTxt.append(x.xmlText()); + errorTxt.append("Errors: "); + for (XmlError xmlError : xel) { + errorTxt.append(xmlError + "\n"); + } + System.err.println(errorTxt.toString()); + throw new Exception("Instance not valid\n" + errorTxt.toString()); + } + } + } + + + /** + * Convenience method for creating an XmlObject from a String + * + * @param XsdAsString + * @return + */ + public static XmlObject compileXsdString(String XsdAsString) { + XmlObject xobj = null; + try { + xobj = XmlObject.Factory.parse(XsdAsString); + } catch (XmlException xme) { + if (!xme.getErrors().isEmpty()) { + for (Iterator itr = xme.getErrors().iterator(); itr.hasNext(); ) { + System.out.println("Parse Errors :" + itr.next()); + } + } + } finally { + assertNotNull(xobj); + return xobj; + } + } + + + /** + * Convenience method for creating an XmlObject from a File referenced as a String of the path to the file + * + * @param XsdFilePath + * @return + */ + public static XmlObject compileXsdFile(String XsdFilePath) { + XmlObject xobj = null; + try { + xobj = XmlObject.Factory.parse(new File(XsdFilePath)); + } catch (XmlException xme) { + if (!xme.getErrors().isEmpty()) { + for (Iterator itr = xme.getErrors().iterator(); itr.hasNext(); ) { + System.out.println("Parse Errors :" + itr.next()); + } + } + } catch (IOException ioe) { + ioe.printStackTrace(); + ioe.getMessage(); + } finally { + assertNotNull(xobj); + return xobj; + } + } + + /** + * Convenience method to create a SchemaTypeLoader from a set of xsds + * + * @param schemas + * @return + * @throws Exception + */ + public static SchemaTypeLoader makeSchemaTypeLoader(String[] schemas) + throws Exception { + XmlObject[] schemaDocs = new XmlObject[schemas.length]; + + for (int i = 0; i < schemas.length; i++) { + schemaDocs[i] = + XmlObject.Factory.parse(schemas[i]); + } + + return XmlBeans.loadXsd(schemaDocs); + } + + /** + * Is the JVM being used a 1.4 version? + * Used for tests involving the javasource=1.5 compilation setting + * + * @return true if java.version starts with 1.4 + */ + public static boolean isJDK14() { + return System.getProperty("java.version").startsWith("1.4"); + } + + /** + * Convenience class for creating tests in a multithreaded env + */ + public static abstract class TestThread extends Thread { + protected Throwable _throwable; + protected boolean _result; + protected XmlOptions xm; + protected ArrayList errors; + + public TestThread() { + xm = new XmlOptions(); + ArrayList errors = new ArrayList(); + xm.setErrorListener(errors); + xm.setValidateOnSet(); + } + + public Throwable getException() { + return _throwable; + } + + public boolean getResult() { + return _result; + } + + + } + + +} diff --git a/test/src/compile/scomp/checkin/CompilationTests.java b/src/test/java/compile/scomp/checkin/CompilationTests.java similarity index 75% rename from test/src/compile/scomp/checkin/CompilationTests.java rename to src/test/java/compile/scomp/checkin/CompilationTests.java index 692f2c5..4d294af 100644 --- a/test/src/compile/scomp/checkin/CompilationTests.java +++ b/src/test/java/compile/scomp/checkin/CompilationTests.java @@ -15,53 +15,47 @@ package compile.scomp.checkin; -import junit.framework.TestCase; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; +import common.Common; +import compile.scomp.common.CompileCommon; +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.tool.SchemaCodeGenerator; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; import org.apache.xmlbeans.impl.tool.CodeGenUtil; import org.apache.xmlbeans.impl.tool.Diff; +import org.apache.xmlbeans.impl.tool.SchemaCodeGenerator; +import org.apache.xmlbeans.impl.tool.SchemaCompiler; import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType; -import org.apache.xmlbeans.SchemaBookmark; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.net.URL; +import java.net.URLClassLoader; import java.util.ArrayList; -import java.util.List; import java.util.Arrays; import java.util.Collections; +import java.util.List; -import tools.util.TestRunUtil; - - -public class CompilationTests extends TestCase -{ - public CompilationTests(String name) { super(name); } - public static Test suite() { return new TestSuite(CompilationTests.class); } +import static common.Common.getRootFile; +import static org.junit.Assert.*; - public void testJ2EE() throws Throwable - { +public class CompilationTests { + @Test + public void testJ2EE() throws Throwable { deltree(xbeanOutput("compile/scomp/j2ee")); // First, compile schema File srcdir = xbeanOutput("compile/scomp/j2ee/j2eeconfigxml/src"); File classesdir = xbeanOutput("compile/scomp/j2ee/j2eeconfigxml/classes"); File outputjar = xbeanOutput("compile/scomp/j2ee/j2eeconfigxml.jar"); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setXsdFiles(new File[] { + params.setXsdFiles(new File[]{ xbeanCase("j2ee/application-client_1_4.xsd"), xbeanCase("j2ee/application_1_4.xsd"), xbeanCase("j2ee/connector_1_5.xsd"), @@ -81,13 +75,13 @@ public void testJ2EE() throws Throwable StringWriter message = new StringWriter(); if (!result) dumpErrors(errors, new PrintWriter(message)); - Assert.assertTrue("Build failed:" + message, result); - Assert.assertTrue("Cannot find " + outputjar, outputjar.exists()); + assertTrue("Build failed:" + message, result); + assertTrue("Cannot find " + outputjar, outputjar.exists()); } - public void testIncrementalCompilation() throws Throwable - { - File[] files = new File[] { + @Test + public void testIncrementalCompilation() throws Throwable { + File[] files = new File[]{ xbeanCase("incr/incr1.xsd"), xbeanCase("incr/incr3.xsd"), xbeanCase("incr/incr4.xsd"), @@ -105,14 +99,14 @@ public void testIncrementalCompilation() throws Throwable schemas[i] = SchemaDocument.Factory.parse(files[i]).getSchema(); // Compile incrementally // Initial compile - schemas[n - 2] = SchemaDocument.Factory.parse(files[n-2]).getSchema(); + schemas[n - 2] = SchemaDocument.Factory.parse(files[n - 2]).getSchema(); List errors = new ArrayList(); XmlOptions options = (new XmlOptions()).setErrorListener(errors); SchemaTypeSystem builtin = XmlBeans.getBuiltinTypeSystem(); system = XmlBeans.compileXsd(schemas, builtin, options); Assert.assertNotNull("Compilation failed during inititial compile.", system); System.out.println("-= Initial Compile =-"); - + for (int i = 0; i < system.globalTypes().length; i++) { System.out.println("[" + i + "]-" + system.globalTypes()[i].getName()); } @@ -126,7 +120,7 @@ public void testIncrementalCompilation() throws Throwable // Incremental compile String url = schemas[n - 2].documentProperties().getSourceName(); SchemaDocument.Schema[] schemas1 = new SchemaDocument.Schema[1]; - schemas1[0] = SchemaDocument.Factory.parse(files[n-1]).getSchema(); + schemas1[0] = SchemaDocument.Factory.parse(files[n - 1]).getSchema(); schemas1[0].documentProperties().setSourceName(url); errors.clear(); system = XmlBeans.compileXsd(system, schemas1, builtin, options); @@ -144,7 +138,7 @@ public void testIncrementalCompilation() throws Throwable } // Now compile non-incrementally for the purpose of comparing the result errors.clear(); - schemas[n-2] = schemas1[0]; + schemas[n - 2] = schemas1[0]; system = XmlBeans.compileXsd(schemas, builtin, options); Assert.assertNotNull("Compilation failed during reference compile.", system); SchemaCodeGenerator.saveTypeSystem(system, out, null, null, null); @@ -166,19 +160,18 @@ public void testIncrementalCompilation() throws Throwable errors.clear(); Diff.dirsAsTypeSystems(out, outincr, errors); System.setProperty("xmlbeans.diff.diffIndex", oldPropValue == null ? "true" : oldPropValue); - if (errors.size() > 0) - { + if (errors.size() > 0) { StringWriter message = new StringWriter(); for (int i = 0; i < errors.size(); i++) message.write(((String) errors.get(i)) + "\n"); - Assert.fail("Differences encountered:" + message); + fail("Differences encountered:" + message); } } - public void testSchemaBookmarks() throws Throwable - { - File srcSchema = xbeanCase("simple/person.xsd"); + @Test + public void testSchemaBookmarks() throws Throwable { + File srcSchema = xbeanCase("../../simple/person/person.xsd"); // Parse SchemaDocument.Schema parsed = SchemaDocument.Factory.parse(srcSchema).getSchema(); // Navigate to the type definition @@ -186,12 +179,11 @@ public void testSchemaBookmarks() throws Throwable boolean found = false; int i; for (i = 0; i < cTypes.length; i++) - if ("person".equals(cTypes[i].getName())) - { + if ("person".equals(cTypes[i].getName())) { found = true; break; } - Assert.assertTrue("Could not find the \"person\" complex type", found); + assertTrue("Could not find the \"person\" complex type", found); // Set the bookmark SchemaBookmark sb = new SchemaBookmark("MyBookmark"); cTypes[i].newCursor().setBookmark(sb); @@ -207,44 +199,45 @@ public void testSchemaBookmarks() throws Throwable Assert.assertEquals("MyBookmark", val); } - - public void __testSimple() throws Throwable - { + @Test + public void testSimple() throws Throwable { deltree(xbeanOutput("compile/scomp/simple")); // First, compile schema // First, compile schema - File inputfile1 = xbeanCase("simple/person.xsd"); - File inputfile2 = xbeanCase("simple/simplec.xsd"); + File inputfile1 = xbeanCase("../../simple/person/person.xsd"); + File inputfile2 = xbeanCase("../../simple/person/simplec.xsd"); - File srcdir = xbeanOutput("simple/simpletypes/src"); + File srcdir = xbeanOutput("simple/simpletypes/src"); File classesdir = xbeanOutput("compile/scomp/simple/simpletypes/classes"); File outputjar = xbeanOutput("compile/scomp/simple/simpletypes.jar"); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setXsdFiles(new File[] { inputfile1, inputfile2 }); + params.setXsdFiles(new File[]{inputfile1, inputfile2}); params.setSrcDir(srcdir); params.setClassesDir(classesdir); params.setOutputJar(outputjar); - Assert.assertTrue("Build failed", SchemaCompiler.compile(params)); + assertTrue("Build failed", SchemaCompiler.compile(params)); // Then, compile java classes - File javasrc = xbeanCase("simple/javasrc"); + File javasrc = new File(CompileCommon.fileLocation+"/simple"); File javaclasses = xbeanOutput("compile/scomp/simple/javaclasses"); javaclasses.mkdirs(); - List testcp = new ArrayList(); - testcp.addAll(Arrays.asList(CodeGenUtil.systemClasspath())); + List testcp = new ArrayList(Arrays.asList(CodeGenUtil.systemClasspath())); testcp.add(outputjar); - CodeGenUtil.externalCompile(Arrays.asList(new File[] { javasrc }), javaclasses, (File[])testcp.toArray(new File[testcp.size()]), true); + CodeGenUtil.externalCompile(Arrays.asList(javasrc), javaclasses, testcp.toArray(new File[0]), true); // Then run the test - testcp.add(javaclasses); - TestRunUtil.run("SimplePersonTest", new File[] { outputjar, javaclasses }); + URLClassLoader childcl = new URLClassLoader(new URL[]{outputjar.toURI().toURL()}, CompilationTests.class.getClassLoader()); + Class cl = childcl.loadClass("scomp.simple.SimplePersonTest"); + Result result = JUnitCore.runClasses(cl); + assertEquals(0, result.getFailureCount()); } - public void __testDownload() throws Throwable - { + @Test + @Ignore + public void testDownload() throws Throwable { deltree(xbeanOutput("compile/scomp/include")); { @@ -253,14 +246,14 @@ public void __testDownload() throws Throwable File classesdir = xbeanOutput("compile/scomp/include/shouldfail/classes"); File outputjar = xbeanOutput("compile/scomp/include/shouldfail.jar"); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setXsdFiles(new File[] { - xbeanCase ("compile/scomp/j2ee/j2ee_1_4.xsd") + params.setXsdFiles(new File[]{ + xbeanCase("compile/scomp/j2ee/j2ee_1_4.xsd") }); params.setSrcDir(srcdir); params.setClassesDir(classesdir); params.setOutputJar(outputjar); - Assert.assertTrue("Build should have failed", !SchemaCompiler.compile(params)); - Assert.assertTrue("Should not have created " + outputjar, !outputjar.exists()); + assertTrue("Build should have failed", !SchemaCompiler.compile(params)); + assertTrue("Should not have created " + outputjar, !outputjar.exists()); } { @@ -270,35 +263,34 @@ public void __testDownload() throws Throwable File outputjar = xbeanOutput("compile/scomp/include/shouldsucceed.jar"); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); params.setDownload(true); - params.setXsdFiles(new File[] { + params.setXsdFiles(new File[]{ xbeanCase("compile/scomp/j2ee/j2ee_1_4.xsd") }); params.setSrcDir(srcdir); params.setClassesDir(classesdir); params.setOutputJar(outputjar); - Assert.assertTrue("Build failed", SchemaCompiler.compile(params)); - Assert.assertTrue("Cannout find " + outputjar, outputjar.exists()); + assertTrue("Build failed", SchemaCompiler.compile(params)); + assertTrue("Cannout find " + outputjar, outputjar.exists()); } } - public void __testPricequote() throws Throwable - { + @Test + public void testPricequote() throws Throwable { deltree(xbeanOutput("compile/scomp/pricequote")); // First, compile schema File srcdir = xbeanOutput("compile/scomp/pricequote/src"); File classesdir = xbeanOutput("compile/scomp/pricequote/classes"); File outputjar = xbeanOutput("compile/scomp/pricequote/pricequote.jar"); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setXsdFiles(new File[] { - xbeanCase("compile/scomp/pricequote/PriceQuote.xsd") }); + params.setXsdFiles(new File[]{xbeanCase("pricequote/PriceQuote.xsd")}); params.setSrcDir(srcdir); params.setClassesDir(classesdir); params.setOutputJar(outputjar); - Assert.assertTrue("Build failed "+fwroot, SchemaCompiler.compile(params)); - Assert.assertTrue("Cannout find " + outputjar, outputjar.exists()); + assertTrue("Build failed " + fwroot, SchemaCompiler.compile(params)); + assertTrue("Cannout find " + outputjar, outputjar.exists()); } - static String [] invalidSchemas = { + private static String[] invalidSchemas = { "\n" + " \n" + " \n" + @@ -336,7 +328,7 @@ public void __testPricequote() throws Throwable "\n", }; - static String [] validSchemas = { + static String[] validSchemas = { "\n" + " \n" + " \n" + @@ -374,36 +366,33 @@ public void __testPricequote() throws Throwable "\n", }; - public void __testFinal() throws Throwable - { + @Test + public void testFinal() throws Throwable { SchemaDocument[] schemas = new SchemaDocument[invalidSchemas.length]; // Parse the invalid schema files - for (int i = 0 ; i < invalidSchemas.length ; i++) + for (int i = 0; i < invalidSchemas.length; i++) schemas[i] = SchemaDocument.Factory.parse(invalidSchemas[i]); // Now compile the invalid schemas, test that they fail - for (int i = 0 ; i < schemas.length ; i++) - { + for (int i = 0; i < schemas.length; i++) { try { - XmlBeans.loadXsd(new XmlObject[] {schemas[i]}); + XmlBeans.loadXsd(new XmlObject[]{schemas[i]}); fail("Schema should have failed to compile:\n" + invalidSchemas[i]); + } catch (XmlException success) { } - catch (XmlException success) {} } // Parse the valid schema files schemas = new SchemaDocument[validSchemas.length]; - for (int i = 0 ; i < validSchemas.length ; i++) + for (int i = 0; i < validSchemas.length; i++) schemas[i] = SchemaDocument.Factory.parse(validSchemas[i]); // Compile the valid schemas. They should not fail - for (int i = 0 ; i < schemas.length ; i++) - { + for (int i = 0; i < schemas.length; i++) { try { XmlBeans.loadXsd(new XmlObject[]{schemas[i]}); - } - catch (XmlException fail) { + } catch (XmlException fail) { fail("Failed to compile schema:\n" + validSchemas[i]); } } @@ -411,70 +400,46 @@ public void __testFinal() throws Throwable //TESTENV: - private static File fwroot = getRootFile(); - private static File caseroot = new File(fwroot, "test/cases"); + private static final File fwroot = new File(getRootFile()); + private static final File caseroot = new File(Common.getCaseLocation()); //location of files under "cases folder" - static String fileLocation="/xbean/compile/scomp/"; - private static File outputroot = new File(fwroot, "build/test/output"); + private static final String fileLocation = CompileCommon.fileLocation; + private static final File outputroot = new File(fwroot, "build/test/output"); - private static void dumpErrors(List errors, PrintWriter out) - { + private static void dumpErrors(List errors, PrintWriter out) { // Display the errors - for (int i = 0; i < errors.size(); i++) - { + for (int i = 0; i < errors.size(); i++) { XmlError error = (XmlError) errors.get(i); if (error.getSeverity() == XmlError.SEVERITY_ERROR) out.println(error.toString()); } } - public static File getRootFile() throws IllegalStateException - { - try - { - return new File( System.getProperty( "xbean.rootdir" ) ).getCanonicalFile(); - } - catch( IOException e ) - { - throw new IllegalStateException(e.toString()); - } - } - - public static File xbeanCase(String str) - { - return (new File(caseroot.getPath()+fileLocation, str)); + private static File xbeanCase(String str) { + return new File(fileLocation, str); } - public static File xbeanOutput(String str) - { + private static File xbeanOutput(String str) { File result = (new File(outputroot, str)); File parentdir = result.getParentFile(); parentdir.mkdirs(); return result; } - public static void deltree(File dir) - throws InterruptedException - { - if (dir.exists()) - { - if (dir.isDirectory()) - { + private static void deltree(File dir) + throws InterruptedException { + if (dir.exists()) { + if (dir.isDirectory()) { String[] list = dir.list(); for (int i = 0; i < list.length; i++) deltree(new File(dir, list[i])); } - if (!dir.delete()) - { - for (int i=0; i<5; i++) - { - try - { + if (!dir.delete()) { + for (int i = 0; i < 5; i++) { + try { System.out.println("Sleep 1s and try do delete it again: " + dir.getCanonicalPath()); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(System.out); } Thread.currentThread().sleep(1000); diff --git a/test/src/compile/scomp/checkin/XmlBeansCompCheckinTests.java b/src/test/java/compile/scomp/checkin/XmlBeansCompCheckinTests.java similarity index 75% rename from test/src/compile/scomp/checkin/XmlBeansCompCheckinTests.java rename to src/test/java/compile/scomp/checkin/XmlBeansCompCheckinTests.java index 37d1e3b..53c629e 100644 --- a/test/src/compile/scomp/checkin/XmlBeansCompCheckinTests.java +++ b/src/test/java/compile/scomp/checkin/XmlBeansCompCheckinTests.java @@ -14,66 +14,56 @@ */ package compile.scomp.checkin; -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; -import compile.scomp.common.mockobj.TestFiler; import compile.scomp.common.CompileCommon; import compile.scomp.common.CompileTestBase; +import compile.scomp.common.mockobj.TestFiler; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; +import org.junit.After; +import org.junit.Test; +import java.io.File; import java.util.ArrayList; import java.util.Iterator; -import java.util.Vector; import java.util.List; -import java.io.File; -import java.io.IOException; +import java.util.Vector; -import junit.framework.Assert; +import static org.junit.Assert.*; -/** - * - * - */ public class XmlBeansCompCheckinTests extends CompileTestBase -{ public List xm_errors; - public XmlOptions xm_opts; - Vector expBinType; - Vector expSrcType; +{ public final List xm_errors = new ArrayList(); + public final XmlOptions xm_opts = new XmlOptions(); + final Vector expBinType = new Vector(); + final Vector expSrcType = new Vector(); + + public XmlBeansCompCheckinTests() { + expBinType.add("org/apache/xmlbeans/metadata/system/apiCompile/atypedb57type.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/system/apiCompile/elname429edoctype.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/system/apiCompile/elnameelement.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/system/apiCompile/index.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/element/http_3A_2F_2Fbaz/elName.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/type/http_3A_2F_2Fbaz/aType.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/namespace/http_3A_2F_2Fbaz/xmlns.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/javaname/baz/ElNameDocument.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/javaname/baz/AType.xsb"); + expBinType.add("org/apache/xmlbeans/metadata/system/apiCompile/TypeSystemHolder.class"); - public XmlBeansCompCheckinTests(String name) - { - super(name); - expBinType = new Vector(); - expBinType.add("schemaorg_apache_xmlbeans/system/apiCompile/atypedb57type.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/system/apiCompile/elname429edoctype.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/system/apiCompile/elnameelement.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/system/apiCompile/index.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/element/http_3A_2F_2Fbaz/elName.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/type/http_3A_2F_2Fbaz/aType.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/namespace/http_3A_2F_2Fbaz/xmlns.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/javaname/baz/ElNameDocument.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/javaname/baz/AType.xsb"); - expBinType.add("schemaorg_apache_xmlbeans/system/apiCompile/TypeSystemHolder.class"); - - expSrcType = new Vector(); expSrcType.add("baz.AType"); expSrcType.add("baz.impl.ATypeImpl"); expSrcType.add("baz.ElNameDocument"); expSrcType.add("baz.impl.ElNameDocumentImpl"); - xm_errors = new ArrayList(); - xm_opts = new XmlOptions(); xm_opts.setErrorListener(xm_errors); xm_opts.setSavePrettyPrint(); } - public void tearDown() throws Exception - { - super.tearDown(); - + @After + public void tearDown() throws Exception { if (xm_errors.size() > 0) xm_errors.clear(); } + @Test public void test_Filer_compilation() throws Exception { XmlObject obj1 = XmlObject.Factory.parse(forXsd); @@ -108,9 +98,8 @@ public void test_Filer_compilation() throws Exception /** * Verify Partial SOM cannot be saved to file system - * - * @throws Exception */ + @Test public void test_sts_noSave() throws Exception { XmlObject obj1 = XmlObject.Factory.parse(forXsd); @@ -124,7 +113,7 @@ public void test_sts_noSave() throws Exception TestFiler f = new TestFiler(); ArrayList err = new ArrayList(); XmlOptions opt = new XmlOptions().setErrorListener(err); - opt.put("COMPILE_PARTIAL_TYPESYSTEM"); + opt.setCompilePartialTypesystem(); try { // since you can't save a partial SOM, don't bother passing in a Filer @@ -160,7 +149,7 @@ public void test_sts_noSave() throws Exception throw e; } - Assert.assertTrue("Expected partial schema type system", ((SchemaTypeSystemImpl)sts).isIncomplete()); + assertTrue("Expected partial schema type system", ((SchemaTypeSystemImpl)sts).isIncomplete()); //call some stupid methods on STS @@ -173,50 +162,47 @@ public void test_sts_noSave() throws Exception tempDir = new File(OUTPUTROOT, "psom_save"); tempDir.mkdirs(); tempDir.deleteOnExit(); - Assert.assertTrue("Output Directory Init needed to be empty", - tempDir.listFiles().length == 0); + assertEquals("Output Directory Init needed to be empty", 0, tempDir.listFiles().length); //This should not Work sts.saveToDirectory(tempDir); - Assert.fail("Expected IllegalStateException"); + fail("Expected IllegalStateException"); } catch (IllegalStateException e) { // ok System.out.println("sts.saveToDirectory() threw IllegalStateException as expected"); } //make sure nothing was written - Assert.assertTrue("Partial SOM output dir needed to be empty", - tempDir.listFiles().length == 0); + assertEquals("Partial SOM output dir needed to be empty", 0, tempDir.listFiles().length); // Check using save(Filer) on Partial SOM TestFiler tf = null; try { //setUp outputDirectory tf = new TestFiler(); - Assert.assertTrue("Filer Source should have been size 0", - tf.getBinFileVec().size() == 0); + assertEquals("Filer Source should have been size 0", 0, tf.getBinFileVec().size()); //This should not Work sts.save(tf); - Assert.fail("Expected IllegalStateException"); + fail("Expected IllegalStateException"); } catch (IllegalStateException e) { // ok System.out.println("sts.save() threw IllegalStateException as expected"); } //make sure nothing was written - Assert.assertTrue("Filer -Bin- Partial SOM " + + assertTrue("Filer -Bin- Partial SOM " + "output dir needed to be empty", tf.getBinFileVec().size() == 0); - Assert.assertTrue("Filer -SRC- Partial SOM " + + assertTrue("Filer -SRC- Partial SOM " + "output dir needed to be empty", tf.getSrcFileVec().size() == 0); - Assert.assertFalse("Filer Create Source File " + + assertFalse("Filer Create Source File " + "method should not have been invoked", tf.isCreateSourceFile()); - Assert.assertFalse("Filer Create Binary File " + + assertFalse("Filer Create Binary File " + "method should not have been invoked", tf.isCreateBinaryFile()); @@ -224,7 +210,7 @@ public void test_sts_noSave() throws Exception try { tf = new TestFiler(); - Assert.assertTrue("Filer Source should have been size 0", + assertTrue("Filer Source should have been size 0", tf.getBinFileVec().size() == 0); //reset data @@ -236,20 +222,20 @@ public void test_sts_noSave() throws Exception null, schemas3, null, XmlBeans.getBuiltinTypeSystem(), tf, opt); - Assert.assertTrue("Errors was not empty", !err.isEmpty()); + assertTrue("Errors was not empty", !err.isEmpty()); //make sure nothing was written - Assert.assertTrue("Filer -Bin- Partial SOM " + + assertTrue("Filer -Bin- Partial SOM " + "output dir needed to be empty", tf.getBinFileVec().size() == 0); - Assert.assertTrue("Filer -SRC- Partial SOM " + + assertTrue("Filer -SRC- Partial SOM " + "output dir needed to be empty", tf.getSrcFileVec().size() == 0); - Assert.assertFalse("Filer Create Source File " + + assertFalse("Filer Create Source File " + "method should not have been invoked", tf.isCreateSourceFile()); - Assert.assertFalse("Filer Create Binary File " + + assertFalse("Filer Create Binary File " + "method should not have been invoked", tf.isCreateBinaryFile()); } catch (Exception e) { @@ -265,6 +251,7 @@ public void test_sts_noSave() throws Exception * ensure that entry point properly handles * different configs with null values */ + @Test public void test_entrypoint_nullVals() throws Exception { XmlObject obj1 = XmlObject.Factory.parse(forXsd); diff --git a/test/src/compile/scomp/common/CompileCommon.java b/src/test/java/compile/scomp/common/CompileCommon.java similarity index 95% rename from test/src/compile/scomp/common/CompileCommon.java rename to src/test/java/compile/scomp/common/CompileCommon.java index 55a5c9e..11b6bab 100644 --- a/test/src/compile/scomp/common/CompileCommon.java +++ b/src/test/java/compile/scomp/common/CompileCommon.java @@ -14,22 +14,14 @@ */ package compile.scomp.common; -import java.util.Vector; - import common.Common; -/** - * - * - */ +import java.util.Vector; + public class CompileCommon extends Common{ public static String fileLocation = XBEAN_CASE_ROOT +P + "compile" + P + "scomp" + P; - public CompileCommon(String name){ - super(name); - } - /** compare contents of two vectors */ public static void comparefNameVectors(Vector act, Vector exp) throws Exception { diff --git a/test/src/compile/scomp/common/CompileTestBase.java b/src/test/java/compile/scomp/common/CompileTestBase.java similarity index 97% rename from test/src/compile/scomp/common/CompileTestBase.java rename to src/test/java/compile/scomp/common/CompileTestBase.java index 995c46d..0acb25a 100644 --- a/test/src/compile/scomp/common/CompileTestBase.java +++ b/src/test/java/compile/scomp/common/CompileTestBase.java @@ -14,19 +14,21 @@ */ package compile.scomp.common; -import junit.framework.Assert; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.tool.Diff; import org.apache.xmlbeans.impl.tool.SchemaCodeGenerator; -import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.tool.SchemaCompiler; import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; import javax.xml.namespace.QName; import java.io.File; import java.io.IOException; import java.io.StringWriter; -import java.util.List; import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; /** * TODO: modify for deprecation warnings @@ -84,8 +86,7 @@ public class CompileTestBase extends CompileCommon { " " + ""; - public CompileTestBase(String name) { - super(name); + public CompileTestBase() { out = xbeanOutput(outPath); sanity = xbeanOutput(sanityPath); outincr = xbeanOutput(incrPath); @@ -188,7 +189,7 @@ public SchemaTypeSystem incrCompileXsd(SchemaTypeSystem system, XmlObject[] sche SchemaTypeSystem sts; sts = XmlBeans.compileXsd(system, schemas, builtin, options); - Assert.assertNotNull("Compilation failed during Incremental Compile.", sts); + assertNotNull("Compilation failed during Incremental Compile.", sts); SchemaCodeGenerator.saveTypeSystem(sts, outincr, null, null, null); return sts; @@ -202,7 +203,7 @@ public SchemaTypeSystem compileSchemas(XmlObject[] schemas, SchemaTypeLoader typ SchemaTypeSystem system; SchemaTypeSystem builtin = XmlBeans.getBuiltinTypeSystem(); system = XmlBeans.compileXsd(schemas, builtin, options); - Assert.assertNotNull("Compilation failed during compile.", system); + assertNotNull("Compilation failed during compile.", system); SchemaCodeGenerator.saveTypeSystem(system, outDir, null, null, null); return system; } @@ -214,7 +215,7 @@ public SchemaTypeSystem compileSchemas(XmlObject[] schemas, SchemaTypeLoader typ SchemaTypeSystem system; SchemaTypeSystem builtin = XmlBeans.getBuiltinTypeSystem(); system = XmlBeans.compileXsd(schemas, builtin, options); - Assert.assertNotNull("Compilation failed during compile.", system); + assertNotNull("Compilation failed during compile.", system); SchemaCodeGenerator.saveTypeSystem(system, out, null, null, null); return system; } @@ -224,7 +225,7 @@ public void handleErrors(List errors) { StringWriter message = new StringWriter(); for (int i = 0; i < errors.size(); i++) message.write(((String) errors.get(i)) + "\n"); - Assert.fail("\nDifferences encountered:\n" + message); + fail("\nDifferences encountered:\n" + message); } } diff --git a/src/test/java/compile/scomp/common/mockobj/TestBindingConfig.java b/src/test/java/compile/scomp/common/mockobj/TestBindingConfig.java new file mode 100644 index 0000000..88ab83c --- /dev/null +++ b/src/test/java/compile/scomp/common/mockobj/TestBindingConfig.java @@ -0,0 +1,133 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package compile.scomp.common.mockobj; + +import org.apache.xmlbeans.BindingConfig; +import org.apache.xmlbeans.InterfaceExtension; +import org.apache.xmlbeans.PrePostExtension; +import org.apache.xmlbeans.impl.config.BindingConfigImpl; +import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument; + +import javax.xml.namespace.QName; +import java.io.File; + +/** + * + */ +public class TestBindingConfig extends BindingConfig { + BindingConfig bindingConfig; + private boolean islookupPackageForNamespace; + private boolean islookupPrefixForNamespace; + private boolean islookupSuffixForNamespace; + private boolean islookupJavanameForQName; + private boolean isgetInterfaceExtensions; + private boolean isgetInterfaceExtensionsString; + private boolean isgetPrePostExtensions; + private boolean isgetPrePostExtensionsString; + + public TestBindingConfig(ConfigDocument.Config[] configs, File[] javaFiles, File[] classpath) { + + bindingConfig = BindingConfigImpl.forConfigDocuments(configs, javaFiles, classpath); + islookupPackageForNamespace = false; + islookupPrefixForNamespace = false; + islookupSuffixForNamespace = false; + islookupJavanameForQName = false; + isgetInterfaceExtensions = false; + isgetInterfaceExtensionsString = false; + isgetPrePostExtensions = false; + isgetPrePostExtensionsString = false; + } + + public boolean isIslookupPackageForNamespace() { + return islookupPackageForNamespace; + } + + public boolean isIslookupPrefixForNamespace() { + return islookupPrefixForNamespace; + } + + public boolean isIslookupSuffixForNamespace() { + return islookupSuffixForNamespace; + } + + public boolean isIslookupJavanameForQName() { + return islookupJavanameForQName; + } + + public boolean isIsgetInterfaceExtensions() { + return isgetInterfaceExtensions; + } + + public boolean isIsgetInterfaceExtensionsString() { + return isgetInterfaceExtensionsString; + } + + public boolean isIsgetPrePostExtensions() { + return isgetPrePostExtensions; + } + + public boolean isIsgetPrePostExtensionsString() { + return isgetPrePostExtensionsString; + } + + public String lookupPackageForNamespace(String s) { + System.out.println("lookupPackageForNamespace: " + s); + islookupPackageForNamespace = true; + return bindingConfig.lookupPackageForNamespace(s); + } + + public String lookupPrefixForNamespace(String s) { + System.out.println("lookupPrefixForNamespace: " + s); + islookupPrefixForNamespace = true; + return bindingConfig.lookupPrefixForNamespace(s); + } + + public String lookupSuffixForNamespace(String s) { + System.out.println("lookupSuffixForNamespace: " + s); + islookupSuffixForNamespace = true; + return bindingConfig.lookupSuffixForNamespace(s); + } + + + public String lookupJavanameForQName(QName qName, int kind) { + System.out.println("lookupJavanameForQName: " + qName); + islookupJavanameForQName = true; + return bindingConfig.lookupJavanameForQName(qName, kind); + } + + public InterfaceExtension[] getInterfaceExtensions() { + System.out.println("getInterfaceExtensions "); + isgetInterfaceExtensions = true; + return bindingConfig.getInterfaceExtensions(); + } + + public InterfaceExtension[] getInterfaceExtensions(String s) { + System.out.println("getInterfaceExtensions: " + s); + isgetInterfaceExtensionsString = true; + return bindingConfig.getInterfaceExtensions(s); + } + + public PrePostExtension[] getPrePostExtensions() { + System.out.println("getPrePostExtensions"); + isgetPrePostExtensions = true; + return bindingConfig.getPrePostExtensions(); + } + + public PrePostExtension getPrePostExtension(String s) { + System.out.println("getPrePostExtension: " + s); + isgetPrePostExtensionsString = true; + return bindingConfig.getPrePostExtension(s); + } +} diff --git a/test/src/compile/scomp/common/mockobj/TestFiler.java b/src/test/java/compile/scomp/common/mockobj/TestFiler.java similarity index 100% rename from test/src/compile/scomp/common/mockobj/TestFiler.java rename to src/test/java/compile/scomp/common/mockobj/TestFiler.java diff --git a/test/src/compile/scomp/detailed/DetailedCompTests.java b/src/test/java/compile/scomp/detailed/DetailedCompTests.java similarity index 94% rename from test/src/compile/scomp/detailed/DetailedCompTests.java rename to src/test/java/compile/scomp/detailed/DetailedCompTests.java index 1d81e2d..438aef7 100644 --- a/test/src/compile/scomp/detailed/DetailedCompTests.java +++ b/src/test/java/compile/scomp/detailed/DetailedCompTests.java @@ -15,35 +15,28 @@ package compile.scomp.detailed; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; +import compile.scomp.common.CompileCommon; import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -import java.io.File; -import java.util.*; - -import compile.scomp.common.CompileCommon; +import org.junit.Test; import javax.xml.namespace.QName; +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; - -public class DetailedCompTests extends TestCase -{ - public DetailedCompTests(String name) { super(name); } - public static Test suite() { return new TestSuite(DetailedCompTests.class); } +import static org.junit.Assert.*; +public class DetailedCompTests { /** * This test requires laxDoc.xsd to be compiled and * on the classpath ahead of time, otherwise documentation * element processing would not occur * @throws Exception */ - public void testLaxDocProcessing() throws Exception - { + @Test + public void testLaxDocProcessing() throws Exception { QName q = new QName("urn:lax.Doc.Compilation", "ItemRequest"); ArrayList err = new ArrayList(); XmlOptions xm_opt = new XmlOptions().setErrorListener(err); @@ -60,7 +53,7 @@ public void testLaxDocProcessing() throws Exception try{ SchemaTypeSystem sts = XmlBeans.compileXmlBeans(null, null, schemas, null, XmlBeans.getBuiltinTypeSystem(), null, xm_opt); - Assert.assertTrue("STS was null", sts != null); + assertNotNull("STS was null", sts); }catch(XmlException xmlEx){ valDocEx = true; System.err.println("Expected Error: "+xmlEx.getMessage()); @@ -152,8 +145,8 @@ public void testLaxDocProcessing() throws Exception /** * This tests usage of the xs:NOTATION type - * @throws Exception */ + @Test public void testNotation() throws Exception { String schema; @@ -164,7 +157,7 @@ public void testNotation() throws Exception XmlOptions opts = new XmlOptions(); ArrayList errors = new ArrayList(); opts.setErrorListener(errors); - opts.put("COMPILE_PARTIAL_TYPESYSTEM"); + opts.setCompilePartialTypesystem(); // 1. Negative test - Error if xs:NOTATION used directly schema = schema_begin + root_decl + notation1 + root_end + schema_end; diff --git a/test/src/compile/scomp/detailed/SchemaCompilerTests.java b/src/test/java/compile/scomp/detailed/SchemaCompilerTests.java similarity index 95% rename from test/src/compile/scomp/detailed/SchemaCompilerTests.java rename to src/test/java/compile/scomp/detailed/SchemaCompilerTests.java index 71d4e9b..e69f473 100644 --- a/test/src/compile/scomp/detailed/SchemaCompilerTests.java +++ b/src/test/java/compile/scomp/detailed/SchemaCompilerTests.java @@ -14,14 +14,15 @@ */ package compile.scomp.detailed; -import junit.framework.TestCase; +import common.Common; +import org.apache.xmlbeans.impl.tool.SchemaCompiler; +import org.junit.Test; -import java.util.List; -import java.util.ArrayList; import java.io.File; +import java.util.ArrayList; +import java.util.List; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; -import common.Common; +import static org.junit.Assert.fail; /** * This class contains tests that need to invoke the SchemaCompiler class which is @@ -30,15 +31,11 @@ * The tests need to be run with cmd line param that points to the test case root directory and xmlbeans root * ex: -Dcases.location=D:\svnnew\xmlbeans\trunk\test\cases -Dxbean.rootdir=D:\svnnew\xmlbeans\trunk */ -public class SchemaCompilerTests extends Common +public class SchemaCompilerTests extends Common { public static String scompTestFilesRoot = XBEAN_CASE_ROOT + P + "compile" + P + "scomp" + P + "schemacompiler" + P; public static String schemaCompOutputDirPath = OUTPUTROOT + P + "compile" + P + "scomp" + P; - public SchemaCompilerTests(String name){ - super(name); - } - private void _testCompile(File[] xsdFiles, String outputDirName, String testName) @@ -56,6 +53,7 @@ private void _testCompile(File[] xsdFiles, } } + @Test public void testUnionRedefine() { File[] xsdFiles = @@ -69,6 +67,7 @@ public void testUnionRedefine() /** This tests a bug where compilation of a schema redefining a type involving an enumeration fails. */ + @Test public void testEnumerationRedefine1() { File[] xsdFiles = @@ -82,6 +81,7 @@ public void testEnumerationRedefine1() /** This tests a bug where compilation of a schema redefining a type involving an enumeration fails. */ + @Test public void testEnumerationRedefine2() { File[] xsdFiles = @@ -95,6 +95,7 @@ public void testEnumerationRedefine2() /** This tests a bug where compilation of a schema redefining a type involving an enumeration fails. */ + @Test public void testEnumerationRedefine3() { File[] xsdFiles = @@ -110,6 +111,7 @@ public void testEnumerationRedefine3() * [XMLBEANS-205]: * using static handlers for extension interfaces with same method names */ + @Test public void testExtensionHandlerMethodNameCollision() { File[] xsdFiles = @@ -143,6 +145,7 @@ public void testExtensionHandlerMethodNameCollision() * [XMLBEANS-278]: * -noext flag for compilation */ + @Test public void testNoExt() { File[] xsdFiles = diff --git a/src/test/java/compile/scomp/detailed/XmlBeanCompilationTests.java b/src/test/java/compile/scomp/detailed/XmlBeanCompilationTests.java new file mode 100644 index 0000000..48ab1f8 --- /dev/null +++ b/src/test/java/compile/scomp/detailed/XmlBeanCompilationTests.java @@ -0,0 +1,310 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package compile.scomp.detailed; + +import compile.scomp.common.CompileTestBase; +import compile.scomp.common.mockobj.TestBindingConfig; +import compile.scomp.common.mockobj.TestFiler; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument; +import org.junit.After; +import org.junit.Test; + +import javax.xml.namespace.QName; +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertTrue; + + +/** + * Ensure that several compilation mechanisms all generate + * the same schematypesystem + */ +public class XmlBeanCompilationTests extends CompileTestBase { + private final List xm_errors = new ArrayList<>(); + private final XmlOptions xm_opts = new XmlOptions(); + + public XmlBeanCompilationTests() { + xm_opts.setErrorListener(xm_errors); + xm_opts.setSavePrettyPrint(); + } + + @After + public void tearDown() throws Exception { + if (xm_errors.size() > 0) { + xm_errors.clear(); + } + } + + /** + * Filer != null for BindingConfig to be used + */ + @Test + public void test_bindingconfig_extension_compilation() throws Exception { + TestFiler f = new TestFiler(); + //initialize all of the values + String extCaseDir = XBEAN_CASE_ROOT + P + "extensions" + P; + String extSrcDir = getRootFile() + P + + "src" + P + "test" + P + "java" + P + "xmlobject" + P + "extensions" + P; + File[] cPath = CompileTestBase.getClassPath(); + String dir = extCaseDir + P + "interfaceFeature" + P + "averageCase"; + String dir2 = extCaseDir + P + "prePostFeature" + P + + "ValueRestriction"; + + ConfigDocument.Config bConf = ConfigDocument.Factory.parse( + new File(dir + P + "po.xsdconfig")) + .getConfig(); + ConfigDocument.Config cConf = ConfigDocument.Factory.parse( + new File(dir2 + P + "company.xsdconfig")) + .getConfig(); + + String simpleConfig = "\n" + + "\n" + + "com.easypo\n" + + ""; + ConfigDocument.Config confDoc = ConfigDocument.Factory.parse(simpleConfig).getConfig(); + ConfigDocument.Config[] confs = new ConfigDocument.Config[]{bConf, confDoc, cConf}; + + String fooHandlerPath = extSrcDir + P + "interfaceFeature" + P + + "averageCase" + P + "existing" + P + "FooHandler.java"; + String iFooPath = extSrcDir + P + "interfaceFeature" + P + + "averageCase" + P + "existing" + P + "IFoo.java"; + String iSetterPath = extSrcDir + P + "prePostFeature" + P + + "ValueRestriction" + P + "existing" + P + "ISetter.java"; + String setterHandlerPath = extSrcDir + P + "prePostFeature" + P + + "ValueRestriction" + P + "existing" + P + "SetterHandler.java"; + + + File[] fList = new File[]{new File(fooHandlerPath), new File(iFooPath), + new File(iSetterPath), + new File(setterHandlerPath)}; + + //use created BindingConfig + TestBindingConfig bind = new TestBindingConfig(confs, fList, cPath); + + //set XSDs + XmlObject obj1 = XmlObject.Factory.parse(new File(dir + P + "po.xsd")); + XmlObject obj2 = XmlObject.Factory.parse( + new File(dir2 + P + "company.xsd")); + XmlObject[] schemas = new XmlObject[]{obj1, obj2}; + + //filer must be present on this method + SchemaTypeSystem apiSts = XmlBeans.compileXmlBeans("apiCompile", null, + schemas, bind, XmlBeans.getBuiltinTypeSystem(), f, xm_opts); + + if (!bind.isIslookupPrefixForNamespace()) { + throw new Exception("isIslookupPrefixForNamespace not invoked"); + } + if (!bind.isIslookupPackageForNamespace()) { + throw new Exception("isIslookupPackageForNamespace not invoked"); + } + if (!bind.isIslookupSuffixForNamespace()) { + throw new Exception("isIslookupSuffixForNamespace not invoked"); + } + if (!bind.isIslookupJavanameForQName()) { + throw new Exception("isIslookupJavanameForQName not invoked"); + } + if (!bind.isIsgetInterfaceExtensionsString()) { + throw new Exception("isIsgetInterfaceExtensionsString not invoked"); + } + if (!bind.isIsgetInterfaceExtensions()) { + throw new Exception("isIsgetInterfaceExtensions not invoked"); + } + if (!bind.isIsgetPrePostExtensions()) { + throw new Exception("isIsgetPrePostExtensions not invoked"); + } + if (!bind.isIsgetPrePostExtensionsString()) { + throw new Exception("isIsgetPrePostExtensionsString not invoked"); + } + } + + /** + * Verify basic incremental compilation + * and compilation with partial SOM usages + */ + @Test + public void test_incrCompile() throws Exception { + XmlObject obj1 = XmlObject.Factory.parse(forXsd); + obj1.documentProperties().setSourceName("OBJ1"); + XmlObject[] schemas = new XmlObject[]{obj1}; + QName sts1 = new QName("http://baz", "elName"); + + XmlObject obj2 = XmlObject.Factory.parse(incrXsd); + obj2.documentProperties().setSourceName("OBJ2"); + XmlObject[] schemas2 = new XmlObject[]{obj2}; + QName sts2 = new QName("http://bar", "elName"); + + XmlObject obj3 = XmlObject.Factory.parse(errXsd); + obj3.documentProperties().setSourceName("OBJ3"); + XmlObject[] schemas3 = new XmlObject[]{obj3}; + QName sts3 = new QName("http://bar", "elErrName"); + + SchemaTypeSystem sts; + ArrayList err = new ArrayList(); + XmlOptions opt = new XmlOptions().setErrorListener(err); + opt.setCompilePartialTypesystem(); + + //BASIC COMPILATION + sts = XmlBeans.compileXmlBeans(null, + null, schemas, null, + XmlBeans.getBuiltinTypeSystem(), null, opt); + + assertTrue("Errors should have been empty", err.isEmpty()); + // find element in the type System + if (!findGlobalElement(sts.globalElements(), sts1)) { + throw new Exception( + "Could Not find Type from first Type System: " + sts1); + } + + //SIMPLE INCR COMPILATION + sts = XmlBeans.compileXmlBeans(null, + sts, schemas2, null, + XmlBeans.getBuiltinTypeSystem(), null, opt); + assertTrue("Errors should have been empty", err.isEmpty()); + // find element in the type System + + if (!findGlobalElement(sts.globalElements(), sts1)) { + throw new Exception("Could Not find Type from first Type System: " + + sts1); + } + + if (!findGlobalElement(sts.globalElements(), sts2)) { + throw new Exception("Could Not find Type from 2nd Type System: " + + sts2); + } + + System.out.println("Building over Existing"); + //BUILDING OFF BASE SIMPLE INCR COMPILATION + sts = XmlBeans.compileXmlBeans(null, + sts, schemas2, null, + sts, null, opt); + assertTrue("Errors should have been empty", err.isEmpty()); + // find element in the type System + + if (!findGlobalElement(sts.globalElements(), sts1)) { + throw new Exception("Could Not find Type from first Type System: " + + sts1); + } + + if (!findGlobalElement(sts.globalElements(), sts2)) { + throw new Exception("Could Not find Type from 2nd Type System: " + + sts2); + } + + //INCR COMPILATION WITH RECOVERABLE ERROR + err.clear(); + SchemaTypeSystem b = XmlBeans.compileXmlBeans(null, + sts, schemas3, null, + XmlBeans.getBuiltinTypeSystem(), null, opt); + // find element in the type System + if (!findGlobalElement(b.globalElements(), sts1)) { + throw new Exception("Could Not find Type from first Type System: " + + sts1); + } + + if (!findGlobalElement(b.globalElements(), sts2)) { + throw new Exception("Could Not find Type from 2nd Type System: " + + sts2); + } + + if (!findGlobalElement(b.globalElements(), sts3)) { + throw new Exception("Could Not find Type from 3rd Type System: " + + sts3); + } + + printSTS(b); + + //INSPECT ERRORS + boolean psom_expError = false; + // print out the recovered xm_errors + if (!err.isEmpty()) { + System.out.println( + "Schema invalid: partial schema type system recovered"); + for (Iterator i = err.iterator(); i.hasNext(); ) { + XmlError xErr = (XmlError) i.next(); + System.out.println(xErr); + //compare to the expected xm_errors + if ((xErr.getErrorCode().compareTo("src-resolve") == 0) && + (xErr.getMessage().compareTo( + "type 'bType@http://baz' not found.") == + 0)) { + psom_expError = true; + } + } + } + if (!psom_expError) { + throw new Exception("Error Code was not as Expected"); + } + + + } + +/* + @Test + public void test_diff_compilationMethods() throws IOException, + XmlException, Exception { + + + //initialize the schema compiler + SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); + params.setXsdFiles(new File[]{scompFile}); + params.setSrcDir(scompDirFile); + params.setClassesDir(scompDirFile); + + //save out schema for use in scomp later + XmlObject obj1 = XmlObject.Factory.parse(forXsd); + obj1.save(scompFile); + + //scomp saved out schema + SchemaCompiler.compile(params); + + //use new api to get typesystem + XmlObject[] schemas = new XmlObject[]{obj1}; + SchemaTypeSystem apiSts = XmlBeans.compileXmlBeans("apiCompile", null, + schemas, null, XmlBeans.getBuiltinTypeSystem(), null, xm_opts); + + //use alternative api to get typesystem + SchemaTypeSystem altSts = XmlBeans.compileXsd(schemas, + XmlBeans.getBuiltinTypeSystem(), null); + + //save out sts for diff later + SchemaCodeGenerator.saveTypeSystem(apiSts, apiDirFile, null, null, + null); + SchemaCodeGenerator.saveTypeSystem(altSts, baseDirFile, null, null, + null); + + //diff new api to old api + xm_errors = null; + xm_errors = new ArrayList(); + Diff.dirsAsTypeSystems(apiDirFile, baseDirFile, xm_errors); + if (xm_errors.size() >= 1) + throw new Exception("API STS ERRORS: " + xm_errors.toString()); + + //diff scomp sts to new api + xm_errors = null; + xm_errors = new ArrayList(); + Diff.dirsAsTypeSystems(apiDirFile, scompDirFile, xm_errors); + if (xm_errors.size() >= 1) + throw new Exception("API SCOMP ERRORS: " + xm_errors.toString()); + } +*/ + +} diff --git a/test/src/compile/scomp/incr/schemaCompile/detailed/IncrCompilationTests.java b/src/test/java/compile/scomp/incr/schemaCompile/detailed/IncrCompilationTests.java similarity index 93% rename from test/src/compile/scomp/incr/schemaCompile/detailed/IncrCompilationTests.java rename to src/test/java/compile/scomp/incr/schemaCompile/detailed/IncrCompilationTests.java index fc7bdd2..01a1ad5 100644 --- a/test/src/compile/scomp/incr/schemaCompile/detailed/IncrCompilationTests.java +++ b/src/test/java/compile/scomp/incr/schemaCompile/detailed/IncrCompilationTests.java @@ -15,46 +15,26 @@ package compile.scomp.incr.schemaCompile.detailed; -import junit.framework.TestCase; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; -import org.apache.xmlbeans.impl.tool.CodeGenUtil; -import org.apache.xmlbeans.impl.tool.SchemaCodeGenerator; -import org.apache.xmlbeans.impl.tool.Diff; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType; -import org.apache.xmlbeans.impl.util.FilerImpl; -import org.apache.xmlbeans.*; - -import java.io.*; -import java.util.*; - -//import tools.util.TestRunUtil; import compile.scomp.common.CompileCommon; import compile.scomp.common.CompileTestBase; -import compile.scomp.common.mockobj.TestFiler; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.util.FilerImpl; +import org.junit.*; import javax.xml.namespace.QName; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; -/** - * - * - */ public class IncrCompilationTests extends CompileTestBase { - - public IncrCompilationTests(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(IncrCompilationTests.class); - } - + @Before public void setUp() throws IOException { CompileCommon.deltree(CompileCommon.xbeanOutput(outputDir)); out = CompileCommon.xbeanOutput(outPath); @@ -67,14 +47,15 @@ public void setUp() throws IOException { xm.setSavePrettyPrint(); } - public void tearDown() throws Exception - { - super.tearDown(); - if (errors.size() > 0) + @After + public void tearDown() throws Exception { + if (errors.size() > 0) errors.clear(); } + @Test + @Ignore public void test_dupetype_diffns() throws Exception { XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); XmlObject obj2 = XmlObject.Factory.parse(getBaseSchema("bar", "elName", "string", "attrName", "string")); @@ -110,7 +91,8 @@ public void test_dupetype_diffns() throws Exception { handleErrors(errors); } - + @Test + @Ignore("Duplicate global type") public void test_dupens_difftypename() throws Exception { XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); XmlObject obj2 = XmlObject.Factory.parse(getBaseSchema("baz", "elName2", "string", "attrName2", "string")); @@ -139,6 +121,8 @@ public void test_dupens_difftypename() throws Exception { * This test should not change sts since xmlobject is same * @throws Exception */ + @Test + @Ignore("Duplicate global type") public void test_dupens_dupetypename() throws Exception { XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); XmlObject obj2 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); @@ -164,6 +148,8 @@ public void test_dupens_dupetypename() throws Exception { handleErrors(errors); } + @Test + @Ignore("Duplicate global type") public void test_dupens_attrnamechange() throws Exception { //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); @@ -183,12 +169,14 @@ public void test_dupens_attrnamechange() throws Exception { findElementbyQName(base, baseTypes); findElementbyQName(incr, incrTypes); - Assert.assertNotSame(base, incr); + assertNotSame(base, incr); compareandPopErrors(out, outincr, errors); handleErrors(errors); } + @Test + @Ignore("Duplicate global type") public void test_dupens_attrtypechange() throws Exception { //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); @@ -208,13 +196,14 @@ public void test_dupens_attrtypechange() throws Exception { findElementbyQName(base, baseTypes); findElementbyQName(incr, incrTypes); - Assert.assertNotSame(base, incr); + assertNotSame(base, incr); compareandPopErrors(out, outincr, errors); handleErrors(errors); } - + @Test + @Ignore("Duplicate global type") public void test_dupens_eltypechange() throws Exception { //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); @@ -235,12 +224,14 @@ public void test_dupens_eltypechange() throws Exception { findElementbyQName(incr, incrTypes); // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); + assertNotSame(base, incr); compareandPopErrors(out, outincr, errors); handleErrors(errors); } + @Test + @Ignore("Duplicate global type") public void test_typechange() throws Exception { //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("baz", "elName", "string", "attrName", "string")); @@ -260,13 +251,14 @@ public void test_typechange() throws Exception { findElementbyQName(base, baseTypes); findElementbyQName(incr, incrTypes); - Assert.assertNotSame(base, incr); + assertNotSame(base, incr); compareandPopErrors(out, outincr, errors); handleErrors(errors); } // test regeneration of generated java files by the Filer + @Test public void test_schemaFilesRegeneration_01() throws Exception { // incremental compile with the same file again. There should be no regeneration of src files @@ -310,7 +302,7 @@ public void test_schemaFilesRegeneration_01() throws Exception { handleErrors(errors); } - + @Test public void test_schemaFilesRegeneration_02() throws Exception { // incremental compile with the changes. Specific files should be regenerated XmlObject obj1 = XmlObject.Factory.parse(schemaFilesRegeneration_schema1); @@ -346,8 +338,9 @@ public void test_schemaFilesRegeneration_02() throws Exception { Set keyset = initialTimeStamps.keySet(); // Atype has been modified, BType has been removed - String modifiedFileName = out.getCanonicalFile() + "\\org\\openuri\\impl\\ATypeImpl.java"; - String modifiedFileName2 = out.getCanonicalFile() + "\\org\\openuri\\AType.java"; + String sep = System.getProperty("file.separator"); + String modifiedFileName = out.getCanonicalFile() + sep + "org" + sep + "openuri" + sep + "impl" + sep + "ATypeImpl.java"; + String modifiedFileName2 = out.getCanonicalFile() + sep + "org" + sep + "openuri" + sep + "AType.java"; for (Iterator iterator = keyset.iterator(); iterator.hasNext();) { String eachFile = (String) iterator.next(); diff --git a/src/test/java/compile/scomp/incr/schemaCompile/detailed/ModelGroupTests.java b/src/test/java/compile/scomp/incr/schemaCompile/detailed/ModelGroupTests.java new file mode 100644 index 0000000..f2dc0d3 --- /dev/null +++ b/src/test/java/compile/scomp/incr/schemaCompile/detailed/ModelGroupTests.java @@ -0,0 +1,338 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package compile.scomp.incr.schemaCompile.detailed; + +import compile.scomp.common.CompileCommon; +import compile.scomp.common.CompileTestBase; +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import javax.xml.namespace.QName; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.util.ArrayList; + +import static org.junit.Assert.assertNotSame; + + +@Ignore("Currently all tests receive a duplicate schema entry exception") +public class ModelGroupTests extends CompileTestBase { + + File obj1File, obj2File; + + @Before + public void setUp() throws IOException { + CompileCommon.deltree(CompileCommon.xbeanOutput(outputDir)); + out = CompileCommon.xbeanOutput(outPath); + sanity = CompileCommon.xbeanOutput(sanityPath); + outincr = CompileCommon.xbeanOutput(incrPath); + + errors = new ArrayList(); + xm = new XmlOptions(); + xm.setErrorListener(errors); + xm.setSavePrettyPrint(); + + obj1File = File.createTempFile("obj1_", ".xsd"); + obj2File = File.createTempFile("obj2_", ".xsd"); + } + + @After + public void tearDown() throws Exception { + if (errors.size() > 0) { + errors.clear(); + } + obj1File.delete(); + obj2File.delete(); + } + + private XmlObject[] getSchema(File objFile, String schemaString) throws IOException, XmlException { + FileOutputStream fos = new FileOutputStream(objFile); + OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8")); + if (!schemaString.startsWith("" + + "" + + "" + + "" + + "" + + "" + + ""); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + // if (incr.findElement(incrTypes[0]).getType().g + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } + + @Test + public void test_model_seq2choicechange() throws Exception { + //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); + XmlObject[] schemas = getSchema(obj1File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } + + @Test + public void test_model_seq2choicechange_diffns() throws Exception { + //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); + XmlObject[] schemas = getSchema(obj1File, + getBaseSchema("bar", "elName", "string", "attrName", "string")); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://bar", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + // if (incr.findElement(incrTypes[0]).getType().g + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } + + @Test + public void test_model_seq2allchange() throws Exception { + //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); + XmlObject[] schemas = getSchema(obj1File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + // if (incr.findElement(incrTypes[0]).getType().g + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } + + @Test + public void test_model_all2seqchange() throws Exception { + //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); + XmlObject[] schemas = getSchema(obj1File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + // if (incr.findElement(incrTypes[0]).getType().g + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } + + @Test + public void test_model_all2choicechange() throws Exception { + //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); + XmlObject[] schemas = getSchema(obj1File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + // if (incr.findElement(incrTypes[0]).getType().g + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } + + @Test + public void test_model_choice2choicechange() throws Exception { + //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); + XmlObject[] schemas = getSchema(obj1File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + XmlObject[] schemas2 = getSchema(obj2File, + "" + + "" + + "" + + "" + + "" + + "" + + ""); + + SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); + SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); + + echoSts(base, incr); + QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; + QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; + + findElementbyQName(base, baseTypes); + findElementbyQName(incr, incrTypes); + + // if (incr.findElement(incrTypes[0]).getType().g + assertNotSame(base, incr); + + compareandPopErrors(out, outincr, errors); + handleErrors(errors); + } +} diff --git a/test/src/compile/scomp/incr/schemaCompile/detailed/PerfTests.java b/src/test/java/compile/scomp/incr/schemaCompile/detailed/PerfTests.java similarity index 79% rename from test/src/compile/scomp/incr/schemaCompile/detailed/PerfTests.java rename to src/test/java/compile/scomp/incr/schemaCompile/detailed/PerfTests.java index f2537cb..2a0859c 100644 --- a/test/src/compile/scomp/incr/schemaCompile/detailed/PerfTests.java +++ b/src/test/java/compile/scomp/incr/schemaCompile/detailed/PerfTests.java @@ -15,46 +15,25 @@ package compile.scomp.incr.schemaCompile.detailed; -import junit.framework.TestCase; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; -import org.apache.xmlbeans.impl.tool.CodeGenUtil; -import org.apache.xmlbeans.impl.tool.SchemaCodeGenerator; -import org.apache.xmlbeans.impl.tool.Diff; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType; -import org.apache.xmlbeans.*; - -import java.io.File; -import java.io.StringWriter; -import java.io.IOException; -import java.util.*; - -import tools.util.TestRunUtil; import compile.scomp.common.CompileCommon; import compile.scomp.common.CompileTestBase; +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; import javax.xml.namespace.QName; +import java.io.IOException; +import java.util.ArrayList; +import static org.junit.Assert.assertNotSame; -/** - * - * - */ -public class PerfTests extends CompileTestBase { - - - public PerfTests(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(PerfTests.class); - } +public class PerfTests extends CompileTestBase { + @Before public void setUp() throws IOException { CompileCommon.deltree(CompileCommon.xbeanOutput(outputDir)); out = CompileCommon.xbeanOutput(outPath); @@ -67,13 +46,14 @@ public void setUp() throws IOException { xm.setSavePrettyPrint(); } - public void tearDown() throws Exception - { - super.tearDown(); + @After + public void tearDown() throws Exception { if (errors.size() > 0) errors.clear(); } + @Ignore("throws duplicate global type") + @Test public void test_perf_choice2seqchange() throws Exception { //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + @@ -113,7 +93,7 @@ public void test_perf_choice2seqchange() throws Exception { findElementbyQName(base, baseTypes); findElementbyQName(incr, incrTypes); - Assert.assertNotSame(base, incr); + assertNotSame(base, incr); compareandPopErrors(out, outincr, errors); handleErrors(errors); diff --git a/src/test/java/compile/scomp/som/checkin/PartialSOMCheckinTest.java b/src/test/java/compile/scomp/som/checkin/PartialSOMCheckinTest.java new file mode 100644 index 0000000..3d948a5 --- /dev/null +++ b/src/test/java/compile/scomp/som/checkin/PartialSOMCheckinTest.java @@ -0,0 +1,1424 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package compile.scomp.som.checkin; + +import compile.scomp.som.common.SomTestBase; +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlOptions; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; + +import static org.junit.Assert.*; + +public class PartialSOMCheckinTest extends SomTestBase +{ + @Before + public void setUp() + { + // initialize the built in schema type + builtin = XmlBeans.getBuiltinTypeSystem(); + + // populate the XmlOptions + if (errors == null) + { + errors = new ArrayList(); + } + if (options == null) + { + options = (new XmlOptions()).setErrorListener(errors); + options.setCompileDownloadUrls(); + options.setCompilePartialTypesystem(); + options.setLoadLineNumbers(); + } + + // initialize the runid to be used for generating output files for the PSOM walk thro's + runid = new Date().getTime(); + + // clean the output from the previous run + // delete directories created by checkPSOMSave() and output text file created by inspectPSOM() + deleteDirRecursive(new File(somOutputRootDir)); + + } + + @After + public void tearDown() + { + errors.clear(); + } + + @Test + public void testAddAttributeAndElements() throws Exception + { + System.out.println("Inside test case testAddAttributeAndElements()"); + + // Step 1 : create a Schema Type System with the base 'bad' xsd and create the Schema Type System (STS) for it + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("elemattr.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", + baseSTS); + + // the tests - Walk thro the SOM, save, validate against an xml instance + inspectSOM(baseSTS, 1, 1, 1, 0); + + // test for recoverable errors + assertTrue("No Recovered Errors for Invalid Schema", + printRecoveredErrors()); + + // Test for saving of the PSOM - should not be able to save + assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should fail!", + checkPSOMSave(baseSTS)); + + // instance validation - should fail + assertFalse("Validation against instance Success - should fail ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), baseSTS)); + + // additional validation + assertFalse("Attribute found but not expected - 'testAttributeComplex'", + lookForAttributeInSTS(baseSTS, + "testAttributeComplex")); + assertFalse("Element found but not expected 'ComplexTypeElem'", + lookForElemInSTS(baseSTS, + "ComplexTypeElem")); + assertFalse("Element found but not expected 'SimpleTypeElem'", + lookForElemInSTS(baseSTS, "SimpleTypeElem")); + + + // Step 2: create a Schema Type System with the new xsd file that has additions to this schema + SchemaTypeSystem modifiedSTS = createNewSTS("elemattr_added.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", + modifiedSTS); + + // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups + inspectSOM(modifiedSTS, 3, 2, 1, 0); + + // Test for successful saving of the PSOM + assertTrue("Valid Partial SOM " + modifiedSTS.getName() + "Save failed", + checkPSOMSave(modifiedSTS)); + + // Look for added attribute(s)/Element(s) by name in the STS + assertTrue("Attribute expected, not found 'testAttributeComplex'", + lookForAttributeInSTS(modifiedSTS, + "testAttributeComplex")); + assertTrue("Element expected, not found 'ComplexTypeElem'", + lookForElemInSTS(modifiedSTS, + "ComplexTypeElem")); + assertTrue("Element expected, not found 'SimpleTypeElem'", + lookForElemInSTS(modifiedSTS, + "SimpleTypeElem")); + + // validate against an xml instance + assertTrue("Validation against instance failed ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), modifiedSTS)); + + // Step 3: now creat the Schema Type System with the original XSD again + SchemaTypeSystem finalSTS = createNewSTS("elemattr.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", finalSTS); + + //walk the SOM + inspectSOM(finalSTS, 1, 1, 1, 0); + + // Test for saving of the PSOM - should not be able to save + assertFalse("Partial SOM " + finalSTS.getName() + "Save successful - should fail!", + checkPSOMSave(finalSTS)); + + // instance validation - should fail + assertFalse("Validation against instance Success - should fail ", + validateInstance(getTestCaseFile("instance_elemattr.xml"), finalSTS)); + + } + + @Test + public void testModifyAttributeAndElements() throws Exception + { + System.out.println("Inside test case testModifyAttributeAndElements()"); + + // Step 1 : create a Schema Type System with the base 'good' xsd and create the Schema Type System (STS) for it + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("elemattr_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // the tests - Walk thro the SOM, save, validate against an xml instance + inspectSOM(baseSTS, 3, 2, 1, 0); + + // validate successful save + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed ", + checkPSOMSave(baseSTS)); + + // validate against instance successfully + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), baseSTS)); + + // Step 2: create a Schema Type System with the new xsd file with modifications to existing schema + SchemaTypeSystem modifiedSTS = createNewSTS("elemattr_modified.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // test for recoverable errors + assertTrue("No Recovered Errors for Invalid Schema", + printRecoveredErrors()); + + // test the PSOM created + inspectSOM(modifiedSTS, 2, 2, 1, 0); // walk thro the PSOM, look for # of elements,attributes,types & attribute groups + + // Look for a modified attribute(s)/elements by name in the STS + assertTrue("Attribute expected, not found 'testAttributeComplex'", + lookForAttributeInSTS(modifiedSTS, "testAttributeComplex")); + assertTrue("Element expected, not found 'ComplexTypeElem'", + lookForElemInSTS(modifiedSTS, "ComplexTypeElem")); + assertFalse("Element expected, not found 'SimpleTypeElem'", + lookForElemInSTS(modifiedSTS, "SimpleTypeElem")); + + // Test for saving of the PSOM - should not be able to save + assertFalse("Partial SOM " + modifiedSTS.getName() + " Save successful- should fail", + checkPSOMSave(modifiedSTS)); + + // validate against an xml instance - should fail + assertFalse("Validation against instance Success - should Fail", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), modifiedSTS)); + + // Step 3: now creat the Schema Type System with the original XSD again + SchemaTypeSystem finalSTS = createNewSTS("elemattr_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", finalSTS); + + // walk the PSOM + inspectSOM(finalSTS, 3, 2, 1, 0); + + // should be able to save as its a valid SOM + assertTrue("Partial SOM " + finalSTS.getName() + "Save failed for complete SOM", + checkPSOMSave(finalSTS)); + + // validate against instance successfully + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), finalSTS)); + + // compare this to the original schema here - the root dir names used to save the PSOMs are the same as the STS names + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + } + + @Test + public void testDeleteAttributeAndElements() throws Exception + { + System.out.println("Inside test case testDeleteAttributeAndElements()"); + + // Step 1 : create a Schema Type System with the base 'good' xsd and create the Schema Type System (STS) for it + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("elemattr_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // the tests - Walk thro the SOM, save, validate against an xml instance + inspectSOM(baseSTS, 3, 2, 1, 0); + + // validate successful save + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed ", + checkPSOMSave(baseSTS)); + + // validate against instance successfully + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), baseSTS)); + + // Step 2: create a Schema Type System with the new xsd file that has deletions + SchemaTypeSystem modifiedSTS = createNewSTS("elemattr.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // test for recoverable errors + assertTrue("No Recovered Errors for Invalid Schema", + printRecoveredErrors()); + + // test the PSOM created + inspectSOM(modifiedSTS, 1, 1, 1, 0); // walk thro the PSOM, look for # of elements,attributes,types & attribute groups + + // Test for saving of the PSOM - should not be able to save + assertFalse("Invalid PSOM " + modifiedSTS.getName() + " Save successful - Should fail", + checkPSOMSave(modifiedSTS)); + + // verify types + assertFalse("Attribute found but not expected - 'testAttributeComplex'", + lookForAttributeInSTS(modifiedSTS, "testAttributeComplex")); + assertFalse("Element found but not expected 'ComplexTypeElem'", + lookForElemInSTS(modifiedSTS, "ComplexTypeElem")); + assertFalse("Element found but not expected 'SimpleTypeElem'", + lookForElemInSTS(modifiedSTS, "SimpleTypeElem")); + + // validate against an xml instance - should fail + assertFalse("Validation against success - should Fail ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), modifiedSTS)); + + // Step 3: now creat the Schema Type System with the original XSD again + SchemaTypeSystem finalSTS = createNewSTS("elemattr_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", finalSTS); + + // walk the SOM + inspectSOM(finalSTS, 3, 2, 1, 0); + + // should be able to save as its a valid SOM + assertTrue("Partial SOM " + finalSTS.getName() + "Save failed for complete SOM", + checkPSOMSave(finalSTS)); + + // validate against instance + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), finalSTS)); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + + } + + @Test + public void testAddDataTypes() throws Exception + { + System.out.println("Inside test case testAddDataTypes()"); + // Step 1 : create a PSOM from an incomplete/invalid xsd (datatypes.xsd) with unresolved references to various types + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("datatypes.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // recovearble errors should exist + assertTrue("No Recovered Errors for Invalid Schema", + printRecoveredErrors()); + + // Walk thro the SOM (pass #Elems, #Attr, #Types, #AttrGroups) + inspectSOM(baseSTS, 12, 1, 4, 1); + + // Test for saving of the PSOM - should not be able to save + assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should fail!", + checkPSOMSave(baseSTS)); + + // instance validation - should fail + assertFalse("Validation against instance Success - should fail ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); + + // additional validation - check to see if the unresolved references to types are 'anyType' + // validate unresolved types + assertEquals("Unresolved Simple Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testAtomicTypeElem")); + assertEquals("Unresolved Simple Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testUnionTypeElem")); + + // moved to detailed PSOMDetailedTest class + //Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", anySimpleType, getElementType(baseSTS, "testListTypeElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testComplexTypeSimpleContentElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testComplexTypeElementOnlyContentElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testComplexTypeMixedElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testComplexTypeEmptyElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testChoiceGroupElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testAllGroupElem")); + + // Step 2 : create an incremental PSOM that is valid by loading datatypes_added.xsd + SchemaTypeSystem modifiedSTS = createNewSTS("datatypes_added.xsd_", baseSTS, "ModifiedSchemaTS", sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // no errors expected to be recovered - should be a valid SOM + assertFalse("Valid Schema Type System, Errors recovered", + printRecoveredErrors()); + + // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups + inspectSOM(modifiedSTS, 13, 1, 15, 1); + + // test successful save + assertTrue("Valid SOM " + modifiedSTS.getName() + " Save failed", + checkPSOMSave(modifiedSTS)); + + // validate against an xml valid instance - should succeed + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), modifiedSTS)); + + // validate against an xml invalid instance - should fail + assertFalse("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_simple_types_invalid.xml"), modifiedSTS)); + + // additional validation - check to see if all types are resolved to their respective types + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(modifiedSTS, "testAtomicTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType'", + "union.attachmentUnionType", + getElementType(modifiedSTS, "testUnionTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(modifiedSTS, "testListTypeElem")); + assertEquals("Unresolved Complex Type should be 'headerType'", + "headerType", + getElementType(modifiedSTS, "testComplexTypeSimpleContentElem")); + assertEquals("Unresolved Complex Type should be 'mailsType'", + "mailsType", + getElementType(modifiedSTS, "testComplexTypeElementOnlyContentElem")); + assertEquals("Unresolved Complex Type should be 'mixedContentType'", + "mixedContentType", + getElementType(modifiedSTS, "testComplexTypeMixedElem")); + assertEquals("Unresolved Complex Type should be 'emptyContentType'", + "emptyContentType", + getElementType(modifiedSTS, "testComplexTypeEmptyElem")); + assertEquals("Unresolved Complex Type should be 'choiceGroupType'", + "choiceGroupType", + getElementType(modifiedSTS, "testChoiceGroupElem")); + assertEquals("Unresolved Complex Type should be 'allGroupType'", + "allGroupType", + getElementType(modifiedSTS, "testAllGroupElem")); + + + // Step 3 : create an incremental STS with the file in step 1 + SchemaTypeSystem finalSTS = createNewSTS("datatypes.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", finalSTS); + + // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups + inspectSOM(finalSTS, 12, 1, 4, 1); + + // test save failure + assertFalse("Partial SOM " + finalSTS.getName() + "Save Success ", + checkPSOMSave(finalSTS)); + + // instance validation - should fail + assertFalse("Validation against instance Success - should fail ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), finalSTS)); + + } + + @Test + public void testDeleteDataTypes() throws Exception + { + System.out.println("Inside test case testDeleteDataTypes()"); + + // Step 1: read a clean XSD file to get a valid SOM + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("datatypes_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertEquals("Recovered Errors for Valid Schema", false, printRecoveredErrors()); + + // the tests - Walk thro the SOM, save, validate against an xml instance + inspectSOM(baseSTS, 13, 1, 15, 1); + + // Recovered Errors, Test for saving of the PSOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); + + // additional validation - check to see if all types are resolved to their respective types + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(baseSTS, "testAtomicTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType'", + "union.attachmentUnionType", + getElementType(baseSTS, "testUnionTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(baseSTS, "testListTypeElem")); + assertEquals("Unresolved Complex Type should be 'headerType'", + "headerType", + getElementType(baseSTS, "testComplexTypeSimpleContentElem")); + assertEquals("Unresolved Complex Type should be 'mailsType'", + "mailsType", + getElementType(baseSTS, "testComplexTypeElementOnlyContentElem")); + assertEquals("Unresolved Complex Type should be 'mixedContentType'", + "mixedContentType", + getElementType(baseSTS, "testComplexTypeMixedElem")); + assertEquals("Unresolved Complex Type should be 'emptyContentType'", + "emptyContentType", + getElementType(baseSTS, "testComplexTypeEmptyElem")); + assertEquals("Unresolved Complex Type should be 'choiceGroupType'", + "choiceGroupType", + getElementType(baseSTS, "testChoiceGroupElem")); + assertEquals("Unresolved Complex Type should be 'allGroupType'", + "allGroupType", + getElementType(baseSTS, "testAllGroupElem")); + + + //Step 2 : delete/remove types from the schema - should result in STS with unresolved refs + SchemaTypeSystem modifiedSTS = createNewSTS("datatypes.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // PSOM - recovered errors are expected + assertEquals("Valid Schema Type System, Errors recovered", true, printRecoveredErrors()); + + // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups + inspectSOM(modifiedSTS, 12, 1, 4, 1); + + // Test for saving of the PSOM - should not be able to save + assertFalse("PSOM " + modifiedSTS.getName() + " Save should fail", + checkPSOMSave(modifiedSTS)); + + // validate unresolved types + assertEquals("Unresolved Simple Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testAtomicTypeElem")); + assertEquals("Unresolved Simple Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testUnionTypeElem")); + // moved to detailed PSOMDetailedTest class + // Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", anySimpleType, getElementType(modifiedSTS, "testListTypeElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testComplexTypeSimpleContentElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testComplexTypeElementOnlyContentElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testComplexTypeMixedElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testComplexTypeEmptyElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testChoiceGroupElem")); + assertEquals("Unresolved Complex Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testAllGroupElem")); + + // validate against an xml valid instance - should fail + assertEquals("Validation against instance should Failed ", false, validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), modifiedSTS)); + + // Step 3 : reaload the xsd in Step 1 + SchemaTypeSystem finalSTS = createNewSTS("datatypes_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + + // should be able to save as its a valid SOM + assertNotNull("Schema Type System created is Null.", finalSTS); + + // walk the PSOM + inspectSOM(finalSTS, 13, 1, 15, 1); + + // should be able to save as its a valid SOM + assertTrue("SOM " + finalSTS.getName() + "Save failed", + checkPSOMSave(finalSTS)); + + // instance validation - should be fine + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), finalSTS)); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + + // additional validation - check to see if all types are resolved to their respective types + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(baseSTS, "testAtomicTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType'", + "union.attachmentUnionType", + getElementType(baseSTS, "testUnionTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(baseSTS, "testListTypeElem")); + assertEquals("Unresolved Complex Type should be 'headerType'", + "headerType", + getElementType(baseSTS, "testComplexTypeSimpleContentElem")); + assertEquals("Unresolved Complex Type should be 'mailsType'", + "mailsType", + getElementType(baseSTS, "testComplexTypeElementOnlyContentElem")); + assertEquals("Unresolved Complex Type should be 'mixedContentType'", + "mixedContentType", + getElementType(baseSTS, "testComplexTypeMixedElem")); + assertEquals("Unresolved Complex Type should be 'emptyContentType'", + "emptyContentType", + getElementType(baseSTS, "testComplexTypeEmptyElem")); + assertEquals("Unresolved Complex Type should be 'choiceGroupType'", + "choiceGroupType", + getElementType(baseSTS, "testChoiceGroupElem")); + assertEquals("Unresolved Complex Type should be 'allGroupType'", + "allGroupType", + getElementType(baseSTS, "testAllGroupElem")); + + } + + @Test + public void testModifyDataTypes() throws Exception + { + System.out.println("Inside test case testModifyDataTypes()"); + + // Step 1: read in a clean XSD datatypes_added.xsd, to create a base schema with no unresolved components + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("datatypes_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 13, 1, 15, 1); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); + + // check types before modify + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(baseSTS, "testAtomicTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(baseSTS, "testListTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", + "union.attachmentUnionType", + getElementType(baseSTS, "testUnionTypeElem")); + + + //Step 2 : modify types from the schema - should result in STS with unresolved refs + //remove one of the constituent types for the union and test to see if union is anySimpleType + SchemaTypeSystem modifiedSTS = createNewSTS("datatypes_modified.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // test the PSOM created :walk thro the PSOM, look for # of elements,attributes,types & attribute groups + inspectSOM(modifiedSTS, 13, 1, 13, 1); + + // Test for saving of the PSOM - should not be able to save + assertFalse("PSOM " + modifiedSTS.getName() + " Save should fail", + checkPSOMSave(modifiedSTS)); + + // validate unresolved types + assertEquals("Unresolved Simple Type - Atomic should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testAtomicTypeElem")); + + // moved to detailed PSOMDetailedTest class + //Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", anySimpleType, getElementType(modifiedSTS, "testListTypeElem")); + //Assert.assertEquals("Unresolved Simple Type - Union should be 'anySimpleType'", anySimpleType, getElementType(modifiedSTS, "testUnionTypeElem")); + + // validate against an xml valid instance - should fail + assertFalse("Validation against instance should Failed ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), modifiedSTS)); + + // step 3: reload the original STS + SchemaTypeSystem finalSTS = createNewSTS("datatypes_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // walk the SOM + inspectSOM(finalSTS, 13, 1, 15, 1); + + // validate successful save + assertTrue("SOM " + finalSTS.getName() + "Save failed", + checkPSOMSave(finalSTS)); // should be able to save as its a valid SOM + + // validate instance - should validate + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), finalSTS)); + + // check types after modify + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(finalSTS, "testAtomicTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(finalSTS, "testListTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", + "union.attachmentUnionType", + getElementType(finalSTS, "testUnionTypeElem")); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + } + + @Test + public void testDeleteDerivedTypes() throws Exception + { + System.out.println("Inside test case testDeleteDerivedTypes()"); + + // Step 1: read in a clean XSD derived_types_added.xsd with base and derived types to create a base schema with no unresolved components + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("derived_types_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 13, 0, 14, 0); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); + + // check types before deletion of base types + assertEquals("Elem Type should be 'ExtensionBaseType' (base)", + "ExtensionBaseType", + getElementType(baseSTS, "ExtensionBaseTypeElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedComplexContentType", + getElementType(baseSTS, "ExtensionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'ExtensionBaseMixedContentType' (base)", + "ExtensionBaseMixedContentType", + getElementType(baseSTS, "ExtensionBaseMixedContentTypElem")); + assertEquals("Elem Type should be 'ExtensionDerivedMixedContentType' (derived)", + "ExtensionDerivedMixedContentType", + getElementType(baseSTS, "ExtensionDerivedMixedContentTypeElem")); + + assertEquals("Elem Type should be 'RestrictionSimpleContentBaseType'", + "RestrictionSimpleContentBaseType", getElementType(baseSTS, "RestrictionSimpleContentBaseTypeElem")); + assertEquals("Elem Type should be 'RestrictionSimpleContentDerivedType'", + "RestrictionSimpleContentDerivedType", getElementType(baseSTS, "RestrictionSimpleContentDerivedTypeElem")); + + assertEquals("Elem Type should be 'RestrictionBaseComplexContentType'", + "RestrictionBaseComplexContentType", + getElementType(baseSTS, "RestrictionBaseComplexContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedComplexContentType'", + "RestrictionDerivedComplexContentType", + getElementType(baseSTS, "RestrictionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'RestrictionBaseMixedContentType'", + "RestrictionBaseMixedContentType", getElementType(baseSTS, "RestrictionBaseMixedContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedMixedContentType'", + "RestrictionDerivedMixedContentType", getElementType(baseSTS, "RestrictionDerivedMixedContentTypeElem")); + + assertEquals("Elem Type should be 'RestrictionBaseEmptyContentType'", + "RestrictionBaseEmptyContentType", getElementType(baseSTS, "RestrictionBaseEmptyContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedEmptyContentType'", + "RestrictionDerivedEmptyContentType", getElementType(baseSTS, "RestrictionDerivedEmptyContentTypeElem")); + + // Step 2: create invalid PSOM with base type removed + SchemaTypeSystem modifiedSTS = createNewSTS("derived_types.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // recovearble errors + assertTrue("No Recovered Errors for Invalid PSOM", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 13, 0, 9, 0); + + // Recovered Errors, Test for saving of the SOM + assertEquals("SOM " + modifiedSTS.getName() + "Save Success - should fail!", + false, checkPSOMSave(modifiedSTS)); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); + + // check types - base should be 'anyType' + assertEquals("Elem Type should be 'anyType' (base)", + anyType, + getElementType(modifiedSTS, "ExtensionBaseTypeElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedComplexContentType", + getElementType(modifiedSTS, "ExtensionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'anyType' (base)", + anyType, + getElementType(modifiedSTS, "ExtensionBaseMixedContentTypElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedMixedContentType", + getElementType(modifiedSTS, "ExtensionDerivedMixedContentTypeElem")); + + // Restriction Simple Content Base type commented does not result in recoverable SOM + // moved to Detailed Test + //Assert.assertEquals("Elem Type should be 'anyType'", + // anyType, + // getElementType(modifiedSTS, "RestrictionSimpleContentBaseTypeElem")); + // + + assertEquals("Elem Type should be 'RestrictionSimpleContentDerivedType'", + "RestrictionSimpleContentDerivedType", + getElementType(modifiedSTS, "RestrictionSimpleContentDerivedTypeElem")); + + assertEquals("Elem Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "RestrictionBaseComplexContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedComplexContentType'", + "RestrictionDerivedComplexContentType", + getElementType(modifiedSTS, "RestrictionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "RestrictionBaseMixedContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedMixedContentType'", + "RestrictionDerivedMixedContentType", + getElementType(modifiedSTS, "RestrictionDerivedMixedContentTypeElem")); + + assertEquals("Elem Type should be 'anyType'", anyType, + getElementType(modifiedSTS, "RestrictionBaseEmptyContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedEmptyContentType'", + "RestrictionDerivedEmptyContentType", getElementType(modifiedSTS, "RestrictionDerivedEmptyContentTypeElem")); + + + // step 3: reload the original STS + SchemaTypeSystem finalSTS = createNewSTS("derived_types_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(finalSTS, 13, 0, 14, 0); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("SOM " + finalSTS.getName() + "Save failed!", + checkPSOMSave(finalSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), finalSTS)); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + } + + @Test + public void testAddDerivedTypes() throws Exception + { + System.out.println("Inside test case testAddDerivedTypes()"); + + // Step 1: start with invalid SOM - one that has derived types but the base types are not defined + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("derived_types.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + assertTrue("No Recovered Errors for Invalid PSOM", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 13, 0, 9, 0); + + // Recovered Errors, Test for saving of the SOM + assertFalse("SOM " + baseSTS.getName() + "Save Success - should fail!", + checkPSOMSave(baseSTS)); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); + + // check types - base should be 'anyType' + assertEquals("Elem Type should be 'anyType' (base)", + anyType, + getElementType(baseSTS, "ExtensionBaseTypeElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedComplexContentType", + getElementType(baseSTS, "ExtensionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'anyType' (base)", + anyType, + getElementType(baseSTS, "ExtensionBaseMixedContentTypElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedMixedContentType", + getElementType(baseSTS, "ExtensionDerivedMixedContentTypeElem")); + + // Step 2: create valid PSOM now from xsd with base types defined + SchemaTypeSystem modifiedSTS = createNewSTS("derived_types_added.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 13, 0, 14, 0); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("SOM " + modifiedSTS.getName() + "Save failed!", + checkPSOMSave(modifiedSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); + + // check types before deletion of base types + assertEquals("Elem Type should be 'ExtensionBaseType' (base)", + "ExtensionBaseType", + getElementType(modifiedSTS, "ExtensionBaseTypeElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedComplexContentType", + getElementType(modifiedSTS, "ExtensionDerivedComplexContentTypeElem")); + assertEquals("Elem Type should be 'ExtensionBaseMixedContentType' (base)", + "ExtensionBaseMixedContentType", + getElementType(modifiedSTS, "ExtensionBaseMixedContentTypElem")); + assertEquals("Elem Type should be 'ExtensionDerivedMixedContentType' (derived)", + "ExtensionDerivedMixedContentType", + getElementType(modifiedSTS, "ExtensionDerivedMixedContentTypeElem")); + + } + + // moved to PSOMDetaiedTest + //public void testDeleteReusableGroups() throws Exception + //{} + //public void testModifyReusableGroups() throws Exception + @Test + public void testAddReusableGroups() throws Exception + { + System.out.println("Inside test case testAddReusableGroups()"); + + // Step 1: read in invalid XSD groups.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("groups.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // recovearble errors + assertTrue("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 7, 0, 4, 1); + + // Recovered Errors, Test for saving of the SOM - should fail + assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); + + // verify types + // named model groups + assertEquals("Elem Type should be 'ModelGrpType'", + "ModelGrpType", + getElementType(baseSTS, "ModelGrpTypeElem")); + assertTrue("Elem Type should be 'AttributeGroup'", + getAttributeGroup(baseSTS, "AttributeGroup")); + + // Step 2: create a SOM with valid xsd + SchemaTypeSystem modifiedSTS = createNewSTS("groups_added.xsd_", + baseSTS, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 7, 0, 5, 2); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + modifiedSTS.getName() + "Save failed!", + checkPSOMSave(modifiedSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); + + // verify named model groups + assertEquals("Elem Type should be 'ModelGrpType'", + "ModelGrpType", + getElementType(modifiedSTS, "ModelGrpTypeElem")); + assertTrue("Elem Type should be 'AttributeGroup'", + getAttributeGroup(modifiedSTS, "AttributeGroup")); + + + } + + @Test + public void testAddSubstitutionGroups() throws Exception + { + System.out.println("Inside test case testAddSubstitutionGroups()"); + + // step1: load an invalid PSOM by with incomplete/missing Subst Grp head elem definition + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("groups.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // errors recovered + assertTrue("No Recovered Errors for recovered PSOM", + printRecoveredErrors()); + + // Recovered Errors, Test for saving of the SOM + assertFalse("SOM " + baseSTS.getName() + "Save Success - should fail!", + checkPSOMSave(baseSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 7, 0, 4, 1); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); + + // verify types + assertEquals("Elem Type should be 'anyType'", + anyType, + getElementType(baseSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'anyType' (Member of Sub. Group)", + anyType, + getElementType(baseSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(baseSTS, "SubGrpMemberElem2")); + + // named model groups + assertEquals("Elem Type should be 'ModelGrpType'", + "ModelGrpType", + getElementType(baseSTS, "ModelGrpTypeElem")); + assertTrue("Elem Type should be 'AttributeGroup'", + getAttributeGroup(baseSTS, "AttributeGroup")); + + // Step 2: create a valid SOM and add to these + SchemaTypeSystem modifiedSTS = createNewSTS("groups_added.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 7, 0, 5, 2); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + modifiedSTS.getName() + "Save failed!", + checkPSOMSave(modifiedSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); + + // verify types - substitution groups + assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", + "SubGrpHeadElemType", + getElementType(modifiedSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", + "SubGrpHeadElemType", + getElementType(modifiedSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(modifiedSTS, "SubGrpMemberElem2")); + + // named model groups - moved to check in test + //Assert.assertEquals("Elem Type should be 'ModelGrpType'", "ModelGrpType", getElementType(baseSTS, "ModelGrpTypeElem")); + //Assert.assertEquals("Elem Type should be 'AttributeGroup'", "AttributeGroup", getAttributeGroup(baseSTS,"AttributeGroup")); + } + + @Test + public void testDeleteSubstitutionGroups() throws Exception + { + System.out.println("Inside test case testDeleteSubstitutionGroups()"); + + // Step 1: read in a clean XSD groups_added.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("groups_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 7, 0, 5, 2); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); + + // verify types - substitution groups + assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", + "SubGrpHeadElemType", + getElementType(baseSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", + "SubGrpHeadElemType", + getElementType(baseSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(baseSTS, "SubGrpMemberElem2")); + + // named model groups + //Assert.assertEquals("Elem Type should be 'ModelGrpType'", "ModelGrpType", getElementType(baseSTS, "ModelGrpTypeElem")); + //Assert.assertEquals("Elem Type should be 'AttributeGroup'", "AttributeGroup", getAttributeGroup(baseSTS,"AttributeGroup")); + + // step2: load an invalid PSOM by deleting the Subst Grp head elem definition + SchemaTypeSystem modifiedSTS = createNewSTS("groups.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + assertTrue("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // Recovered Errors, Test for saving of the SOM + assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", + checkPSOMSave(modifiedSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 7, 0, 4, 1); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); + + // verify types + assertEquals("Elem Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'anyType' (Member of Sub. Group)", + anyType, + getElementType(modifiedSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(modifiedSTS, "SubGrpMemberElem2")); + + // named model groups + assertEquals("Elem Type should be 'ModelGrpType'", + "ModelGrpType", + getElementType(modifiedSTS, "ModelGrpTypeElem")); + assertTrue("Elem Type should be 'AttributeGroup'", + getAttributeGroup(modifiedSTS, "AttributeGroup")); + + // step 3: create a PSOM with the original xsd + SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // Test for saving of the SOM - should go thro + assertEquals("SOM " + finalSTS.getName() + "Save failed!", + true, + checkPSOMSave(finalSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); + + // verify types + assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", + "SubGrpHeadElemType", + getElementType(finalSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", + "SubGrpHeadElemType", + getElementType(finalSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(finalSTS, "SubGrpMemberElem2")); + + // named model groups + //Assert.assertEquals("Elem Type should be 'ModelGrpType'", "ModelGrpType", getElementType(baseSTS, "ModelGrpTypeElem")); + //Assert.assertEquals("Elem Type should be 'AttributeGroup'", "AttributeGroup", getAttributeGroup(baseSTS,"AttributeGroup")); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + } + + @Test + public void testModifySubstitutionGroups() throws Exception + { + System.out.println("Inside test case testModifySubstitutionGroups()"); + + // Step 1: read in a clean XSD groups_added.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("groups_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 7, 0, 5, 2); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); + + // verify types + assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", + "SubGrpHeadElemType", + getElementType(baseSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", + "SubGrpHeadElemType", + getElementType(baseSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(baseSTS, "SubGrpMemberElem2")); + + // step2: load a modified xsd with type of head elem in subs grp changed + SchemaTypeSystem modifiedSTS = createNewSTS("groups_modified.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // Recovered Errors, Test for saving of the SOM - still a valid PSOM + assertTrue("SOM " + modifiedSTS.getName() + "Save Success - should fail!", + checkPSOMSave(modifiedSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 5, 0, 3, 0); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); + + // verify types + assertEquals("Elem Type should be 'SubGrpHeadElemType2'", + "SubGrpHeadElemType2", + getElementType(modifiedSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'SubGrpHeadElemType2' (derived)", + "SubGrpHeadElemType2", + getElementType(modifiedSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", + getElementType(modifiedSTS, "SubGrpMemberElem2")); + + // step3 : reload the original xsd + SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + finalSTS.getName() + "Save failed!", + checkPSOMSave(finalSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(finalSTS, 7, 0, 5, 2); + + // verify types + assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", + "SubGrpHeadElemType", + getElementType(finalSTS, "SubGrpHeadElem")); + assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", + "SubGrpHeadElemType", + getElementType(finalSTS, "SubGrpMemberElem1")); + assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", + "ExtensionSubGrpHeadElemType", getElementType(finalSTS, "SubGrpMemberElem2")); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + } + + @Test + public void testModifyIdConstraints() throws Exception + { + System.out.println("Inside test case testModifyIdConstraints()"); + + // Step 1: read in a clean XSD groups_added.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("constraints_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 5, 0, 2, 0); + + assertTrue("Constraint 'uniqueConstraint' should be found",lookForIdentityConstraint(baseSTS,"uniqueConstraint")); + assertTrue("Constraint 'keyConstraint' should be found",lookForIdentityConstraint(baseSTS,"keyConstraint")); + assertTrue("Constraint 'KeyRefConstraint' should be found",lookForIdentityConstraint(baseSTS,"KeyRefConstraint")); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation against valid instance- should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_constraints_valid.xml"), baseSTS)); + + // validation against instance which violates the Constraints - should fail + assertFalse("Validation against invalid should fail", + validateInstance(getTestCaseFile("instance_constraints_invalid.xml"), baseSTS)); + + // Step 2: create an incremental PSOM with the constraint commented out + // Note: Partial SOMs cannot be created for Unique/Key constraints. They generate valid complete SOMs. + // The xsd includes these but the invalid SOM in this case is from a keyref definition referring to a + // non existant key + + SchemaTypeSystem modifiedSTS = createNewSTS("constraints.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // recovearble errors + assertTrue("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // Recovered Errors, Test for saving of the SOM + assertFalse("valid PSOM " + modifiedSTS.getName() + "Save failed !", + checkPSOMSave(modifiedSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 5, 0, 2, 0); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_constraints_valid.xml"), modifiedSTS)); + + // Invalid instance validation - should fail bcos of Unique constraint definition missing + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_constraints_invalid.xml"), modifiedSTS)); + + assertFalse("KeyRef 'KeyRefConstraint' should not be resolved", + lookForIdentityConstraint(modifiedSTS, "KeyConstraint")); + + // Step 3 : recreate SOM in first step and compare it + SchemaTypeSystem finalSTS = createNewSTS("constraints_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(finalSTS, 5, 0, 2, 0); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + finalSTS.getName() + "Save failed!", + checkPSOMSave(finalSTS)); + + // instance validation against valid instance- should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_constraints_valid.xml"), finalSTS)); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); + } + +} + + + + diff --git a/test/src/compile/scomp/som/common/SomTestBase.java b/src/test/java/compile/scomp/som/common/SomTestBase.java similarity index 95% rename from test/src/compile/scomp/som/common/SomTestBase.java rename to src/test/java/compile/scomp/som/common/SomTestBase.java index 36109c4..e5de084 100644 --- a/test/src/compile/scomp/som/common/SomTestBase.java +++ b/src/test/java/compile/scomp/som/common/SomTestBase.java @@ -28,11 +28,10 @@ */ package compile.scomp.som.common; -import compile.scomp.common.CompileCommon; import compile.scomp.common.CompileTestBase; -import junit.framework.Assert; import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.tool.Diff; +import org.junit.Assert; import javax.xml.namespace.QName; import java.io.File; @@ -43,10 +42,9 @@ import java.util.Iterator; import java.util.List; -/** - * - * - */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + public class SomTestBase extends CompileTestBase { public static String casesRootDir = XBEAN_CASE_ROOT+ P + "compile" + P + "som" + P; @@ -61,11 +59,6 @@ public class SomTestBase extends CompileTestBase public static final String anySimpleType = "anySimpleType"; public static final String anyType = "anyType"; - public SomTestBase(String name) - { - super(name); - } - public static void inspectSOM(SchemaTypeSystem schematypesys, int expectedGlobalElems, int expectedGlobalAttrs, @@ -126,7 +119,7 @@ public static void inspectSOM(SchemaTypeSystem schematypesys, // # of global attributes out.println("----- # Global Attributes :" + schematypesys.globalAttributes().length); - Assert.assertEquals("Incorrect Number of Global Attributes in STS " + schematypesys.getName(), expectedGlobalAttrs, schematypesys.globalAttributes().length); + assertEquals("Incorrect Number of Global Attributes in STS " + schematypesys.getName(), expectedGlobalAttrs, schematypesys.globalAttributes().length); for (int i = 0; i < schematypesys.globalAttributes().length; i++) { out.println("\t------> Attr Name :" + schematypesys.globalAttributes()[i].getName()); @@ -135,7 +128,7 @@ public static void inspectSOM(SchemaTypeSystem schematypesys, // # of global elements out.println("----- # Global Elements :" + schematypesys.globalElements().length); - Assert.assertEquals("Incorrect Number of Global Elements in STS " + schematypesys.getName(), expectedGlobalElems, schematypesys.globalElements().length); + assertEquals("Incorrect Number of Global Elements in STS " + schematypesys.getName(), expectedGlobalElems, schematypesys.globalElements().length); for (int i = 0; i < schematypesys.globalElements().length; i++) { out.println("\t------> Elem Name :" + schematypesys.globalElements()[i].getName()); @@ -144,7 +137,7 @@ public static void inspectSOM(SchemaTypeSystem schematypesys, // # of global Types out.println("----- # Global Types :" + schematypesys.globalTypes().length); - Assert.assertEquals("Incorrect Number of Global Types in STS " + schematypesys.getName(), expectedGlobalTypes, schematypesys.globalTypes().length); + assertEquals("Incorrect Number of Global Types in STS " + schematypesys.getName(), expectedGlobalTypes, schematypesys.globalTypes().length); for (int i = 0; i < schematypesys.globalTypes().length; i++) { out.println("\t------> TypeName:" + schematypesys.globalTypes()[i].getName()); @@ -152,7 +145,7 @@ public static void inspectSOM(SchemaTypeSystem schematypesys, // # of attribute Groups out.println("----- # of Attribute Groups :" + schematypesys.attributeGroups().length); - Assert.assertEquals("Incorrect Number of Attribute Groups in STS " + schematypesys.getName(), expectedAttrGroups, schematypesys.attributeGroups().length); + assertEquals("Incorrect Number of Attribute Groups in STS " + schematypesys.getName(), expectedAttrGroups, schematypesys.attributeGroups().length); for (int i = 0; i < schematypesys.attributeGroups().length; i++) { out.println("\t------> Attr Group Name :" + schematypesys.attributeGroups()[i].getName()); @@ -310,7 +303,7 @@ public boolean lookForIdentityConstraint(SchemaTypeSystem sts, public boolean checkPSOMSave(SchemaTypeSystem tgtSTS) { - String outDirName = tgtSTS.getName().split("schemaorg_apache_xmlbeans.system.")[1]; + String outDirName = tgtSTS.getName().split("org.apache.xmlbeans.metadata.system.")[1]; String outDirNameWithPath = somOutputRootDir + P + runid + P + outDirName; // call the save @@ -421,7 +414,7 @@ public boolean validateInstance(File instancefile, { ioe.getMessage(); ioe.printStackTrace(); - Assert.fail("IOException throw when accessing instance xml file " + instancefile.getAbsoluteFile()); + fail("IOException throw when accessing instance xml file " + instancefile.getAbsoluteFile()); } catch (XmlException xme) { @@ -438,7 +431,7 @@ public boolean validateInstance(File instancefile, } } System.out.println("END Instance Validation Errors .. .. .."); - Assert.fail("Instance Validation - Xml Exception caught"); + fail("Instance Validation - Xml Exception caught"); } // validation successful diff --git a/src/test/java/compile/scomp/som/detailed/PartialSOMDetailedTest.java b/src/test/java/compile/scomp/som/detailed/PartialSOMDetailedTest.java new file mode 100644 index 0000000..6e19a9e --- /dev/null +++ b/src/test/java/compile/scomp/som/detailed/PartialSOMDetailedTest.java @@ -0,0 +1,623 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package compile.scomp.som.detailed; + +import compile.scomp.som.common.SomTestBase; +import org.apache.xmlbeans.SchemaTypeSystem; +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlOptions; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; + +import static org.junit.Assert.*; + + +public class PartialSOMDetailedTest extends SomTestBase { + + // inherited methods + @Before + public void setUp() throws Exception { + // initialize the built in schema type + builtin = XmlBeans.getBuiltinTypeSystem(); + + // populate the XmlOptions + if (errors == null) { + errors = new ArrayList(); + } + if (options == null) { + options = (new XmlOptions()).setErrorListener(errors); + options.setCompileDownloadUrls(); + options.setCompilePartialTypesystem(); + options.setLoadLineNumbers(); + } + + // initialize the runid to be used for generating output files for the PSOM walk thro's + runid = new Date().getTime(); + + // clean the output from the previous run + // delete directories created by checkPSOMSave() and output text file created by inspectPSOM() + deleteDirRecursive(new File(somOutputRootDir)); + } + + @After + public void tearDown() { + errors.clear(); + } + + @Test + public void testAddDataTypesList() { + System.out.println("Inside test case testAddDataTypesList()"); + + // Step 1 : create a PSOM from an incomplete/invalid xsd (datatypes.xsd) with unresolved references to various types + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("datatypes.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // recovearble errors should exist + assertTrue("No Recovered Errors for Invalid Schema", + printRecoveredErrors()); + + // Walk thro the SOM (pass #Elems, #Attr, #Types, #AttrGroups) + inspectSOM(baseSTS, 12, 1, 4, 1); + + // Test for saving of the PSOM - should not be able to save + assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should fail!", + checkPSOMSave(baseSTS)); + + // instance validation - should fail + assertFalse("Validation against instance Success - should fail ", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); + + // validate unresolved types - the ListType should resolve to 'anyType' + assertEquals("Unresolved List Type should be 'anyType'", + anyType, + getElementType(baseSTS, "testListTypeElem")); + } + + @Test + public void testDeleteReusableGroups() { + System.out.println("Inside test case testDeleteSubstitutionGroups()"); + + // Step 1: read in a clean XSD groups_added.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("reusable_grps_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 7, 0, 5, 1); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); + + // verify named model groups + assertTrue("Attribute Group 'AttributeGroup' should exist", + getAttributeGroup(baseSTS, "AttributeGroup")); + assertTrue("Model Group 'NamedModelGroup' should exist", + getModelGroup(baseSTS, "NamedModelGroup")); + + // step2: load an invalid PSOM by deleting the ModelGroup and AttributeGroup definitions commented + SchemaTypeSystem modifiedSTS = createNewSTS("reusable_grps.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // Recovered Errors, Test for saving of the SOM + printRecoveredErrors(); + assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", + checkPSOMSave(modifiedSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 7, 0, 5, 0); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); + + // named model groups + assertFalse("Attribute Group 'AttributeGroup' should not exist", + getAttributeGroup(modifiedSTS, "AttributeGroup")); + assertFalse("Model Group 'NamedModelGroup' should not exist", + getModelGroup(modifiedSTS, "NamedModelGroup")); + + // step 3: create a PSOM with the original xsd + SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", + modifiedSTS, + "FinalSchemaTS", sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + finalSTS.getName() + "Save failed!", + checkPSOMSave(finalSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); + + // verify named model groups types + assertTrue("Attribute Group 'AttributeGroup' should exist", + getAttributeGroup(baseSTS, "AttributeGroup")); + assertTrue("Model Group 'NamedModelGroup' should exist", + getModelGroup(baseSTS, "NamedModelGroup")); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS", "FinalSchemaTS")); + } + + @Test + public void testModifyDataTypesList() { + System.out.println("Inside test case testModifyDataTypes()"); + + // 1. remove one of the constituent types for the union and test to see if union is anySimpleType + + // Step 1: read in a clean XSD datatypes_added.xsd, to create a base schema with no unresolved components + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("datatypes_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 13, 1, 15, 1); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); + + // check types before modify + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(baseSTS, "testAtomicTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(baseSTS, "testListTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", + "union.attachmentUnionType", + getElementType(baseSTS, "testUnionTypeElem")); + + + //Step 2 : modify types from the schema - should result in STS with unresolved refs + SchemaTypeSystem modifiedSTS = createNewSTS("datatypes_modified.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // test the PSOM created :walk thro the PSOM, look for # of elements,attributes,types & attribute groups + inspectSOM(modifiedSTS, 13, 1, 13, 1); + + // Test for saving of the PSOM - should not be able to save + assertFalse("PSOM " + modifiedSTS.getName() + " Save should fail", + checkPSOMSave(modifiedSTS)); + + // validate unresolved types + // list and union types are of type "anyType" and not "anySimpleType + // https://stackoverflow.com/questions/37801268/what-are-the-restrictions-of-xsdanysimpletype-on-xsdanytype-and-where-are-the + assertEquals("Unresolved Simple Type - Atomic should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testAtomicTypeElem")); + assertEquals("Unresolved List Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "testListTypeElem")); +// assertEquals("Unresolved Simple Type - Union should be 'anySimpleType'", +// anySimpleType, +// getElementType(modifiedSTS, "testUnionTypeElem")); + + // validate against an xml valid instance - should fail + assertFalse("Validation against instance should Failed ", + validateInstance(getTestCaseFile("instance_simple_types_invalid.xml"), modifiedSTS)); + + // step 3: reload the original STS + SchemaTypeSystem finalSTS = createNewSTS("datatypes_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // walk the SOM + inspectSOM(finalSTS, 13, 1, 15, 1); + + // validate successful save + assertTrue("SOM " + finalSTS.getName() + "Save failed", + checkPSOMSave(finalSTS)); // should be able to save as its a valid SOM + + // validate instance - should validate + assertTrue("Validation against instance Failed ", + validateInstance(getTestCaseFile("instance_simple_types_valid.xml"), finalSTS)); + + // check types after modify + assertEquals("Unresolved Simple Type should be 'attachmentTypes'", + "attachmentTypes", + getElementType(finalSTS, "testAtomicTypeElem")); + assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", + "attchmentExtensionListTypes", + getElementType(finalSTS, "testListTypeElem")); + assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", + "union.attachmentUnionType", + getElementType(finalSTS, "testUnionTypeElem")); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS", "FinalSchemaTS")); + } + + @Test + public void testDeleteDerivedTypes() { + System.out.println("Inside test case testDeleteDerivedTypes()"); + + // Step 1: read in a clean XSD derived_types_added.xsd with base and derived types to create a base schema with no unresolved components + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("derived_types_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 13, 0, 14, 0); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); + + // check types before deletion of base types + assertEquals("Elem Type should be 'RestrictionSimpleContentBaseType'", + "RestrictionSimpleContentBaseType", getElementType(baseSTS, "RestrictionSimpleContentBaseTypeElem")); + + // Step 2: create invalid PSOM with base type removed + SchemaTypeSystem modifiedSTS = createNewSTS("derived_types.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // recovearble errors + assertTrue("No Recovered Errors for Invalid PSOM", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 13, 0, 9, 0); + + // Recovered Errors, Test for saving of the SOM + assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", checkPSOMSave(modifiedSTS)); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); + + // check types - base should be 'anyType' + // Restriction Complex Content Base type commented + assertEquals("Elem Type should be 'anyType'", + anyType, + getElementType(modifiedSTS, "RestrictionBaseComplexContentTypeElem")); + + + } + + @Test + public void testModifyReusableGroups() { + System.out.println("Inside test case testModifyReusableGroups()"); + + // Step 1: read in a clean XSD groups_added.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("groups_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 7, 0, 5, 2); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); + + // verify named model groups + assertTrue("Model Group 'NamedModelGroup' should exist ", + getModelGroup(baseSTS, "NamedModelGroup")); + assertTrue("Attribute Group 'AttributeGroup' should exist", + getAttributeGroup(baseSTS, "AttributeGroup")); + + // step2: load a modified xsd with type of head elem in subs grp changed + SchemaTypeSystem modifiedSTS = createNewSTS("reusable_grps_modified.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // Recovered Errors, Test for saving of the SOM , invalid since grp definitions are commented out + printRecoveredErrors(); + assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", + checkPSOMSave(modifiedSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 7, 0, 5, 1); + + // instance validation - should fail + assertFalse("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); + + // verify named model groups + assertEquals("Elem Type should be 'ModelGrpType'", + "ModelGrpType", + getElementType(modifiedSTS, "ModelGrpTypeElem")); + assertTrue("Elem Type should be 'AttributeGroup'", + getAttributeGroup(modifiedSTS, "AttributeGroup")); + + // step3 : reload the original xsd + SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", + modifiedSTS, + "FinalSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", finalSTS); + + // Test for saving of the SOM - should go thro + assertTrue("SOM " + finalSTS.getName() + "Save failed!", + checkPSOMSave(finalSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(finalSTS, 7, 0, 5, 2); + + // verify named model groups + assertEquals("Elem Type should be 'ModelGrpType'", + "ModelGrpType", + getElementType(finalSTS, "ModelGrpTypeElem")); + assertTrue("Elem Type should be 'AttributeGroup'", + getAttributeGroup(finalSTS, "AttributeGroup")); + + // compare this to the original schema here + assertTrue(compareSavedSOMs("BaseSchemaTS", "FinalSchemaTS")); + } + + @Test + public void testModifyDerivedTypes() { + System.out.println("Inside test case testModifyDerivedTypes()"); + + // Step 1: read in a clean XSD derived_types_added.xsd + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("derived_types_added.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 13, 0, 14, 0); + + // Recovered Errors, Test for saving of the SOM - should go thro + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // instance validation - should be ok + assertTrue("Validation against instance failed", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); + + // check types before deletion of base types + assertEquals("Elem Type should be 'ExtensionBaseType' (base)", + "ExtensionBaseType", + getElementType(baseSTS, "ExtensionBaseTypeElem")); + assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", + "ExtensionDerivedComplexContentType", + getElementType(baseSTS, "ExtensionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'ExtensionBaseMixedContentType' (base)", + "ExtensionBaseMixedContentType", + getElementType(baseSTS, "ExtensionBaseMixedContentTypElem")); + assertEquals("Elem Type should be 'ExtensionDerivedMixedContentType' (derived)", + "ExtensionDerivedMixedContentType", + getElementType(baseSTS, "ExtensionDerivedMixedContentTypeElem")); + + assertEquals("Elem Type should be 'RestrictionSimpleContentBaseType'", + "RestrictionSimpleContentBaseType", + getElementType(baseSTS, "RestrictionSimpleContentBaseTypeElem")); + assertEquals("Elem Type should be 'RestrictionSimpleContentDerivedType'", + "RestrictionSimpleContentDerivedType", + getElementType(baseSTS, "RestrictionSimpleContentDerivedTypeElem")); + + assertEquals("Elem Type should be 'RestrictionBaseComplexContentType'", + "RestrictionBaseComplexContentType", + getElementType(baseSTS, "RestrictionBaseComplexContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedComplexContentType'", + "RestrictionDerivedComplexContentType", + getElementType(baseSTS, "RestrictionDerivedComplexContentTypeElem")); + + assertEquals("Elem Type should be 'RestrictionBaseMixedContentType'", + "RestrictionBaseMixedContentType", + getElementType(baseSTS, "RestrictionBaseMixedContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedMixedContentType'", + "RestrictionDerivedMixedContentType", + getElementType(baseSTS, "RestrictionDerivedMixedContentTypeElem")); + + assertEquals("Elem Type should be 'RestrictionBaseEmptyContentType'", + "RestrictionBaseEmptyContentType", + getElementType(baseSTS, "RestrictionBaseEmptyContentTypeElem")); + assertEquals("Elem Type should be 'RestrictionDerivedEmptyContentType'", + "RestrictionDerivedEmptyContentType", + getElementType(baseSTS, "RestrictionDerivedEmptyContentTypeElem")); + + + // step 2 : change the base types now : derived_types_modified.xsd + SchemaTypeSystem modifiedSTS = createNewSTS("derived_types_modifed.xsd_", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // no recovearble errors just added another type + assertFalse("valid PSOM", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + //inspectSOM(modifiedSTS, 13, 0, 14, 0); + inspectSOM(modifiedSTS, 13, 0, 17, 0); + + // instance validation - should fail + assertFalse("Validation against instance success - should fail", + validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); + + // now validate instance with new base type - this should go thro + // TODO resolve this validation + //Assert.assertTrue("Validation against instance failed", + // validateInstance(getTestCaseFile("instance_derived_types_modify.xml"), modifiedSTS)); + + } + + @Test + public void testNameSpacesImportFile() { + System.out.println("Inside test case testNameSpacesImportFile()"); + + // Step 1: read in an xsd that imports from another xsd file providing file name only + // The source name is not specified as this confuses the dereferecing of the location for the schemaLocation Attribute + // The absolute rul specified in tbe basename (if specified) would also work. + + //String sBaseSourceName = "file:/D:/SVNNEW/xmlbeans/trunk/test/cases/xbean/compile/som/"; + SchemaTypeSystem baseSTS = createNewSTS("namespaces_import_fileonly.xsd_", + null, + "BaseSchemaTS", + null); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors this should not be a partial Schema + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + } + + @Test + public void testNameSpacesWithInclude() { + System.out.println("Inside test case testNameSpacesWithInclude()"); + + // Step 1: read in an xsd that includes another namespace in xsd file namespaces2.xsd + //String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("namespaces_include.xsd_", + null, + "BaseSchemaTS", + null); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors - this should not be a partial Schema + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // Test for saving of the SOM - should go thro + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 2, 0, 1, 0); + + + } + + @Test + @Ignore + public void testNameSpacesImportFileWithPath() { + System.out.println("Inside test case testNameSpacesImportFileWithPath()"); + + //Step 1: read in an xsd that does not have any imports + String sBaseSourceName = "testsourcename"; + SchemaTypeSystem baseSTS = createNewSTS("namespaces_noimports.xsd_", + null, + "BaseSchemaTS", + sBaseSourceName); + + assertNotNull("Schema Type System created is Null.", baseSTS); + + // there should be NO recovearble errors - this should not be a partial Schema + assertFalse("Recovered Errors for Valid Schema", + printRecoveredErrors()); + + // Test for saving of the SOM - should go thro + assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", + checkPSOMSave(baseSTS)); + + // the tests - Walk thro the valid SOM + inspectSOM(baseSTS, 1, 0, 0, 0); + + // step 2 : read in an xsd that imports a namespace from another xsd file providing the complete file path for the imported xsd + SchemaTypeSystem modifiedSTS = createNewSTS("namespaces_import_filepath.xsd", + baseSTS, + "ModifiedSchemaTS", + sBaseSourceName); + assertNotNull("Schema Type System created is Null.", modifiedSTS); + + // no recovearble errors just added another type + assertFalse("valid PSOM", + printRecoveredErrors()); + + // the tests - Walk thro the valid SOM + inspectSOM(modifiedSTS, 2, 0, 1, 0); + + } +} + + + + diff --git a/test/src/dom/checkin/AttributeSyncTest.java b/src/test/java/dom/checkin/AttributeSyncTest.java similarity index 77% rename from test/src/dom/checkin/AttributeSyncTest.java rename to src/test/java/dom/checkin/AttributeSyncTest.java index 0a565b7..5ef9e14 100755 --- a/test/src/dom/checkin/AttributeSyncTest.java +++ b/src/test/java/dom/checkin/AttributeSyncTest.java @@ -17,24 +17,10 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; - - -/** - * - * - */ +import org.junit.Before; public class AttributeSyncTest extends AttributeTest { - public AttributeSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(AttributeSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); diff --git a/src/test/java/dom/checkin/AttributeTest.java b/src/test/java/dom/checkin/AttributeTest.java new file mode 100755 index 0000000..5dc7278 --- /dev/null +++ b/src/test/java/dom/checkin/AttributeTest.java @@ -0,0 +1,425 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package dom.checkin; + + +import dom.common.DomUtils; +import dom.common.NodeWithChildrenTest; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.*; + +import static org.junit.Assert.*; + + +public class AttributeTest extends NodeWithChildrenTest { + + public AttributeTest() { + String sDTD = "" + + "" + + "" + + "]>"; + + sXml = "some text"; + if (bDTD) + sXml = sDTD + sXml; + sXmlNS = + ""; + } + + @Test + public void testNodeName() { + + String sExpected = "myns:at0"; + assertEquals(sExpected, m_node.getNodeName()); + } + + @Test + public void testGetName() { + + String sExpected = "myns:at0"; + assertEquals(sExpected, ((Attr) m_node).getName()); + } + + @Test + public void testNodeType() { + assertEquals(Node.ATTRIBUTE_NODE, m_node.getNodeType()); + } + + @Test + public void testNodeValue() { + assertEquals("val01", m_node.getNodeValue()); + } + + + //following are null here + @Test + public void testNextSibling() { + assertEquals(null, m_node.getNextSibling()); + } + + @Test + public void testPreviousSibling() { + assertEquals(null, m_node.getPreviousSibling()); + } + + @Test + public void testParent() { + assertEquals(null, m_node.getParentNode()); + } + + @Test + public void testPrefix() { + assertEquals("myns", m_node.getPrefix()); + } + + @Test + public void testNamespaceUri() { + assertEquals("uri:foo", m_node.getNamespaceURI()); + } + + @Test + public void testLocalName() { + assertEquals("at0", m_node.getLocalName()); + } + + @Test + public void testAppendChild() { + //elt + Node newChild = m_doc.createElement("foo"); + try { + m_node.appendChild(newChild); + fail("Cannot append an element children to attributes " + + m_node.getChildNodes().getLength()); + } + catch (DOMException de) { + assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); + } + + newChild = m_doc.createTextNode("foobar"); + m_node.appendChild(newChild); + assertEquals(2, m_node.getChildNodes().getLength()); + +//TODO + m_node.normalize(); + assertEquals(1, m_node.getChildNodes().getLength()); + assertEquals("val01foobar", ((Text) m_node.getFirstChild()).getData()); + } + + @Test + public void testCloneNode() { + Attr cloned, + cloned1; + cloned = (Attr) m_node.cloneNode(true); + + + assertEquals(true, DomUtils.compareNodesDeep(m_node, cloned)); + assertEquals(false, m_node == cloned); + + +//TODO + cloned1 = (Attr) m_node.cloneNode(false); + // assertEquals(m_node.getChildNodes(), ); + assertEquals(true, DomUtils.compareNodesShallow(m_node, cloned)); + + if (bDTD) { + assertEquals(false, cloned.getSpecified()); + assertEquals(false, ((Attr) m_node).getSpecified()); + m_node = m_doc.getAttributes().getNamedItem("at_spec"); + cloned = (Attr) m_node.cloneNode(true); + cloned1 = (Attr) m_node.cloneNode(false); + assertEquals(cloned, cloned1); + assertEquals(true, m_node.equals(cloned)); + assertEquals(false, m_node == cloned); + assertEquals(true, cloned.getSpecified()); + assertEquals(false, ((Attr) m_node).getSpecified()); + } + } + + /** + * public void testXercesClone()throws Exception{ + * org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); + * parser.parse(new InputSource(new StringReader(sXml))); + * Document xercesDocument = parser.getDocument(); + * assertFalse (xercesDocument==null); + *

      + * Node test = m_doc.getFirstChild(); + * assertTrue(test.hasChildNodes()); + * test = ((Element) test).getAttributeNodeNS("uri:foo", "at0"); + * Node clone=test.cloneNode(false); + * assertTrue(clone.hasChildNodes()); + *

      + * } + */ + @Test + public void testGetChildNodes() { + assertEquals(1, m_node.getChildNodes().getLength()); + } + + @Test + public void testFirstChild() { + assertEquals("val01", ((Text) m_node.getFirstChild()).getData()); + } + + @Test + public void testLastChild() { + assertEquals("val01", ((Text) m_node.getLastChild()).getData()); + } + + @Test + public void testInsertBefore() { + Node newChild = m_doc.createElement("foo"); + assertEquals(1, m_node.getChildNodes().getLength()); + + Node textNode = m_node.getFirstChild(); + + try { + m_node.insertBefore(newChild, textNode); + } + catch (DOMException de) { + assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); + } + + newChild = m_doc.createTextNode("foo"); + m_node.insertBefore(newChild, textNode); + assertEquals("foo", m_node.getFirstChild().getNodeValue()); + assertEquals("val01", m_node.getLastChild().getNodeValue()); + } + + @Test + public void testRemoveChild() { + //attr w/o a value + Element owner = (Element) ((Attr) m_node).getOwnerElement(); + m_node.removeChild(m_node.getFirstChild()); + assertEquals("", ((Attr) m_node).getValue()); + // assertEquals(false,owner.hasAttributeNS("uri:foo","at0")); + } + + @Test + public void testReplaceChild() { + + //assertFalse(m_node.hasChildNodes()); + Node newChild = m_doc.createElement("foo"); + assertEquals(1, m_node.getChildNodes().getLength()); + try { + m_node.replaceChild(newChild, m_node.getFirstChild()); + fail("can not put an element under an attr"); + } + catch (DOMException de) { + assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); + } + newChild = m_doc.createTextNode("realnewval"); + assertEquals(1, m_node.getChildNodes().getLength()); + m_node.replaceChild(newChild, m_node.getFirstChild()); + if (!"realnewval".equals(((Attr) m_node).getValue())) + fail(" Expected realnewval but got " + ((Attr) m_node).getValue()); + + } + + @Test + public void testGetOwnerElement() { + assertEquals("foo", ((Attr) m_node).getOwnerElement().getLocalName()); + Node newNode = m_doc.createAttributeNS("foo1:org", "name"); + assertEquals(null, ((Attr) newNode).getOwnerElement()); + newNode = m_doc.createAttribute("name"); + assertEquals(null, ((Attr) newNode).getOwnerElement()); + } + + /*Not implem + //TODO + public void testGetSpecified(){ + if (bDTD){ + Attr at_true=(Attr)m_doc.getAttributes().getNamedItem("at_spec"); + assertEquals(false,at_true.getSpecified()); + } + assertEquals(true,((Attr)m_node).getSpecified()); + } + */ + @Test + public void testSetValue() { + String newVal = "new"; sXmlNS = - ""; - } - - public static Test suite() { - return new TestSuite(DocumentFragmentTest.class); + ""; } - + @Test public void testNodeName() { assertEquals("#document-fragment", m_node.getNodeName()); } + @Test public void testNodeType() { assertEquals(Node.DOCUMENT_FRAGMENT_NODE, m_node.getNodeType()); } - + @Test public void testNodeValue() { - assertEquals(null, m_node.getNodeValue()); + assertNull(m_node.getNodeValue()); } - + @Test public void testNextSibling() { - assertEquals(null, m_node.getNextSibling()); + assertNull(m_node.getNextSibling()); } + @Test public void testPreviousSibling() { - assertFalse(m_node == null); - assertEquals(null, m_node.getPreviousSibling()); + assertNotNull(m_node); + assertNull(m_node.getPreviousSibling()); } + @Test public void testParent() { - assertEquals(null, m_node.getParentNode()); + assertNull(m_node.getParentNode()); } + @Test public void testGetChildNodes() { assertEquals(1, m_node.getChildNodes().getLength()); } + @Test public void testFirstChild() { assertEquals("foo", m_node.getFirstChild().getNodeName()); } - + @Test public void testLastChild() { assertEquals("foo", m_node.getLastChild().getNodeName()); } + @Test public void testInsertExisitingNode() { Node child = m_doc.getFirstChild().getFirstChild();//some text if (child == m_node) @@ -91,6 +90,7 @@ public void testInsertExisitingNode() { super.testInsertExistingNode(child); } + @Test public void testAppendChildExisting() { Node child = m_doc.getFirstChild().getFirstChild();//some text if (child == m_node) @@ -105,10 +105,9 @@ public void moveToNode() { } + @Before public void setUp() throws Exception { super.setUp(); moveToNode(); } - - } diff --git a/test/src/dom/checkin/DocumentSyncTest.java b/src/test/java/dom/checkin/DocumentSyncTest.java similarity index 77% rename from test/src/dom/checkin/DocumentSyncTest.java rename to src/test/java/dom/checkin/DocumentSyncTest.java index fcba4fe..c438aa1 100755 --- a/test/src/dom/checkin/DocumentSyncTest.java +++ b/src/test/java/dom/checkin/DocumentSyncTest.java @@ -16,27 +16,13 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Before; -/** - * - * - */ - public class DocumentSyncTest extends DocumentTest { - public DocumentSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(DocumentSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); } - } diff --git a/test/src/dom/checkin/DocumentTest.java b/src/test/java/dom/checkin/DocumentTest.java similarity index 89% rename from test/src/dom/checkin/DocumentTest.java rename to src/test/java/dom/checkin/DocumentTest.java index 7ce1206..935eab6 100755 --- a/test/src/dom/checkin/DocumentTest.java +++ b/src/test/java/dom/checkin/DocumentTest.java @@ -17,28 +17,22 @@ package dom.checkin; import dom.common.NodeWithChildrenTest; -import junit.framework.AssertionFailedError; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Before; +import org.junit.Test; import org.w3c.dom.*; import org.xml.sax.InputSource; import java.io.IOException; import java.io.StringReader; +import static org.junit.Assert.*; -/** - * - * - */ public class DocumentTest extends NodeWithChildrenTest { - public DocumentTest(String s) { - super(s); - sXml = - ""; + public DocumentTest() { + sXml = ""; sXmlNS = "" + "" + @@ -48,54 +42,57 @@ public DocumentTest(String s) { ""; } - public static Test suite() { - return new TestSuite(DocumentTest.class); - } - - + @Test public void testNodeName() { assertEquals("#document", m_node.getNodeName()); } + @Test public void testNodeType() { assertEquals(Node.DOCUMENT_NODE, m_node.getNodeType()); } - + @Test public void testNodeValue() { - assertEquals(null, m_node.getNodeValue()); + assertNull(m_node.getNodeValue()); } - + @Test public void testNextSibling() { - assertEquals(null, m_node.getNextSibling()); + assertNull(m_node.getNextSibling()); } + @Test public void testPreviousSibling() { - assertEquals(null, m_node.getPreviousSibling()); + assertNull(m_node.getPreviousSibling()); } + @Test public void testParent() { - assertEquals(null, m_node.getParentNode()); + assertNull(m_node.getParentNode()); } + @Test public void testOwnerDocument() { - assertEquals(null, m_node.getOwnerDocument());//API spec + assertNull(m_node.getOwnerDocument());//API spec } + @Test public void testChildNodes() { assertEquals(1, m_node.getChildNodes().getLength()); } + @Test public void testFirstChild() { assertEquals("foo", m_node.getFirstChild().getLocalName()); } + @Test public void testLastChild() { assertEquals("foo", m_node.getLastChild().getLocalName()); } - + @Test public void testAppendChild() { try { super.testAppendChild(); @@ -103,9 +100,9 @@ public void testAppendChild() { catch (DOMException de) { assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); } - } + @Test public void testInsertBefore() { try { super.testInsertBefore(); @@ -115,6 +112,7 @@ public void testInsertBefore() { } } + @Test public void testInsertBeforeNullTarget() { try { super.testInsertBeforeNullTarget(); @@ -124,6 +122,7 @@ public void testInsertBeforeNullTarget() { } } + @Test public void testInsertExistingNode() { try { super.testInsertExistingNode(m_node.getFirstChild()); @@ -133,6 +132,7 @@ public void testInsertExistingNode() { } } + @Test public void testInsertBeforeInvalidRefNode() { try { super.testInsertBeforeInvalidRefNode(); @@ -140,12 +140,13 @@ public void testInsertBeforeInvalidRefNode() { catch (DOMException de) { assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); } - catch (AssertionFailedError af) { + catch (AssertionError af) { assertEquals(((DOMException) af.getCause()).code, DOMException.HIERARCHY_REQUEST_ERR); } } + @Test public void testAppendChildIllegal0() { try { super.testAppendChildIllegal0(); @@ -153,12 +154,13 @@ public void testAppendChildIllegal0() { catch (DOMException de) { assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); } - catch (AssertionFailedError af) { + catch (AssertionError af) { assertEquals(((DOMException) af.getCause()).code, DOMException.HIERARCHY_REQUEST_ERR); } } + @Test public void testAppendChildIllegal1() { try { super.testAppendChildIllegal1(); @@ -166,20 +168,23 @@ public void testAppendChildIllegal1() { catch (DOMException de) { assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); } - catch (AssertionFailedError af) { + catch (AssertionError af) { assertEquals(((DOMException) af.getCause()).code, DOMException.HIERARCHY_REQUEST_ERR); } } + @Test public void testGetChildNodes() { assertEquals(1, m_node.getChildNodes().getLength()); } + @Test public void testSetPrefix() { super.testSetPrefix(); //see charData--is the exception correct } + @Test public void testInsertExisitingNode() { Node child = m_doc.getFirstChild().getFirstChild();//some text if (child == m_node) @@ -193,6 +198,7 @@ public void testInsertExisitingNode() { } } + @Test public void testAppendChildExisting() { Node child = m_node.getFirstChild().getFirstChild(); try { @@ -207,6 +213,7 @@ public void testNormalize() { //unque doc child--normalize in elt. or text or comment, etc } + @Test public void testInsertBeforeDocFrag() { try { super.testInsertBeforeDocFrag(); @@ -216,6 +223,7 @@ public void testInsertBeforeDocFrag() { } } + @Test public void testAppendChildDocFrag() { try { super.testAppendChildDocFrag(); @@ -225,6 +233,7 @@ public void testAppendChildDocFrag() { } } + @Test public void testReplaceChildFront() { Node node = m_doc.getDocumentElement(); assertEquals(node, m_node.getFirstChild()); @@ -233,6 +242,7 @@ public void testReplaceChildFront() { assertEquals(m_doc.getDocumentElement(), newNode); } + @Test public void testReplaceChildEnd() { Node node = m_doc.getDocumentElement(); assertEquals(node, m_node.getFirstChild()); @@ -240,6 +250,7 @@ public void testReplaceChildEnd() { super.testReplaceChild(newNode, node); } + @Test public void testReplaceChildDocFrag() { try { super.testReplaceChildDocFrag(); @@ -249,73 +260,76 @@ public void testReplaceChildDocFrag() { } } + @Test public void testCreateAttribute() { Attr att = m_doc.createAttribute("at0"); - assertEquals(null, att.getOwnerElement()); + assertNull(att.getOwnerElement()); assertEquals(m_doc, att.getOwnerDocument()); assertFalse(att.hasChildNodes()); assertEquals("", att.getValue()); } + @Test public void testCreateAttributeNS() { Attr att = m_doc.createAttributeNS("foo:uri", "at0"); assertEquals("foo:uri", att.getNamespaceURI()); - assertEquals(null, att.getOwnerElement()); + assertNull(att.getOwnerElement()); assertEquals(m_doc, att.getOwnerDocument()); } - //not implem + @Test public void testCreateCDATASection() { CDATASection cdata = m_doc.createCDATASection(""); - assertEquals(null, cdata.getParentNode()); + assertNull(cdata.getParentNode()); assertEquals(m_doc, cdata.getOwnerDocument()); cdata = m_doc.createCDATASection(null); - assertEquals(null, cdata.getParentNode()); + assertNull(cdata.getParentNode()); assertEquals(m_doc, cdata.getOwnerDocument()); assertEquals("", cdata.getData()); } + @Test public void testCreateComment() { Comment comment = m_doc.createComment("A comment"); - assertEquals(null, comment.getParentNode()); + assertNull(comment.getParentNode()); assertEquals(m_doc, comment.getOwnerDocument()); comment = m_doc.createComment(null); assertEquals("", comment.getData()); } + @Test public void testCreateDocumentFragment() { DocumentFragment doc_frag = m_doc.createDocumentFragment(); - assertEquals(null, doc_frag.getParentNode()); + assertNull(doc_frag.getParentNode()); assertEquals(m_doc, doc_frag.getOwnerDocument()); } + @Test public void testCreateElement() { Element elt1 = m_doc.createElement("elt1"); - assertEquals(null, elt1.getParentNode()); + assertNull(elt1.getParentNode()); assertEquals(m_doc, elt1.getOwnerDocument()); } + @Test public void testCreateElementNS() { Element elt1 = m_doc.createElementNS("uri:foo", "ns:elt1"); assertEquals("uri:foo", elt1.getNamespaceURI()); - assertEquals(null, elt1.getParentNode()); + assertNull(elt1.getParentNode()); assertEquals(m_doc, elt1.getOwnerDocument()); } - public void testCreateEntityReference() { - //not implemented - } - + @Test public void testCreateProcessingInstruction() { ProcessingInstruction pi = null; try { pi = m_doc.createProcessingInstruction("xml", "version 1.0"); - assertEquals(null, pi.getParentNode()); + assertNull(pi.getParentNode()); assertEquals(m_doc, pi.getOwnerDocument()); fail(" this is a no-go"); } @@ -346,29 +360,22 @@ public void testCreateProcessingInstruction() { } + @Test public void testCreateTextNode() { Text txt0 = m_doc.createTextNode("foo"); - assertEquals(null, txt0.getParentNode()); + assertNull(txt0.getParentNode()); assertEquals(m_doc, txt0.getOwnerDocument()); txt0 = m_doc.createTextNode(null); assertEquals("", txt0.getData()); } - public void testGetDoctype() { - //TODO throws not impl exception assertEquals(null,m_doc.getDoctype()); - } - + @Test public void testGetDocumentElement() { assertEquals(m_doc.getDocumentElement(), m_node.getFirstChild()); } -/* public void testGetElementById() - { - // TODO - fail("Test Not implemented"); - } -*/ + @Test public void testGetElementsByTagName() { //move node @ foo m_node = m_docNS; @@ -382,6 +389,7 @@ public void testGetElementsByTagName() { } //elts need to come out in preorder order + @Test public void testGetElementsByTagNamePreorder() { m_node = m_docNS; NodeList result = ((Document) m_node).getElementsByTagName("foo"); @@ -391,13 +399,14 @@ public void testGetElementsByTagNamePreorder() { result.item(1).getFirstChild().getNodeValue()); } - + @Test public void testGetElementsByTagNameDNE() { m_node = m_docNS; NodeList result = ((Document) m_node).getElementsByTagName("foobar"); assertEquals(0, result.getLength()); } + @Test public void testGetElementsByTagNameNS() { m_node = m_docNS; NodeList result = ((Document) m_node).getElementsByTagNameNS("*", "*"); @@ -423,7 +432,7 @@ public void testGetElementsByTagNameNS() { result.item(1).getFirstChild().getNodeValue()); NodeList result1 = ((Document) m_node).getElementsByTagNameNS("", "foo"); - assertEquals(true, compareNodeList(result, result1)); + assertTrue(compareNodeList(result, result1)); result = ((Document) m_node).getElementsByTagNameNS(null, "*"); @@ -431,6 +440,7 @@ public void testGetElementsByTagNameNS() { assertEquals("ZeD", ((Element) result.item(3)).getTagName()); } + @Test public void testGetElementsByTagNameNS_DNE() { m_node = m_docNS; NodeList result = ((Document) m_node).getElementsByTagNameNS("uri:foo", @@ -444,12 +454,14 @@ public void testGetElementsByTagNameNS_DNE() { } + @Test public void testGetImplementation() { assertTrue( m_doc.getImplementation().toString().startsWith( "org.apache.xmlbeans.impl.store")); } + @Test public void testImportNode() { Node toImport = m_docNS.getFirstChild(); @@ -471,7 +483,7 @@ public void testImportNode() { } Document xercesDocument = parser.getDocument(); - assertFalse(xercesDocument == null); + assertNotNull(xercesDocument); toImport = xercesDocument.getFirstChild(); ((Document) m_node).importNode(toImport, true); @@ -482,7 +494,6 @@ public void testImportNode() { ((Document) m_node).importNode(toImport, false); ((Document) m_node).importNode(toImport, true); - } /** @@ -494,17 +505,16 @@ public void testImportNode() { * Note that the deep parameter has no effect on Attr nodes; * they always carry their children with them when imported */ - + @Test public void testImportAttrNode() { Node toImport = m_doc.getFirstChild().getAttributes().item(0); toImport.appendChild(m_doc.createTextNode("more text")); Node imported = m_docNS.importNode(toImport, false); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.ATTRIBUTE_NODE, imported.getNodeType()); assertEquals(2, imported.getChildNodes().getLength()); assertEquals(imported.getOwnerDocument(), m_docNS); - } /** @@ -515,19 +525,20 @@ public void testImportAttrNode() { * corresponding subtree. * Otherwise, this simply generates an empty DocumentFragment. */ + @Test public void testImportDocFrag() { Node toImport = m_doc.createDocumentFragment(); toImport.appendChild(m_doc.getFirstChild()); toImport.appendChild(m_doc.createTextNode("some text")); Node imported = m_docNS.importNode(toImport, false); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.DOCUMENT_FRAGMENT_NODE, imported.getNodeType()); - assertEquals(false, imported.hasChildNodes()); + assertFalse(imported.hasChildNodes()); assertEquals(imported.getOwnerDocument(), m_docNS); imported = m_docNS.importNode(toImport, true); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.DOCUMENT_FRAGMENT_NODE, imported.getNodeType()); assertEquals(2, imported.getChildNodes().getLength()); assertEquals(imported.getOwnerDocument(), m_docNS); @@ -537,9 +548,8 @@ public void testImportDocFrag() { * DOCUMENT_NODE * Document nodes cannot be imported. */ - + @Test public void testImportDocument() { - DOMException e1 = null; try { m_docNS.importNode(m_doc, false); @@ -572,11 +582,12 @@ public void testImportDocument() { * reassembled to form the corresponding subtree. */ //TODO: specified and default attributes + @Test public void testImportElement() { Node toImport = m_doc.getFirstChild(); Node imported = m_docNS.importNode(toImport, false); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.ELEMENT_NODE, imported.getNodeType()); assertEquals(0, imported.getChildNodes().getLength()); assertEquals(5, imported.getAttributes().getLength()); @@ -584,12 +595,11 @@ public void testImportElement() { imported = m_docNS.importNode(toImport, true); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.ELEMENT_NODE, imported.getNodeType()); assertEquals(1, imported.getChildNodes().getLength()); assertEquals(5, imported.getAttributes().getLength()); assertEquals(imported.getOwnerDocument(), m_docNS); - } /** @@ -614,21 +624,20 @@ public void testImportElement() { * The imported node copies its target and data * values from those of the source node. */ + @Test public void testImportPI() { Node pi = m_doc.createProcessingInstruction("xml-stylesheet", "do something"); m_doc.getFirstChild().appendChild(pi); Node imported = m_docNS.importNode(pi, false); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.PROCESSING_INSTRUCTION_NODE, imported.getNodeType()); assertEquals("do something", ((ProcessingInstruction) imported).getData()); assertEquals("xml-stylesheet", ((ProcessingInstruction) imported).getTarget()); assertEquals(imported.getOwnerDocument(), m_docNS); - - } /** @@ -636,6 +645,7 @@ public void testImportPI() { * These three types of nodes inheriting from CharacterData copy their * data and length attributes from those of the source node. */ + @Test public void testImportChars() { //import CDATA--nothing to do--it's always text @@ -646,7 +656,7 @@ public void testImportChars() { Node imported = m_docNS.importNode( m_doc.getFirstChild().getLastChild(), false); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); assertEquals(Node.TEXT_NODE, imported.getNodeType()); assertEquals("some text", ((Text) imported).getData()); assertEquals(9, ((Text) imported).getLength()); @@ -657,7 +667,7 @@ public void testImportChars() { //import Comment txt = m_doc.createComment("some text"); m_doc.getFirstChild().appendChild(txt); - assertEquals(null, imported.getParentNode()); + assertNull(imported.getParentNode()); imported = m_docNS.importNode(m_doc.getFirstChild().getLastChild(), false); @@ -669,6 +679,7 @@ public void testImportChars() { } + @Test public void testImportNodeNull() { Node _Null = null; ((Document) m_node).importNode(_Null, true); @@ -678,11 +689,10 @@ public void testImportNodeNull() { public void moveToNode() { m_node = m_doc; - } + @Before public void setUp() throws Exception { - super.setUp(); moveToNode(); } diff --git a/test/src/dom/checkin/DomImplementationSyncTest.java b/src/test/java/dom/checkin/DomImplementationSyncTest.java similarity index 76% rename from test/src/dom/checkin/DomImplementationSyncTest.java rename to src/test/java/dom/checkin/DomImplementationSyncTest.java index e46acbd..1dffc6f 100755 --- a/test/src/dom/checkin/DomImplementationSyncTest.java +++ b/src/test/java/dom/checkin/DomImplementationSyncTest.java @@ -17,24 +17,10 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; - - -/** - * - * - */ +import org.junit.Before; public class DomImplementationSyncTest extends DomImplementationTest { - public DomImplementationSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(DomImplementationSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); diff --git a/test/src/dom/checkin/DomImplementationTest.java b/src/test/java/dom/checkin/DomImplementationTest.java similarity index 89% rename from test/src/dom/checkin/DomImplementationTest.java rename to src/test/java/dom/checkin/DomImplementationTest.java index a7098d2..9370ab9 100755 --- a/test/src/dom/checkin/DomImplementationTest.java +++ b/src/test/java/dom/checkin/DomImplementationTest.java @@ -17,20 +17,16 @@ package dom.checkin; import dom.common.Loader; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import org.junit.Before; +import org.junit.Test; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; -/** - * - * - */ +import static org.junit.Assert.*; -public class DomImplementationTest extends TestCase { +public class DomImplementationTest { DOMImplementation m_imp; DocumentType m_docType; @@ -39,22 +35,13 @@ public class DomImplementationTest extends TestCase { Document m_docNS; String sXmlNS; - public DomImplementationTest(String sName) { - super(sName); + public DomImplementationTest() { sXmlNS = ""; } - public static Test suite() { - return new TestSuite(DomImplementationTest.class); - } - - public void testCreateDocumentType() { - //not implemented by Eric - - } - //$TODO: non null doctype + @Test public void testCreateDocument() { String sUri = "http://foo.org"; String sQName = "qname"; @@ -66,6 +53,7 @@ public void testCreateDocument() { //$TODO: implem. w/o "XML" feature; WRONG_DOCUMENT_ERR //NOT_SUPPORTED_ERR + @Test public void testCreateDocumentInvalid() { String sUri = "http://foo.org"; String sQName = "" ) ) ); // // XmlObject x = XmlLoader.Factory.parse( parser.getDocument() ); @@ -83,6 +75,7 @@ public void doTest(String xml) // System.out.println( x.xmlText() ); // } + @Test public void testDom() throws Exception { doTest(""); diff --git a/test/src/dom/checkin/ElementSyncTest.java b/src/test/java/dom/checkin/ElementSyncTest.java similarity index 77% rename from test/src/dom/checkin/ElementSyncTest.java rename to src/test/java/dom/checkin/ElementSyncTest.java index becceec..e3a6600 100755 --- a/test/src/dom/checkin/ElementSyncTest.java +++ b/src/test/java/dom/checkin/ElementSyncTest.java @@ -16,24 +16,11 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Before; -/** - * - * - */ - public class ElementSyncTest extends ElementTest { - public ElementSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(ElementSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); diff --git a/src/test/java/dom/checkin/ElementTest.java b/src/test/java/dom/checkin/ElementTest.java new file mode 100755 index 0000000..daf7574 --- /dev/null +++ b/src/test/java/dom/checkin/ElementTest.java @@ -0,0 +1,715 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package dom.checkin; + + +import dom.common.NodeWithChildrenTest; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.*; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class ElementTest extends NodeWithChildrenTest { + + public ElementTest() { + String sDTD = + "" + + "" + + "" + + "" + + "]>"; + sXmlNS = + "" + + "" + + "txt0nestedfoo" + + "" + + "nstext" + + ""; + if (bDTD) + sXmlNS = sDTD + sXmlNS; + sXml = Common.XML_FOO_BAR_NESTED_SIBLINGS; + } + + @Test + public void testNodeName() { + assertEquals("zed", m_node.getNodeName()); + } + + @Test + public void testNodeType() { + assertEquals(Node.ELEMENT_NODE, m_node.getNodeType()); + } + + @Test + public void testNodeValue() { + assertNull(m_node.getNodeValue()); + } + + @Test + public void testNextSibling() { + assertNull(m_node.getNextSibling()); + } + + @Test + public void testPreviousSibling() { + Node prSib = m_node.getPreviousSibling(); + assertEquals("text0", prSib.getNodeValue()); + } + + @Test + public void testParent() { + Node parent = m_node.getParentNode(); + assertEquals("bar", parent.getLocalName()); + assertEquals(m_doc.getFirstChild().getFirstChild(), parent); + } + + @Test + public void testPrefix() { + assertEquals("", m_node.getPrefix()); + + m_node = m_docNS.getDocumentElement().getChildNodes().item(1); + assertEquals("myns:foo", m_node.getNodeName()); + assertEquals("myns", m_node.getPrefix()); + } + + @Test + public void testNamespaceUri() { + assertEquals("", m_node.getNamespaceURI()); + } + + @Test + public void testCloneNode() { + super.testCloneNode(); + } + + /** + * Clone node with atts + */ + @Test + public void testCloneNodeAttrs() { + Node toClone = m_docNS.getFirstChild(); //the foo elt + /* Node clone1=toClone.cloneNode(false); + + NamedNodeMap attrSet1=toClone.getAttributes(); + assertEquals(true,DomUtils.compareNamedNodeMaps(attrSet1,clone1.getAttributes())); + */ + Node clone2 = toClone.cloneNode(true); + } + + @Test + public void testHasAttributes() { + super.testHasAttributes(); + m_node = m_doc.getFirstChild(); + assertTrue(m_node.hasAttributes()); + } + + @Test + public void testGetAttribute() { + m_node = m_docNS.getFirstChild(); + if (bDTD) + assertEquals("0", ((Element) m_node).getAttribute("at_spec")); + assertEquals("val2", + ((Element) m_node.getFirstChild()).getAttribute("at2")); + } + + @Test + public void testGetAttributeDNE() { + m_node = m_docNS.getFirstChild(); + assertEquals("", ((Element) m_node).getAttribute("at3")); + assertEquals("", ((Element) m_node).getAttribute("foobar")); + String sNull = null; + assertEquals("", ((Element) m_node).getAttribute(sNull)); + } + + @Test + public void testGetAttributeNode() { + m_node = m_docNS.getFirstChild(); + assertEquals("bar", ((Element) m_node).getTagName()); + //assertEquals("uri:foo",((Attr)((Element)m_node).getAttributeNodeNS("xmlns","myns")).getNodeValue()); + m_node = m_node.getFirstChild(); + assertEquals("val2", + ((Element) m_node).getAttributeNode("at2").getNodeValue()); + if (bDTD) + assertEquals("0", + ((Element) m_node).getAttributeNode("at_spec").getNodeValue()); + } + + @Test + public void testGetAttributeNodeDNE() { + m_node = m_docNS.getFirstChild(); + assertNull(((Element) m_node).getAttributeNode("at3")); + assertNull(((Element) m_node).getAttributeNode("foobar")); + String sNull = null; + assertEquals("", ((Element) m_node).getAttribute(sNull)); + } + + @Test + public void getAttributeNodeNS() { + m_node = m_docNS.getFirstChild().getFirstChild(); + if (bDTD) { + assertEquals("0", + ((Element) m_node).getAttributeNodeNS("", "at_spec").getNodeValue()); + } + assertEquals("val01", + ((Element) m_node).getAttributeNodeNS("uri:foo", "at0").getNodeValue()); + assertEquals("val2", + ((Element) m_node).getAttributeNodeNS(null, "at2").getNodeValue()); + assertEquals("val3", + ((Element) m_node).getAttributeNodeNS("uri:foo", "at3").getNodeValue()); + } + + @Test + public void testGetAttributeNodeNS_DNE() { + m_node = m_docNS.getFirstChild(); + assertNull(((Element) m_node).getAttributeNodeNS("", "at3")); + assertNull(((Element) m_node).getAttributeNodeNS("uri:foo", "at1")); + String sNull = null; + assertNull(((Element) m_node).getAttributeNodeNS("uri:foo", sNull)); + } + + @Test + public void testGetAttributeNS() { + m_node = m_docNS.getFirstChild().getFirstChild(); + if (bDTD) + assertEquals("0", + ((Element) m_node).getAttributeNS(null, "at_spec")); + assertEquals("val01", + ((Element) m_node).getAttributeNS("uri:foo", "at0")); + assertEquals("val2", ((Element) m_node).getAttributeNS("", "at2")); + } + + @Test + public void testGetAttributeNS_DNE() { + m_node = m_docNS.getFirstChild(); + assertEquals("", ((Element) m_node).getAttributeNS("", "at3")); + assertEquals("", ((Element) m_node).getAttributeNS("uri:foo", "at1")); + String sNull = null; + assertEquals("", ((Element) m_node).getAttributeNS("uri:foo", sNull)); + } + + @Test + public void testGetElementsByTagName() { + //move node @ foo + m_node = m_node.getParentNode().getParentNode(); + NodeList result = ((Element) m_node).getElementsByTagName("*"); + int nEltCount = 5;//num elts in the XML + assertEquals(nEltCount - 1, result.getLength()); + + result = ((Element) m_node).getElementsByTagName("zed"); + assertEquals(2, result.getLength()); + assertEquals("nested0", result.item(0).getFirstChild().getNodeValue()); + assertEquals("nested1", result.item(1).getFirstChild().getNodeValue()); + } + + @Test + public void testGetElementsByTagNameDNE() { + NodeList result = ((Element) m_node.getParentNode()).getElementsByTagName( + "foobar"); + assertEquals(0, result.getLength()); + } + + //elts need to come out in preorder order + @Test + public void testGetElementsByTagNamePreorder() { + m_node = m_docNS.getFirstChild(); + NodeList result = ((Element) m_node).getElementsByTagName("foo"); + assertEquals(2, result.getLength()); + assertEquals("txt0", result.item(0).getFirstChild().getNodeValue()); + assertEquals("nestedfoo", + result.item(1).getFirstChild().getNodeValue()); + } + + @Test + public void testGetElementsByTagNameDescendant() { + m_node = m_docNS.getFirstChild().getFirstChild(); + NodeList result = ((Element) m_node).getElementsByTagName("foo");//self should not be selected + assertEquals(1, result.getLength()); + assertEquals("nestedfoo", + result.item(0).getFirstChild().getNodeValue()); + } + + @Test + public void testGetElementsByTagNameNS() { + m_node = m_docNS.getFirstChild(); + NodeList result = ((Element) m_node).getElementsByTagNameNS("*", "*"); + int nEltCount = 6; + assertEquals(nEltCount - 1, result.getLength()); + + result = ((Element) m_node).getElementsByTagNameNS("*", "foo"); + nEltCount = 3; + assertEquals(nEltCount, result.getLength()); + assertEquals("txt0", result.item(0).getFirstChild().getNodeValue()); + assertEquals("nestedfoo", + result.item(1).getFirstChild().getNodeValue()); + assertEquals("nstext", result.item(2).getFirstChild().getNodeValue()); + + + result = ((Element) m_node).getElementsByTagNameNS("uri:foo", "foo"); + assertEquals(1, result.getLength()); + assertEquals("nstext", result.item(0).getFirstChild().getNodeValue()); + + result = ((Element) m_node).getElementsByTagNameNS(null, "foo"); + assertEquals("txt0", result.item(0).getFirstChild().getNodeValue()); + assertEquals("nestedfoo", + result.item(1).getFirstChild().getNodeValue()); + NodeList result1 = ((Element) m_node).getElementsByTagNameNS("", "foo"); + assertTrue(compareNodeList(result, result1)); + + + result = ((Element) m_node).getElementsByTagNameNS(null, "*"); + assertEquals(3, result.getLength()); + assertEquals("ZeD", ((Element) result.item(2)).getTagName()); + } + + @Test + public void testGetElementsByTagNameNS_DNE() { + m_node = m_docNS.getFirstChild(); + NodeList result = ((Element) m_node).getElementsByTagNameNS("uri:foo", + "zed"); + assertEquals(0, result.getLength()); + + result = + ((Element) m_node).getElementsByTagNameNS("foo:uri_DNE", "foo"); + assertEquals(0, result.getLength()); + } + + @Test + public void testGetTagName() { + m_node = + m_docNS.getFirstChild().getChildNodes().item(1).getChildNodes() + .item(1); + assertEquals("ZeD", ((Element) m_node).getTagName()); + } + + @Test + public void testHasAttribute() { + m_node = m_docNS.getFirstChild(); + if (bDTD) + assertTrue(((Element) m_node).hasAttribute("at_spec")); + + m_node = m_docNS.getFirstChild(); + assertFalse(((Element) m_node).hasAttribute("at3")); + assertFalse(((Element) m_node).hasAttribute("at0")); + } + + @Test + public void testHasAttributeNS() { + m_node = m_docNS.getFirstChild(); + if (bDTD) + assertTrue(((Element) m_node).hasAttributeNS(null, "at_spec")); + + m_node = m_node.getFirstChild(); + assertTrue(((Element) m_node).hasAttributeNS("uri:foo", "at3")); + assertFalse(((Element) m_node).hasAttributeNS("uri:foo:org", "at0")); + assertFalse(((Element) m_node).hasAttributeNS("uri:foo", null)); + } + + @Test + public void testRemoveAttribute() { + m_node = m_docNS.getFirstChild(); + //remove default + if (bDTD) { + + ((Element) m_node).removeAttribute("at_spec"); + assertEquals(1, m_node.getAttributes().getLength()); + } + + m_node = m_node.getFirstChild(); + assertEquals("foo", m_node.getNodeName()); + assertEquals(5, m_node.getAttributes().getLength()); + ((Element) m_node).removeAttribute("at2"); + assertEquals(4, m_node.getAttributes().getLength()); + + //DNE + ((Element) m_node).removeAttribute("at3"); + assertEquals(4, m_node.getAttributes().getLength()); + + } + + @Test + public void testRemoveAttributeNode() { + Node removed; + //remove default + m_node = m_docNS.getFirstChild(); + if (bDTD) { + ((Element) m_node).removeAttributeNode( + ((Element) m_node).getAttributeNode("at_spec")); + assertEquals(1, m_node.getAttributes().getLength()); + } + m_node = m_node.getFirstChild(); + assertEquals("foo", m_node.getNodeName()); + assertEquals(5, m_node.getAttributes().getLength()); + Attr remove = ((Element) m_node).getAttributeNode("at2"); + removed = ((Element) m_node).removeAttributeNode(remove); + assertNotNull(removed); + assertEquals(4, m_node.getAttributes().getLength()); + assertEquals(removed, remove); + } + + @Test + public void testRemoveAttributeNode_DNE() { + //DNE + Node removed; + Attr remove = ((Element) m_node).getAttributeNode("at3"); + try { + removed = ((Element) m_node).removeAttributeNode(remove); + fail("removing Non existing attr"); + } catch (DOMException de) { + assertEquals(DOMException.NOT_FOUND_ERR, de.code); + } + + remove = null; + try { + removed = ((Element) m_node).removeAttributeNode(remove); + fail("removing Non existing attr"); + } catch (DOMException de) { + assertEquals(DOMException.NOT_FOUND_ERR, de.code); + } + + //differentParent + remove = m_doc.getDocumentElement().getAttributeNode("attr0"); + try { + removed = ((Element) m_node).removeAttributeNode(remove); + fail("removing Non existing attr"); + } catch (DOMException de) { + assertEquals(DOMException.NOT_FOUND_ERR, de.code); + } + } + + @Test + public void testRemoveAttributeNS() { + //remove default + m_node = m_docNS.getFirstChild(); + if (bDTD) { + ((Element) m_node).removeAttributeNS(null, "at_spec"); + assertEquals(1, m_node.getAttributes().getLength()); + } + m_node = ((Element) m_node).getFirstChild(); + ((Element) m_node).removeAttributeNS("uri:foo", "at0"); + assertEquals(4, m_node.getAttributes().getLength()); + + //DNE + ((Element) m_node).removeAttributeNS(null, "at3"); + assertEquals(4, m_node.getAttributes().getLength()); + + ((Element) m_node).removeAttributeNS("uri:foo", null); + assertEquals(4, m_node.getAttributes().getLength()); + } + + @Test + public void testSetAttribute() { + m_node = m_doc.getDocumentElement(); + + try { + ((Element) m_node).setAttribute("invalid<", "0"); + fail("Invalid attr name"); + } catch (DOMException de) { + assertEquals(DOMException.INVALID_CHARACTER_ERR, de.code); + } + + ((Element) m_node).setAttribute("attr0", "newval"); + assertEquals("newval", ((Element) m_node).getAttribute("attr0")); + + + ((Element) m_node).setAttribute("attr1", "newval"); + assertEquals("newval", ((Element) m_node).getAttribute("attr1")); + assertEquals(2, m_node.getAttributes().getLength()); + } + + @Test + public void testSetAttributeNode() { + Attr result; + Attr newAttr = m_doc.createAttribute("attr0"); + Attr oldAttr = ((Element) m_node).getAttributeNode("attr0"); + newAttr.setValue("newval"); + result = ((Element) m_node).setAttributeNode(newAttr); + assertEquals(oldAttr, result); + assertEquals("newval", + ((Element) m_node).getAttributeNode("attr0").getNodeValue()); + + //insert self + try { + Attr at0 = ((Element) m_node).getAttributeNode("attr0"); + String v1 = at0.getNodeValue(); + ((Element) m_node).setAttributeNode(at0); + assertEquals(v1, ((Element) m_node).getAttribute("attr0")); + } catch (DOMException de) { + assertEquals(de.code, DOMException.INUSE_ATTRIBUTE_ERR); + } + + //insert new + newAttr = m_doc.createAttribute("attr1"); + newAttr.setValue("newval"); + result = ((Element) m_node).setAttributeNode(newAttr); + assertNull(result); + assertEquals("newval", + ((Element) m_node).getAttributeNode("attr1").getNodeValue()); + assertEquals(2, m_node.getAttributes().getLength()); + } + + @Test + public void testSetAttributeNodeDiffDoc() { + Attr result; + Attr newAttr = m_docNS.createAttribute("attr0"); + try { + result = ((Element) m_node).setAttributeNode(newAttr); + fail("Attr Node diff doc in use"); + } catch (DOMException de) { + assertEquals(DOMException.WRONG_DOCUMENT_ERR, de.code); + } + } + + @Test + public void testSetAttributeNodeInUse() { + //insert new + m_node = m_node.getParentNode().getParentNode(); + Attr newAttr = ((Element) m_node).getAttributeNode("attr0"); + m_node = m_node.getFirstChild(); + try { + ((Element) m_node).setAttributeNode(newAttr); + fail("Attr Node in use"); + } catch (DOMException de) { + assertEquals(DOMException.INUSE_ATTRIBUTE_ERR, de.code); + } + } + + @Test + public void testSetAttributeNodeNS() { + m_node = m_docNS.getFirstChild().getFirstChild(); + Attr result; + Attr newAttr = m_docNS.createAttributeNS("uri:foo", "at0"); + Attr oldAttr = ((Element) m_node).getAttributeNodeNS("uri:foo", "at0"); + assertNotNull(oldAttr); + newAttr.setValue("newval"); + result = ((Element) m_node).setAttributeNodeNS(newAttr); + assertEquals(oldAttr, result); + Attr insertedAtt = ((Element) m_node).getAttributeNodeNS("uri:foo", + "at0"); + assertNotNull(insertedAtt); + assertEquals("newval", insertedAtt.getNodeValue()); + + //insert new + int nAttrCnt = m_node.getAttributes().getLength(); + newAttr = m_docNS.createAttributeNS("uri:foo", "attr1"); + newAttr.setValue("newval"); + result = ((Element) m_node).setAttributeNode(newAttr); + assertNull(result); + assertEquals("newval", + ((Element) m_node).getAttributeNS("uri:foo", "attr1")); + assertEquals(nAttrCnt + 1, m_node.getAttributes().getLength()); + + //insert new + newAttr = m_docNS.createAttributeNS("uri:foo:org", "attr1"); + newAttr.setValue("newURIval"); + result = ((Element) m_node).setAttributeNodeNS(newAttr); + + assertNull(result); + assertEquals("newURIval", + ((Element) m_node).getAttributeNS("uri:foo:org", "attr1")); + assertEquals(nAttrCnt + 2, m_node.getAttributes().getLength()); + } + + @Test + public void testSetAttributeNS() { + m_node = m_docNS.getFirstChild().getFirstChild(); + //overwrite + ((Element) m_node).setAttributeNS("uri:foo", "at0", "newval"); + assertEquals("newval", + ((Element) m_node).getAttributeNS("uri:foo", "at0")); + + + ((Element) m_node).setAttributeNS("uri:foo:org", "attr1", "newval"); + assertEquals("newval", + ((Element) m_node).getAttributeNS("uri:foo:org", "attr1")); + assertEquals(6, m_node.getAttributes().getLength()); + } + + @Test + public void testSetAttributeNSBadNS() { + //qualifiedName is malformed + try { + ((Element) m_node).setAttributeNS("foo:org", "invalid<", "0"); + fail("Invalid attr name"); + } catch (DOMException de) { + assertEquals(DOMException.INVALID_CHARACTER_ERR, de.code); + } + + //the qualifiedName has a prefix and the namespaceURI is null + try { + String sNull = null; + ((Element) m_node).setAttributeNS(sNull, "myfoo:at", "0"); + fail("Invalid attr name"); + } catch (DOMException de) { + assertEquals(DOMException.NAMESPACE_ERR, de.code); + } + } + + @Test + public void testSetAttributeNSBadNS_xmlns() { + //the qualifiedName, or its prefix, is "xmlns" and the namespaceURI is different from " http://www.w3.org/2000/xmlns/". + try { + ((Element) m_node).setAttributeNS("foo:org:uri", "xmlns", "0"); + fail("Invalid attr name"); + } catch (DOMException de) { + assertEquals(DOMException.NAMESPACE_ERR, de.code); + } + + try { + ((Element) m_node).setAttributeNS("foo:org:uri", "xmlns:foo", "0"); + fail("Invalid attr name"); + } catch (DOMException de) { + assertEquals(DOMException.NAMESPACE_ERR, de.code); + } + } + + @Test + public void testSetAttributeNSBadNS_xml() { + //if the qualifiedName has a prefix that is "xml" + // and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace" + try { + ((Element) m_node).setAttributeNS("foo:org:uri", "xml:foo", "0"); + fail("Invalid attr name"); + } catch (DOMException de) { + assertEquals(DOMException.NAMESPACE_ERR, de.code); + } + } + + @Test + public void testGetChildNodes() { + m_node = m_node.getParentNode(); + assertEquals(2, m_node.getChildNodes().getLength()); + } + + @Test + public void testFirstChild() { + assertEquals("nested0", m_node.getFirstChild().getNodeValue()); + } + + @Test + public void testLastChild() { + assertEquals("nested0", m_node.getLastChild().getNodeValue()); + } + + //code coverage: need a node with penultimate elt and last text + @Test + public void testLastChildMixedContent() { + Node prevSibling = m_doc.createElement("penultimateNode"); + m_node.insertBefore(prevSibling, m_node.getFirstChild()); + assertEquals("nested0", m_node.getLastChild().getNodeValue()); + } + + @Test + public void testGetAttributes() { + assertEquals(0, m_node.getAttributes().getLength()); + } + + @Test + public void testLocalName() { + assertEquals("zed", m_node.getLocalName()); + } + + @Test + public void testSetPrefix() { + //set a null prefix + m_node = + m_docNS.getFirstChild().getFirstChild().getChildNodes().item(2);// + assertNotNull(m_node); + m_node.setPrefix(null); + assertEquals("", m_node.getPrefix()); + + m_node.setPrefix("other"); + + assertEquals("other:yana", m_node.getNodeName()); + assertEquals("other:yana", ((Element) m_node).getTagName()); + // assertEquals("uri:other",m_node.getNamespaceURI());--this is the URI @ creation--never changes + assertEquals(1, + ((Element) m_docNS.getDocumentElement()).getElementsByTagName( + "other:yana") + .getLength()); + } + + @Test + public void testNormalizeNode() throws Exception { + m_node = m_node.getParentNode(); + m_node.replaceChild(m_doc.createTextNode("txt1"), + m_node.getLastChild()); + assertEquals(2, m_node.getChildNodes().getLength()); + + m_node.normalize(); + assertEquals(1, m_node.getChildNodes().getLength()); + } + + @Test + public void testNormalizeNodeNoChildren() throws Exception { + m_node = m_doc.createElement("foobar"); + assertEquals(0, m_node.getChildNodes().getLength()); + m_node.normalize(); + assertEquals(0, m_node.getChildNodes().getLength()); + } + + @Test + public void testNormalizeNodeOneChild() throws Exception { + m_node = m_doc.createElement("foobar"); + m_node.appendChild(m_doc.createElement("foobar")); + assertEquals(1, m_node.getChildNodes().getLength()); + m_node.normalize(); + assertEquals(1, m_node.getChildNodes().getLength()); + } + + @Test + public void testAppendChildExisting() { + m_node = m_docNS.getFirstChild().getLastChild(); + Node child = m_docNS.getFirstChild().getFirstChild(); + super.testAppendChildExisting(child); + } + + @Test + public void testInsertExisitingNode() { + m_node = m_docNS.getFirstChild().getLastChild(); + Node child = m_docNS.getFirstChild().getFirstChild(); + super.testAppendChildExisting(child); + } + + @Test + public void testDomLevel1() { + Element elt = m_doc.createElement("foobar"); + assertNull("L1 prefix null", elt.getPrefix()); + assertNull("L1 LocalName null", elt.getLocalName()); + assertNull("L1 Uri null", elt.getNamespaceURI()); + try { + elt.setPrefix("foo"); + fail("L1 prefix null"); + } catch (DOMException de) { + assertEquals(DOMException.NAMESPACE_ERR, de.code); + } + } + + public void moveToNode() { + m_node = m_doc.getFirstChild().getFirstChild().getChildNodes().item(1);//zed node; + assertNotNull(m_node); + } + + @Before + public void setUp() throws Exception { + super.setUp(); + moveToNode(); + } +} diff --git a/test/src/dom/checkin/NamedNodeMapSyncTest.java b/src/test/java/dom/checkin/NamedNodeMapSyncTest.java similarity index 76% rename from test/src/dom/checkin/NamedNodeMapSyncTest.java rename to src/test/java/dom/checkin/NamedNodeMapSyncTest.java index fc13fb3..0e6d34b 100755 --- a/test/src/dom/checkin/NamedNodeMapSyncTest.java +++ b/src/test/java/dom/checkin/NamedNodeMapSyncTest.java @@ -17,27 +17,12 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; - - -/** - * - * - */ +import org.junit.Before; public class NamedNodeMapSyncTest extends NamedNodeMapTest { - public NamedNodeMapSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(NamedNodeMapSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); } - } diff --git a/test/src/dom/checkin/NamedNodeMapTest.java b/src/test/java/dom/checkin/NamedNodeMapTest.java similarity index 87% rename from test/src/dom/checkin/NamedNodeMapTest.java rename to src/test/java/dom/checkin/NamedNodeMapTest.java index 77b0be7..d4b58f4 100755 --- a/test/src/dom/checkin/NamedNodeMapTest.java +++ b/src/test/java/dom/checkin/NamedNodeMapTest.java @@ -19,19 +19,15 @@ import dom.common.Loader; import dom.common.NodeTest; import dom.common.TestSetup; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import org.junit.Before; +import org.junit.Test; import org.w3c.dom.*; import org.apache.xmlbeans.XmlObject; -/** - * - * - */ +import static org.junit.Assert.*; -public class NamedNodeMapTest extends TestCase implements TestSetup { +public class NamedNodeMapTest implements TestSetup { Document m_doc; Document m_docNS; Node m_node; @@ -42,19 +38,13 @@ public class NamedNodeMapTest extends TestCase implements TestSetup { int nCount = 5; - public NamedNodeMapTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(NamedNodeMapTest.class); - } - + @Test public void testLength() { //assertEquals(m_nodeMap.length,nCount); assertEquals(m_nodeMap.getLength(), nCount); } + @Test public void testGetNamedItem() { result = m_nodeMap.getNamedItem("at0"); assertEquals("val0", result.getNodeValue()); @@ -63,13 +53,14 @@ public void testGetNamedItem() { assertEquals("val4", result.getNodeValue()); } + @Test public void testGetNamedItemDNE() { result = m_nodeMap.getNamedItem("attt4"); assertEquals(null, result); } + @Test public void testGetNamedItemNS() { - m_nodeMap = m_docNS.getFirstChild().getAttributes(); result = m_nodeMap.getNamedItemNS("uri:foo", "at0"); @@ -85,12 +76,10 @@ public void testGetNamedItemNS() { result = m_nodeMap.getNamedItemNS(null, "at3"); assertEquals("val3", result.getNodeValue()); - - } + @Test public void testGetNamedItemNS_DNE() { - m_nodeMap = m_docNS.getFirstChild().getAttributes(); result = m_nodeMap.getNamedItemNS("uri:fol", "at0"); @@ -108,6 +97,7 @@ public void testGetNamedItemNS_DNE() { */ } + @Test public void testItem() { result = m_nodeMap.item(0); assertEquals("val0", result.getNodeValue()); @@ -115,14 +105,16 @@ public void testItem() { assertEquals("val3", result.getNodeValue()); } + @Test public void testItemNeg() { - assertFalse(null == m_nodeMap); - assertEquals(null, m_nodeMap.item(-1)); + assertNotNull(m_nodeMap); + assertNull(m_nodeMap.item(-1)); } + @Test public void testItemLarge() { - assertFalse(null == m_nodeMap); - assertEquals(null, m_nodeMap.item(m_nodeMap.getLength() + 1)); + assertNotNull(m_nodeMap); + assertNull(m_nodeMap.item(m_nodeMap.getLength() + 1)); } /** @@ -130,6 +122,7 @@ public void testItemLarge() { * read-only map * attr w/ default val */ + @Test public void testRemoveNamedItemNull() { try { m_nodeMap.removeNamedItem(null); @@ -140,6 +133,7 @@ public void testRemoveNamedItemNull() { } } + @Test public void testRemoveNamedItem() { try { m_nodeMap.removeNamedItem("at7"); @@ -151,17 +145,13 @@ public void testRemoveNamedItem() { result = m_nodeMap.removeNamedItem("at3"); assertEquals("val3", result.getNodeValue()); - assertEquals(m_nodeMap.getNamedItem("at3"), null); + assertNull(m_nodeMap.getNamedItem("at3")); //liveness test assertEquals(m_node.getAttributes().getLength(), nCount - 1); - assertEquals(m_node.getAttributes().getNamedItem("at3"), null); - + assertNull(m_node.getAttributes().getNamedItem("at3")); } - /** - * - */ - + @Test public void testRemoveNamedItemNS() { m_node = m_docNS.getDocumentElement(); m_nodeMap = m_node.getAttributes(); @@ -175,22 +165,22 @@ public void testRemoveNamedItemNS() { result = m_nodeMap.getNamedItemNS("uri:foo", "at4"); assertEquals(result, m_nodeMap.removeNamedItemNS("uri:foo", "at4")); - assertEquals(null, m_nodeMap.getNamedItemNS("uri:foo", "at4")); + assertNull(m_nodeMap.getNamedItemNS("uri:foo", "at4")); assertEquals(nCount - 1, m_node.getAttributes().getLength()); result = m_nodeMap.removeNamedItemNS(null, "at3"); assertEquals("val3", result.getNodeValue()); - assertEquals(null, m_nodeMap.getNamedItem("at3")); + assertNull(m_nodeMap.getNamedItem("at3")); assertEquals(m_node.getAttributes().getLength(), nCount - 2); //liveness test assertEquals(nCount - 2, m_docNS.getFirstChild().getAttributes().getLength()); - assertEquals(null, - m_docNS.getFirstChild().getAttributes().getNamedItem("at3")); + assertNull(m_docNS.getFirstChild().getAttributes().getNamedItem("at3")); } + @Test public void testRemoveNamedItemNS_DNE() { m_nodeMap = m_docNS.getFirstChild().getAttributes(); int nLen = m_node.getAttributes().getLength(); @@ -219,6 +209,7 @@ public void testRemoveNamedItemNS_DNE() { * node in diff elt * node not an attr */ + @Test public void testSetNamedItem() { Node newAt = m_doc.createAttribute("newAt"); ((Attr) newAt).setValue("newval"); @@ -260,15 +251,12 @@ public void testSetNamedItem() { } + @Test(expected = IllegalArgumentException.class) public void testSetNamedItemNull() { - try { - m_nodeMap.setNamedItem(null); - fail("Setting to null"); - } - catch (java.lang.IllegalArgumentException e) { - } + m_nodeMap.setNamedItem(null); } + @Test public void testSetNamedItemDiffImpl() throws Exception { Node toSet = NodeTest.getApacheNode(sXml, false, 'A'); try { @@ -280,22 +268,23 @@ public void testSetNamedItemDiffImpl() throws Exception { } } + @Test public void testSetNamedItemNS() { - Node newAt = m_doc.createAttributeNS("uri:foo", "newAt"); - ((Attr) newAt).setValue("newval"); + Attr newAt = m_doc.createAttributeNS("uri:foo", "newAt"); + newAt.setValue("newval"); m_nodeMap.setNamedItemNS(newAt); assertEquals(nCount + 1, m_nodeMap.getLength()); result = m_nodeMap.getNamedItemNS("uri:foo", "newAt"); assertEquals("newval", result.getNodeValue()); //OK, reset value - ((Attr) newAt).setValue("newval_overwrite"); + newAt.setValue("newval_overwrite"); m_nodeMap.setNamedItemNS(newAt); assertEquals(nCount + 1, m_nodeMap.getLength()); result = m_nodeMap.getNamedItemNS("uri:foo", "newAt"); assertEquals("newval_overwrite", result.getNodeValue()); newAt = m_doc.createAttributeNS("uri:foo1", "newAt"); - ((Attr) newAt).setValue("newval1"); + newAt.setValue("newval1"); //insert a new item m_nodeMap.setNamedItemNS(newAt); assertEquals(nCount + 2, m_nodeMap.getLength()); @@ -304,15 +293,12 @@ public void testSetNamedItemNS() { //the path cases are the same as in SetNamedItem } + @Test(expected = IllegalArgumentException.class) public void testSetNamedItemNSNull() { - try { - m_nodeMap.setNamedItemNS(null); - fail("Setting to null"); - } - catch (java.lang.IllegalArgumentException e) { - } + m_nodeMap.setNamedItemNS(null); } + @Test public void testSetNamedItemNSDiffImpl() throws Exception { Node toSet = NodeTest.getApacheNode(sXml, true, 'A'); try { @@ -325,6 +311,7 @@ public void testSetNamedItemNSDiffImpl() throws Exception { } //try to set a node of a diff type than the current collection + @Test public void testSetNamedItemDiffType() throws Exception { Node toSet = m_doc.createElement("foobar"); try { @@ -336,6 +323,7 @@ public void testSetNamedItemDiffType() throws Exception { } } + @Test public void testSetNamedItemNSDiffType() throws Exception { Node toSet = m_doc.createElementNS("foo:org", "com:foobar"); try { @@ -365,12 +353,11 @@ public void loadSync() throws Exception { } + @Before public void setUp() throws Exception { - m_doc = (org.w3c.dom.Document) XmlObject.Factory.parse( sXml ).getDomNode(); m_docNS = (org.w3c.dom.Document) XmlObject.Factory.parse( sXmlNS ).getDomNode(); moveToNode(); - } private Loader _loader; diff --git a/test/src/dom/checkin/NodeListSyncTest.java b/src/test/java/dom/checkin/NodeListSyncTest.java similarity index 77% rename from test/src/dom/checkin/NodeListSyncTest.java rename to src/test/java/dom/checkin/NodeListSyncTest.java index 6f92f9e..0b0cf65 100755 --- a/test/src/dom/checkin/NodeListSyncTest.java +++ b/src/test/java/dom/checkin/NodeListSyncTest.java @@ -17,27 +17,12 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; - - -/** - * - * - */ +import org.junit.Before; public class NodeListSyncTest extends NodeListTest { - public NodeListSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(NodeListSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); } - } diff --git a/test/src/dom/checkin/NodeListTest.java b/src/test/java/dom/checkin/NodeListTest.java similarity index 79% rename from test/src/dom/checkin/NodeListTest.java rename to src/test/java/dom/checkin/NodeListTest.java index 137a40c..d5b9648 100755 --- a/test/src/dom/checkin/NodeListTest.java +++ b/src/test/java/dom/checkin/NodeListTest.java @@ -19,20 +19,16 @@ import dom.common.Loader; import dom.common.TestSetup; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import org.junit.Before; +import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -/** - * - * - */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; - -public class NodeListTest extends TestCase implements TestSetup { +public class NodeListTest implements TestSetup { Document m_doc; Document m_docNS; @@ -41,37 +37,35 @@ public class NodeListTest extends TestCase implements TestSetup { String sXml = "val0val1val2val3val4"; int nCount = 5; - public NodeListTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(NodeListTest.class); - } - + @Test public void testLength() { assertEquals(m_nodeList.getLength(), nCount); } + @Test public void testItem() { for (int i = 0; i < m_nodeList.getLength(); i++) assertEquals("ch" + i, m_nodeList.item(i).getNodeName()); } + @Test public void testItemNeg() { - assertEquals(null, m_nodeList.item(-1)); + assertNull(m_nodeList.item(-1)); } + @Test public void testItemLarge() { - assertEquals(null, m_nodeList.item(nCount + 1)); + assertNull(m_nodeList.item(nCount + 1)); } + @Test public void voidTestLive() { m_node.removeChild(m_nodeList.item(1));//"ch1" assertEquals(m_nodeList.getLength(), nCount - 1); assertEquals("ch2", m_nodeList.item(1).getNodeName()); } + @Test public void moveToNode() { m_node = m_doc.getFirstChild(); m_nodeList = m_node.getChildNodes(); @@ -79,15 +73,15 @@ public void moveToNode() { public void loadSync() throws Exception { _loader = Loader.getLoader(); - m_doc = (org.w3c.dom.Document) _loader.loadSync(sXml); + m_doc = _loader.loadSync(sXml); } + @Before public void setUp() throws Exception { _loader = Loader.getLoader(); m_doc = (org.w3c.dom.Document) _loader.load(sXml); moveToNode(); - } private Loader _loader; diff --git a/test/src/dom/checkin/PISyncTest.java b/src/test/java/dom/checkin/PISyncTest.java similarity index 78% rename from test/src/dom/checkin/PISyncTest.java rename to src/test/java/dom/checkin/PISyncTest.java index 447f487..6eeafdf 100755 --- a/test/src/dom/checkin/PISyncTest.java +++ b/src/test/java/dom/checkin/PISyncTest.java @@ -17,24 +17,11 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Before; -/** - * - * - */ - public class PISyncTest extends PITest { - public PISyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(PISyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); diff --git a/src/test/java/dom/checkin/PITest.java b/src/test/java/dom/checkin/PITest.java new file mode 100755 index 0000000..1d5f87f --- /dev/null +++ b/src/test/java/dom/checkin/PITest.java @@ -0,0 +1,142 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package dom.checkin; + +import dom.common.NodeTest; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.DOMException; +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; + +import static org.junit.Assert.*; + + +public class PITest extends NodeTest { + + public PITest() { + sXml = "text"; + //inspired by Common.XML_FOO_PROCINST; + } + + @Test + public void testNodeName() { + assertEquals("xml-stylesheet", m_node.getNodeName()); + } + + @Test + public void testLocalName() { + assertEquals("xml-stylesheet", m_node.getNodeName()); + } + + @Test + public void testNodeType() { + assertEquals(Node.PROCESSING_INSTRUCTION_NODE, m_node.getNodeType()); + } + + @Test + public void testNodeValue() { + assertEquals( + "type=\"text/xsl\" xmlns=\"http://openuri.org/shipping/\"", + m_node.getNodeValue()); + } + + @Test + public void testNextSibling() { + Node nxtSibling = m_node.getNextSibling(); + assertEquals("foo", nxtSibling.getNodeName()); + + } + + @Test + public void testSetNodeValue() { + String sNewVal = "type=\"text/xsl\" xmlns=\"http://xbean.foo.org\""; + m_node.setNodeValue(sNewVal); + assertEquals(sNewVal, m_node.getNodeValue()); + + } + + @Test + public void testPreviousSibling() { + Node prSibling = m_node.getPreviousSibling(); + assertNull(prSibling); + } + + @Test + public void testParent() { + Node parent = m_node.getParentNode(); + assertEquals(m_doc.getFirstChild(), parent); + assertEquals("bar", parent.getLocalName()); + } + + @Test + public void testGetData() { + assertEquals( + "type=\"text/xsl\" xmlns=\"http://openuri.org/shipping/\"", + ((ProcessingInstruction) m_node).getData()); + } + + @Test + public void testGetTarget() { + assertEquals("xml-stylesheet", + ((ProcessingInstruction) m_node).getTarget()); + } + + public void moveToNode() { + m_node = m_doc.getDocumentElement().getFirstChild();//pi + assertNotNull(m_node); + } + + //TODO: Test PI with funky but legal chatacters in the name, eg. : + @Test + public void testPiTargetChars() { + ProcessingInstruction node = m_doc.createProcessingInstruction( + "foo:123-_", "some body"); + m_node.getParentNode().appendChild(node); + m_node = m_node.getParentNode().getLastChild(); + assertEquals("foo:123-_", ((ProcessingInstruction) m_node).getTarget()); + } + + //TODO: Test Illegal PI Targets: xml target, starting with a digit + @Test + public void testPiTargetIllegalChars() { + ProcessingInstruction node; + try { + node = + m_doc.createProcessingInstruction("7foo:?123-&", + "some body"); + fail("Can't start w/ a digit"); + } + catch (DOMException e) { + assertEquals(DOMException.INVALID_CHARACTER_ERR, e.code); + } + + try { + node = m_doc.createProcessingInstruction("xml", "foo"); + fail("Can't be xml"); + } + catch (DOMException e) { + assertEquals(DOMException.INVALID_CHARACTER_ERR, e.code); + } + } + + @Before + public void setUp() throws Exception { + super.setUp(); + moveToNode(); + } +} diff --git a/test/src/dom/checkin/ParserTest.java b/src/test/java/dom/checkin/ParserTest.java similarity index 93% rename from test/src/dom/checkin/ParserTest.java rename to src/test/java/dom/checkin/ParserTest.java index 9e82a08..5f58d30 100755 --- a/test/src/dom/checkin/ParserTest.java +++ b/src/test/java/dom/checkin/ParserTest.java @@ -16,23 +16,26 @@ package dom.checkin; -import java.io.ByteArrayInputStream; -import javax.xml.XMLConstants; -import javax.xml.stream.XMLInputFactory; - -import junit.framework.*; - import org.apache.xmlbeans.XmlOptionsBean; -import org.apache.xmlbeans.impl.common.*; +import org.apache.xmlbeans.impl.common.SAXHelper; +import org.apache.xmlbeans.impl.common.StaxHelper; +import org.apache.xmlbeans.impl.common.XMLBeansConstants; +import org.junit.Test; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; +import javax.xml.stream.XMLInputFactory; +import java.io.ByteArrayInputStream; + +import static org.junit.Assert.*; + /** * Tests for XML Parser settings */ -public class ParserTest extends TestCase { +public class ParserTest { + @Test public void testXmlOptionsDefaults() { XmlOptionsBean options = new XmlOptionsBean(); assertEquals(2048, options.getEntityExpansionLimit()); @@ -40,6 +43,7 @@ public void testXmlOptionsDefaults() { assertFalse(options.isLoadExternalDTD()); } + @Test public void testXMLBeansConstantsOverrides() { XmlOptionsBean options = new XmlOptionsBean(); options.setEntityExpansionLimit(1); @@ -50,6 +54,7 @@ public void testXMLBeansConstantsOverrides() { assertTrue(options.isLoadExternalDTD()); } + @Test public void testXmlInputFactoryPropertyDefaults() { XmlOptionsBean options = new XmlOptionsBean(); XMLInputFactory factory = StaxHelper.newXMLInputFactory(options); @@ -59,6 +64,7 @@ public void testXmlInputFactoryPropertyDefaults() { assertEquals(false, factory.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)); } + @Test public void testXmlInputFactoryPropertyOverrides() { XmlOptionsBean options = new XmlOptionsBean(); options.setEntityExpansionLimit(1); @@ -69,6 +75,7 @@ public void testXmlInputFactoryPropertyOverrides() { assertEquals(true, factory.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)); } + @Test public void testXMLReader() throws Exception { XmlOptionsBean options = new XmlOptionsBean(); XMLReader reader = SAXHelper.newXMLReader(options); @@ -81,6 +88,7 @@ public void testXMLReader() throws Exception { reader.parse(new InputSource(new ByteArrayInputStream("".getBytes("UTF-8")))); } + @Test public void testXMLReaderOverrides() throws Exception { XmlOptionsBean options = new XmlOptionsBean(); options.setEntityExpansionLimit(1); diff --git a/test/src/dom/checkin/TextSyncTest.java b/src/test/java/dom/checkin/TextSyncTest.java similarity index 77% rename from test/src/dom/checkin/TextSyncTest.java rename to src/test/java/dom/checkin/TextSyncTest.java index d96ed0f..96a1870 100755 --- a/test/src/dom/checkin/TextSyncTest.java +++ b/src/test/java/dom/checkin/TextSyncTest.java @@ -17,24 +17,11 @@ package dom.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Before; -/** - * - * - */ - public class TextSyncTest extends TextTest { - public TextSyncTest(String s) { - super(s); - } - - public static Test suite() { - return new TestSuite(TextSyncTest.class); - } - + @Before public void setUp() throws Exception { super.loadSync(); super.moveToNode(); diff --git a/src/test/java/dom/checkin/TextTest.java b/src/test/java/dom/checkin/TextTest.java new file mode 100755 index 0000000..cb81c48 --- /dev/null +++ b/src/test/java/dom/checkin/TextTest.java @@ -0,0 +1,143 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package dom.checkin; + + +import dom.common.CharacterDataTest; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.DOMException; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + + +public class TextTest extends CharacterDataTest { + + public TextTest() { + sXml = Common.XML_FOO_BAR_TEXT_EXT; + } + + @Test + public void testNodeName() { + assertEquals("#text", m_node.getNodeName()); + } + + @Test + public void testNodeType() { + assertEquals(Node.TEXT_NODE, m_node.getNodeType()); + } + + @Test + public void testNodeValue() { + assertEquals("extended", m_node.getNodeValue()); + } + + @Test + public void testNextSibling() { + Node nxtSibling = m_node.getNextSibling(); + assertEquals(null, nxtSibling); + } + + @Test + public void testPreviousSibling() { + Node prSibling = m_node.getPreviousSibling(); + assertEquals("bar", prSibling.getLocalName()); + assertEquals("text", ((Text) prSibling.getFirstChild()).getData()); + } + + @Test + public void testParent() { + Node parent = m_node.getParentNode(); + assertEquals(m_doc.getFirstChild(), parent); + assertEquals("foo", parent.getLocalName()); + } + + @Test + public void testSplitTextNegative() { + try { + ((Text) m_node).splitText(-1); + fail("Deleting OOB chars"); + } + catch (DOMException de) { + assertEquals(de.code, DOMException.INDEX_SIZE_ERR); + } + } + + @Test + public void testSplitTextLarge() { + try { + ((Text) m_node).splitText(((Text) m_node).getLength() + 1); + fail("Deleting OOB chars"); + } + catch (DOMException de) { + assertEquals(de.code, DOMException.INDEX_SIZE_ERR); + } + } + + @Test + public void testSplitText() { + Node parent = m_node.getParentNode(); + int nChildCount = parent.getChildNodes().getLength(); + ((Text) m_node).splitText(2); + assertEquals(nChildCount + 1, parent.getChildNodes().getLength()); + } + + @Test + public void testSplitTextBorder() { + Node parent = m_node.getParentNode(); + int nChildCount = parent.getChildNodes().getLength(); + ((Text) m_node).splitText(((Text) m_node).getLength()); + assertEquals(nChildCount + 1, parent.getChildNodes().getLength()); + ((Text) m_node).splitText(0); + assertEquals(nChildCount + 2, parent.getChildNodes().getLength()); + } + + //code coverage case; not sure why it's important + @Test + public void testSplitTextNoParent() { + m_node = m_doc.createTextNode("foobar"); + ((Text) m_node).splitText(3); + assertEquals("foo", m_node.getNodeValue()); + } + + @Test + public void testSetNodeValue() { + m_node.setNodeValue("new text value"); + assertEquals("new text value", m_node.getNodeValue()); + } + + public void moveToNode() { + m_node = m_doc.getFirstChild().getChildNodes().item(1);//"extended" + } + + @Before + public void setUp() throws Exception { + super.setUp(); + moveToNode(); + } + + @Test + public void testDelete()throws Exception{ + org.apache.xmlbeans.XmlObject o= org.apache.xmlbeans.XmlObject.Factory.parse(""); + Node d = o.newDomNode(); + assertEquals("foo",d.getFirstChild().getLocalName()); + } +} diff --git a/test/src/dom/common/CharacterDataTest.java b/src/test/java/dom/common/CharacterDataTest.java similarity index 86% rename from test/src/dom/common/CharacterDataTest.java rename to src/test/java/dom/common/CharacterDataTest.java index 5f5435f..69f9594 100755 --- a/test/src/dom/common/CharacterDataTest.java +++ b/src/test/java/dom/common/CharacterDataTest.java @@ -16,57 +16,52 @@ package dom.common; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Ignore; +import org.junit.Test; import org.w3c.dom.CharacterData; import org.w3c.dom.DOMException; import org.w3c.dom.Node; +import static org.junit.Assert.*; +@Ignore public abstract class CharacterDataTest extends NodeTest { - String NULL = ""; - - public static Test suite() { - return new TestSuite(CharacterDataTest.class); - } - - - public CharacterDataTest(String s) { - super(s); - } - + @Test public void testAppendChild() { Node newChild = m_doc.createElement("foo"); try { - ((CharacterData) m_node).appendChild(newChild); + m_node.appendChild(newChild); } catch (DOMException de) { assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); } } //super method not relevant + @Test public void testInsertBefore() { Node newChild = m_doc.createElement("foo"); - assertEquals(false, m_node.hasChildNodes()); + assertFalse(m_node.hasChildNodes()); Node nullNode = m_node.getFirstChild(); try { - ((CharacterData) m_node).insertBefore(newChild, nullNode); + m_node.insertBefore(newChild, nullNode); } catch (DOMException de) { assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); } } + @Test public void testRemoveChild() { - assertEquals(false, m_node.hasChildNodes()); + assertFalse(m_node.hasChildNodes()); } + @Test public void testReplaceChild() { Node newChild = m_doc.createElement("foo"); - assertEquals(false, m_node.hasChildNodes()); + assertFalse(m_node.hasChildNodes()); if (m_node.getFirstChild() != null) try { - ((CharacterData) m_node).replaceChild(newChild, m_node.getFirstChild()); + m_node.replaceChild(newChild, m_node.getFirstChild()); } catch (DOMException de) { if (DOMException.HIERARCHY_REQUEST_ERR != de.code) throw de; @@ -74,7 +69,7 @@ public void testReplaceChild() { } - + @Test public void testAppendData() { String sOrig = ((CharacterData) m_node).getData(); String sNewData = "some new data"; @@ -84,41 +79,41 @@ public void testAppendData() { fail(" Expected " + sExpected + " but got " + ((CharacterData) m_node).getData()); } + @Test public void testAppendDataNull() { String sOrig = ((CharacterData) m_node).getData(); - String sNewData = ""; - ((CharacterData) m_node).appendData(sNewData); - assertEquals(sOrig + sNewData, ((CharacterData) m_node).getData()); - - sNewData = null; - ((CharacterData) m_node).appendData(sNewData); + ((CharacterData) m_node).appendData(""); assertEquals(sOrig, ((CharacterData) m_node).getData()); + ((CharacterData) m_node).appendData(null); + assertEquals(sOrig, ((CharacterData) m_node).getData()); } - + @Test public void testDeleteDataNegOff() { _testDeleteData(-1, 10); } + @Test public void testDeleteDataNegLen() { _testDeleteData(1, -10); } + @Test public void testDeleteDataLargeOff() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testDeleteData(nDataLen + 1, 10); - } + @Test public void testDeleteDataLargeLen() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testDeleteData(0, nDataLen + 30); } - + @Test public void testDeleteDataAverage() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); @@ -142,14 +137,14 @@ private void _testDeleteData(int offset, int count) { else if (offset + count == nDataLen || (offset + count) > nDataLen) assertEquals("", ((CharacterData) m_node).getData()); else if (offset == 0) { - assertEquals(sData.substring(count, sData.length()), ((CharacterData) m_node).getData()); + assertEquals(sData.substring(count), ((CharacterData) m_node).getData()); } else assertEquals(sData.substring(0, offset) + sData.substring(offset + count, sData.length() - (offset + count)), ((CharacterData) m_node).getData()); } } - + @Test public void testGetData() { char[] buff = new char[200]; java.util.Arrays.fill(buff, 'a'); @@ -162,28 +157,30 @@ public void testGetData() { } } - + @Test public void testGetLength() { int nDataLen = ((CharacterData) m_node).getData().length(); assertEquals(((CharacterData) m_node).getLength(), nDataLen); } - + @Test public void testInsertNull() { - _testInsertData(0, null); } + @Test public void testInsertNeg() { _testInsertData(-1, "foo"); } + @Test public void testInsertOOB() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testInsertData(nDataLen + 2, "foo"); } + @Test public void testInsertAverage() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); @@ -203,7 +200,7 @@ private void _testInsertData(int offset, String toInsert) { else { ((CharacterData) m_node).insertData(offset, toInsert); if (toInsert == null) - assertTrue(sData.equals(((CharacterData) m_node).getData())); + assertEquals(sData, ((CharacterData) m_node).getData()); else if (offset == nDataLen) assertEquals(sData + toInsert, ((CharacterData) m_node).getData()); else { @@ -218,44 +215,50 @@ else if (offset == nDataLen) } } - + @Test public void testReplaceDataNull() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); - String repl = null; - _testReplaceData(0, nDataLen, repl); + _testReplaceData(0, nDataLen, null); } + @Test public void testReplaceDataNegOff() { _testReplaceData(-1, 3, "foo"); } + @Test public void testReplaceDataNegCount() { _testReplaceData(1, -3, "foo"); } - public void testReplaceDataZeroCount() { + @Test + public void testReplaceDataZeroCount() { _testReplaceData(1, 0, "foo"); } + @Test public void testReplaceDataLargeOff() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testReplaceData(nDataLen + 1, 2, "foo"); } + @Test public void testReplaceDataLargeCount() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testReplaceData(0, nDataLen + 2, "foo"); } + @Test public void testReplaceDataLarge() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testReplaceData(nDataLen / 2, nDataLen / 2 + 1, "foo"); } + @Test public void testReplaceDataAverage() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); @@ -292,44 +295,37 @@ else if (offset + count == nDataLen || (offset + count) > nDataLen) { } + @Test public void testSetDataNull() { - String sNull = null; - ((CharacterData) m_node).setData(sNull); + ((CharacterData) m_node).setData(null); assertEquals("", ((CharacterData) m_node).getData()); } - public void testSetData(String newData) { - ((CharacterData) m_node).setData(newData); - assertEquals(newData, ((CharacterData) m_node).getData()); - } - - //nothing happens here - public void testNormalize() { - } - - + @Test public void testSubstringDataNegOff() { _testSubstringData(-1, 10); } + @Test public void testSubstringDataNegLen() { _testSubstringData(1, -10); } + @Test public void testSubstringDataLargeOff() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testSubstringData(nDataLen + 1, 10); - } + @Test public void testSubstringDataLargeLen() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); _testSubstringData(0, nDataLen + 30); } - + @Test public void testSubstringDataAverage() { String sData = ((CharacterData) m_node).getData(); int nDataLen = sData.length(); @@ -358,23 +354,14 @@ else if (offset + count == nDataLen || (offset + count) > nDataLen) } } - public void testSetNodeValue() { - fail("Override"); - } - - - public void testSetPrefix() - { - try - { + @Test + public void testSetPrefix() { + try { m_node.setPrefix("foobar"); fail("Can't set prefix on node other than Element or Attribute"); - } - catch (DOMException de) - { + } catch (DOMException de) { assertEquals(DOMException.NAMESPACE_ERR, de.code); } - } } diff --git a/test/src/dom/common/DomUtils.java b/src/test/java/dom/common/DomUtils.java similarity index 100% rename from test/src/dom/common/DomUtils.java rename to src/test/java/dom/common/DomUtils.java diff --git a/test/src/dom/common/Loader.java b/src/test/java/dom/common/Loader.java similarity index 100% rename from test/src/dom/common/Loader.java rename to src/test/java/dom/common/Loader.java diff --git a/test/src/dom/common/NewLoader.java b/src/test/java/dom/common/NewLoader.java similarity index 100% rename from test/src/dom/common/NewLoader.java rename to src/test/java/dom/common/NewLoader.java diff --git a/src/test/java/dom/common/NodeTest.java b/src/test/java/dom/common/NodeTest.java new file mode 100755 index 0000000..6fe83a0 --- /dev/null +++ b/src/test/java/dom/common/NodeTest.java @@ -0,0 +1,375 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dom.common; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +import java.io.StringReader; + +import static org.junit.Assert.*; + +@Ignore +public abstract class NodeTest implements TestSetup { + protected Node m_node; + + protected Document m_doc; + protected String sXml; + + protected Document m_docNS; + protected String sXmlNS; + //attributes + + @Test + public void testOwnerDocument() { + assertEquals(m_doc, m_node.getOwnerDocument()); + } + + @Test + public void testPrefix() { + assertNotNull(m_node); + assertNull(m_node.getPrefix()); + // assertEquals("", m_node.getPrefix()); + } + + @Test + public void testNamespaceUri() { + assertNotNull(m_node); + assertNull(m_node.getNamespaceURI()); + //assertEquals("", m_node.getNamespaceURI()); + } + + @Test + public void testLocalName() { + assertNotNull(m_node); + assertNull(m_node.getLocalName()); + // assertEquals("", m_node.getLocalName()); + } + + //0 length list as of API + @Test + public void testGetChildNodes() { + assertEquals(0, m_node.getChildNodes().getLength()); + } + + @Test + public void testFirstChild() { + assertNull(m_node.getFirstChild()); + } + + @Test + public void testLastChild() { + assertNull(m_node.getLastChild()); + } + + /** + * pathologic cases: newChild is m_node or an ancestor + * newChild is from a different document + * newChild is not allowed at this pos + */ + protected void testAppendChild(Node newChild) { + Node inserted = m_node.appendChild(newChild); + if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) + assertTrue(compareNodeListPrefix(newChild.getChildNodes(), m_node.getChildNodes())); + else + assertEquals(inserted, m_node.getLastChild()); + if (isInTree(m_node, newChild)) //new child is in the tree + //$NOTE: assert the child is removed first + ; + } + + /** + * $NOTE: + * override for Element; + * override for Attribute + * $TODO: ER results in a mutable copy + */ + @Test + public void testCloneNode() { + + Node m_clone; + m_clone=m_node.cloneNode(false); + assertTrue(DomUtils.compareNodesShallow(m_node, m_clone)); +// assertEquals(true, DomUtils.compareNodeTreePtr(m_clone.getChildNodes(),m_node.getChildNodes())); //ptr eq for ch. + assertNotSame(m_clone, m_node); + + + m_clone = m_node.cloneNode(true); + assertTrue(DomUtils.compareNodesDeep(m_node, m_clone)); //deep clone: should do for whole tree, not just ch. + assertNotSame(m_clone, m_node); + + assertNull(m_clone.getParentNode()); + } + + protected void testInsertBefore(Node newChild, Node refChild) { + + int newChPos = getChildPos(m_node, newChild); + int pos = getChildPos(m_node, refChild); + Node prevParent = null; + if (newChPos > -1) + prevParent = newChild.getParentNode(); + NodeList childNodes = m_node.getChildNodes(); + int nOrigChildNum = childNodes.getLength(); //get it now, List is live + + + if (newChild == null) { + try { + m_node.insertBefore(newChild, refChild); + fail("Inserting null"); + } catch (IllegalArgumentException e) { + return; + } + } + Node inserted = m_node.insertBefore(newChild, refChild); + + + if (refChild == null) + assertEquals(inserted, m_node.getLastChild()); + else if (pos == -1)//would have thrown exc + fail("Inserting after fake child"); + else if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) + assertTrue(compareNodeListPrefix(newChild.getChildNodes(), m_node.getChildNodes())); + else if (newChPos != -1) //new child is in the tree + //assert the child is removed first + assertNotEquals(inserted.getParentNode(), prevParent); + else { + assertEquals(newChild, childNodes.item(pos)); + assertEquals(nOrigChildNum + 1, m_node.getChildNodes().getLength()); + } + + } + + /** + * $NOTE: override for element + */ + @Test + public void testGetAttributes() { + assertNull(m_node.getAttributes()); + } + + @Test + public void testHasChildNodes() { + int i = m_node.getChildNodes().getLength(); + if (i > 0) + assertTrue(m_node.hasChildNodes()); + else + assertFalse(m_node.hasChildNodes()); + } + + //Override for Element + @Test + public void testHasAttributes() { + assertFalse(m_node.hasAttributes()); + } + + @Test + public void testIsSupported() { + String[] features=new String[]{ + "Core","XML","Events","MutationEvents","Range","Traversal","HTML","Views","StyleSheets","CSS","CSS2","UIEvents","HTMLEvents" + }; + boolean bResult=true; + for (int i=0;i1) bResult=false; + System.out.println("============== "+features[i]+" ============="+bResult); + assertEquals(bResult,m_node.isSupported(features[i],"2.0")); + } + + } + + void testRemoveChild(Node removed) { + int pos = getChildPos(m_node, removed); + int len = m_node.getChildNodes().getLength(); + if (removed == null) + try { + m_node.removeChild(removed); + fail("Should not be Removing non-existing node"); + } catch (DOMException de) { + assertEquals(DOMException.NOT_FOUND_ERR, de.code); + } + else if (pos == -1) + try { + m_node.removeChild(removed); + fail("Removing non-existing node"); + } catch (DOMException de) { + throw de; + } + else { + m_node.removeChild(removed); + assertEquals(len - 1, m_node.getChildNodes().getLength()); + } + + } + + /** + * pathological cases: + * node is DocFrag + * node is already in tree + */ + protected void testReplaceChild(final Node newChild, Node oldChild) { + int pos = getChildPos(m_node, oldChild); + boolean existing = isInTree(m_doc.getDocumentElement(), newChild); //new Child has a parent + + int len = m_node.getChildNodes().getLength(); + + + if (newChild == null) { + try { + m_node.replaceChild(newChild, oldChild); + fail("Inserting null"); + } catch (IllegalArgumentException e) { + } + } else if (pos == -1) { + try { + m_node.replaceChild(newChild, oldChild); + fail("Replacing non-existing node"); + } catch (DOMException de) { + if (DOMException.NOT_FOUND_ERR != de.code) + throw de; + } + } else if (existing) { + Node oldParent = newChild.getParentNode(); + NodeList old = m_node.getChildNodes(); + assertEquals(oldChild, m_node.replaceChild(newChild, oldChild)); + assertNotEquals(newChild.getParentNode(), oldParent); + } else if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) { + int new_len = newChild.getChildNodes().getLength(); + assertEquals(oldChild, m_node.replaceChild(newChild, oldChild)); + assertEquals(new_len + len - 1, m_node.getChildNodes().getLength());//new+old-one replaced + } else + m_node.replaceChild(newChild, oldChild); + + + } + + //$NOTE:override for element and attribute + @Test + public void testSetPrefix() + { + //any prefix here is invalid + String val = null; + val = "blah"; //Eric's default + try + { + m_node.setPrefix(val); + fail(" set prefix only works for at/elt"); + } + catch (DOMException de) + { + assertEquals(DOMException.NAMESPACE_ERR, de.code); + } + } + + private static int getChildPos(Node node, Node child) { + if (child == null) return -1; + NodeList ch = node.getChildNodes(); + for (int i = 0; i < ch.getLength(); i++) + if (ch.item(i) == child) + return i; + return -1; + } + + private static boolean isInTree(Node root, Node find) { + if (find == null) return false; + if (root == null) return false; + if (root == find) return true; + NodeList ch = root.getChildNodes(); + boolean temp_res = false; + for (int i = 0; i < ch.getLength(); i++) + temp_res = temp_res || isInTree(ch.item(i), find); + return temp_res; + } + + protected static boolean compareNodeList(NodeList l1, NodeList l2) { + if (l1.getLength() != l2.getLength()) return false; + for (int i = 0; i < l1.getLength(); i++) + if (l1.item(i) != l2.item(i)) //pointer eq + return false; + return true; + } + + //l1 is a prefix of l2 + private static boolean compareNodeListPrefix(NodeList l1, NodeList l2) { + if (l1.getLength() > l2.getLength()) return false; + for (int i = 0; i < l1.getLength(); i++) + if (l1.item(i) != l2.item(i)) //pointer eq + return false; + return true; + } + + public void loadSync() { + _loader = Loader.getLoader(); + + if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); + m_doc = (org.w3c.dom.Document) _loader.loadSync(sXml); + if (sXmlNS != null && sXmlNS.length() > 0) + m_docNS = (org.w3c.dom.Document) _loader.loadSync(sXmlNS); + + } + + + public static Node getApacheNode(String sXml,boolean namespace,char type) + throws Exception{ + org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); + parser.parse(new InputSource(new StringReader(sXml))); + Document doc = parser.getDocument(); + + String name="apache_node"; + String nsname="pre:apache_node"; + String uri="uri:apache:test"; + + switch(type){ + case 'A': + if (namespace) + return doc.createAttributeNS(uri,nsname); + else + return doc.createAttribute(name); + case 'E': + if (namespace) + return doc.createElementNS(uri,nsname); + else return doc.createElement(name); + default: return doc.createTextNode(name); + + } + + } + + //exposing a node for other tests...saver in particular + public Node getNode(){ + return m_node; + } + + @Before + public void setUp() throws Exception { + //m_doc=(org.w3c.dom.Document)org.apache.xmlbeans.XmlObject.Factory.parse(xml).newDomNode(); + _loader = Loader.getLoader(); + + if (sXml == null && sXmlNS == null) { + throw new IllegalArgumentException("Test bug : Initialize xml strings"); + } + m_doc = _loader.load(sXml); + if (sXmlNS != null && sXmlNS.length() > 0) + m_docNS = _loader.load(sXmlNS); + } + + private Loader _loader; +} + diff --git a/test/src/dom/common/NodeWithChildrenTest.java b/src/test/java/dom/common/NodeWithChildrenTest.java similarity index 89% rename from test/src/dom/common/NodeWithChildrenTest.java rename to src/test/java/dom/common/NodeWithChildrenTest.java index a913acd..78ed21c 100755 --- a/test/src/dom/common/NodeWithChildrenTest.java +++ b/src/test/java/dom/common/NodeWithChildrenTest.java @@ -15,24 +15,23 @@ package dom.common; +import org.junit.Ignore; +import org.junit.Test; import org.w3c.dom.*; +import static org.junit.Assert.*; - - +@Ignore public abstract class NodeWithChildrenTest extends NodeTest { - - public NodeWithChildrenTest(String s) { - super(s); - } - + @Test public void testRemoveChildEnd() { Node node = m_node.getLastChild(); super.testRemoveChild(node); } + @Test public void testRemoveChild() { NodeList children = m_node.getChildNodes(); int pos = children.getLength() / 2; @@ -41,12 +40,12 @@ public void testRemoveChild() { } - + @Test public void testRemoveChildDiffImpl() throws Exception { Node toRemove=NodeTest.getApacheNode(sXml,true,'E'); try { - super.testRemoveChild(toRemove); + super.testRemoveChild(toRemove); fail("Removing node from a different impl"); } catch (DOMException de) { assertEquals(de.code, DOMException.WRONG_DOCUMENT_ERR); @@ -54,6 +53,7 @@ public void testRemoveChildDiffImpl() throws Exception { } + @Test public void testRemoveChildDiffDoc() throws Exception { Node toRemove=m_docNS.getDocumentElement(); try { @@ -65,18 +65,19 @@ public void testRemoveChildDiffDoc() throws Exception { } - - + @Test public void testRemoveChildFront() { Node node = m_node.getFirstChild(); super.testRemoveChild(node); } + @Test public void testRemoveChildNull() { super.testRemoveChild(null); } + @Test public void testReplaceChild() { NodeList children = m_node.getChildNodes(); int pos = children.getLength() / 2; @@ -90,25 +91,29 @@ public void testReplaceChild() { } + @Test public void testReplaceChildEnd() { Node node = m_node.getLastChild(); Node newNode = m_doc.createTextNode("fooBAR"); super.testReplaceChild(newNode, node); } + @Test public void testReplaceChildFront() { Node node = m_node.getFirstChild(); Node newNode = m_doc.createTextNode("fooBAR"); super.testReplaceChild(newNode, node); } + @Test public void testReplaceChildNullChild() { Node node = m_node.getChildNodes().item(0); Node newNode = null; - assertFalse(null == node); + assertNotNull(node); super.testReplaceChild(newNode, node); } + @Test public void testReplaceChildNull() { Node node = null; Node newNode; @@ -119,6 +124,7 @@ public void testReplaceChildNull() { super.testReplaceChild(newNode, node); } + @Test public void testReplaceChildDNE() { if (!(m_doc instanceof Document)) @@ -136,7 +142,7 @@ public void testReplaceChildDNE() { //newChild was created from a different document than the one that created this node newNode = m_docNS.createElement("fooBAR"); - assertFalse(m_docNS.equals(m_node.getOwnerDocument())); + assertNotEquals(m_docNS, m_node.getOwnerDocument()); try { super.testReplaceChild(newNode, node); fail("Node is from the wrong document"); @@ -161,7 +167,7 @@ public void testReplaceChildDNE() { // public void testInsertBeforeDiffDoc(){}:done above - + @Test public void testReplace_replacement_DiffImpl() throws Exception { Node node = m_node.getFirstChild(); Node newnode=NodeTest.getApacheNode(sXml,true,'T'); @@ -175,6 +181,7 @@ public void testReplace_replacement_DiffImpl() throws Exception { } //ref child is diff impl + @Test public void testReplace_target_DiffImpl() throws Exception { Node node =NodeTest.getApacheNode(sXml,true,'E'); Node newnode=m_node.getFirstChild(); @@ -187,6 +194,7 @@ public void testReplace_target_DiffImpl() throws Exception { } + @Test public void testReplaceChildDocFrag() { DocumentFragment child = m_doc.createDocumentFragment(); child.appendChild(m_doc.createElement("foo")); @@ -195,18 +203,21 @@ public void testReplaceChildDocFrag() { super.testReplaceChild(child, toReplace); } + @Test public void testInsertBefore() { Node target = m_node.getFirstChild(); Node child = m_doc.createElementNS("org.foo.www", "foonode"); - assertFalse(target == null); + assertNotNull(target); super.testInsertBefore(child, target); } + @Test public void testInsertBeforeNullTarget() { Node child = m_doc.createElementNS("org.foo.www", "foonode"); super.testInsertBefore(child, null); } + @Test public void testInsertBeforeInvalidRefNode() { Node child = m_doc.createElementNS("org.foo.www", "foonode"); Node target = m_doc.createElement("foo"); @@ -219,6 +230,7 @@ public void testInsertBeforeInvalidRefNode() { } } + @Test public void testInsertBeforeNewChildDiffDoc(){ Node target = m_node.getFirstChild(); Node toInsert=m_docNS.getDocumentElement(); @@ -232,6 +244,7 @@ public void testInsertBeforeNewChildDiffDoc(){ } + @Test public void testInsertBeforeNewChildDiffImpl() throws Exception { Node target = m_node.getFirstChild(); Node toInsert=NodeTest.getApacheNode(sXml,true,'T'); @@ -244,32 +257,32 @@ public void testInsertBeforeNewChildDiffImpl() throws Exception { } + @Test public void testInsertBeforeRefChildDiffDoc(){ - Node target = m_docNS.getDocumentElement(); - Node toInsert= m_node.getFirstChild();; - try { - super.testInsertBefore(toInsert, target); - fail("Ref Child from a different doc"); - } catch (DOMException de) { - assertEquals(de.code, DOMException.WRONG_DOCUMENT_ERR); - } - - + Node target = m_docNS.getDocumentElement(); + Node toInsert = m_node.getFirstChild(); + try { + super.testInsertBefore(toInsert, target); + fail("Ref Child from a different doc"); + } catch (DOMException de) { + assertEquals(de.code, DOMException.WRONG_DOCUMENT_ERR); } + } - public void testInsertBeforeRefChildDiffImpl() throws Exception { - Node target = NodeTest.getApacheNode(sXml,true,'T'); - Node toInsert=m_node.getFirstChild();; - try { - super.testInsertBefore(toInsert, target); - fail("Inserting node created from a different impl"); - } catch (DOMException de) { - assertEquals(de.code, DOMException.WRONG_DOCUMENT_ERR); - } - + @Test + public void testInsertBeforeRefChildDiffImpl() throws Exception { + Node target = NodeTest.getApacheNode(sXml, true, 'T'); + Node toInsert = m_node.getFirstChild(); + try { + super.testInsertBefore(toInsert, target); + fail("Inserting node created from a different impl"); + } catch (DOMException de) { + assertEquals(de.code, DOMException.WRONG_DOCUMENT_ERR); } + } + @Test public void testInsertBeforeNullChild() { Node target = m_doc.createElement("foo"); super.testInsertBefore(null, target); @@ -279,7 +292,6 @@ public void testInsertBeforeNullChild() { * pre: child is not a parent ancestor */ public void testAppendChildExisting(Node child) { - if (child == m_node) child = m_doc.getLastChild(); //if still the same, too bad @@ -297,7 +309,8 @@ public void testInsertExistingNode(Node child) { assertFalse(target == null || child == null); super.testInsertBefore(child, target); } - + + @Test public void testInsertBeforeDocFrag() { DocumentFragment child = m_doc.createDocumentFragment(); child.appendChild(m_doc.createElement("foo1")); @@ -305,12 +318,14 @@ public void testInsertBeforeDocFrag() { super.testInsertBefore(child, target); } + @Test public void testAppendChild() { Node newNode = m_doc.createElement("foo"); super.testAppendChild(newNode); } //try to append the parent + @Test public void testAppendChildIllegal0() { Node parent = m_node.getFirstChild(); m_node = m_node.getFirstChild(); @@ -323,6 +338,7 @@ public void testAppendChildIllegal0() { } //try to insert diff doc + @Test public void testAppendChildIllegal1() { Node newNode = m_docNS.createElement("newNode"); try { @@ -334,6 +350,7 @@ public void testAppendChildIllegal1() { } //append doc frag + @Test public void testAppendChildDocFrag() { DocumentFragment child = m_doc.createDocumentFragment(); child.appendChild(m_doc.createElement("foo")); @@ -341,8 +358,8 @@ public void testAppendChildDocFrag() { } //TODO : not implemented + @Test public void testNormalize() { - int nCount=m_node.getChildNodes().getLength(); String value=""; if (m_node.getLastChild() instanceof Text) @@ -370,11 +387,10 @@ public void testNormalize() { value+="foo bar"; assertEquals(value,m_node.getLastChild().getNodeValue()); - - } + @Test public void testSetPrefixInvalid() { //test only applies to Attrs and Elems if (!(m_node.getNodeType() == Node.ATTRIBUTE_NODE @@ -405,11 +421,12 @@ public void testSetPrefixInvalid() { } + @Test public void testSetNodeValue() { int nCount = m_node.getChildNodes().getLength(); m_node.setNodeValue("blah"); assertEquals(nCount, m_node.getChildNodes().getLength()); for (int i = 0; i < nCount; i++) - assertEquals(false, ("blah".equals(m_node.getChildNodes().item(i).getNodeValue()))); + assertNotEquals("blah", m_node.getChildNodes().item(i).getNodeValue()); } } diff --git a/test/src/dom/common/TestSetup.java b/src/test/java/dom/common/TestSetup.java similarity index 94% rename from test/src/dom/common/TestSetup.java rename to src/test/java/dom/common/TestSetup.java index 037c639..385c4e5 100755 --- a/test/src/dom/common/TestSetup.java +++ b/src/test/java/dom/common/TestSetup.java @@ -17,5 +17,5 @@ public interface TestSetup{ - public static boolean bDTD=false; + boolean bDTD=false; } diff --git a/test/src/dom/detailed/AttrNamespaceTest.java b/src/test/java/dom/detailed/AttrNamespaceTest.java similarity index 90% rename from test/src/dom/detailed/AttrNamespaceTest.java rename to src/test/java/dom/detailed/AttrNamespaceTest.java index 9856724..6041618 100755 --- a/test/src/dom/detailed/AttrNamespaceTest.java +++ b/src/test/java/dom/detailed/AttrNamespaceTest.java @@ -16,25 +16,26 @@ package dom.detailed; import dom.common.Loader; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; -import org.apache.xmlbeans.XmlObject; import java.io.StringReader; -import java.io.IOException; + +import static org.junit.Assert.*; /** * Tests conversion of regular attributes to namespaces and vv */ -public class AttrNamespaceTest extends TestCase { +public class AttrNamespaceTest { String sXml = ""; String sXmlNS = ""; Document m_doc, @@ -42,18 +43,13 @@ public class AttrNamespaceTest extends TestCase { Node m_node; - public AttrNamespaceTest(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(AttrNamespaceTest.class); - } - + @Test + @Ignore public void testDefaultNamespace() { - //assertEquals(true,((Element)m_node).hasAttribute("xmlns")); + assertTrue(((Element) m_node).hasAttribute("xmlns")); } + @Test public void testAttr2Namespace() { Attr at = (Attr) ((Element) m_node).getAttributeNode("at0"); String namespaceURI = "http://foo.org"; @@ -61,7 +57,7 @@ public void testAttr2Namespace() { at.setValue(namespaceURI); m_node.appendChild(m_doc.createElementNS(namespaceURI, qualifiedName)); Element bar = (Element) ((Element) m_node).getElementsByTagNameNS(namespaceURI, "bar").item(0); - assertFalse(null == bar); + assertNotNull(bar); assertEquals(namespaceURI, bar.getNamespaceURI()); assertEquals(qualifiedName, bar.getNodeName()); /* @@ -72,6 +68,7 @@ public void testAttr2Namespace() { */ } + @Test public void testNamespace2Attr() { m_node = m_docNS.getFirstChild(); @@ -102,6 +99,7 @@ public void testNamespace2Attr() { * ""/NULL...Do we get an error since now there is a prefix * with NULL URI? */ + @Test public void testInsertBadAttribute() throws Exception{ String sER=""; org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); @@ -120,9 +118,8 @@ public void testInsertBadAttribute() throws Exception{ at_xerces.setValue(""); } - + @Before public void setUp() throws Exception { - if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); Loader loader = Loader.getLoader(); m_doc = (org.w3c.dom.Document) loader.load(sXml); diff --git a/src/test/java/dom/detailed/IDTest.java b/src/test/java/dom/detailed/IDTest.java new file mode 100644 index 0000000..7816528 --- /dev/null +++ b/src/test/java/dom/detailed/IDTest.java @@ -0,0 +1,128 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dom.detailed; + +import common.Common; +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import xbean.dom.id.FooDocument; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.*; + +public class IDTest { + private String P = File.separator; + + // Test the getElementById() DOM API with DTDs , run with jvm arg -Dcases.location + @Test + public void testGetElemById() throws Exception { + Document doc; + Element element; + String tagname; + XmlOptions xmlOptions = new XmlOptions(); + xmlOptions.setLoadUseDefaultResolver(); + XmlObject o = XmlObject.Factory.parse(new File(Common.CASEROOT + P + "xbean" + P + "dom" + P + "id.xml")); + doc = (Document) o.getDomNode(); + element = doc.getElementById("CANADA"); + assertNotNull(element); + + tagname = element.getTagName(); + assertEquals("throw_Equals", "emp:address", tagname); + assertNull(doc.getDoctype()); + } + + // test getElementById() with schema containing DTD with ID definition for untyped XmlObject + @Test + public void testIDSchema() throws Exception { + String dtdAndData = + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "]>" + + ""; + + XmlObject o = XmlObject.Factory.parse(dtdAndData); + Document n = (Document) o.getDomNode(); + Element elem = n.getElementById("25"); + assertNotNull(elem); + System.out.println("Elem: " + elem.getNodeName()); + + Element elemInvalid = n.getElementById("100"); + assertNull(elemInvalid); + } + + // typed XmlObject + @Test + @Ignore("doesn't work anymore - xerces 2.11 is not calling the DeclHandler and so no ID attribute is added") + public void testSchemaWithDTD() throws Exception { + XmlOptions opt = new XmlOptions(); + List err = new ArrayList(); + opt.setErrorListener(err); + // opt.setLoadSaxSchema(true); + + String instance = + "" + + " John" + + ""; + + try { + FooDocument fooDoc = FooDocument.Factory.parse(instance, opt); + + Document d = (Document) fooDoc.getDomNode(); + Element elem = d.getElementById("abc"); + assertNotNull(elem); + + Element elemInvalid = d.getElementById("100"); + assertNull(elemInvalid); + } catch (XmlException xme) { + Collection xmlerrs = xme.getErrors(); + for (Object xmlerr : xmlerrs) { + XmlError xerr = (XmlError) xmlerr; + System.out.println("Exception:" + xerr.getMessage()); + } + throw (new XmlException(new Throwable("XmlException occured"))); + } + + // parse errors + for (Object o : err) { + System.out.println("Err:" + o); + } + } + +} diff --git a/src/test/java/dom/detailed/ImportUnsupportedNodesTest.java b/src/test/java/dom/detailed/ImportUnsupportedNodesTest.java new file mode 100755 index 0000000..36af4f0 --- /dev/null +++ b/src/test/java/dom/detailed/ImportUnsupportedNodesTest.java @@ -0,0 +1,131 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dom.detailed; + +import dom.common.Loader; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +import java.io.StringReader; + +import static org.junit.Assert.*; + + +public class ImportUnsupportedNodesTest { + String sXml=""; + // String sXmlNS=""; + Document m_doc; + Node m_node; + String sER="] >" + +"&ORG;"; + + @Test + @Ignore("not implemented") + public void testImportEnitityNode()throws Exception{ + org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); + parser.parse(new InputSource(new StringReader(sER))); + Document xercesDocument = parser.getDocument(); + assertNotNull(xercesDocument); + Node toImport = xercesDocument.getDoctype().getEntities().item(0); + assertEquals(Node.ENTITY_NODE, toImport.getNodeType()); + Node importedNode = m_doc.importNode(toImport, true); + m_node.insertBefore(importedNode, m_node.getFirstChild()); + + assertEquals(importedNode, m_node.getFirstChild()); + assertEquals(Node.ENTITY_NODE, m_node.getFirstChild().getNodeType()); + } + + @Test + @Ignore("not implemented") + public void testImportERNode()throws Exception{ + org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); + parser.parse(new InputSource(new StringReader(sER))); + Document xercesDocument = parser.getDocument(); + assertNotNull(xercesDocument); + Node toImport = xercesDocument.getDocumentElement().getFirstChild(); + + assertEquals(Node.ENTITY_REFERENCE_NODE, toImport.getNodeType()); + Node importedNode = m_doc.importNode(toImport, true); + m_node.insertBefore(importedNode, m_node.getFirstChild()); + + assertEquals(importedNode, m_node.getFirstChild()); + assertEquals(Node.ENTITY_REFERENCE_NODE, m_node.getFirstChild().getNodeType()); + } + + /** + * DOCUMENT_TYPE_NODE + * cannot be imported. + */ + @Test(expected = DOMException.class) + public void testImportDocType() throws Exception{ + org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); + parser.parse(new InputSource(new StringReader(sER))); + Document xercesDocument = parser.getDocument(); + assertNotNull(xercesDocument); + Node toImport = xercesDocument.getDoctype(); + + try { + Node importedNode = m_doc.importNode(toImport, true); + fail("can't import DocType Node"); + } catch (DOMException e) { + + } + + m_doc.importNode(toImport, false); + } + + @Test + public void testImportCDATAType() throws Exception{ + org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); + parser.parse(new InputSource(new StringReader(sER))); + Document xercesDocument = parser.getDocument(); + assertNotNull(xercesDocument); + Node toImport = xercesDocument.createCDATASection("My < CData"); + xercesDocument.getDocumentElement().appendChild(toImport); + + assertEquals(Node.CDATA_SECTION_NODE, toImport.getNodeType()); + Node importedNode = m_doc.importNode(toImport, true); + m_node.insertBefore(importedNode, m_node.getFirstChild()); + + assertEquals(importedNode, m_node.getFirstChild()); + assertEquals(Node.CDATA_SECTION_NODE, m_node.getFirstChild().getNodeType()); + + + assertEquals(Node.CDATA_SECTION_NODE, toImport.getNodeType()); + importedNode = m_doc.importNode(toImport, false); + m_node.replaceChild(importedNode, m_node.getFirstChild()); + + assertEquals(importedNode, m_node.getFirstChild()); + assertEquals(Node.CDATA_SECTION_NODE, m_node.getFirstChild().getNodeType()); + } + + + //TODO: see if code coverage can help id gaps here... + @Before + public void setUp() throws Exception{ + Loader _loader = Loader.getLoader(); + if (sXml == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); + m_doc = (org.w3c.dom.Document) _loader.load(sXml); + + m_node = m_doc.getFirstChild(); + } +} + diff --git a/src/test/java/dom/detailed/InsertDeleteNodesTest.java b/src/test/java/dom/detailed/InsertDeleteNodesTest.java new file mode 100755 index 0000000..3adae49 --- /dev/null +++ b/src/test/java/dom/detailed/InsertDeleteNodesTest.java @@ -0,0 +1,164 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dom.detailed; + +import dom.common.Loader; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + + +/** + * Insertion and deletion of nodes, normalization of text children + */ +public class InsertDeleteNodesTest { + String sXml=""; + String sXmlNS=""; + Document m_doc, + m_docNS; + Node m_node; + + @Test + public void testInsertNodes(){ + //insert one of each type of node: + Text txt0 = m_doc.createTextNode("foo"); + Text txt1 = m_doc.createTextNode(" "); + Text txt2 = m_doc.createTextNode("bar"); + Element elt1 = m_doc.createElement("elt1"); + + Attr attr0 = m_doc.createAttributeNS("xmlns", "attr0"); + + Comment comment = m_doc.createComment("A comment"); + DocumentFragment doc_frag = m_doc.createDocumentFragment(); + //Document new_doc: what to do with this... + //CDATASection cdata=m_doc.createCDATASection("");--Not impl + //ProcessingInstruction pi=m_doc.createProcessingInstruction("xml","version 1.0"); --Not impl + // DocumentType--TODO + //Entity + //EntityReference + //Notation + + Text nested_txt = m_doc.createTextNode("foo"); + + + //m_doc.appendChild(m_doc.createElement("root")); + + m_doc.getDocumentElement().appendChild(txt2); + m_doc.getDocumentElement().insertBefore(elt1, txt2); + m_doc.getDocumentElement().insertBefore(txt1, elt1); + m_doc.getDocumentElement().insertBefore(txt0, txt1); + + //insert level 1 + System.out.println("=======Basic inserts passed ==================="); + int nAttrs = 20; + for (int i = 0; i < nAttrs; i++) { + Attr insertAttr = (Attr) attr0.cloneNode(true); + insertAttr.setValue(i + ""); + elt1.setAttributeNode(insertAttr); + } + + assertEquals(1, elt1.getAttributes().getLength()); + assertEquals((nAttrs - 1) + "", elt1.getAttributes().getNamedItemNS("xmlns", "attr0").getNodeValue()); + + + //elt1.appendChild(cdata); + elt1.appendChild(comment); + //elt1.appendChild(pi); + elt1.appendChild(nested_txt); + + Element childElt = m_doc.createElement("childElt"); + childElt.setAttributeNode(attr0); + attr0.setValue("Attr0Value"); + + //a chain of depth 100 under doc frag of elt w/ attr + doc_frag.appendChild((Element) childElt.cloneNode(true)); + + System.out.println("======= Overwriting same attr ==================="); + Element last = (Element) doc_frag.getFirstChild(); + + + int nMaxTries = 100; + + + for (int i = 0; i < nMaxTries; i++) { + Element deep_nested = (Element) childElt.cloneNode(true); + last.appendChild(deep_nested); + last = (Element) last.getFirstChild(); + } + + elt1.appendChild(doc_frag); + + System.out.println("======= Inserted deep chain ==================="); + NodeList deepChain = m_doc.getDocumentElement().getElementsByTagName("childElt"); + assertEquals(nMaxTries + 1, deepChain.getLength());//newly inserted + 1 original + + for (int i = 0; i < nMaxTries; i++) + assertEquals("Attr0Value", deepChain.item(i).getAttributes().getNamedItemNS("xmlns", "attr0").getNodeValue()); + + //check doc frag isn't there + assertEquals("childElt", elt1.getLastChild().getNodeName()); + + + /////Done inserting: begin deletion: + + //1. delete the deep tree at depth 50 + Node toRemove = deepChain.item(nMaxTries / 2); + toRemove.removeChild(toRemove.getFirstChild()); + + assertEquals(nMaxTries / 2 + 1, deepChain.getLength()); + + //test normalization with Elt node + Element root = m_doc.getDocumentElement(); + assertEquals(4, root.getChildNodes().getLength()); + root.removeChild(root.getChildNodes().item(2)); + + assertEquals(0, deepChain.getLength()); + //TODO: normalize + //root.normalize(); +// assertEquals(1,root.getChildNodes().getLength()); +// assertEquals("foo bar",root.getFirstChild()); + + + //insert stuff under doc node: should be able to insert comments and PI here.... + + + m_doc.insertBefore(comment, root); + //m_doc.insertBefore(pi,root); + //m_doc.insertBefore(cdata,root); + + try { + m_doc.insertBefore(root, doc_frag.getLastChild()); + fail("Should except here"); + } catch (DOMException de) { + assertEquals(de.code, DOMException.HIERARCHY_REQUEST_ERR); + } + } + //TODO: insert nodes at all illegal places: + + @Before + public void setUp() throws Exception{ + Loader loader = Loader.getLoader(); + if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); + m_doc = (org.w3c.dom.Document) loader.load(sXml); + if (sXmlNS != null && sXmlNS.length() > 0) + m_docNS = (org.w3c.dom.Document) loader.load(sXmlNS); + m_doc = m_doc.getImplementation().createDocument(null, "root", null); + m_node = m_doc.getFirstChild(); + } +} diff --git a/src/test/java/dom/detailed/MoveImportNodeTest.java b/src/test/java/dom/detailed/MoveImportNodeTest.java new file mode 100755 index 0000000..a644a5e --- /dev/null +++ b/src/test/java/dom/detailed/MoveImportNodeTest.java @@ -0,0 +1,142 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package dom.detailed; + +import dom.common.Loader; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +import java.io.StringReader; + +import static org.junit.Assert.*; + + +public class MoveImportNodeTest { + String sXmlNS=""; + + String sXml=""; + Document m_doc, + m_docNS; + Node m_node; + + + + //insert a node from a ns into a non-ns: node will move "as is" + //even though ns is not in scope as DOM does no prefix resolution + @Test + public void testMoveNodeNStoNoNS(){ + Node toMove = m_docNS.getFirstChild().getFirstChild().getFirstChild(); //bar + assertEquals("myns:bar", toMove.getNodeName()); + Element newParent = (Element) m_docNS.getFirstChild(); + assertEquals("foo", newParent.getNodeName()); + newParent.insertBefore(toMove, newParent.getFirstChild()); + + assertEquals(2, newParent.getChildNodes().getLength()); + assertEquals(toMove, newParent.getElementsByTagNameNS("http://foo.org", "bar").item(0)); + assertEquals(newParent.getElementsByTagName("bar").item(0), + newParent.getElementsByTagNameNS(null, "bar").item(0)); + + } + + //move node to a different namespace + //namespace of node should be unchanged -- DOM does not care + @Test + public void testMoveDiffNS(){ + Node toMove = m_docNS.getFirstChild().getFirstChild().getFirstChild(); //bar + Element newParent = (Element) m_docNS.getFirstChild(); + newParent.insertBefore(toMove, newParent.getFirstChild()); + newParent.getFirstChild().setPrefix("other"); + assertEquals(2, newParent.getChildNodes().getLength()); + assertEquals(0, (newParent).getElementsByTagNameNS(null, "bar").getLength()); + assertTrue((toMove == newParent.getElementsByTagNameNS("http://foo.org", "bar").item(0))); + } + + + //import to a doc where the given ns DNE + @Test + public void testMoveDiffDoc(){ + Node toMove=m_docNS.getFirstChild().getFirstChild().getFirstChild(); //bar + try{ + m_node.insertBefore(toMove,m_node.getFirstChild()); + fail(" Cannot move nodes across docs"); + }catch(DOMException de){ + assertEquals(DOMException.WRONG_DOCUMENT_ERR,de.code); + } + } + + @Test + public void testMoveDiffImplementations() throws Exception{ + org.apache.xerces.parsers.DOMParser parser = + new org.apache.xerces.parsers.DOMParser(); + + + parser.parse(new InputSource(new StringReader(sXmlNS))); + + Document xercesDocument = parser.getDocument(); + assertNotNull(xercesDocument); + Node toMove = xercesDocument.getFirstChild().getFirstChild().getFirstChild(); //bar + System.out.println("=======Source Impl " + xercesDocument.getImplementation()); + System.out.println("=======Dest Impl " + m_doc.getImplementation()); + + try { + m_node.insertBefore(toMove, m_node.getFirstChild()); + fail(" Cannot move nodes across implementations"); + } catch (DOMException de) { + assertEquals(DOMException.WRONG_DOCUMENT_ERR, de.code); + } + + Node imported = m_doc.importNode(toMove, true);//deep would be the same here + m_node.appendChild(imported); + + assertEquals(2, m_node.getChildNodes().getLength()); + //node should be imported w/ prefix and all + assertEquals(imported, ((Element) m_node).getElementsByTagNameNS("http://foo.org", "bar").item(0)); + // assertEquals(((Element)m_node).getElementsByTagName("bar").item(1),imported); + assertEquals(((Element) m_node).getElementsByTagName("bar").item(0), ((Element) m_node).getElementsByTagNameNS(null, "bar").item(0)); + } + + + // public void + @Test + public void testImportSameDoc(){ + //inspired by nist documentimportnode10? + + Node toImport = m_doc.createElement("foobar"); + toImport = m_doc.importNode(toImport, true); + + toImport = m_doc.createDocumentFragment(); + toImport.appendChild(m_doc.getDocumentElement().getFirstChild()); + + m_doc.importNode(toImport, true); + } + + @Before + public void setUp() throws Exception{ + Loader loader = Loader.getLoader(); + if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); + m_doc = (org.w3c.dom.Document) loader.load(sXml); + if (sXmlNS != null && sXmlNS.length() > 0) + m_docNS = (org.w3c.dom.Document) loader.load(sXmlNS); + + m_node =m_doc.getFirstChild(); + } +} diff --git a/test/src/dom/detailed/MultipleDocsTest.java b/src/test/java/dom/detailed/MultipleDocsTest.java similarity index 85% rename from test/src/dom/detailed/MultipleDocsTest.java rename to src/test/java/dom/detailed/MultipleDocsTest.java index 33e73f1..a573847 100755 --- a/test/src/dom/detailed/MultipleDocsTest.java +++ b/src/test/java/dom/detailed/MultipleDocsTest.java @@ -16,7 +16,8 @@ package dom.detailed; import dom.common.Loader; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.w3c.dom.*; @@ -25,13 +26,13 @@ * * */ -public class MultipleDocsTest extends TestCase { - String[] sXml = new String[]{"", - "", - "text", - "text text ", - "text text ", - "text text " +public class MultipleDocsTest { + String[] sXml = {"", + "", + "text", + "text text ", + "text text ", + "text text " }; Thread[] threads; @@ -39,10 +40,7 @@ public class MultipleDocsTest extends TestCase { int nIterations = 100; Document[] m_doc; - public MultipleDocsTest(String name) { - super(name); - } - + @Test public void testRunThreads() { for (int j = 0; j < nThreadCount; j++) @@ -56,10 +54,10 @@ public void testRunThreads() { System.err.println("Thread " + j + " interrupted"); } - } } + @Before public void setUp() throws Exception { threads = new Thread[nThreadCount]; for (int i = 0; i < nThreadCount; i++) { @@ -73,11 +71,6 @@ public void setUp() throws Exception { } } - public void tearDown() throws Exception - { - super.tearDown(); - } - private class Worker extends Thread { int _ID; Document doc; @@ -189,16 +182,4 @@ public void run() { } } } - - public static void main(String[] a) { - try { - MultipleDocsTest test = new MultipleDocsTest(""); - test.setUp(); - test.testRunThreads(); - } - catch (Throwable t) { - t.printStackTrace(System.err); - } - } - } diff --git a/test/src/dom/detailed/TextInsertDeleteTest.java b/src/test/java/dom/detailed/TextInsertDeleteTest.java similarity index 85% rename from test/src/dom/detailed/TextInsertDeleteTest.java rename to src/test/java/dom/detailed/TextInsertDeleteTest.java index 879b238..e3aea1a 100755 --- a/test/src/dom/detailed/TextInsertDeleteTest.java +++ b/src/test/java/dom/detailed/TextInsertDeleteTest.java @@ -17,36 +17,36 @@ package dom.detailed; import dom.common.Loader; -import junit.framework.TestCase; -import org.w3c.dom.*; import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.*; +import static org.junit.Assert.assertEquals; -/** - * - * - */ -public class TextInsertDeleteTest extends TestCase { +public class TextInsertDeleteTest { String sXml = "txt0txt1txt2"; String sXmlNS = ""; Document m_doc, m_docNS; Node m_node; + @Test public void testBuildMixedContent(){ - DOMImplementation domImpl = XmlObject.Factory.newDomImplementation( null ); - m_doc=domImpl.createDocument("foobar","val",null); - Element root=m_doc.getDocumentElement(); + DOMImplementation domImpl = XmlObject.Factory.newDomImplementation(null); + m_doc = domImpl.createDocument("foobar", "val", null); + Element root = m_doc.getDocumentElement(); //m_doc.appendChild(root); - Element n=(Element)m_doc.createElement("foo"); - Text txt1=m_doc.createTextNode("foobar"); - Text txt2=m_doc.createTextNode("baz"); - root.appendChild(txt1); - root.appendChild(n); - root.appendChild(txt2); - System.out.println(m_doc.toString()) ; + Element n = (Element) m_doc.createElement("foo"); + Text txt1 = m_doc.createTextNode("foobar"); + Text txt2 = m_doc.createTextNode("baz"); + root.appendChild(txt1); + root.appendChild(n); + root.appendChild(txt2); + System.out.println(m_doc.toString()); } + @Test public void testAdjacent() { NodeList ch = m_node.getChildNodes(); m_node.removeChild(ch.item(1)); @@ -59,6 +59,7 @@ public void testAdjacent() { } + @Test public void testInsertDelete() { //eric test // TODO: three children delete middle--verify length @@ -89,10 +90,9 @@ public void testInsertDelete() { assertEquals(1, ch.getLength()); assertEquals("bar", m_node.getLastChild().getNodeValue()); assertEquals("bar", m_node.getFirstChild().getNodeValue()); - - } + @Test public void testInsertDeleteBulk() { int nNodeCnt = 16; @@ -134,13 +134,13 @@ public void testInsertDeleteBulk() { } + @Before public void setUp() throws Exception { - Loader loader = Loader.getLoader(); if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); - m_doc = (org.w3c.dom.Document) loader.load(sXml); + m_doc = loader.load(sXml); if (sXmlNS != null && sXmlNS.length() > 0) - m_docNS = (org.w3c.dom.Document) loader.load(sXmlNS); + m_docNS = loader.load(sXmlNS); m_node = m_doc.getFirstChild(); } diff --git a/src/test/java/dom/detailed/TextTest.java b/src/test/java/dom/detailed/TextTest.java new file mode 100755 index 0000000..139392e --- /dev/null +++ b/src/test/java/dom/detailed/TextTest.java @@ -0,0 +1,57 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package dom.detailed; + +import dom.common.Loader; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import static org.junit.Assert.assertEquals; + +public class TextTest { + String sXml=""; + String sXmlNS="footext"; + Document m_doc, + m_docNS; + Node m_node; + + @Test + public void testTextToAttrValue(){ + m_node = m_docNS.getFirstChild().getFirstChild().getFirstChild();//footext + Attr attrib = (Attr) m_docNS.getFirstChild().getFirstChild().getAttributes().getNamedItem("xmlns:myns"); + assertEquals("http://foo.org", attrib.getNodeValue()); + //attrib.replaceChild(m_node,attrib.getFirstChild()); + attrib.setValue(m_node.getNodeValue()); + assertEquals("footext", attrib.getNodeValue()); + //assertFalse(m_docNS.getFirstChild().getFirstChild().hasChildNodes()); + } + + @Before + public void setUp() throws Exception { + + Loader loader = Loader.getLoader(); + if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); + m_doc = loader.load(sXml); + if (sXmlNS != null && sXmlNS.length() > 0) + m_docNS = loader.load(sXmlNS); + + m_node = m_doc.getFirstChild(); + } +} diff --git a/src/test/java/dom/detailed/w3c/alltests.java b/src/test/java/dom/detailed/w3c/alltests.java new file mode 100755 index 0000000..0c6e812 --- /dev/null +++ b/src/test/java/dom/detailed/w3c/alltests.java @@ -0,0 +1,345 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* +This Java source file was generated by test-to-java.xsl +and is a derived work from the source document. +The source document contained the following notice: + + +Copyright (c) 2001-2003 World Wide Web Consortium, +(Massachusetts Institute of Technology, Institut National de +Recherche en Informatique et en Automatique, Keio University). All +Rights Reserved. This program is distributed under the W3C's Software +Intellectual Property License. This program is distributed in the +hope that it will be useful, but WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. +See W3C License http://www.w3.org/Consortium/Legal/ for more details. + +*/ + +//package org.w3c.domts.level2.core; +package dom.detailed.w3c; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.w3c.domts.level2.core.*; + + +/** +* Test suite +* @author W3C DOM Test Working Group +**/ +@RunWith(Suite.class) +@Suite.SuiteClasses({ + // attrgetownerelement01.class, + attrgetownerelement02.class, + attrgetownerelement03.class, + // attrgetownerelement04.class, + attrgetownerelement05.class, + createAttributeNS01.class, + createAttributeNS02.class, + createAttributeNS03.class, + createAttributeNS04.class, + createAttributeNS05.class, + createDocument01.class, + createDocument02.class, + // createDocument03.class, + // createDocument04.class, + createDocument05.class, + createDocument06.class, + createDocument07.class, + // createDocumentType01.class, + // createDocumentType02.class, + // createDocumentType03.class, + createElementNS01.class, + createElementNS02.class, + createElementNS03.class, + createElementNS04.class, + createElementNS05.class, + documentcreateattributeNS01.class, + documentcreateattributeNS02.class, + documentcreateattributeNS03.class, + documentcreateattributeNS04.class, + documentcreateattributeNS05.class, + documentcreateattributeNS06.class, + documentcreateattributeNS07.class, + documentcreateelementNS01.class, + documentcreateelementNS02.class, + documentcreateelementNS05.class, + documentcreateelementNS06.class, + // documentgetelementbyid01.class, + documentgetelementsbytagnameNS01.class, + documentgetelementsbytagnameNS02.class, + documentgetelementsbytagnameNS03.class, + documentgetelementsbytagnameNS04.class, + documentgetelementsbytagnameNS05.class, + documentimportnode01.class, + // documentimportnode02.class, + // documentimportnode03.class, + // documentimportnode04.class, + documentimportnode05.class, + documentimportnode06.class, + // documentimportnode07.class, + // documentimportnode08.class, + documentimportnode09.class, + documentimportnode10.class, + documentimportnode11.class, + documentimportnode12.class, + documentimportnode13.class, + documentimportnode14.class, + documentimportnode15.class, + documentimportnode17.class, + documentimportnode18.class, + // documentimportnode19.class, + // documentimportnode20.class, + // documentimportnode21.class, + // documentimportnode22.class, + // documenttypeinternalSubset01.class, + // documenttypepublicid01.class, + // documenttypesystemid01.class, + domimplementationcreatedocument03.class, + domimplementationcreatedocument04.class, + domimplementationcreatedocument05.class, + domimplementationcreatedocument07.class, + // domimplementationcreatedocumenttype01.class, + // domimplementationcreatedocumenttype02.class, + // domimplementationcreatedocumenttype04.class, + // domimplementationfeaturecore.class, + // domimplementationfeaturexmlversion2.class, + // domimplementationhasfeature01.class, + // domimplementationhasfeature02.class, + elementgetattributenodens01.class, + elementgetattributenodens02.class, + // elementgetattributenodens03.class, + // elementgetattributens02.class, + elementgetelementsbytagnamens02.class, + elementgetelementsbytagnamens04.class, + elementgetelementsbytagnamens05.class, + elementhasattribute01.class, + // elementhasattribute02.class, + elementhasattribute03.class, + elementhasattribute04.class, + elementhasattributens01.class, + elementhasattributens02.class, + elementhasattributens03.class, + elementremoveattributens01.class, + elementsetattributenodens01.class, + elementsetattributenodens02.class, + elementsetattributenodens03.class, + elementsetattributenodens04.class, + elementsetattributenodens05.class, + // elementsetattributenodens06.class, + elementsetattributens01.class, + elementsetattributens02.class, + elementsetattributens03.class, + elementsetattributens04.class, + elementsetattributens05.class, + elementsetattributens08.class, + elementsetattributensurinull.class, + // getAttributeNS01.class, + getAttributeNS02.class, + getAttributeNS03.class, + getAttributeNS04.class, + getAttributeNS05.class, + getAttributeNodeNS01.class, + getAttributeNodeNS02.class, + // getElementById01.class, + // getElementById02.class, + // getElementsByTagNameNS01.class, + getElementsByTagNameNS02.class, + getElementsByTagNameNS03.class, + getElementsByTagNameNS04.class, + getElementsByTagNameNS05.class, + getElementsByTagNameNS06.class, + getElementsByTagNameNS07.class, + getElementsByTagNameNS08.class, + getElementsByTagNameNS09.class, + getElementsByTagNameNS10.class, + getElementsByTagNameNS11.class, + getElementsByTagNameNS12.class, + getElementsByTagNameNS13.class, + getElementsByTagNameNS14.class, + getNamedItemNS01.class, + getNamedItemNS02.class, + // getNamedItemNS03.class, + // getNamedItemNS04.class, + hasAttribute01.class, + hasAttribute02.class, + hasAttribute03.class, + hasAttribute04.class, + hasAttributeNS01.class, + hasAttributeNS02.class, + hasAttributeNS03.class, + // hasAttributeNS04.class, + hasAttributeNS05.class, + hasAttributes01.class, + hasAttributes02.class, + hc_attrcreatedocumentfragment.class, + hc_attrname.class, + hc_documentcreateattribute.class, + hc_elementgetattributenode.class, + // hc_entitiesremovenameditemns1.class, + // hc_entitiessetnameditemns1.class, + hc_namednodemapgetnameditem.class, + hc_nodedocumentfragmentnormalize1.class, + hc_nodedocumentfragmentnormalize2.class, + // hc_notationsremovenameditemns1.class, + // hc_notationssetnameditemns1.class, + // ibmtests.class, + // importNode01.class, + // importNode02.class, + importNode03.class, + importNode04.class, + // importNode05.class, + // importNode06.class, + importNode07.class, + importNode08.class, + // importNode09.class, + // importNode10.class, + // importNode11.class, + // importNode12.class, + // importNode13.class, + importNode14.class, + importNode15.class, + // importNode16.class, + importNode17.class, + // internalSubset01.class, + isSupported01.class, + isSupported02.class, + isSupported04.class, + isSupported05.class, + isSupported06.class, + isSupported07.class, + isSupported09.class, + isSupported10.class, + isSupported11.class, + isSupported12.class, + isSupported13.class, + isSupported14.class, + localName01.class, + localName02.class, + localName03.class, + localName04.class, + // namednodemapgetnameditemns01.class, + namednodemapgetnameditemns02.class, + namednodemapgetnameditemns03.class, + namednodemapgetnameditemns04.class, + namednodemapgetnameditemns05.class, + namednodemapgetnameditemns06.class, + namednodemapremovenameditemns01.class, + //default Attr + // namednodemapremovenameditemns02.class, + // ER + // namednodemapremovenameditemns03.class, + namednodemapremovenameditemns04.class, + // namednodemapremovenameditemns05.class, + namednodemapremovenameditemns06.class, + namednodemapremovenameditemns07.class, + namednodemapremovenameditemns08.class, + namednodemapremovenameditemns09.class, + namednodemapsetnameditemns01.class, + namednodemapsetnameditemns02.class, + namednodemapsetnameditemns03.class, + namednodemapsetnameditemns04.class, + // namednodemapsetnameditemns05.class, + namednodemapsetnameditemns06.class, + namednodemapsetnameditemns07.class, + namednodemapsetnameditemns08.class, + // namednodemapsetnameditemns09.class, + // namednodemapsetnameditemns10.class, + // namednodemapsetnameditemns11.class, + namespaceURI01.class, + namespaceURI02.class, + namespaceURI03.class, + namespaceURI04.class, + nodegetlocalname03.class, + nodegetnamespaceuri03.class, + // nodegetownerdocument01.class, + nodegetownerdocument02.class, + nodegetprefix03.class, + nodehasattributes01.class, + // nodehasattributes02.class, + nodehasattributes03.class, + nodehasattributes04.class, + // nodeissupported01.class, + // nodeissupported02.class, + // nodeissupported03.class, + // nodeissupported04.class, + // nodeissupported05.class, + // nodenormalize01.class, + nodesetprefix01.class, + nodesetprefix02.class, + nodesetprefix03.class, + // nodesetprefix04.class, + nodesetprefix05.class, + nodesetprefix06.class, + nodesetprefix07.class, + nodesetprefix08.class, + nodesetprefix09.class, + normalize01.class, + ownerDocument01.class, + ownerElement01.class, + ownerElement02.class, + prefix01.class, + prefix02.class, + prefix03.class, + prefix04.class, + prefix05.class, + prefix06.class, + prefix07.class, + // prefix08.class, + prefix09.class, + prefix10.class, + prefix11.class, + // publicId01.class, + // removeAttributeNS01.class, + // removeAttributeNS02.class, + removeNamedItemNS01.class, + removeNamedItemNS02.class, + removeNamedItemNS03.class, + setAttributeNS01.class, + setAttributeNS02.class, + //Test makes no sense w/o ER + // setAttributeNS03.class, + setAttributeNS04.class, + setAttributeNS05.class, + setAttributeNS06.class, + setAttributeNS07.class, + setAttributeNS09.class, + setAttributeNodeNS01.class, + //Test makes no sense w/o ER + // setAttributeNodeNS02.class, + setAttributeNodeNS03.class, + setAttributeNodeNS04.class, + setAttributeNodeNS05.class, + setNamedItemNS01.class, + setNamedItemNS02.class, + setNamedItemNS03.class, + //Test makes no sense w/o ER + // setNamedItemNS04.class, + setNamedItemNS05.class, + // systemId01.class, +}) +public class alltests { + /** + * Gets URI that identifies the test suite + * @return uri identifier of test suite + */ + public String getTargetURI() { + return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/alltests"; + } +} diff --git a/src/test/java/dom/detailed/w3c/ibmtests.java b/src/test/java/dom/detailed/w3c/ibmtests.java new file mode 100755 index 0000000..46cb7cb --- /dev/null +++ b/src/test/java/dom/detailed/w3c/ibmtests.java @@ -0,0 +1,180 @@ + +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* +This Java source file was generated by test-to-java.xsl +and is a derived work from the source document. +The source document contained the following notice: + + +Copyright (c) 2001 World Wide Web Consortium, +(Massachusetts Institute of Technology, Institut National de +Recherche en Informatique et en Automatique, Keio University). All +Rights Reserved. This program is distributed under the W3C's Software +Intellectual Property License. This program is distributed in the +hope that it will be useful, but WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. +See W3C License http://www.w3.org/Consortium/Legal/ for more details. + +*/ + +//package org.w3c.domts.level2.core; +package dom.detailed.w3c; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.w3c.domts.level2.core.*; + + +/** +* Test suite +* @author W3C DOM Test Working Group +**/ +@RunWith(Suite.class) +@Suite.SuiteClasses({ + // attrgetownerelement01.class, + attrgetownerelement02.class, + attrgetownerelement03.class, + // attrgetownerelement04.class, + attrgetownerelement05.class, + documentcreateattributeNS01.class, + documentcreateattributeNS02.class, + documentcreateattributeNS03.class, + documentcreateattributeNS04.class, + documentcreateattributeNS05.class, + documentcreateattributeNS06.class, + documentcreateattributeNS07.class, + documentcreateelementNS01.class, + documentcreateelementNS02.class, + documentcreateelementNS05.class, + documentcreateelementNS06.class, + domimplementationcreatedocument03.class, + domimplementationcreatedocument04.class, + domimplementationcreatedocument05.class, + domimplementationcreatedocument07.class, + domimplementationcreatedocumenttype02.class, + domimplementationcreatedocumenttype04.class, + domimplementationhasfeature01.class, + domimplementationhasfeature02.class, + // documentgetelementbyid01.class, + documentgetelementsbytagnameNS01.class, + documentgetelementsbytagnameNS02.class, + documentgetelementsbytagnameNS03.class, + documentgetelementsbytagnameNS04.class, + documentgetelementsbytagnameNS05.class, + documentimportnode01.class, + // documentimportnode02.class, + documentimportnode03.class, + // documentimportnode04.class, + documentimportnode05.class, + documentimportnode06.class, + // documentimportnode07.class, + documentimportnode08.class, + documentimportnode09.class, + // documentimportnode10.class, + documentimportnode11.class, + documentimportnode12.class, + documentimportnode13.class, + documentimportnode14.class, + documentimportnode15.class, + documentimportnode17.class, + documentimportnode18.class, + // documentimportnode19.class, + // documentimportnode20.class, + // documentimportnode21.class, + // documentimportnode22.class, + // documenttypeinternalSubset01.class, + // documenttypepublicid01.class, + // documenttypesystemid01.class, + elementgetattributens02.class, + elementgetattributenodens01.class, + elementgetattributenodens02.class, + elementgetattributenodens03.class, + elementgetelementsbytagnamens02.class, + elementgetelementsbytagnamens04.class, + elementgetelementsbytagnamens05.class, + elementhasattribute01.class, + elementhasattribute02.class, + elementhasattribute03.class, + elementhasattribute04.class, + elementhasattributens01.class, + elementhasattributens02.class, + elementhasattributens03.class, + elementremoveattributens01.class, + elementsetattributens01.class, + elementsetattributens02.class, + elementsetattributens03.class, + elementsetattributens04.class, + elementsetattributens05.class, + elementsetattributens08.class, + elementsetattributenodens01.class, + elementsetattributenodens02.class, + elementsetattributenodens03.class, + elementsetattributenodens04.class, + elementsetattributenodens05.class, + elementsetattributenodens06.class, + namednodemapgetnameditemns01.class, + namednodemapgetnameditemns02.class, + namednodemapgetnameditemns03.class, + namednodemapgetnameditemns04.class, + namednodemapgetnameditemns05.class, + namednodemapgetnameditemns06.class, + namednodemapsetnameditemns01.class, + namednodemapsetnameditemns02.class, + namednodemapsetnameditemns03.class, + namednodemapsetnameditemns04.class, + namednodemapsetnameditemns05.class, + namednodemapsetnameditemns06.class, + namednodemapsetnameditemns07.class, + namednodemapsetnameditemns08.class, + namednodemapsetnameditemns09.class, + namednodemapsetnameditemns10.class, + namednodemapremovenameditemns01.class, + namednodemapremovenameditemns02.class, + namednodemapremovenameditemns03.class, + namednodemapremovenameditemns04.class, + namednodemapremovenameditemns05.class, + namednodemapremovenameditemns06.class, + namednodemapremovenameditemns07.class, + namednodemapremovenameditemns08.class, + namednodemapremovenameditemns09.class, + nodegetlocalname03.class, + nodegetnamespaceuri03.class, + nodegetownerdocument01.class, + nodegetownerdocument02.class, + nodegetprefix03.class, + nodesetprefix01.class, + nodesetprefix02.class, + nodesetprefix03.class, + nodesetprefix04.class, + nodesetprefix05.class, + nodesetprefix06.class, + nodesetprefix07.class, + nodesetprefix08.class, + nodesetprefix09.class, + nodehasattributes01.class, + nodehasattributes02.class, + nodehasattributes03.class, + nodehasattributes04.class, + nodeissupported01.class, + nodeissupported02.class, + nodeissupported03.class, + nodeissupported04.class, + nodeissupported05.class +}) +public class ibmtests { +} diff --git a/test/src/drt/drtcases/BindingTests.java b/src/test/java/drt/drtcases/BindingTests.java similarity index 100% rename from test/src/drt/drtcases/BindingTests.java rename to src/test/java/drt/drtcases/BindingTests.java diff --git a/test/src/drt/drtcases/MarshalTests.java b/src/test/java/drt/drtcases/MarshalTests.java similarity index 99% rename from test/src/drt/drtcases/MarshalTests.java rename to src/test/java/drt/drtcases/MarshalTests.java index b1336f1..3ddcc14 100644 --- a/test/src/drt/drtcases/MarshalTests.java +++ b/src/test/java/drt/drtcases/MarshalTests.java @@ -1580,7 +1580,7 @@ private static void dumpReader(final XMLStreamReader reader, boolean verbose) } } - public void testByNameBeanUnmarshal()StreamInstanceValidator + public void testByNameBeanUnmarshal() throws Exception { BindingContext bindingContext = getBindingContext(getBindingConfigDocument()); diff --git a/test/src/drt/drtcases/TestEnv.java b/src/test/java/drt/drtcases/TestEnv.java similarity index 100% rename from test/src/drt/drtcases/TestEnv.java rename to src/test/java/drt/drtcases/TestEnv.java diff --git a/test/src/misc/checkin/CharUtilTests.java b/src/test/java/misc/checkin/CharUtilTests.java similarity index 85% rename from test/src/misc/checkin/CharUtilTests.java rename to src/test/java/misc/checkin/CharUtilTests.java index 1f97834..66b865b 100644 --- a/test/src/misc/checkin/CharUtilTests.java +++ b/src/test/java/misc/checkin/CharUtilTests.java @@ -15,31 +15,18 @@ package misc.checkin; +import org.apache.xmlbeans.impl.store.CharUtil; +import org.junit.Test; + import java.util.ArrayList; import java.util.Random; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.xmlbeans.impl.store.CharUtil; -import org.apache.xmlbeans.impl.store.CharUtil.CharJoin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -public class CharUtilTests extends TestCase +public class CharUtilTests { - public CharUtilTests ( String name ) - { - super( name ); - } - - public static Test suite ( ) - { - return new TestSuite( CharUtilTests.class ); - } - - private static class Triple - { + private static class Triple { Triple ( Object src, int off, int cch ) { @@ -66,7 +53,7 @@ private char randomChar ( ) private String randomString ( ) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for ( int i = rnd( 128 ) ; i >= 0 ; i-- ) sb.append( randomChar() ); @@ -177,6 +164,7 @@ public void remove ( int i, int off, int cch ) ArrayList _strings = new ArrayList(); } + @Test public void testCharUtil ( ) throws Exception { RealCharUtil real = new RealCharUtil(); @@ -198,13 +186,13 @@ public void testCharUtil ( ) throws Exception case 1 : { - Assert.assertTrue( real.numTexts() == fake.numTexts() ); + assertEquals(real.numTexts(), fake.numTexts()); if (real.numTexts() > 0) { int j = rnd( real.numTexts() ); - Assert.assertTrue( real.getText( j ).equals( fake.getText( j ) ) ); + assertEquals(real.getText(j), fake.getText(j)); } } @@ -218,9 +206,9 @@ public void testCharUtil ( ) throws Exception real.insert( i, j, off ); fake.insert( i, j, off ); - - Assert.assertTrue( real.getText( i ).equals( fake.getText( i ) ) ); - Assert.assertTrue( real.getText( j ).equals( fake.getText( j ) ) ); + + assertEquals(real.getText(i), fake.getText(i)); + assertEquals(real.getText(j), fake.getText(j)); } } case 3 : @@ -232,8 +220,8 @@ public void testCharUtil ( ) throws Exception real.remove( i, off, cch ); fake.remove( i, off, cch ); - - Assert.assertTrue( real.getText( i ).equals( fake.getText( i ) ) ); + + assertEquals(real.getText(i), fake.getText(i)); } } } @@ -245,4 +233,11 @@ private int rnd ( int n ) } private Random _rnd = new Random( 0 ); + + @Test + public void testThreadLocal() { + assertNotNull("Should always get a CharUtil from ThreadLocals", CharUtil.getThreadLocalCharUtil()); + CharUtil.clearThreadLocals(); + assertNotNull("Should always get a CharUtil from ThreadLocals", CharUtil.getThreadLocalCharUtil()); + } } \ No newline at end of file diff --git a/test/src/misc/checkin/ErrorCodeTest.java b/src/test/java/misc/checkin/ErrorCodeTest.java similarity index 85% rename from test/src/misc/checkin/ErrorCodeTest.java rename to src/test/java/misc/checkin/ErrorCodeTest.java index 5bfd8e4..e7f51f1 100644 --- a/test/src/misc/checkin/ErrorCodeTest.java +++ b/src/test/java/misc/checkin/ErrorCodeTest.java @@ -16,38 +16,17 @@ package misc.checkin; import org.apache.xmlbeans.XmlErrorCodes; - -import junit.framework.Assert; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Test; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.util.Map; -import java.util.Set; +import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Properties; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ArrayList; -import java.io.FileInputStream; -import java.io.InputStream; - -public class ErrorCodeTest extends TestCase -{ - - public ErrorCodeTest(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(ErrorCodeTest.class); - } +import java.util.Set; +public class ErrorCodeTest { + @Test public void testCodes() throws Exception { // throws Exception if a duplicate error code value is found. @@ -70,9 +49,8 @@ public void testCodes() throws Exception } // each error code value should have a message key - Iterator iter = codes.iterator(); - while (iter.hasNext()) { - String code = (String) iter.next(); + for (Object code1 : codes) { + String code = (String) code1; if (messages.get(code) == null) throw new Exception("missing message.properties key for error code: " + code); } diff --git a/src/test/java/misc/checkin/HexBinTest.java b/src/test/java/misc/checkin/HexBinTest.java new file mode 100644 index 0000000..c41ccef --- /dev/null +++ b/src/test/java/misc/checkin/HexBinTest.java @@ -0,0 +1,56 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.checkin; + +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.HexBinaryValue; +import org.apache.xmlbeans.impl.util.HexBin; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; + +public class HexBinTest { + + @Test + public void testSurrogate() throws Exception { + String exp = "ABC\ud83c\udf09123"; + String enc = HexBin.encode(exp); + String dec = HexBin.decode(enc); + assertEquals(exp, dec); + } + + @Test + public void knownValue() throws XPathException { + // I've looked for comparison values but the following definition seems to be wrong, + // because Saxon also returns the same encoded value + // see http://books.xmlschemata.org/relaxng/ch19-77143.html + // "Relax NG" by Eric van der Vlist + + String in = "a"; + + String exp = "3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e61"; + String enc = HexBin.encode(in); + + HexBinaryValue val = new HexBinaryValue(enc); + String saxIn = new String(val.getBinaryValue(), StandardCharsets.UTF_8); + + assertEquals(exp, enc.toLowerCase(Locale.ROOT)); + assertEquals(in, saxIn); + } +} diff --git a/test/src/misc/checkin/RichParserTests.java b/src/test/java/misc/checkin/RichParserTests.java similarity index 79% rename from test/src/misc/checkin/RichParserTests.java rename to src/test/java/misc/checkin/RichParserTests.java index 29e4abc..1c50af6 100755 --- a/test/src/misc/checkin/RichParserTests.java +++ b/src/test/java/misc/checkin/RichParserTests.java @@ -15,19 +15,11 @@ package misc.checkin; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDateBuilder; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.GDurationBuilder; -import org.apache.xmlbeans.XmlCalendar; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.richParser.XMLStreamReaderExt; import org.apache.xmlbeans.impl.richParser.XMLStreamReaderExtImpl; +import org.junit.Test; +import tools.util.JarUtil; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; @@ -43,20 +35,15 @@ import java.util.Calendar; import java.util.Date; - -import tools.util.*; - +import static org.junit.Assert.assertEquals; /** * Author: Cezar Andrei (cezar.andrei at bea.com) * Date: Nov 19, 2003 */ -public class RichParserTests extends TestCase -{ - public RichParserTests(String name) { super(name); } - public static Test suite() { return new TestSuite(RichParserTests.class); } - +public class RichParserTests { + @Test public void testPrimitiveTypes() throws Exception { XMLStreamReader xsr = XmlObject.Factory.parse(new FileInputStream( @@ -112,75 +99,73 @@ private static void processText(String ln, XMLStreamReaderExt xs, int attIndex) if ("int".equals(ln)) { int v = attIndex>-1 ? xs.getAttributeIntValue(attIndex) : xs.getIntValue(); - Assert.assertTrue("int " + v, ints[intsIdx++]==v); + assertEquals("int " + v, ints[intsIdx++], v); } else if ("boolean".equals(ln)) { boolean v = attIndex>-1 ? xs.getAttributeBooleanValue(attIndex) : xs.getBooleanValue(); - Assert.assertTrue("boolean " + v, bools[boolsIdx++]==v); + assertEquals("boolean " + v, bools[boolsIdx++], v); } else if ("short".equals(ln)) { short v = attIndex>-1 ? xs.getAttributeShortValue(attIndex) : xs.getShortValue(); - Assert.assertTrue("short " + v, shorts[shortsIdx++]==v); + assertEquals("short " + v, shorts[shortsIdx++], v); } else if ("byte".equals(ln)) { byte v = attIndex>-1 ? xs.getAttributeByteValue(attIndex) : xs.getByteValue(); - Assert.assertTrue("byte " + v, bytes[bytesIdx++]==v); + assertEquals("byte " + v, bytes[bytesIdx++], v); } else if ("long".equals(ln)) { long v = attIndex>-1 ? xs.getAttributeLongValue(attIndex) : xs.getLongValue(); - Assert.assertTrue("long " + v, longs[longsIdx++]==v); + assertEquals("long " + v, longs[longsIdx++], v); } else if ("double".equals(ln)) { double v = attIndex>-1 ? xs.getAttributeDoubleValue(attIndex) : xs.getDoubleValue(); - Assert.assertTrue("double expected: " + doubles[doublesIdx] + " actual: " + v, - new Double(doubles[doublesIdx++]).equals(new Double(v))); + assertEquals("double expected: " + doubles[doublesIdx] + " actual: " + v, new Double(doubles[doublesIdx++]), new Double(v)); // makeing new Doubles because Double.NaN==Double.NaN is false; } else if ("float".equals(ln)) { float v = attIndex>-1 ? xs.getAttributeFloatValue(attIndex) : xs.getFloatValue(); - Assert.assertTrue("float expected: " + floats[floatsIdx] + " actual: " + v, - new Float(floats[floatsIdx++]).equals( new Float(v))); + assertEquals("float expected: " + floats[floatsIdx] + " actual: " + v, new Float(floats[floatsIdx++]), new Float(v)); // makeing new Floats because Float.NaN==Float.NaN is false; } else if ("decimal".equals(ln)) { BigDecimal v = attIndex>-1 ? xs.getAttributeBigDecimalValue(attIndex) : xs.getBigDecimalValue(); - Assert.assertTrue("BigDecimal " + v, new BigDecimal("1.001").equals(v)); + assertEquals("BigDecimal " + v, new BigDecimal("1.001"), v); } else if ("integer".equals(ln)) { BigInteger v = attIndex>-1 ? xs.getAttributeBigIntegerValue(attIndex) : xs.getBigIntegerValue(); - Assert.assertTrue("BigInteger " + v, new BigInteger("1000000000").equals(v)); + assertEquals("BigInteger " + v, new BigInteger("1000000000"), v); } else if ("base64Binary".equals(ln)) { InputStream v = attIndex>-1 ? xs.getAttributeBase64Value(attIndex) : xs.getBase64Value(); String a = readIS(v); - Assert.assertTrue("Base64Binary " + a, "base64Binary".equals(a)); + assertEquals("Base64Binary " + a, "base64Binary", a); } else if ("hexBinary".equals(ln)) { InputStream v = attIndex>-1 ? xs.getAttributeHexBinaryValue(attIndex) : xs.getHexBinaryValue(); String a = readIS(v); - Assert.assertTrue("HexBinary " + a, "hexBinary".equals(a)); + assertEquals("HexBinary " + a, "hexBinary", a); } else if ("date".equals(ln)) { Calendar v = attIndex>-1 ? xs.getAttributeCalendarValue(attIndex) : xs.getCalendarValue(); Calendar c = new XmlCalendar( "2001-11-26T21:32:52Z" ); - Assert.assertTrue("Calendar expected:" + c.getTimeInMillis() + " actual:" + v.getTimeInMillis(), c.getTimeInMillis()==v.getTimeInMillis()); + assertEquals("Calendar expected:" + c.getTimeInMillis() + " actual:" + v.getTimeInMillis(), c.getTimeInMillis(), v.getTimeInMillis()); } else if ("dateTime".equals(ln)) { Date v = attIndex>-1 ? xs.getAttributeDateValue(attIndex) : xs.getDateValue(); Date d = new XmlCalendar("2001-11-26T21:32:52").getTime(); - Assert.assertTrue("Date expected:" + d + " actual:" + v, d.equals(v)); + assertEquals("Date expected:" + d + " actual:" + v, d, v); } else if ("gYearMonth".equals(ln)) { @@ -188,7 +173,7 @@ else if ("gYearMonth".equals(ln)) GDateBuilder gdb = new GDateBuilder(); gdb.setYear(2001); gdb.setMonth(11); - Assert.assertTrue("GDate expected:" + gdb + " actual:" + v, gdb.toGDate().equals(v)); + assertEquals("GDate expected:" + gdb + " actual:" + v, gdb.toGDate(), v); } else if ("duration".equals(ln)) { @@ -196,12 +181,12 @@ else if ("duration".equals(ln)) GDurationBuilder gdb = new GDurationBuilder(); gdb.setSign(-1); gdb.setSecond(7); - Assert.assertTrue("GDuration expected:" + gdb + " actual:" + v, gdb.toGDuration().equals(v)); + assertEquals("GDuration expected:" + gdb + " actual:" + v, gdb.toGDuration(), v); } else if ("QName".equals(ln)) { QName v = attIndex>-1 ? xs.getAttributeQNameValue(attIndex) : xs.getQNameValue(); - Assert.assertTrue("QName expected:" + qnames[qnamesIdx] + " actual:" + v, qnames[qnamesIdx++].equals(v)); + assertEquals("QName expected:" + qnames[qnamesIdx] + " actual:" + v, qnames[qnamesIdx++], v); } else if ("string".equals(ln)) { @@ -209,7 +194,7 @@ else if ("string".equals(ln)) String s = strings[stringsIdx++]; - Assert.assertTrue("String expected:\n'" + s + "' actual:\n'" + v + "'", s.equals(v)); + assertEquals("String expected:\n'" + s + "' actual:\n'" + v + "'", s, v); } } diff --git a/test/src/misc/checkin/RuntimeSchemaLoaderTest.java b/src/test/java/misc/checkin/RuntimeSchemaLoaderTest.java similarity index 82% rename from test/src/misc/checkin/RuntimeSchemaLoaderTest.java rename to src/test/java/misc/checkin/RuntimeSchemaLoaderTest.java index d053a8f..0916696 100755 --- a/test/src/misc/checkin/RuntimeSchemaLoaderTest.java +++ b/src/test/java/misc/checkin/RuntimeSchemaLoaderTest.java @@ -15,36 +15,24 @@ package misc.checkin; +import org.apache.xmlbeans.SchemaTypeLoader; import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.SchemaTypeLoader; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; +import org.junit.Assert; +import org.junit.Test; +import tools.util.JarUtil; import javax.xml.namespace.QName; - import java.io.File; -import junit.framework.Assert; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; +public class RuntimeSchemaLoaderTest { -import tools.util.*; - - -public class RuntimeSchemaLoaderTest extends TestCase { - public RuntimeSchemaLoaderTest(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(RuntimeSchemaLoaderTest.class); - } - + @Test public void testDynamicLoad() throws Throwable { File inputfile1 = JarUtil .getResourceFromJarasFile("xbean/misc/dyntest.xsd"); @@ -53,16 +41,17 @@ public void testDynamicLoad() throws Throwable { XmlObject result = loader.parse( JarUtil.getResourceFromJarasFile("xbean/misc/dyntest.xml"), null, null); - Assert.assertEquals( + assertEquals( "D=wrappedinstance@http://openuri.org/test/dyntest", result.schemaType().toString()); - Assert.assertEquals( + assertEquals( loader.findDocumentType( new QName("http://openuri.org/test/dyntest", "wrappedinstance")), result.schemaType()); } + @Test public void testDynamicLoad2() throws Throwable { File inputfile1 = JarUtil .getResourceFromJarasFile("xbean/misc/dyntest2.xsd"); @@ -71,10 +60,10 @@ public void testDynamicLoad2() throws Throwable { XmlObject result = loader.parse( JarUtil.getResourceFromJarasFile("xbean/misc/dyntest2.xml"), null, null); - Assert.assertEquals( + assertEquals( "D=wrappedwildcard@http://openuri.org/test/dyntest", result.schemaType().toString()); - Assert.assertEquals( + assertEquals( loader.findDocumentType( new QName("http://openuri.org/test/dyntest", "wrappedwildcard")), @@ -82,20 +71,20 @@ public void testDynamicLoad2() throws Throwable { XmlCursor cur = result.newCursor(); Assert.assertTrue("Should have a root element", cur.toFirstChild()); result = cur.getObject(); - Assert.assertEquals( + assertEquals( "E=wrappedwildcard|D=wrappedwildcard@http://openuri.org/test/dyntest", result.schemaType().toString()); - Assert.assertEquals( + assertEquals( loader.findElement( new QName("http://openuri.org/test/dyntest", "wrappedwildcard")) .getType(), result.schemaType()); Assert.assertTrue("Should have a first child", cur.toFirstChild()); - Assert.assertEquals( + assertEquals( new QName("http://www.w3.org/2001/XMLSchema", "schema"), cur.getName()); XmlObject obj = cur.getObject(); - Assert.assertEquals(Schema.type, obj.schemaType()); + assertEquals(Schema.type, obj.schemaType()); } } diff --git a/test/src/misc/checkin/ThreadingTest.java b/src/test/java/misc/checkin/ThreadingTest.java similarity index 84% rename from test/src/misc/checkin/ThreadingTest.java rename to src/test/java/misc/checkin/ThreadingTest.java index c444693..61774d3 100644 --- a/test/src/misc/checkin/ThreadingTest.java +++ b/src/test/java/misc/checkin/ThreadingTest.java @@ -15,29 +15,20 @@ package misc.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Assert; import org.apache.xmlbeans.SchemaTypeLoader; import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; +import org.junit.Assert; +import org.junit.Test; +import tools.util.JarUtil; import javax.xml.namespace.QName; - -import tools.util.*; - import java.io.File; -public class ThreadingTest extends TestCase { - public ThreadingTest(String name) { - super(name); - } +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; - public static Test suite() { - return new TestSuite(ThreadingTest.class); - } +public class ThreadingTest { public static final int THREAD_COUNT = 4; public static final int ITERATION_COUNT = 1; @@ -78,6 +69,7 @@ public void run() { } } + @Test public void testThreadedCompilation() throws Throwable { CompilationThread[] threads = new CompilationThread[THREAD_COUNT]; for (int i = 0; i < threads.length; i++) { @@ -93,8 +85,8 @@ public void testThreadedCompilation() throws Throwable { } for (int i = 0; i < threads.length; i++) { - Assert.assertNull(threads[i].getException()); - Assert.assertTrue("Thread " + i + " didn't succeed", + assertNull(threads[i].getException()); + assertTrue("Thread " + i + " didn't succeed", threads[i].getResult()); } } diff --git a/src/test/java/misc/checkin/VersionTest.java b/src/test/java/misc/checkin/VersionTest.java new file mode 100644 index 0000000..502a23a --- /dev/null +++ b/src/test/java/misc/checkin/VersionTest.java @@ -0,0 +1,33 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.checkin; + +import org.apache.xmlbeans.XmlBeans; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; + +public class VersionTest { + + + // Test the getVersion API + @Test + public void testXBeansVersion() { + String version = XmlBeans.getVersion(); + assertNotNull(version); + } + +} diff --git a/src/test/java/misc/checkin/XMLBEANS412Test.java b/src/test/java/misc/checkin/XMLBEANS412Test.java new file mode 100644 index 0000000..355f875 --- /dev/null +++ b/src/test/java/misc/checkin/XMLBEANS412Test.java @@ -0,0 +1,104 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.checkin; + +import org.apache.xmlbeans.impl.regex.ParseException; +import org.apache.xmlbeans.impl.regex.RegularExpression; +import org.junit.Test; + +import java.util.StringTokenizer; + +import static org.junit.Assert.fail; + +public class XMLBEANS412Test { + static String PassedPosCharGroups = "-,\\-,--,\\--,---,\\---,--\\-,\\--\\-,-\\--,\\-\\--,-a,\\-a,a-,"+ + "a\\-,a-b,a\\-b,a\\--,-a-z,\\-a-z,a-z-,a-z\\-,a-z\\-0-9,a\\-z-,a\\-z\\-,a\\-z\\-0-9,"+ + "-0-9,0-9-,0-9aaa,0-9a-,a-z\\--/,A-F0-9.+-,-A-F0-9.+,A-F0-9.+\\-,\\-A-F0-9.+"; + + static String FailedPosCharGroups = "[a--],[a-z-0-9],[a\\-z-0-9],[0-9--],[0-9a--],[0-9-a],[0-9-a-z]"; + static String MiscPassedPatterns = "([\\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(([a-zA-Z0-9_-])*\\.([a-zA-Z0-9_-])+)+"; + + @Test + public void testPassedPosCharGroupPatterns() + { + StringTokenizer tok = new StringTokenizer(PassedPosCharGroups,","); + while (tok.hasMoreElements()) { + String pattern = "[" + tok.nextToken() + "]"; + try { + new RegularExpression(pattern, "X"); + } catch (ParseException e) { + fail("Pattern " + pattern + " failed due to " + e.getMessage()); + } + } + } + + @Test + public void testNegatedPassedPosCharGroupPatterns() + { + StringTokenizer tok = new StringTokenizer(PassedPosCharGroups,","); + while (tok.hasMoreElements()) { + String pattern = "[^" + tok.nextToken() + "]"; + try { + new RegularExpression(pattern, "X"); + } catch (ParseException e) { + fail("Pattern " + pattern + " failed due to " + e.getMessage()); + } + } + } + + @Test + public void testFailedPosCharGroupPatterns() + { + StringTokenizer tok = new StringTokenizer(FailedPosCharGroups,","); + while (tok.hasMoreElements()) { + String pattern = "[" + tok.nextToken() + "]"; + try { + new RegularExpression(pattern,"X"); + } catch (ParseException e) { + continue; + } + fail("Pattern " + pattern + " did not fail."); + } + } + + @Test + public void testNegatedFailedPosCharGroupPatterns() + { + StringTokenizer tok = new StringTokenizer(FailedPosCharGroups,","); + while (tok.hasMoreElements()) { + String pattern = "[^" + tok.nextToken() + "]"; + try { + new RegularExpression(pattern,"X"); + } catch (ParseException e) { + continue; + } + fail("Pattern " + pattern + " did not fail."); + } + } + + @Test + public void testMiscPassedPatterns() { + StringTokenizer tok = new StringTokenizer(MiscPassedPatterns,","); + while (tok.hasMoreElements()) { + String pattern = tok.nextToken(); + try { + new RegularExpression(pattern, "X"); + } catch (ParseException e) { + fail("Pattern " + pattern + " failed due to " + e.getMessage()); + } + } + } +} diff --git a/src/test/java/misc/checkin/XmlDocumentPropertiesTest.java b/src/test/java/misc/checkin/XmlDocumentPropertiesTest.java new file mode 100644 index 0000000..1aa370c --- /dev/null +++ b/src/test/java/misc/checkin/XmlDocumentPropertiesTest.java @@ -0,0 +1,54 @@ +/* Copyright 2019 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.checkin; + +import java.util.HashMap; + +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlDocumentProperties; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class XmlDocumentPropertiesTest { + + @Test + public void testSetStandalone() { + XmlDocumentProperties props = new XmlDocumentProperties() { + HashMap props = new HashMap<>(); + @Override + public Object put ( Object key, Object value ) { + return props.put(key, value); + } + + @Override + public Object get ( Object key ) { + return props.get(key); + } + + @Override + public Object remove ( Object key ) { + return props.remove(key); + } + }; + assertFalse(props.getStandalone()); + props.setStandalone(true); + assertTrue(props.getStandalone()); + props.setStandalone(false); + assertFalse(props.getStandalone()); + } + +} diff --git a/test/src/misc/common/JiraTestBase.java b/src/test/java/misc/common/JiraTestBase.java similarity index 92% rename from test/src/misc/common/JiraTestBase.java rename to src/test/java/misc/common/JiraTestBase.java index eab4556..536bdd8 100644 --- a/test/src/misc/common/JiraTestBase.java +++ b/src/test/java/misc/common/JiraTestBase.java @@ -15,9 +15,10 @@ */ package misc.common; -import java.io.File; import common.Common; +import java.io.File; + /** * */ @@ -34,12 +35,9 @@ public class JiraTestBase extends Common public static File schemaCompSrcDir = null; public static File schemaCompClassesDir = null; - public static final int THREAD_COUNT = 150; public static final int ITERATION_COUNT = 2; - public JiraTestBase(String name){ - super(name); - + public JiraTestBase(){ // directories for the SchemaCompiler.Parameter class members if (schemaCompSrcDir == null) { schemaCompSrcDir = new File(schemaCompOutputDirPath + P + "src"); diff --git a/test/src/misc/common/ParsersBase.java b/src/test/java/misc/common/ParsersBase.java similarity index 96% rename from test/src/misc/common/ParsersBase.java rename to src/test/java/misc/common/ParsersBase.java index 96bd523..4fd7d39 100644 --- a/test/src/misc/common/ParsersBase.java +++ b/src/test/java/misc/common/ParsersBase.java @@ -16,7 +16,6 @@ package misc.common; -import junit.framework.TestCase; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -30,8 +29,10 @@ import java.io.IOException; import java.io.StringReader; +import static org.junit.Assert.fail; -public class ParsersBase extends TestCase { + +public class ParsersBase { private static final String outputEncoding = "UTF-8"; diff --git a/test/src/misc/detailed/CharEncodingTest.java b/src/test/java/misc/detailed/CharEncodingTest.java similarity index 95% rename from test/src/misc/detailed/CharEncodingTest.java rename to src/test/java/misc/detailed/CharEncodingTest.java index 048e6d4..49433c5 100644 --- a/test/src/misc/detailed/CharEncodingTest.java +++ b/src/test/java/misc/detailed/CharEncodingTest.java @@ -17,18 +17,22 @@ package misc.detailed; import misc.common.ParsersBase; +import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; +import org.junit.Test; -import java.util.List; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.fail; public class CharEncodingTest extends ParsersBase { // Piccolo fails when trying to parse I18N chars in some QNames // String 2 fails with piccolo and hence with xbeans + @Test public void testCharEncodingI18N() { String I18N_test_string1 = ""; String I18N_test_string2 = ""; @@ -48,6 +52,7 @@ public void testCharEncodingI18N() { // Piccolo has an issue with handling external identifiers when the value is PUBLIC // refer : http://cafeconleche.org/SAXTest/results/com.bluecast.xml.Piccolo/xmltest/valid/not-sa/009.xml.html // results for the SAX conformance suite. This has been fixed in newer versions of Piccolo + @Test public void testExternalPublicIdentifier() { // repro using piccolo and other parsers via JAXP API String netPubEntity = ""; static final String end2 = ""; - public CharEscapeTest(String name) - { - super(name); - } - + @Test public void testAddMapping() throws Exception { XmlOptionCharEscapeMap charEsc = new XmlOptionCharEscapeMap(); @@ -96,6 +93,7 @@ public void testAddMapping() throws Exception } } + @Test public void testAddMappings() throws Exception { XmlOptionCharEscapeMap charEsc = new XmlOptionCharEscapeMap(); @@ -140,6 +138,7 @@ public void testAddMappings() throws Exception assertEquals("Z", charEsc.getEscapedString('Z')); } + @Test public void testEscape1() throws Exception { File f = new File(inputFile); @@ -156,7 +155,7 @@ public void testEscape1() throws Exception " Character data may not contain the three-character sequence ]]> with the > unescaped.\n" + " In particular, character data in a CDATA section may not contain the three-character sequence ]]&gt; with the > unescaped.\n" + end; - assertEquals(exp1, doc.xmlText()); + assertEquals(exp1, doc.xmlText().replaceFirst("(?s)","")); XmlOptionCharEscapeMap charEsc = new XmlOptionCharEscapeMap(); charEsc.addMapping('>', XmlOptionCharEscapeMap.PREDEF_ENTITY); @@ -173,7 +172,7 @@ public void testEscape1() throws Exception " Character data may not contain the three-character sequence ]]> with the > unescaped.\n" + " In particular, character data in a CDATA section may not contain the three-character sequence ]]&gt; with the > unescaped.\n" + end; - assertEquals(exp2, doc.xmlText(opts)); + assertEquals(exp2, doc.xmlText(opts).replaceFirst("(?s)","")); // escape block of chars as hexadecimal charEsc.addMappings('A', 'D', XmlOptionCharEscapeMap.HEXADECIMAL); @@ -187,7 +186,7 @@ public void testEscape1() throws Exception " Character data may not contain the three-character sequence ]]> with the > unescaped.\n" + " In particular, character data in a CDATA section may not contain the three-character sequence ]]&gt; with the > unescaped.\n" + end; - assertEquals(exp3, doc.xmlText(opts)); + assertEquals(exp3, doc.xmlText(opts).replaceFirst("(?s)","")); /* File od = new File(outputDir); od.mkdir(); @@ -198,6 +197,7 @@ public void testEscape1() throws Exception */ } + @Test public void testEscape2() throws Exception { TestListDocument doc = TestListDocument.Factory.newInstance(); @@ -227,6 +227,7 @@ public void testEscape2() throws Exception assertEquals(exp, doc.xmlText(opts)); } + @Test public void testEscapeAttribute() throws Exception { File f = new File(inputFile2); @@ -241,7 +242,7 @@ public void testEscapeAttribute() throws Exception " \n" + " \n" + end2; - assertEquals(exp1, doc.xmlText()); + assertEquals(exp1, doc.xmlText().replaceFirst("(?s)","")); XmlOptionCharEscapeMap charEsc = new XmlOptionCharEscapeMap(); charEsc.addMapping('>', XmlOptionCharEscapeMap.PREDEF_ENTITY); @@ -256,7 +257,7 @@ public void testEscapeAttribute() throws Exception " \n" + " \n" + end2; - assertEquals(exp2, doc.xmlText(opts)); + assertEquals(exp2, doc.xmlText(opts).replaceFirst("(?s)","")); // escape block of chars as hexadecimal charEsc.addMappings('A', 'D', XmlOptionCharEscapeMap.HEXADECIMAL); @@ -268,17 +269,6 @@ public void testEscapeAttribute() throws Exception " \n" + " \n" + end2; - assertEquals(exp3, doc.xmlText(opts)); - } - - public static Test suite() - { - TestSuite suite = new TestSuite(CharEscapeTest.class); - return suite; - } - - public static void main(String args[]) - { - junit.textui.TestRunner.run(suite()); + assertEquals(exp3, doc.xmlText(opts).replaceFirst("(?s)","")); } } diff --git a/test/src/misc/detailed/ClassLoadingTest.java b/src/test/java/misc/detailed/ClassLoadingTest.java similarity index 92% rename from test/src/misc/detailed/ClassLoadingTest.java rename to src/test/java/misc/detailed/ClassLoadingTest.java index 447809d..d77a839 100644 --- a/test/src/misc/detailed/ClassLoadingTest.java +++ b/src/test/java/misc/detailed/ClassLoadingTest.java @@ -15,10 +15,9 @@ package misc.detailed; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; import org.apache.xmlbeans.*; +import org.junit.Ignore; +import org.junit.Test; import java.io.File; import java.util.ArrayList; @@ -27,18 +26,8 @@ import java.net.URL; import java.net.URLClassLoader; - -public class ClassLoadingTest extends TestCase -{ - public ClassLoadingTest(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(ClassLoadingTest.class); - } +@Ignore("needs to be updated to current jars") +public class ClassLoadingTest { public static class CompilationThread extends Thread { @@ -263,7 +252,8 @@ public void testPerson(ClassLoader validateLoader) /** * OOM Error happens around thread 97 with the params listed below */ - public static void testThreadedCompilation() throws Throwable + @Test + public void testThreadedCompilation() throws Throwable { Runtime r = Runtime.getRuntime(); CompilationThread[] threads = new CompilationThread[THREAD_COUNT]; @@ -288,24 +278,5 @@ public static void testThreadedCompilation() throws Throwable // threads[i].getResult()); //} } - - /** - * Call this with something like the following - * D:\xml\xml-xmlbeans\v2\build\test\lib> - * java - * -Xms8M -Xmx16M - * -cp .\testcases.jar;.\testtools.jar;.;..\..\lib\xbean.jar; - * ..\..\lib\jsr173.jar;..\..\lib\xmlpublic.jar; - * ..\..\lib\jsr173_api.jar;..\..\lib\jsr173_ri.jar; - * ..\..\..\external\lib\junit.jar; - * misc.detailed.ClassLoadingTest - * @param args - * @throws Throwable - */ - public static void main(String[] args) throws Throwable - { - testThreadedCompilation(); - throw new Exception("FOO"); - } } diff --git a/test/src/misc/detailed/JiraRegression151_200Test.java b/src/test/java/misc/detailed/JiraRegression151_200Test.java similarity index 90% rename from test/src/misc/detailed/JiraRegression151_200Test.java rename to src/test/java/misc/detailed/JiraRegression151_200Test.java index 46cb159..ff9bffb 100644 --- a/test/src/misc/detailed/JiraRegression151_200Test.java +++ b/src/test/java/misc/detailed/JiraRegression151_200Test.java @@ -16,33 +16,31 @@ package misc.detailed; import misc.common.JiraTestBase; -import org.apache.xmlbeans.XmlOptions; +import net.eads.space.scoexml.test.TestExponentDocument; import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.impl.tool.SchemaCompiler; +import org.junit.Test; +import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.io.File; -import net.eads.space.scoexml.test.TestExponentDocument; -import junit.framework.Assert; +import static org.junit.Assert.*; /** * */ public class JiraRegression151_200Test extends JiraTestBase { - public JiraRegression151_200Test(String name) - { - super(name); - } /** * [XMLBEANS-175] Validation of decimal in exponential representation fails * @throws Exception */ + @Test public void test_jira_xmlbeans175() throws Exception{ TestExponentDocument.TestExponent exponent = TestExponentDocument.TestExponent.Factory.newInstance(); @@ -71,6 +69,7 @@ public void test_jira_xmlbeans175() throws Exception{ /** * [XMLBEANS-179] Saving xml with '&' and '<' characters in attribute values throws an ArrayIndexOutOfBoundsException */ + @Test public void test_jira_xmlbeans179() throws Exception{ String xmlWithIssues = ""; @@ -86,8 +85,8 @@ public void test_jira_xmlbeans179() throws Exception{ /* * [XMLBEANS-184]: NPE when running scomp without nopvr option - * */ + @Test public void test_jira_xmlbeans184() throws Exception { List errors = new ArrayList(); @@ -107,7 +106,7 @@ public void test_jira_xmlbeans184() throws Exception { } if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans184() : Errors found when executing scomp"); + fail("test_jira_xmlbeans184() : Errors found when executing scomp"); } // now compile without the pvr option and NPE is thrown @@ -120,7 +119,7 @@ public void test_jira_xmlbeans184() throws Exception { } if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans184() : Errors found when executing scomp "); + fail("test_jira_xmlbeans184() : Errors found when executing scomp "); } } diff --git a/test/src/misc/detailed/JiraRegression1_50Test.java b/src/test/java/misc/detailed/JiraRegression1_50Test.java similarity index 90% rename from test/src/misc/detailed/JiraRegression1_50Test.java rename to src/test/java/misc/detailed/JiraRegression1_50Test.java index bc3a800..30b3f1e 100644 --- a/test/src/misc/detailed/JiraRegression1_50Test.java +++ b/src/test/java/misc/detailed/JiraRegression1_50Test.java @@ -15,35 +15,29 @@ package misc.detailed; import misc.common.JiraTestBase; - -import java.io.*; -import java.util.*; - import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.tool.SchemaCompiler; import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Ignore; +import org.junit.Test; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; -import junit.framework.Assert; +import xmlbeans48.FeedInfoType; import javax.xml.namespace.QName; +import java.io.*; +import java.util.*; -import xmlbeans48.FeedInfoType; +import static org.junit.Assert.*; -/** - * - */ public class JiraRegression1_50Test extends JiraTestBase { - public JiraRegression1_50Test(String name) { - super(name); - } - /* * [XMLBEANS-2] Problem with XmlError.forObject(String,int,XmlObject) */ + @Test public void test_jira_xmlbeans02() throws Exception { - StringBuffer xmlstringbuf = new StringBuffer(""); + StringBuilder xmlstringbuf = new StringBuilder(""); xmlstringbuf.append(""); xmlstringbuf.append(" Jira02 "); xmlstringbuf.append(""); @@ -67,7 +61,7 @@ public void test_jira_xmlbeans02() throws Exception { } } catch (NullPointerException npe) { - Assert.fail("test_jira_xmlbeans02() : Null Pointer Exception thrown !"); + fail("test_jira_xmlbeans02() : Null Pointer Exception thrown !"); } printOptionErrMsgs(errors); @@ -75,8 +69,8 @@ public void test_jira_xmlbeans02() throws Exception { /* * [XMLBEANS-4] xs:decimal size greater than 18 results in uncompilable java code - * */ + @Test public void test_jira_xmlbeans04() { List errors = new ArrayList(); @@ -88,7 +82,7 @@ public void test_jira_xmlbeans04() { SchemaCompiler.compile(params); if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans04() : Errors found when executing scomp"); + fail("test_jira_xmlbeans04() : Errors found when executing scomp"); } } @@ -96,19 +90,20 @@ public void test_jira_xmlbeans04() { /* * [XMLBEANS-9] Null Pointer Exception when running validate from cmd line - * */ + @Test + @Ignore("no shell tests on junit") public void test_jira_xmlbeans09() throws Exception { // Exec validate script from cmd line - Refer xmlbeans_09.xsd, xmlbeans_09.xml - StringBuffer sb = new StringBuffer(" "); + StringBuilder sb = new StringBuilder(" "); sb.append(System.getProperty("xbean.rootdir") + P + "bin" + P + "validate.cmd "); sb.append(scompTestFilesRoot + "xmlbeans_09.xsd_" + " " + scompTestFilesRoot + "xmlbeans_09.xml"); Process validator_proc = null; try { validator_proc = Runtime.getRuntime().exec(sb.toString()); } catch (NullPointerException npe) { - Assert.fail("test_jira_xmlbeans09() : Null Pointer Exception when running validate for schema"); + fail("test_jira_xmlbeans09() : Null Pointer Exception when running validate for schema"); } System.out.println("cmd:" + sb); @@ -131,9 +126,10 @@ public void test_jira_xmlbeans09() throws Exception { * [XMLBEANS-11]: Calling getUnionMemberTypes() on SchemaType for non-union types results in NullPointerException * status : fixed */ + @Test public void test_jira_xmlbeans11() throws Exception { - StringBuffer xsdAsString = new StringBuffer(""); + StringBuilder xsdAsString = new StringBuilder(""); xsdAsString.append(" \n"); xsdAsString.append(" \n"); @@ -164,15 +160,15 @@ public void test_jira_xmlbeans11() throws Exception { System.out.println("IS UNION TYPE: " + (st[i].getUnionMemberTypes() != null)); } } catch (NullPointerException npe) { - Assert.fail("test_jira_xmlbeans11(): Null Pointer Exception thrown !"); + fail("test_jira_xmlbeans11(): Null Pointer Exception thrown !"); } } /* * [XMLBEANS-14]: newDomNode() throws NullPointerException - * */ + @Test public void test_jira_xmlbeans14() throws Exception { XmlObject xObj = XmlObject.Factory.parse(""); // add element @@ -189,7 +185,7 @@ public void test_jira_xmlbeans14() throws Exception { try { xObj.newDomNode(); } catch (NullPointerException npe) { - Assert.fail("test_jira_xmlbeans14() : Null Pointer Exception when create Dom Node"); + fail("test_jira_xmlbeans14() : Null Pointer Exception when create Dom Node"); } } @@ -200,8 +196,10 @@ public void test_jira_xmlbeans14() throws Exception { * attributes (rather than null) * status : fails with crimson and not with Xerces */ + @Test + @Ignore("still happens with current xerces 2.11") public void test_jira_xmlbeans16() throws Exception { - StringBuffer sb = new StringBuffer(100); + StringBuilder sb = new StringBuilder(100); sb.append("\n"); sb.append(" // */ @@ -68,6 +66,7 @@ public JiraRegression50_100Test(String name) /** * [XMLBEANS-52] Validator loops when schema has certain conditions */ + @Test public void test_jira_XmlBeans52() throws Exception{ //reusing code from method test_jira_XmlBeans48() String correctXml = " \n" + @@ -86,8 +85,8 @@ public void test_jira_XmlBeans52() throws Exception{ /* * [XMLBEANS-54]: problem with default value - * */ + @Test public void test_jira_xmlbeans54() throws Exception { List errors = new ArrayList(); @@ -111,15 +110,15 @@ public void test_jira_xmlbeans54() throws Exception { } if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans54() : Errors found when executing scomp"); + fail("test_jira_xmlbeans54() : Errors found when executing scomp"); } } /** * [XMLBEANS-56] samples issue with easypo schema and config file */ - public void test_jira_XmlBeans56() throws Exception - { + @Test + public void test_jira_XmlBeans56() throws Exception { String xsdConfig = "\n" + @@ -156,8 +155,8 @@ public void test_jira_XmlBeans56() throws Exception /** * [XMLBEANS-57] scomp failure for XSD namespace "DAV:" */ - public void test_jira_XmlBeans57() throws Exception - { + @Test + public void test_jira_XmlBeans57() throws Exception { String P = File.separator; String outputDir = OUTPUTROOT + P + "dav"; @@ -201,6 +200,8 @@ public void test_jira_XmlBeans57() throws Exception * This is realted to xmlbeans36 - its the same case but the schemas seem to have been updated at the w3c site. * Hence adding a new testcase with the new schemas */ + @Test + @Ignore("the url doesn't exist anymore ...") public void test_jira_xmlbeans58() throws Exception { List errors = new ArrayList(); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); @@ -216,7 +217,7 @@ public void test_jira_xmlbeans58() throws Exception { SchemaCompiler.compile(params); if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans55() : Errors found when executing scomp"); + fail("test_jira_xmlbeans55() : Errors found when executing scomp"); } } @@ -225,8 +226,8 @@ public void test_jira_xmlbeans58() throws Exception { /** * [XMLBEANS-62] Avoid class cast exception when compiling older schema namespace */ - public void test_jira_XmlBeans62() throws Exception - { + @Test + public void test_jira_XmlBeans62() throws Exception { String P = File.separator; String outputDir = System.getProperty("xbean.rootdir") + P + "build" + P + "test" + P + "output" + P + "x1999"; @@ -265,8 +266,8 @@ public void test_jira_XmlBeans62() throws Exception /** * [XMLBEANS-64] ArrayIndexOutOfBoundsException during validation */ - public void test_jira_XmlBeans64() throws Exception - { + @Test + public void test_jira_XmlBeans64() throws Exception { // load the document File inst = new File(JIRA_CASES + "xmlbeans_64.xml"); XmlObject doc = RecorderSessionDocument.Factory.parse(inst); @@ -284,8 +285,8 @@ public void test_jira_XmlBeans64() throws Exception /** * [XMLBEANS-66] NullPointerException when restricting a union with one of the union members */ - public void test_jira_XmlBeans66() throws Exception - { + @Test + public void test_jira_XmlBeans66() throws Exception { String reproXsd = " \n" + "12"; validateInstance(new String[]{reproXsd}, new String[]{reproInst}, null); @@ -327,8 +328,8 @@ public void test_jira_XmlBeans66() throws Exception /** * [XMLBEANS-68] GDateBuilder outputs empty string when used without time or timezone */ - public void test_jira_XmlBeans68() throws Exception - { + @Test + public void test_jira_XmlBeans68() throws Exception { Calendar cal = Calendar.getInstance(); GDateBuilder gdateBuilder = new GDateBuilder(cal); gdateBuilder.clearTime(); @@ -356,8 +357,8 @@ public void test_jira_XmlBeans68() throws Exception * This issue needed an elementFormDefault=qualified added to the schema * [XMLBEANS-71] when trying to retrieve data from a XMLBean with Input from a XML Document, we cannot get any data from the Bean. */ - public void test_jira_XmlBeans71() throws Exception - { + @Test + public void test_jira_XmlBeans71() throws Exception { //schema src lives in cases/xbean/xmlobject/xmlbeans_71.xsd abc.BazResponseDocument doc = abc.BazResponseDocument.Factory.parse(JarUtil.getResourceFromJarasFile("xbean/misc/jira/xmlbeans_71.xml"), xmOpts); xmOpts.setErrorListener(errorList); @@ -380,15 +381,16 @@ public void test_jira_XmlBeans71() throws Exception if (baz.getStatus().compareTo("SUCCESS") != 0) throw new Exception("Status was not loaded properly"); else - System.out.println("Sucess was recieved correctly"); + System.out.println("Sucess was received correctly"); } /** * [XMLBEANS-72] Document properties are lost */ - public void test_jira_XmlBeans72() throws Exception - { + @Test + @Ignore + public void test_jira_XmlBeans72() throws Exception { String docTypeName = "struts-config"; String docTypePublicID = "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"; String docTypeSystemID = "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"; @@ -422,7 +424,7 @@ public void test_jira_XmlBeans72() throws Exception //System.out.println("System: "+ doc2Props.getDoctypeSystemId() + " = " + docType.getSystemId()); //System.out.println("Public: "+ doc2Props.getDoctypePublicId()+ " = " + docType.getPublicId()); - StringBuffer compareText = new StringBuffer(); + StringBuilder compareText = new StringBuilder(); //check values - compare to expected and DOM if (doc2Props != null) { if (doc2Props.getDoctypeName() == null || @@ -461,11 +463,9 @@ public void test_jira_XmlBeans72() throws Exception /** * BUGBUG: XMLBEANS-78 - NPE when processing XMLStreamReader Midstream * XMLBEANS-78 - NPE when processing XMLStreamReader Midstream - * - * @throws Exception */ - public void test_jira_xmlbeans78() throws Exception - { + @Test + public void test_jira_xmlbeans78() throws Exception { XMLInputFactory factory = XMLInputFactory.newInstance(); FileInputStream fis = new FileInputStream(new File(JIRA_CASES+ "xmlbeans_78.xml")); XMLStreamReader reader = factory.createXMLStreamReader(fis); @@ -480,8 +480,7 @@ public void test_jira_xmlbeans78() throws Exception * @throws javax.xml.stream.XMLStreamException * */ - private void skipToBody(XMLStreamReader reader) throws javax.xml.stream.XMLStreamException - { + private void skipToBody(XMLStreamReader reader) throws javax.xml.stream.XMLStreamException { while (true) { int event = reader.next(); switch (event) { @@ -502,8 +501,8 @@ private void skipToBody(XMLStreamReader reader) throws javax.xml.stream.XMLStrea * Repro case for jira issue * XMLBEANS-80 problems in XPath selecting with namespaces and Predicates. */ - public void test_jira_xmlbeans80() throws Exception - { + @Test + public void test_jira_xmlbeans80() throws Exception { String xpathDoc = " \n" + " \n" + " \n" + @@ -522,7 +521,7 @@ public void test_jira_xmlbeans80() throws Exception "ext='http://somebody.elses.extension'; .//ext:a[@test='test']"); - Assert.assertTrue(resSet.length == 1); + assertEquals(1, resSet.length); System.out.println("Result was: " + resSet[0].xmlText()); } @@ -530,8 +529,8 @@ public void test_jira_xmlbeans80() throws Exception * Repro case for jira issue * XMLBEANS-81 Cursor selectPath() method not working with predicates */ - public void test_jira_xmlbeans81() throws Exception - { + @Test + public void test_jira_xmlbeans81() throws Exception { String xpathDoc = "" + " " + " " + @@ -557,8 +556,8 @@ public void test_jira_xmlbeans81() throws Exception /** * XMLBeans-84 Cannot run XmlObject.selectPath using Jaxen in multi threaded environment */ - public void test_jira_XmlBeans84() throws Exception - { + @Test + public void test_jira_XmlBeans84() throws Exception { XPathThread[] threads = new XPathThread[15]; for (int i = 0; i < threads.length; i++) { @@ -578,9 +577,9 @@ public void test_jira_XmlBeans84() throws Exception /* * [XMLBEANS-88]:Cannot compile eBay schema - * */ - /* + @Ignore + @Test public void test_jira_xmlbeans88() throws Exception { List errors = new ArrayList(); SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); @@ -603,41 +602,41 @@ public void test_jira_xmlbeans88() throws Exception { System.out.println(ome.getCause()); System.out.println(ome.getMessage()); System.out.println(ome.getStackTrace()); - Assert.fail("test_jira_xmlbeans88(): Out Of Memory Error"); + fail("test_jira_xmlbeans88(): Out Of Memory Error"); } catch (Throwable t) { t.getMessage(); System.out.println("Ok Some Exception is caught here"); } if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans88() : Errors found when executing scomp"); + fail("test_jira_xmlbeans88() : Errors found when executing scomp"); } - } - */ /** * [XMLBEANS-96]:XmlDocumentProperties missing version and encoding */ + @Test + @Ignore public void test_jira_xmlbeans96() throws Exception { - StringBuffer xmlstringbuf = new StringBuffer(""); + StringBuilder xmlstringbuf = new StringBuilder(""); xmlstringbuf.append(""); xmlstringbuf.append(" Jira02 "); xmlstringbuf.append(""); XmlObject doc = XmlObject.Factory.parse(xmlstringbuf.toString()); XmlDocumentProperties props = doc.documentProperties(); - Assert.assertEquals("test_jira_xmlbeans96() : Xml Version is not picked up", props.getVersion(), "1.0"); - Assert.assertEquals("test_jira_xmlbeans96() : Xml Encoding is not picked up", props.getEncoding(), "UTF-8"); + assertEquals("test_jira_xmlbeans96() : Xml Version is not picked up", "1.0", props.getVersion()); + assertEquals("test_jira_xmlbeans96() : Xml Encoding is not picked up", "UTF-8", props.getEncoding()); } /** * [XMLBEANS-98] setSaveSuggestedPrefixes doesn't * work for QName attribute values - * - * @throws Exception */ + @Test + @Ignore public void test_jira_xmlbeans98() throws Exception { String outfn = outputroot + "xmlbeans_98.xml"; String structnamespace = "http://www.orthogony.net/xml/sample/structure"; @@ -696,9 +695,8 @@ public void test_jira_xmlbeans98() throws Exception { /** * [XMLBEANS-99] NPE/AssertionFailure in newDomNode() - * - * @throws Exception */ + @Test public void test_jira_xmlbeans99_a() throws Exception { //typed verification DummyDocument doc = DummyDocument.Factory.parse(new File(JIRA_CASES + "xmlbeans_99.xml")); @@ -715,8 +713,9 @@ public void test_jira_xmlbeans99_a() throws Exception { * [XMLBEANS-99]: NPE/AssertionFailure in newDomNode() * refer to [XMLBEANS-14] */ + @Test public void test_jira_xmlbeans99_b() throws Exception { - StringBuffer xmlstringbuf = new StringBuffer(" \n"); + StringBuilder xmlstringbuf = new StringBuilder(" \n"); xmlstringbuf.append(" \n"); xmlstringbuf.append(" \n"); xmlstringbuf.append(" toto \n"); @@ -754,9 +753,9 @@ public void test_jira_xmlbeans99_b() throws Exception { System.out.println("New Father Type Node: "+ fatherTypeNode); } catch (NullPointerException npe) { - Assert.fail("test_jira_xmlbeans99() : Null Pointer Exception when create Dom Node"); + fail("test_jira_xmlbeans99() : Null Pointer Exception when create Dom Node"); } catch (Exception e) { - Assert.fail("test_jira_xmlbeans99() : Exception when create Dom Node"); + fail("test_jira_xmlbeans99() : Exception when create Dom Node"); } } @@ -845,10 +844,5 @@ public void runDocXPath() } } } - - - - - } diff --git a/test/src/misc/detailed/JiraRegressionSchemaCompilerTest.java b/src/test/java/misc/detailed/JiraRegressionSchemaCompilerTest.java similarity index 93% rename from test/src/misc/detailed/JiraRegressionSchemaCompilerTest.java rename to src/test/java/misc/detailed/JiraRegressionSchemaCompilerTest.java index d7f4877..1ccfef2 100644 --- a/test/src/misc/detailed/JiraRegressionSchemaCompilerTest.java +++ b/src/test/java/misc/detailed/JiraRegressionSchemaCompilerTest.java @@ -14,24 +14,21 @@ */ package misc.detailed; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ArrayList; -import java.io.File; - +import misc.common.JiraTestBase; import org.apache.xmlbeans.XmlError; import org.apache.xmlbeans.impl.tool.SchemaCompiler; +import org.junit.Test; -import misc.common.JiraTestBase; +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; -public class JiraRegressionSchemaCompilerTest extends JiraTestBase -{ - public JiraRegressionSchemaCompilerTest(String name) - { - super(name); - } +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +public class JiraRegressionSchemaCompilerTest extends JiraTestBase { private List _testCompile(File[] xsdFiles, String outputDirName) { @@ -42,6 +39,7 @@ private List _testCompile(File[] xsdFiles, params.setErrorListener(errors); params.setSrcDir(new File(schemaCompOutputDirPath + outputDirName + P + "src")); params.setClassesDir(new File(schemaCompOutputDirPath + outputDirName + P + "classes")); + params.setQuiet(true); SchemaCompiler.compile(params); return errors; } @@ -66,6 +64,7 @@ private boolean findErrMsg(Collection errors, String msg) return errFound; } + @Test public void test_jira_xmlbeans236() { File[] xsdFiles = @@ -78,6 +77,7 @@ public void test_jira_xmlbeans236() } } + @Test public void test_jira_xmlbeans239() { /* complexType with complexContent extending base type with @@ -107,6 +107,7 @@ public void test_jira_xmlbeans239() assertTrue(findErrMsg(errors, msg)); } + @Test public void test_jira_xmlbeans251() { File[] xsdFiles = diff --git a/src/test/java/misc/detailed/JiraRegressionTest101_150.java b/src/test/java/misc/detailed/JiraRegressionTest101_150.java new file mode 100644 index 0000000..23d7fc4 --- /dev/null +++ b/src/test/java/misc/detailed/JiraRegressionTest101_150.java @@ -0,0 +1,102 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.detailed; + +import misc.common.JiraTestBase; +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.tool.SchemaCompiler; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * + */ +public class JiraRegressionTest101_150 extends JiraTestBase +{ + /** + * [XMLBEANS-103] XMLBeans - QName thread cache, cause memory leaks + */ + @Test + public void test_jira_xmlbeans102a() throws Exception{ + // set the parameters similar to those in the bug + SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); + params.setXsdFiles(new File[]{new File(JIRA_CASES + "xmlbeans_102.xsd")}); + params.setOutputJar(new File(outputroot+P+"xmlbeans_102.jar")); + File outputDir = new File(outputroot + P + "xmlbeans_102"); + outputDir.mkdirs(); + params.setClassesDir(outputDir); + params.setSrcDir(outputDir); + // compile schema + SchemaCompiler.compile(params); + // check for jar - compilation success + if(!(new File(outputroot + P + "xmlbeans_102.jar").exists()) ) + throw new Exception("Jar File was not found"); + //cleanup + deltree(outputroot); + } + + /* + * [XMLBEANS-102]: scomp - infinite loop during jar for specific xsd and params for netui_config.xsd + */ + @Test + public void test_jira_xmlbeans102b() { + //Assert.fail("test_jira_xmlbeans102: Infinite loop after completion of parsing" ); + + SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); + params.setOutputJar(new File(schemaCompOutputDirPath + "jira102.jar")); + params.setClassesDir(schemaCompClassesDir); + + params.setXsdFiles(new File[]{new File(scompTestFilesRoot + "xmlbeans_102_netui-config.xsd_")}); + List errors = new ArrayList(); + params.setErrorListener(errors); + params.setSrcDir(schemaCompSrcDir); + params.setClassesDir(schemaCompClassesDir); + + SchemaCompiler.compile(params); + if (printOptionErrMsgs(errors)) { + fail("test_jira_xmlbeans102() : Errors found when executing scomp"); + } + + } + + /** + * NPE while initializing a type system w/ a type that extends + * an a complex type from a different type system + */ + @Test + public void test_jira_xmlbeans105() throws Exception { + //run untyped parse + XmlObject obj = XmlObject.Factory.parse(new File(JIRA_CASES + "xmlbeans_105.xml")); + + //run Typed Parse + jira.xmlbeans105.ResourceUnknownFaultDocument rud = + jira.xmlbeans105.ResourceUnknownFaultDocument.Factory.parse(new File(JIRA_CASES + "xmlbeans_105.xml")); + + // / we know the instance is invalid + // make sure the error message is what is expected + rud.validate(xmOpts); + assertEquals("More Errors than expected", 1, errorList.size()); + assertEquals("Did not receive the expected error code: " + ((XmlError) errorList.get(0)).getErrorCode(), 0, ((XmlError) errorList.get(0)).getErrorCode().compareToIgnoreCase("cvc-complex-type.2.4a")); + + } +} diff --git a/src/test/java/misc/detailed/LargeEnumTest.java b/src/test/java/misc/detailed/LargeEnumTest.java new file mode 100644 index 0000000..1826b58 --- /dev/null +++ b/src/test/java/misc/detailed/LargeEnumTest.java @@ -0,0 +1,132 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.detailed; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.XmlToken; +import org.junit.Test; +import xmlbeans307.*; + +import java.util.ArrayList; + +import static org.junit.Assert.*; + +/** + * This test was put together for: + * http://issues.apache.org/jira/browse/XMLBEANS-307 + * XMLBeans scomp throws error "code too large" + */ +public class LargeEnumTest { + /** + * These are tests for a enumeration type + */ + @Test + public void testEnumCount_closeToMax() throws Exception { + SchemaType mType = MaxAllowedEnumType.type; + assertNotNull("Enumeration SchemaType was null", mType.getEnumerationValues()); + assertEquals("EnumerationValue was not 3660 as expected was" + mType.getEnumerationValues().length, 3660, mType.getEnumerationValues().length); + + SchemaType mElem = MaxAllowedElementDocument.type; + assertNull("Enumeration SchemaType was null", mElem.getEnumerationValues()); + + // Test that the Java type associated to this is an enum type + assertNotNull("This type does not correspond to a Java enumeration", mType.getStringEnumEntries()); + } + + @Test + public void testEnumCount_greaterThanMax() throws Exception { + // TODO: verify if any xpath/xquery issues + SchemaType mType = MoreThanAllowedEnumType.type; + + assertNotNull("Enumeration should be null as type should be base type " + mType.getEnumerationValues(), + mType.getEnumerationValues()); + assertEquals("EnumerationValue was not 3678 as expected was " + mType.getEnumerationValues().length, 3678, mType.getEnumerationValues().length); + System.out.println("GET BASE TYPE: " + mType.getBaseType()); + System.out.println("GET BASE TYPE: " + mType.getPrimitiveType()); + assertEquals("type should have been base type, was " + mType.getBaseType(), mType.getBaseType().getBuiltinTypeCode(), XmlToken.type.getBuiltinTypeCode()); + + SchemaType mElem = GlobalMoreThanElementDocument.type; + assertNull("Enumeration SchemaType was null", mElem.getBaseEnumType()); + + // Test that the Java type associated to this is not an enum type + assertNull("This type corresponds to a Java enumeration, even though it has too many enumeration values", + mType.getStringEnumEntries()); + } + + @Test + public void testEnumCount_validate_invalid_enum() throws Exception { + MoreThanAllowedEnumType mType = MoreThanAllowedEnumType.Factory.newInstance(); + + //This value dos not exist in the enumeration set + mType.setStringValue("12345AAA"); + ArrayList errors = new ArrayList(); + XmlOptions options = (new XmlOptions()).setErrorListener(errors); + mType.validate(options); + XmlError[] xErr = new XmlError[errors.size()]; + for (int i = 0; i < errors.size(); i++) { + System.out.println("ERROR: " + errors.get(i)); + xErr[i] = (XmlError)errors.get(i); + } + + assertEquals("NO Expected Errors after validating enumType after set", 1, errors.size()); + assertEquals("Expected ERROR CODE was not as expected", 0, xErr[0].getErrorCode().compareTo("cvc-enumeration-valid")); + // string value '12345AAA' is not a valid enumeration value for MoreThanAllowedEnumType in + } + + @Test + public void test_MoreEnum_Operations() throws Exception { + MoreThanAllowedEnumType mType = MoreThanAllowedEnumType.Factory.newInstance(); + + mType.setStringValue("AAA"); + ArrayList errors = new ArrayList(); + XmlOptions options = (new XmlOptions()).setErrorListener(errors); + mType.validate(options); + + for (int i = 0; i < errors.size(); i++) { + System.out.println("ERROR: " + errors.get(i)); + } + assertEquals("There were errors validating enumType after set", 0, errors.size()); + + GlobalMoreThanElementDocument mDoc = GlobalMoreThanElementDocument.Factory.newInstance(); + mDoc.setGlobalMoreThanElement("AAA"); + errors = null; + errors = new ArrayList(); + options = (new XmlOptions()).setErrorListener(errors); + mDoc.validate(options); + + for (int i = 0; i < errors.size(); i++) { + System.out.println("ERROR: " + errors.get(i)); + } + + assertEquals("There were errors validating enumDoc after set", 0, errors.size()); + + MoreThanAllowedComplexType mcType = MoreThanAllowedComplexType.Factory.newInstance(); + mcType.setComplexTypeMoreThanEnum("AAA"); + mcType.setSimpleString("This should work"); + errors = null; + errors = new ArrayList(); + mcType.validate(options); + for (int i = 0; i < errors.size(); i++) { + System.out.println("ERROR: " + errors.get(i)); + } + + assertEquals("There were errors validating complxType after set", 0, errors.size()); + } + + +} diff --git a/src/test/java/misc/detailed/SampleRunner.java b/src/test/java/misc/detailed/SampleRunner.java new file mode 100644 index 0000000..e95b00a --- /dev/null +++ b/src/test/java/misc/detailed/SampleRunner.java @@ -0,0 +1,302 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package misc.detailed; + +import org.apache.tools.ant.*; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.PrintStream; +import java.util.ArrayList; + +/** + * Date: Feb 8, 2005 + * Time: 11:30:24 AM + */ +public class SampleRunner { + + private ArrayList samples; + private Project proj; + private Target target; + private String XMLBEANS_HOME; + private SamplesBuildFileTest runSampleTest; + + + @Before + protected void setUp() throws Exception { + proj = new Project(); + proj.setName("Samples Task Tests"); + XMLBEANS_HOME = proj.getBaseDir().getAbsolutePath(); + samples = new ArrayList(); + runSampleTest = new SamplesBuildFileTest(); + } + + @Test + public void testSamples() throws Exception { + loadSampleDirs(new File("./samples")); + ArrayList exceptions = new ArrayList(); + for (int i = 0; i < samples.size(); i++) + { + + runSampleTest.call_samples_task( + ((File) samples.get(i)).getAbsolutePath() + , "test"); + BuildException e; + if ((e = runSampleTest.getAnyExceptions()) != null) + { + exceptions.add(((File) samples.get(i)).getAbsolutePath()); + exceptions.add(e.getException()); + } + } + if (exceptions.size() != 0) + throw new RuntimeException(getMessageFromExceptions(exceptions)); + + } + + private String getMessageFromExceptions(ArrayList ex) + { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < ex.size(); i += 2) + { + sb.append("\n\nFILE:" + (String) ex.get(i)); + sb.append( + "\n **Error: " + ((BuildException) ex.get(i + 1)).getMessage()); + } + return sb.toString(); + } + + private void loadSampleDirs(File dir) + { + assert dir != null && dir.exists(); + File[] files = dir.listFiles(new BuildFilter()); + assert files.length == 1; + samples.add(files[0]); + + } + + private class BuildFilter + implements FilenameFilter + { + public boolean accept(File file, String name) + { + return name.equals("build.xml"); + } + } + + private class SamplesBuildFileTest extends BuildFileTest { + public void call_samples_task(String projectPath, String taskName) + { + configureProject(projectPath); + Project proj = getProject(); + proj.setProperty("xmlbeans.home", XMLBEANS_HOME); + executeTarget(proj.getDefaultTarget()); + } + + public BuildException getAnyExceptions() + throws Exception + { + return this.getBuildException(); + } + } +} + +abstract class BuildFileTest { + + protected Project project; + + private StringBuilder logBuffer; + private StringBuilder fullLogBuffer; + private StringBuilder outBuffer; + private StringBuilder errBuffer; + private BuildException buildException; + + protected String getOutput() { + return cleanBuffer(outBuffer); + } + + protected String getError() { + return cleanBuffer(errBuffer); + } + + protected BuildException getBuildException() { + return buildException; + } + + private String cleanBuffer(StringBuilder buffer) { + StringBuilder cleanedBuffer = new StringBuilder(); + boolean cr = false; + for (int i = 0; i < buffer.length(); i++) { + char ch = buffer.charAt(i); + if (ch == '\r') { + cr = true; + continue; + } + + if (!cr) { + cleanedBuffer.append(ch); + } else { + if (ch == '\n') { + cleanedBuffer.append(ch); + } else { + cleanedBuffer.append('\r').append(ch); + } + } + } + return cleanedBuffer.toString(); + } + + /** + * set up to run the named project + * + * @param filename name of project file to run + */ + protected void configureProject(String filename) throws BuildException { + logBuffer = new StringBuilder(); + fullLogBuffer = new StringBuilder(); + project = new Project(); + project.init(); + project.setUserProperty( "ant.file" , new File(filename).getAbsolutePath() ); + project.addBuildListener(new BuildFileTest.AntTestListener()); + //ProjectHelper.configureProject(project, new File(filename)); + ProjectHelper.getProjectHelper().parse(project, new File(filename)); + } + + /** + * execute a target we have set up + * @pre configureProject has been called + * @param targetName target to run + */ + protected void executeTarget(String targetName) { + PrintStream sysOut = System.out; + PrintStream sysErr = System.err; + try { + sysOut.flush(); + sysErr.flush(); + outBuffer = new StringBuilder(); + PrintStream out = new PrintStream(new BuildFileTest.AntOutputStream()); + System.setOut(out); + errBuffer = new StringBuilder(); + PrintStream err = new PrintStream(new BuildFileTest.AntOutputStream()); + System.setErr(err); + logBuffer = new StringBuilder(); + fullLogBuffer = new StringBuilder(); + buildException = null; + project.executeTarget(targetName); + } finally { + System.setOut(sysOut); + System.setErr(sysErr); + // rajus: 2004/04/07 + System.out.println("STDOUT+STDERR:\n" + getOutput() + getError()); + System.out.println("END STDOUT+STDERR:"); + } + + } + + /** + * Get the project which has been configured for a test. + * + * @return the Project instance for this test. + */ + protected Project getProject() { + return project; + } + + /** + * an output stream which saves stuff to our buffer. + */ + private class AntOutputStream extends java.io.OutputStream { + public void write(int b) { + outBuffer.append((char)b); + } + } + + /** + * our own personal build listener + */ + private class AntTestListener implements BuildListener { + /** + * Fired before any targets are started. + */ + public void buildStarted(BuildEvent event) { + } + + /** + * Fired after the last target has finished. This event + * will still be thrown if an error occured during the build. + * + * @see BuildEvent#getException() + */ + public void buildFinished(BuildEvent event) { + } + + /** + * Fired when a target is started. + * + * @see BuildEvent#getTarget() + */ + public void targetStarted(BuildEvent event) { + //System.out.println("targetStarted " + event.getTarget().getName()); + } + + /** + * Fired when a target has finished. This event will + * still be thrown if an error occured during the build. + * + * @see BuildEvent#getException() + */ + public void targetFinished(BuildEvent event) { + //System.out.println("targetFinished " + event.getTarget().getName()); + } + + /** + * Fired when a task is started. + * + * @see BuildEvent#getTask() + */ + public void taskStarted(BuildEvent event) { + //System.out.println("taskStarted " + event.getTask().getTaskName()); + } + + /** + * Fired when a task has finished. This event will still + * be throw if an error occured during the build. + * + * @see BuildEvent#getException() + */ + public void taskFinished(BuildEvent event) { + //System.out.println("taskFinished " + event.getTask().getTaskName()); + } + + /** + * Fired whenever a message is logged. + * + * @see BuildEvent#getMessage() + * @see BuildEvent#getPriority() + */ + public void messageLogged(BuildEvent event) { + if (event.getPriority() == Project.MSG_INFO || + event.getPriority() == Project.MSG_WARN || + event.getPriority() == Project.MSG_ERR) { + logBuffer.append(event.getMessage()); + } + fullLogBuffer.append(event.getMessage()); + + } + } + + +} diff --git a/src/test/java/misc/detailed/SystemCacheClassloadersTest.java b/src/test/java/misc/detailed/SystemCacheClassloadersTest.java new file mode 100644 index 0000000..0a5c44d --- /dev/null +++ b/src/test/java/misc/detailed/SystemCacheClassloadersTest.java @@ -0,0 +1,170 @@ +/* + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.detailed; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SchemaTypeLoader; +import org.apache.xmlbeans.XmlBeans; +import org.junit.Test; + +import javax.xml.namespace.QName; +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; + +/* Test class loading using XmlBeans.getContextLoader() after changes to SystemCache.java (r240333) +* Now a custom implementation of the SystemCache can be provided +*/ +public class SystemCacheClassloadersTest { + + @Test + public void testSystemCacheAndThreadLocal() + { + Thread testThread = new SystemCacheThread("SchemTypeLoader Test Thread"); + + try { + testThread.start(); + } + catch (Exception e) { + e.printStackTrace(); + } + + finally { + try { + testThread.join(); + } + catch (InterruptedException ie) { + ie.printStackTrace(); + } + } + + } + + public static class SystemCacheThread extends Thread + { + private String name; + + SystemCacheThread(String threadName) + { + super(); + name = threadName; + } + + /** + */ + public void run() + { + System.out.println("Run Method of thread " + name); + + try { + + // test classloading from 2 different scomp jars using the default impl of SystemCache + testDefaultSystemCacheClassLoading(); + + } + catch (Throwable t) { + t.printStackTrace(); + } + } + + void testDefaultSystemCacheClassLoading() + { + try { + // create classloaders here + String xbean_home = System.getProperty("xbean.rootdir"); + if (xbean_home == null) { + xbean_home = new File(".").getAbsolutePath(); + } + + String[] domPaths = { + "build/classes", + "build/test-syscache/2/classes", + "build/test-syscache/2/generated-resources" + }; + + List domUrls = new ArrayList(); + for (String p : domPaths) { + domUrls.add(new File(xbean_home, p).toURI().toURL()); + } + + String[] miscPaths = { + "build/classes", + "build/test-syscache/1/classes", + "build/test-syscache/1/generated-resources" + }; + + List miscUrls = new ArrayList(); + for (String p : miscPaths) { + miscUrls.add(new File(xbean_home, p).toURI().toURL()); + } + + + URLClassLoader domCL = new URLClassLoader(domUrls.toArray(new URL[0])); + URLClassLoader miscCL = new URLClassLoader(miscUrls.toArray(new URL[0])); + + // define the Qnames of types to look for in the compiled xbeans after switching the class loaders + QName domTypeQName = new QName("http://xbean/misc/SyscacheTests2", "elementT"); + QName miscPersonTypeQName = new QName("http://xbean/misc/SyscacheTests1", "personType", "test"); + + setContextClassLoader(domCL); + //System.out.println("Testing elementT Type From dom tests complexTypeTest.xsd"); + SchemaTypeLoader initialDomLoader = XmlBeans.getContextTypeLoader(); + SchemaType domSchemaType = initialDomLoader.findType(domTypeQName); + assertNotNull(domSchemaType); + assertEquals("Invalid Type!", domSchemaType.getFullJavaImplName(), "xbean.misc.syscacheTests2.impl.ElementTImpl"); + + // -ve test, look for the person type from cases\misc\syscachetest.xsd + SchemaType personTypeFromMiscTests = initialDomLoader.findType(miscPersonTypeQName); + assertNull(personTypeFromMiscTests); + + // switch the SchemaTypeLoader + setContextClassLoader(miscCL); + //System.out.println("Testing Person Type From misc syscachetests.xsd"); + SchemaTypeLoader initialMiscSchemaLoader = XmlBeans.getContextTypeLoader(); + SchemaType miscPersonType = initialMiscSchemaLoader.findType(miscPersonTypeQName); + assertNotNull(miscPersonType); + assertEquals("Invalid Type!", miscPersonType.getFullJavaImplName(), "xbean.misc.syscacheTests1.impl.PersonTypeImpl"); + + // -ve test + SchemaType personTypeFromMisc = initialMiscSchemaLoader.findType(domTypeQName); + assertNull(personTypeFromMisc); + + // reload the original loader + setContextClassLoader(domCL); + SchemaTypeLoader secondDomLoader = XmlBeans.getContextTypeLoader(); + assertNotNull(secondDomLoader.findType(domTypeQName)); + assertSame("SchemaTypeLoaders expected to be equal", initialDomLoader, secondDomLoader); + + setContextClassLoader(miscCL); + SchemaTypeLoader secondMiscLoader = XmlBeans.getContextTypeLoader(); + assertSame("SchemaTypeLoaders expected to be equal", initialMiscSchemaLoader, secondMiscLoader); + + } + catch (Throwable t) { + t.printStackTrace(); + } + + } + + + } + +} diff --git a/src/test/java/misc/detailed/SystemCacheTestImpl.java b/src/test/java/misc/detailed/SystemCacheTestImpl.java new file mode 100644 index 0000000..dddb4f9 --- /dev/null +++ b/src/test/java/misc/detailed/SystemCacheTestImpl.java @@ -0,0 +1,40 @@ +/* + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.detailed; + +import org.apache.xmlbeans.impl.common.SystemCache; + +// This class provides an alternative implementation to the SystemCache that essentially does nothing special +// Used in testing the SystemCache.set() API to test an alternate implementation being picked up. Used in +// SystemCacheTests +public class SystemCacheTestImpl extends SystemCache { + private static int _accessed; + + public SystemCacheTestImpl() { + _accessed++; + } + + public String testCacheImpl() { + return (this.getClass().getName()); + } + + public static final int getAccessed() { + return _accessed; + } + +} + diff --git a/src/test/java/misc/detailed/SystemCacheTests.java b/src/test/java/misc/detailed/SystemCacheTests.java new file mode 100644 index 0000000..16bfaee --- /dev/null +++ b/src/test/java/misc/detailed/SystemCacheTests.java @@ -0,0 +1,58 @@ +/* + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.detailed; + +import org.apache.xmlbeans.impl.common.SystemCache; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class SystemCacheTests { + @Test + public void testSystemCacheImplFromAPITest() { + // store the default SystemCache implementation before switch + SystemCache defaultImpl = SystemCache.get(); + + assertEquals("org.apache.xmlbeans.impl.common.SystemCache", defaultImpl.getClass().getName()); + + // switch the Impl to the test Impl + SystemCacheTestImpl testImpl = new SystemCacheTestImpl(); + SystemCache.set(testImpl); + assertEquals("misc.detailed.SystemCacheTestImpl", testImpl.getClass().getName()); + assertEquals(SystemCacheTestImpl.getAccessed(), 1); + + // switch back to default impl + SystemCache.set(defaultImpl); + assertEquals("org.apache.xmlbeans.impl.common.SystemCache", defaultImpl.getClass().getName()); + } + + @Test + public void testClearThreadLocal() { + SystemCache cache = SystemCache.get(); + String saxLoader = "object is not cast currently..."; + + cache.setSaxLoader(saxLoader); + assertEquals(saxLoader, cache.getSaxLoader()); + + cache.clearThreadLocals(); + assertNull(cache.getSaxLoader()); + + cache.setSaxLoader(saxLoader); + assertEquals(saxLoader, cache.getSaxLoader()); + } +} diff --git a/src/test/java/misc/detailed/ThreadLocalUtilTest.java b/src/test/java/misc/detailed/ThreadLocalUtilTest.java new file mode 100644 index 0000000..b0335c8 --- /dev/null +++ b/src/test/java/misc/detailed/ThreadLocalUtilTest.java @@ -0,0 +1,44 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package misc.detailed; + +import org.apache.xmlbeans.ThreadLocalUtil; +import org.apache.xmlbeans.impl.common.SystemCache; +import org.apache.xmlbeans.impl.schema.StscState; +import org.apache.xmlbeans.impl.store.CharUtil; +import org.junit.Test; + +public class ThreadLocalUtilTest { + @Test + public void testClearThreadLocalsNoData() { + // simply calling it without any thread locals should work + ThreadLocalUtil.clearAllThreadLocals(); + } + + @Test + public void testClearThreadLocalsWithData() { + // calling it with thread locals should work as well + CharUtil.getThreadLocalCharUtil(); + + SystemCache cache = SystemCache.get(); + String saxLoader = "object is not cast currently..."; + cache.setSaxLoader(saxLoader); + StscState.start(); + StscState.end(); + + ThreadLocalUtil.clearAllThreadLocals(); + } +} diff --git a/test/src/misc/detailed/XMLStreamReaderTest.java b/src/test/java/misc/detailed/XMLStreamReaderTest.java similarity index 93% rename from test/src/misc/detailed/XMLStreamReaderTest.java rename to src/test/java/misc/detailed/XMLStreamReaderTest.java index 776ce98..7f156e5 100644 --- a/test/src/misc/detailed/XMLStreamReaderTest.java +++ b/src/test/java/misc/detailed/XMLStreamReaderTest.java @@ -14,21 +14,19 @@ */ package misc.detailed; -import java.io.InputStream; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamReader; - import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; -import junit.framework.TestCase; +import javax.xml.stream.XMLStreamReader; + +import static org.junit.Assert.assertTrue; /** * Adapted from testcase submitted by Brian Bonner for JIRA issue * XMLBEANS-222, based on comments by Cezar Andrei. */ -public class XMLStreamReaderTest extends TestCase { +public class XMLStreamReaderTest { private static final String soapMsg = "" @@ -41,7 +39,7 @@ public class XMLStreamReaderTest extends TestCase { + "" + "" + ""; - + @Test public void testXmlStreamReader1() throws Exception { XmlObject object = XmlObject.Factory.parse(soapMsg); @@ -66,7 +64,8 @@ public void testXmlStreamReader1() throws Exception { } assertTrue("xsi namespace is not found", foundXsiNamespace); } - + + @Test public void testXmlStreamReader2() throws Exception { XmlObject object = XmlObject.Factory.parse(soapMsg); diff --git a/src/test/java/org/apache/xmlbeans/impl/tool/Diff.java b/src/test/java/org/apache/xmlbeans/impl/tool/Diff.java new file mode 100644 index 0000000..49adb83 --- /dev/null +++ b/src/test/java/org/apache/xmlbeans/impl/tool/Diff.java @@ -0,0 +1,295 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xmlbeans.impl.tool; + +import org.apache.xmlbeans.SystemProperties; +import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; + +public class Diff { + public static void main(String[] args) { + if (args.length != 2) { + System.out.println("Usage: diff to compare two jars"); + System.out.println(" or diff to compare two dirs"); + return; + } + File file1 = new File(args[0]); + if (!file1.exists()) { + System.out.println("File \"" + args[0] + "\" not found."); + return; + } + File file2 = new File(args[1]); + if (!file2.exists()) { + System.out.println("File \"" + args[1] + "\" not found."); + return; + } + List result = new ArrayList<>(); + if (file1.isDirectory()) { + if (!file2.isDirectory()) { + System.out.println("Both parameters have to be directories if the first parameter is a directory."); + return; + } + dirsAsTypeSystems(file1, file2, result); + } else { + if (file2.isDirectory()) { + System.out.println("Both parameters have to be jar files if the first parameter is a jar file."); + return; + } + try { + JarFile jar1 = new JarFile(file1); + JarFile jar2 = new JarFile(file2); + jarsAsTypeSystems(jar1, jar2, result); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + if (result.size() < 1) { + System.out.println("No differences encountered."); + } else { + System.out.println("Differences:"); + for (String s : result) { + System.out.println(s); + } + } + } + + /** + * Diffs the contents of two jars, looking only at the schema typesystems + * saved inside those jars + */ + public static void jarsAsTypeSystems(JarFile jar1, JarFile jar2, List diffs) { + Enumeration entries1 = jar1.entries(); + Enumeration entries2 = jar2.entries(); + List list1 = new ArrayList<>(); + List list2 = new ArrayList<>(); + while (entries1.hasMoreElements()) { + ZipEntry ze = entries1.nextElement(); + String name = ze.getName(); + if (name.startsWith(SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb")) { + list1.add(ze); + } + } + while (entries2.hasMoreElements()) { + ZipEntry ze = entries2.nextElement(); + String name = ze.getName(); + if (name.startsWith(SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb")) { + list2.add(ze); + } + } + ZipEntry[] files1 = list1.toArray(new ZipEntry[0]); + ZipEntry[] files2 = list2.toArray(new ZipEntry[0]); + Comparator comparator = Comparator.comparing(ZipEntry::getName); + Arrays.sort(files1, comparator); + Arrays.sort(files2, comparator); + int i1 = 0; + int i2 = 0; + while (i1 < files1.length && i2 < files2.length) { + String name1 = files1[i1].getName(); + String name2 = files2[i2].getName(); + int dif = name1.compareTo(name2); + if (dif == 0) { + // Compare the files + zipEntriesAsXsb(files1[i1], jar1, files2[i2], jar2, diffs); + i1++; + i2++; // Move to next pair + } else if (dif < 0) { + // dir1 contains a file that dir2 doesn't + diffs.add("Jar \"" + jar1.getName() + "\" contains an extra file: \"" + + name1 + "\""); + i1++; + } else { + // dir2 contains a file that dir1 doesn't + diffs.add("Jar \"" + jar2.getName() + "\" contains an extra file: \"" + + name2 + "\""); + i2++; + } + } + while (i1 < files1.length) { + diffs.add("Jar \"" + jar1.getName() + "\" contains an extra file: \"" + + files1[i1].getName() + "\""); + i1++; + } + while (i2 < files2.length) { + diffs.add("Jar \"" + jar2.getName() + "\" contains an extra file: \"" + + files2[i2].getName() + "\""); + i2++; + } + } + + /** + * Diffs the contents of two dirs looking only at the xsb files + * contained in these two dirs + * Updated diffs with a list of differences (for the time being, strings + * describing the difference) + */ + public static void dirsAsTypeSystems(File dir1, File dir2, List diffs) { + assert dir1.isDirectory() : "Parameters must be directories"; + assert dir2.isDirectory() : "Parameters must be directories"; + + /* + Navigate three directories deep to get to the type system. + Assume the schema[METADATA_PACKAGE_LOAD]/system/* structure + */ + File temp1 = new File(dir1, SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system"); + File temp2 = new File(dir2, SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system"); + if (temp1.exists() && temp2.exists()) { + File[] files1 = temp1.listFiles(); + File[] files2 = temp2.listFiles(); + + assert (files1 != null && files2 != null); + + if (files1.length == 1 && files2.length == 1) { + temp1 = files1[0]; + temp2 = files2[0]; + } else { + if (files1.length == 0) { + temp1 = null; + } + if (files2.length == 0) { + temp2 = null; + } + if (files1.length > 1) { + diffs.add("More than one typesystem found in dir \"" + + dir1.getName() + "\""); + return; + } + if (files2.length > 1) { + diffs.add("More than one typesystem found in dir \"" + + dir2.getName() + "\""); + return; + } + } + } else { + if (!temp1.exists()) { + temp1 = null; + } + if (!temp2.exists()) { + temp2 = null; + } + } + if (temp1 == null && temp2 == null) { + return; + } else if (temp1 == null || temp2 == null) { + if (temp1 == null) { + diffs.add("No typesystems found in dir \"" + dir1 + "\""); + } + if (temp2 == null) { + diffs.add("No typesystems found in dir \"" + dir2 + "\""); + } + return; + } else { + dir1 = temp1; + dir2 = temp2; + } + + boolean diffIndex = isDiffIndex(); + FilenameFilter xsbName = (dir, name) -> name.endsWith(".xsb"); + File[] files1 = dir1.listFiles(xsbName); + File[] files2 = dir2.listFiles(xsbName); + + assert (files1 != null && files2 != null); + + Comparator comparator = Comparator.comparing(File::getName); + Arrays.sort(files1, comparator); + Arrays.sort(files2, comparator); + int i1 = 0; + int i2 = 0; + while (i1 < files1.length && i2 < files2.length) { + String name1 = files1[i1].getName(); + String name2 = files2[i2].getName(); + int dif = name1.compareTo(name2); + if (dif == 0) { + if (diffIndex || !files1[i1].getName().equals("index.xsb")) { + filesAsXsb(files1[i1], files2[i2], diffs); // Compare the files + } + i1++; + i2++; // Move to next pair + } else if (dif < 0) { + // dir1 contains a file that dir2 doesn't + diffs.add("Dir \"" + dir1.getName() + "\" contains an extra file: \"" + + name1 + "\""); + i1++; + } else { + // dir2 contains a file that dir1 doesn't + diffs.add("Dir \"" + dir2.getName() + "\" contains an extra file: \"" + + name2 + "\""); + i2++; + } + } + while (i1 < files1.length) { + diffs.add("Dir \"" + dir1.getName() + "\" contains an extra file: \"" + + files1[i1].getName() + "\""); + i1++; + } + while (i2 < files2.length) { + diffs.add("Dir \"" + dir2.getName() + "\" contains an extra file: \"" + + files2[i2].getName() + "\""); + i2++; + } + } + + private static boolean isDiffIndex() { + String prop = SystemProperties.getProperty("xmlbeans.diff.diffIndex"); + return prop == null || !"0".equals(prop) && !"false".equalsIgnoreCase(prop); + } + + /** + * Diffs the two given files assuming they are in xsb format + * Updates diffs with differences in string format + */ + public static void filesAsXsb(File file1, File file2, List diffs) { + assert file1.exists() : "File \"" + file1.getAbsolutePath() + "\" does not exist."; + assert file2.exists() : "File \"" + file2.getAbsolutePath() + "\" does not exist."; + try (FileInputStream stream1 = new FileInputStream(file1); + FileInputStream stream2 = new FileInputStream(file2)) { + streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs); + } catch (IOException ignored) { + } + } + + public static void zipEntriesAsXsb(ZipEntry file1, JarFile jar1, + ZipEntry file2, JarFile jar2, List diffs) { + try (InputStream stream1 = jar1.getInputStream(file1); + InputStream stream2 = jar2.getInputStream(file2)) { + streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs); + } catch (IOException ignored) { + } + } + + public static void streamsAsXsb(InputStream stream1, String name1, + InputStream stream2, String name2, List diffs) + throws IOException { + String charset = StandardCharsets.UTF_8.name(); + ByteArrayOutputStream buf1 = new ByteArrayOutputStream(); + ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); + XsbDumper.dump(stream1, "", new PrintStream(buf1, true, charset)); + XsbDumper.dump(stream2, "", new PrintStream(buf2, true, charset)); + readersAsText(new StringReader(buf1.toString(charset)), name1, + new StringReader(buf2.toString(charset)), name2, diffs); + } + + public static void readersAsText(Reader r1, String name1, Reader r2, String name2, + List diffs) + throws IOException { + org.apache.xmlbeans.impl.util.Diff.readersAsText(r1, name1, r2, name2, diffs); + } +} diff --git a/test/src/random/checkin/RandomTest.java b/src/test/java/random/checkin/RandomTest.java similarity index 90% rename from test/src/random/checkin/RandomTest.java rename to src/test/java/random/checkin/RandomTest.java index 31f5ac7..26f8a45 100755 --- a/test/src/random/checkin/RandomTest.java +++ b/src/test/java/random/checkin/RandomTest.java @@ -16,27 +16,30 @@ package random.checkin; import org.apache.xmlbeans.impl.tool.CommandLine; +import org.junit.Before; +import org.junit.Test; +import random.common.Random; import java.util.Arrays; -import random.common.Random; -import junit.framework.TestCase; - -public class RandomTest extends TestCase { +public class RandomTest { long seed; int iterations; int threads; int docs; + @Before public void setUp() { seed = System.currentTimeMillis(); iterations = Integer.MAX_VALUE; threads = 1; docs = 10; } - public static void testNoQuery() throws Exception { + + @Test + public void testNoQuery() { String[] args = new String[]{"-seed", "0", "-i", "20", "-noquery"}; CommandLine cl = new CommandLine(args, Arrays.asList(new String[]{"?", "help", "readonly", "noquery", "nosave"}), diff --git a/test/src/random/common/Random.java b/src/test/java/random/common/Random.java similarity index 81% rename from test/src/random/common/Random.java rename to src/test/java/random/common/Random.java index 3efa926..1f46dd2 100755 --- a/test/src/random/common/Random.java +++ b/src/test/java/random/common/Random.java @@ -15,55 +15,52 @@ package random.common; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SchemaType; +import com.easypo.XmlCustomerBean; +import com.easypo.XmlLineItemBean; +import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; +import com.easypo.XmlShipperBean; +import org.apache.xmlbeans.*; import org.apache.xmlbeans.impl.tool.CommandLine; import org.apache.xmlbeans.impl.values.XmlValueDisconnectedException; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Arrays; import java.math.BigDecimal; import java.math.BigInteger; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; -import com.easypo.XmlCustomerBean; -import com.easypo.XmlLineItemBean; -import com.easypo.XmlShipperBean; +import java.util.ArrayList; +import java.util.Calendar; public class Random implements Runnable { - static long seed; - static int iterations; - static int threads; - static int docs; + static long seed; + static int iterations; + static int threads; + static int docs; public static void runTest(CommandLine cl) { if (cl.getOpt("?") != null || cl.getOpt("help") != null || - cl.args().length != 0) + cl.args().length != 0) { System.out.println( - "Usage: random [-seed #] [-i iterations] [-t threads] [-docs docs] [-readonly] [-nosave]"); - else { + "Usage: random [-seed #] [-i iterations] [-t threads] [-docs docs] [-readonly] [-nosave]"); + } else { boolean readonly = false; boolean nosave = false; boolean noquery = false; - if (cl.getOpt("seed") != null) + if (cl.getOpt("seed") != null) { seed = Long.parseLong(cl.getOpt("seed")); - if (cl.getOpt("i") != null) + } + if (cl.getOpt("i") != null) { iterations = Integer.parseInt(cl.getOpt("i")); - if (cl.getOpt("t") != null) + } + if (cl.getOpt("t") != null) { threads = Integer.parseInt(cl.getOpt("t")); - if (cl.getOpt("docs") != null) + } + if (cl.getOpt("docs") != null) { docs = Integer.parseInt(cl.getOpt("docs")); + } noquery = (cl.getOpt("noquery") != null); readonly = (cl.getOpt("readonly") != null); nosave = (cl.getOpt("nosave") != null); @@ -90,7 +87,7 @@ private static void doTests(long seed, int iterations, int threadCount, for (int i = 0; i < iterations; i++) { for (int j = 0; j < threadCount; j++) { Random runnable = new Random(seed, sharedDocs, readonly, - nosave, noquery, threadCount > 1); + nosave, noquery, threadCount > 1); threads[j] = new Thread(runnable); threads[j].start(); seed++; @@ -98,8 +95,7 @@ private static void doTests(long seed, int iterations, int threadCount, for (int j = 0; j < threadCount; j++) { try { threads[j].join(); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { System.err.println("Thread interrupted"); } } @@ -109,15 +105,16 @@ private static void doTests(long seed, int iterations, int threadCount, System.err.println(); System.err.println( - "Seconds to run random tests: " + (end - start) / 1000); + "Seconds to run random tests: " + (end - start) / 1000); } public void run() { System.err.print("\rSeed: " + _seed); try { - for (int d = 0; d < _docs.length; d++) + for (int d = 0; d < _docs.length; d++) { _docs[d] = XmlObject.Factory.newInstance(); + } _cursors = new ArrayList(); @@ -129,8 +126,7 @@ public void run() { _iter++; iterate(); good = true; - } - finally { + } finally { if (!good) { System.err.println(); System.err.println("Error on iteration " + _iter); @@ -138,8 +134,7 @@ public void run() { } } } - } - catch (Throwable e) { + } catch (Throwable e) { System.err.println("Error on seed " + _seed); e.printStackTrace(System.err); } @@ -199,16 +194,15 @@ private void iterate() throws Exception { interateLow(); break; } - } - catch (IllegalStateException e) { - if (!_interference) + } catch (IllegalStateException e) { + if (!_interference) { throw e; - } - catch (IllegalArgumentException e) { - if (!_interference) + } + } catch (IllegalArgumentException e) { + if (!_interference) { throw e; - } - catch (XmlValueDisconnectedException e) { + } + } catch (XmlValueDisconnectedException e) { } } @@ -337,7 +331,7 @@ private void interateLow() throws Exception { execQuery(); break; case 10: - xmlInputStream(); + xmlStreamReader(); break; case 11: docBytes(); @@ -364,31 +358,37 @@ private XmlObject findObject() { XmlCursor c = getCursor(); c.push(); - while (!(c.isContainer() || c.isAttr())) - if (c.toNextToken().isNone()) + while (!(c.isContainer() || c.isAttr())) { + if (c.toNextToken().isNone()) { break; + } + } if (!c.isEnddoc()) { XmlObject x = c.getObject(); c.pop(); - if (x == null) + if (x == null) { throw new IllegalStateException( - "getObject returned null - content must have changed"); + "getObject returned null - content must have changed"); + } return x; } c.pop(); c.push(); - while (!(c.isContainer() || c.isAttr())) - if (c.toPrevToken().isNone()) + while (!(c.isContainer() || c.isAttr())) { + if (c.toPrevToken().isNone()) { break; + } + } XmlObject x = c.getObject(); c.pop(); - if (x == null) + if (x == null) { throw new IllegalStateException( - "getObject returned null - content must have changed"); + "getObject returned null - content must have changed"); + } return x; } @@ -413,11 +413,9 @@ private void changeType() { o = findObject(); SchemaType type = findObject().schemaType(); n = o.changeType(type); - } - catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { return; - } - catch (IllegalStateException e) { + } catch (IllegalStateException e) { return; } @@ -440,38 +438,40 @@ private void newCursor() { private void setName() { XmlCursor c = findObject().newCursor(); - if (!c.isStartdoc()) + if (!c.isStartdoc()) { c.setName(getQName()); + } c.dispose(); } private void newDomNode() { - if (rnd(5) != 0) + if (rnd(5) != 0) { return; + } try { getCursor().newDomNode(); - } - catch (IllegalStateException e) { + } catch (IllegalStateException e) { } } - private void xmlInputStream() throws Exception { - if (rnd(5) != 0) + private void xmlStreamReader() throws Exception { + if (rnd(5) != 0) { return; + } - XMLInputStream xis; + XMLStreamReader xis; try { - xis = getCursor().newXMLInputStream(); - } - catch (IllegalStateException e) { + xis = getCursor().newXMLStreamReader(); + } catch (IllegalStateException e) { return; } - while (xis.next() != null) - ; + while (xis.hasNext()) { + xis.next(); + } } private void objectSet() { @@ -488,14 +488,17 @@ private void setStrong() { XmlCustomerBean o = (XmlCustomerBean) x; o.setName("Bob"); - if (rnd(2) == 0) + if (rnd(2) == 0) { o.setAge(23); + } - if (rnd(2) == 0) + if (rnd(2) == 0) { o.setMoo(24); + } - if (rnd(2) == 0) + if (rnd(2) == 0) { o.setPoo(200); + } } else if (x instanceof XmlLineItemBean) { XmlLineItemBean o = (XmlLineItemBean) x; o.setPerUnitOunces(new BigDecimal(122.44)); @@ -517,22 +520,25 @@ private void validate() { } private void execQuery() { - if (_noquery) + if (_noquery) { return; + } - if (rnd(20) > 0) + if (rnd(20) > 0) { return; + } QName name = getQName(); String query = - "declare namespace xxx='" + name.getNamespaceURI() + "' " + - ".//xxx:" + name.getLocalPart(); + "declare namespace xxx='" + name.getNamespaceURI() + "' " + + ".//xxx:" + name.getLocalPart(); XmlObject x = getCursor().execQuery(query).getObject(); - if (rnd(3) == 0) + if (rnd(3) == 0) { _docs[rnd(_docs.length)] = x; + } } private void getObject() { @@ -548,19 +554,18 @@ private void compareCursors() { getCursor().isInSameDocument(getCursor()); getCursor().comparePosition(getCursor()); getCursor().isAtSamePositionAs(getCursor()); - } - catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { } } private String[] _xmls = - { - "", - }; + { + "", + }; private String[] _schema_xmls = - { - "\n" + + { + "\n" + "\n" + "David Bau\n" + "Gladwyne, PA\n" + @@ -594,20 +599,20 @@ private void compareCursors() { "\n" + "\n" + "", - }; + }; private void loadDoc() throws Exception { if (rnd(15) == 0) { _docs[rnd(_docs.length)] = - XmlObject.Factory.parse(_xmls[rnd(_xmls.length)]); + XmlObject.Factory.parse(_xmls[rnd(_xmls.length)]); } } private void loadSchemadDoc() throws Exception { if (rnd(4) == 0) { _docs[rnd(_docs.length)] = - XmlObject.Factory.parse( - _schema_xmls[rnd(_schema_xmls.length)]); + XmlObject.Factory.parse( + _schema_xmls[rnd(_schema_xmls.length)]); } } @@ -620,18 +625,19 @@ private void moveCursorRightOneToken() { } private char[] _chars = - { - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - ' ', '<', '>', '&', '-', '?' - }; + { + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + ' ', '<', '>', '&', '-', '?' + }; private void getTextValue() { XmlCursor c = getCursor(); - if (c.isFinish() || c.isNamespace() || c.isText()) + if (c.isFinish() || c.isNamespace() || c.isText()) { return; + } c.getTextValue(); } @@ -639,13 +645,15 @@ private void getTextValue() { private void setTextValue() { XmlCursor c = getCursor(); - if (c.isFinish() || c.isNamespace() || c.isText()) + if (c.isFinish() || c.isNamespace() || c.isText()) { return; + } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); - for (int i = rnd(10); i >= 0; i--) + for (int i = rnd(10); i >= 0; i--) { sb.append(_chars[rnd(_chars.length)]); + } c.setTextValue(sb.toString()); } @@ -653,20 +661,16 @@ private void setTextValue() { private void moveText() { try { getCursor().moveChars(rnd(10), getCursor()); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } private void copyText() { try { getCursor().copyChars(rnd(10), getCursor()); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } @@ -677,33 +681,31 @@ private void removeText() { private void insertComment() { try { getCursor().insertComment("poo"); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } private void insertProcinst() { try { getCursor().insertProcInst("target", "val"); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } private void insertText() { XmlCursor c = getCursor(); - if (c.isAnyAttr() || c.isStartdoc()) + if (c.isAnyAttr() || c.isStartdoc()) { return; + } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); - for (int i = rnd(10); i >= 0; i--) + for (int i = rnd(10); i >= 0; i--) { sb.append(_chars[rnd(_chars.length)]); + } c.insertChars(sb.toString()); } @@ -753,8 +755,9 @@ private QName getQName() { private void insertElem() throws Exception { XmlCursor c = getCursor(); - if (c.isAnyAttr() || c.isStartdoc()) + if (c.isAnyAttr() || c.isStartdoc()) { return; + } c.insertElement(getQName()); } @@ -762,11 +765,13 @@ private void insertElem() throws Exception { public void insertAttr() { XmlCursor c = getCursor(); - while (!c.isEnddoc() && !c.isContainer()) + while (!c.isEnddoc() && !c.isContainer()) { c.toNextToken(); + } - if (c.isEnddoc()) + if (c.isEnddoc()) { return; + } c.toNextToken(); @@ -782,48 +787,41 @@ public void removeXmlContents() { public void copyXmlContents() { try { getCursor().copyXmlContents(getCursor()); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } public void copyXml() { try { getCursor().copyXml(getCursor()); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } public void moveXmlContents() { try { getCursor().moveXmlContents(getCursor()); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } public void moveXml() { try { getCursor().moveXml(getCursor()); - } - catch (IllegalArgumentException e) { - } - catch (IllegalStateException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalStateException e) { } } public void removeXml() { XmlCursor c = getCursor(); - if (!c.isStartdoc() && !c.isFinish()) + if (!c.isStartdoc() && !c.isFinish()) { c.removeXml(); + } } public static class Bookmark extends XmlCursor.XmlBookmark { diff --git a/test/src/scomp/attributes/detailed/AttrGroupTest.java b/src/test/java/scomp/attributes/detailed/AttrGroupTest.java similarity index 95% rename from test/src/scomp/attributes/detailed/AttrGroupTest.java rename to src/test/java/scomp/attributes/detailed/AttrGroupTest.java index c9124ae..f0abab3 100644 --- a/test/src/scomp/attributes/detailed/AttrGroupTest.java +++ b/src/test/java/scomp/attributes/detailed/AttrGroupTest.java @@ -15,21 +15,21 @@ package scomp.attributes.detailed; +import org.apache.xmlbeans.*; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.attribute.attributeGroup.AttGroupEltDocument; import xbean.scomp.attribute.attributeGroup.GlobalT; -import org.apache.xmlbeans.*; import javax.xml.namespace.QName; import java.math.BigDecimal; import java.math.BigInteger; -/** - * - * - * - */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + public class AttrGroupTest extends BaseCase { + @Test public void testAttributeGroup() throws Throwable { AttGroupEltDocument doc = AttGroupEltDocument.Factory.newInstance(); GlobalT elt = doc.addNewAttGroupElt(); @@ -70,7 +70,5 @@ public void testAttributeGroup() throws Throwable { showErrors(); throw t; } - - } } diff --git a/test/src/scomp/attributes/detailed/GlobalAttrDefault.java b/src/test/java/scomp/attributes/detailed/GlobalAttrDefault.java similarity index 87% rename from test/src/scomp/attributes/detailed/GlobalAttrDefault.java rename to src/test/java/scomp/attributes/detailed/GlobalAttrDefault.java index f14cbde..3e28159 100644 --- a/test/src/scomp/attributes/detailed/GlobalAttrDefault.java +++ b/src/test/java/scomp/attributes/detailed/GlobalAttrDefault.java @@ -14,21 +14,21 @@ */ package scomp.attributes.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlException; +import org.junit.Test; +import scomp.common.BaseCase; import xbean.scomp.attribute.globalAttrDefault.GlobalAttrDefaultDocDocument; import xbean.scomp.attribute.globalAttrDefault.GlobalAttrDefaultT; -import scomp.common.BaseCase; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlErrorCodes; -/** - * - * - * - */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + public class GlobalAttrDefault extends BaseCase { /** * If value is missing default should appear */ + @Test public void testMissing() { GlobalAttrDefaultT testDoc = GlobalAttrDefaultDocDocument.Factory.newInstance() @@ -39,6 +39,7 @@ public void testMissing() { /** * Test val preservation */ + @Test public void testPresent() { GlobalAttrDefaultT testDoc = GlobalAttrDefaultDocDocument.Factory.newInstance() @@ -50,20 +51,19 @@ public void testPresent() { /** * Test empty string: should be preserved */ + @Test public void testPresentEmpty() throws Throwable { GlobalAttrDefaultT testDoc = - GlobalAttrDefaultDocDocument.Factory.parse("").getGlobalAttrDefaultDoc(); assertEquals("", testDoc.getTestattribute()); try { - assertTrue(testDoc.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - + assertTrue(testDoc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } } diff --git a/test/src/scomp/attributes/detailed/GlobalAttrFixed.java b/src/test/java/scomp/attributes/detailed/GlobalAttrFixed.java similarity index 94% rename from test/src/scomp/attributes/detailed/GlobalAttrFixed.java rename to src/test/java/scomp/attributes/detailed/GlobalAttrFixed.java index a43a29e..6778ded 100644 --- a/test/src/scomp/attributes/detailed/GlobalAttrFixed.java +++ b/src/test/java/scomp/attributes/detailed/GlobalAttrFixed.java @@ -16,29 +16,24 @@ package scomp.attributes.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlException; +import org.junit.Test; +import scomp.common.BaseCase; import xbean.scomp.attribute.globalAttrFixed.GlobalAttrFixedDocDocument; -import xbean.scomp.attribute.globalAttrFixed.TestattributeStrAttribute; -import xbean.scomp.attribute.globalAttrFixed.TestattributeIntAttribute; import xbean.scomp.attribute.globalAttrFixed.GlobalAttrFixedT; -import scomp.common.BaseCase; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlErrorCodes; import java.math.BigInteger; -import java.util.ArrayList; -/** - * - * - * - */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + public class GlobalAttrFixed extends BaseCase { /** * Missing OK */ + @Test public void testValidMissing() throws Exception { GlobalAttrFixedT testDoc = GlobalAttrFixedDocDocument.Factory.parse("0) + if (errMessage.length() > 0) System.err.println(errMessage); ArrayList exp=new ArrayList(); @@ -86,7 +79,7 @@ public boolean compareErrorCodes(String[] expected) { public String stringOfCodes(String[] errorCodes, ArrayList actual_errorCodes) { - StringBuffer res=new StringBuffer(); + StringBuilder res = new StringBuilder(); res.append("\n Expected codes:\n"); int i=0; for (;i < errorCodes.length; i++ ) diff --git a/test/src/scomp/contentType/complex/detailed/AnonymousTest.java b/src/test/java/scomp/contentType/complex/detailed/AnonymousTest.java similarity index 85% rename from test/src/scomp/contentType/complex/detailed/AnonymousTest.java rename to src/test/java/scomp/contentType/complex/detailed/AnonymousTest.java index a255ff4..7ca3f99 100644 --- a/test/src/scomp/contentType/complex/detailed/AnonymousTest.java +++ b/src/test/java/scomp/contentType/complex/detailed/AnonymousTest.java @@ -15,35 +15,26 @@ package scomp.contentType.complex.detailed; -import xbean.scomp.contentType.anonymous.AnonymousEltDocument.*; -import xbean.scomp.contentType.anonymous.AnonymousMixedEltDocument.*; - -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlInteger; import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlInteger; +import org.junit.Test; import scomp.common.BaseCase; +import xbean.scomp.contentType.anonymous.AnonymousEltDocument.AnonymousElt; +import xbean.scomp.contentType.anonymous.AnonymousMixedEltDocument.AnonymousMixedElt; -/** - * - * - * - */ +import java.math.BigInteger; + +import static org.junit.Assert.*; /** * testing anonymous complex types */ -public class AnonymousTest - extends BaseCase -{ - - - public void testSimpleAnonymous() - throws Throwable - { +public class AnonymousTest extends BaseCase { + @Test + public void testSimpleAnonymous() throws Throwable { AnonymousElt testElt = AnonymousElt.Factory.newInstance(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); XmlInteger ival = XmlInteger.Factory.newInstance(); testElt.xsetChild1(ival); testElt.setChild2(new BigInteger("5")); @@ -70,12 +61,11 @@ public void testSimpleAnonymous() } } - public void testMixedAnonymous() - throws Throwable - { + @Test + public void testMixedAnonymous() throws Throwable { AnonymousMixedElt testElt = AnonymousMixedElt.Factory.newInstance(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); testElt.setChild2(new BigInteger("5")); assertEquals(5, testElt.getChild2().intValue()); assertTrue(XmlInteger.Factory.parse("5") diff --git a/test/src/scomp/contentType/complex/detailed/ComplexContentTest.java b/src/test/java/scomp/contentType/complex/detailed/ComplexContentTest.java similarity index 86% rename from test/src/scomp/contentType/complex/detailed/ComplexContentTest.java rename to src/test/java/scomp/contentType/complex/detailed/ComplexContentTest.java index 3f9ab84..7ab4747 100644 --- a/test/src/scomp/contentType/complex/detailed/ComplexContentTest.java +++ b/src/test/java/scomp/contentType/complex/detailed/ComplexContentTest.java @@ -15,30 +15,24 @@ package scomp.contentType.complex.detailed; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; import scomp.common.BaseCase; -import org.apache.xmlbeans.*; import java.util.ArrayList; -import java.util.List; import java.util.Iterator; -import java.util.Collection; +import java.util.List; -import junit.framework.Assert; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -/** - * - * - * - */ public class ComplexContentTest extends BaseCase { - //TODO: this should be a detailed - // test on a complex elt w/ annotations and other such - public void testRun() { - fail("Implement me"); - } // complex types with simple content whose content is declared via an inline // Issue fixed with Svn revision 165352 + @Test public void testSimpleContentDerivation() { String sInputXsd = "\n" + "\n" + @@ -69,7 +63,7 @@ public void testSimpleContentDerivation() { } catch (XmlException xme) { xme.printStackTrace(); - Assert.fail("XmlException thrown when compiling schema"); + fail("XmlException thrown when compiling schema"); } // check for errors @@ -77,7 +71,7 @@ public void testSimpleContentDerivation() { System.out.println("Xsd Compilation Errors : " + iterator.next()); } if (!errors.isEmpty()) { - Assert.fail("Errors found when compiling schema"); + fail("Errors found when compiling schema"); } } } diff --git a/test/src/scomp/contentType/complex/detailed/ElementOnlyContentTest.java b/src/test/java/scomp/contentType/complex/detailed/ElementOnlyContentTest.java similarity index 96% rename from test/src/scomp/contentType/complex/detailed/ElementOnlyContentTest.java rename to src/test/java/scomp/contentType/complex/detailed/ElementOnlyContentTest.java index 3905d66..e033adc 100644 --- a/test/src/scomp/contentType/complex/detailed/ElementOnlyContentTest.java +++ b/src/test/java/scomp/contentType/complex/detailed/ElementOnlyContentTest.java @@ -15,31 +15,25 @@ package scomp.contentType.complex.detailed; -import junit.framework.TestCase; - -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlInteger; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlErrorCodes; - -import xbean.scomp.contentType.complexTypeTest.EltTypeDocument; -import xbean.scomp.contentType.complexTypeTest.ElementT; +import org.apache.xmlbeans.XmlInteger; +import org.junit.Test; import scomp.common.BaseCase; +import xbean.scomp.contentType.complexTypeTest.ElementT; +import xbean.scomp.contentType.complexTypeTest.EltTypeDocument; + +import java.math.BigInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -/** - * - * - * - */ public class ElementOnlyContentTest extends BaseCase { /** * Element only content - * - * @throws Throwable */ - + @Test public void testElementOnly() throws Throwable { EltTypeDocument doc = EltTypeDocument.Factory.newInstance(); ElementT testElt @@ -72,6 +66,7 @@ public void testElementOnly() throws Throwable { /** * Mixed content is invalid for element only types */ + @Test public void testInvalidContent() { EltTypeDocument doc = EltTypeDocument.Factory.newInstance(); ElementT testElt diff --git a/test/src/scomp/contentType/complex/detailed/EmptyContentTest.java b/src/test/java/scomp/contentType/complex/detailed/EmptyContentTest.java similarity index 90% rename from test/src/scomp/contentType/complex/detailed/EmptyContentTest.java rename to src/test/java/scomp/contentType/complex/detailed/EmptyContentTest.java index 4c1ddde..9f510bf 100644 --- a/test/src/scomp/contentType/complex/detailed/EmptyContentTest.java +++ b/src/test/java/scomp/contentType/complex/detailed/EmptyContentTest.java @@ -14,21 +14,19 @@ */ package scomp.contentType.complex.detailed; -import xbean.scomp.contentType.complexTypeTest.EmptyTypeDocument; -import xbean.scomp.contentType.complexTypeTest.EmptyT; -import xbean.scomp.contentType.complexTypeTest.EmptyMixedTypeDocument; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlString; -import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlString; +import org.junit.Test; import scomp.common.BaseCase; +import xbean.scomp.contentType.complexTypeTest.EmptyT; +import xbean.scomp.contentType.complexTypeTest.EmptyTypeDocument; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -/** - * - * - * - */ public class EmptyContentTest extends BaseCase { + @Test public void testIllegalContent() { EmptyTypeDocument doc = EmptyTypeDocument.Factory.newInstance(); EmptyT elt = doc.addNewEmptyType(); @@ -43,11 +41,12 @@ public void testIllegalContent() { String[] errExpected = new String[]{ XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_NOT_ALLOWED }; - assertTrue(compareErrorCodes(errExpected)); + assertTrue(compareErrorCodes(errExpected)); } - public void testLegalContent() throws XmlException { + @Test + public void testLegalContent() { EmptyTypeDocument doc = EmptyTypeDocument.Factory.newInstance(); EmptyT elt = doc.addNewEmptyType(); assertTrue(!elt.isSetEmptyAttr()); diff --git a/test/src/scomp/contentType/complex/detailed/MixedContentTest.java b/src/test/java/scomp/contentType/complex/detailed/MixedContentTest.java similarity index 89% rename from test/src/scomp/contentType/complex/detailed/MixedContentTest.java rename to src/test/java/scomp/contentType/complex/detailed/MixedContentTest.java index 97cb03d..1595825 100644 --- a/test/src/scomp/contentType/complex/detailed/MixedContentTest.java +++ b/src/test/java/scomp/contentType/complex/detailed/MixedContentTest.java @@ -14,31 +14,29 @@ */ package scomp.contentType.complex.detailed; -import junit.framework.TestCase; -import xbean.scomp.contentType.complexTypeTest.MixedTypeDocument; -import xbean.scomp.contentType.complexTypeTest.MixedT; -import xbean.scomp.contentType.complexTypeTest.MixedFixedEltDocument; - -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlInteger; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlInteger; +import org.junit.Before; +import org.junit.Test; import scomp.common.BaseCase; +import xbean.scomp.contentType.complexTypeTest.MixedFixedEltDocument; +import xbean.scomp.contentType.complexTypeTest.MixedT; +import xbean.scomp.contentType.complexTypeTest.MixedTypeDocument; + +import java.math.BigInteger; + +import static org.junit.Assert.*; -/** - * - * - * - */ public class MixedContentTest extends BaseCase { + @Test public void testElementsOnly() throws Throwable { testElt = doc.addNewMixedType(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); testElt.setChild2(new BigInteger("5")); testElt.setChild3(new BigInteger("1")); testElt.setChild1(new BigInteger("0")); @@ -65,13 +63,13 @@ public void testElementsOnly() throws Throwable { * mixed model in XML 1.0. Under the XML Schema mixed model, the order and * number of child elements appearing in an instance must agree with the * order and number of child elements specified in the model - * @throws Throwable */ - public void testTextOnly() throws Throwable { + @Test + public void testTextOnly() { testElt = doc.addNewMixedType(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); XmlCursor cur = testElt.newCursor(); cur.insertChars("Random mixed content"); assertTrue( !testElt.validate(validateOptions) ); @@ -84,10 +82,11 @@ public void testTextOnly() throws Throwable { } + @Test public void testMixed() throws Throwable { testElt = doc.addNewMixedType(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); testElt.setChild2(new BigInteger("5")); testElt.setChild3(new BigInteger("1")); testElt.setChild1(new BigInteger("0")); @@ -119,6 +118,8 @@ public void testMixed() throws Throwable { "0Random mixed content15" + "1",testElt.xmlText() ); } + + @Test public void testInsertDelete() throws Throwable{ testElt = doc.addNewMixedType(); testElt.setChild2(new BigInteger("5")); @@ -158,14 +159,14 @@ public void testInsertDelete() throws Throwable{ } - /** - * see CR related to CR194159: - -clause 5.2.2.1 of - "Validation Rule: Element Locally Valid (Element)" says - if there is a fixed value constraint, the element may not have element children. - * @throws XmlException - */ + /** + * see CR related to CR194159: + *

      + * clause 5.2.2.1 of + * "Validation Rule: Element Locally Valid (Element)" says + * if there is a fixed value constraint, the element may not have element children. + */ + @Test public void testMixedFixed() throws XmlException{ MixedFixedEltDocument doc= MixedFixedEltDocument.Factory @@ -180,11 +181,12 @@ public void testMixedFixed() throws XmlException{ assertTrue(compareErrorCodes(expected)); } + + @Before public void setUp() { doc = MixedTypeDocument.Factory.newInstance(); - testElt - = doc.getMixedType(); - assertEquals(null, testElt); + testElt = doc.getMixedType(); + assertNull(testElt); super.setUp(); } diff --git a/test/src/scomp/contentType/complex/detailed/NamedTest.java b/src/test/java/scomp/contentType/complex/detailed/NamedTest.java similarity index 91% rename from test/src/scomp/contentType/complex/detailed/NamedTest.java rename to src/test/java/scomp/contentType/complex/detailed/NamedTest.java index b4e4c26..4d64f99 100644 --- a/test/src/scomp/contentType/complex/detailed/NamedTest.java +++ b/src/test/java/scomp/contentType/complex/detailed/NamedTest.java @@ -14,34 +14,29 @@ */ package scomp.contentType.complex.detailed; -import junit.framework.TestCase; - - -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlInteger; import org.apache.xmlbeans.XmlCursor; -import xbean.scomp.contentType.named.NamedEltDocument; +import org.apache.xmlbeans.XmlInteger; +import org.junit.Test; +import scomp.common.BaseCase; import xbean.scomp.contentType.named.ElementT; -import xbean.scomp.contentType.named.NamedMixedEltDocument; import xbean.scomp.contentType.named.MixedT; +import xbean.scomp.contentType.named.NamedEltDocument; +import xbean.scomp.contentType.named.NamedMixedEltDocument; -import scomp.common.BaseCase; +import java.math.BigInteger; + +import static org.junit.Assert.*; -/** - * - * - * - */ public class NamedTest extends BaseCase { + @Test public void testSimpleAnonymous() throws Throwable { NamedEltDocument doc = NamedEltDocument.Factory.newInstance(); ElementT testElt = doc.getNamedElt(); - assertEquals(null, testElt); + assertNull(testElt); testElt = doc.addNewNamedElt(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); testElt.setChild2(new BigInteger("5")); testElt.setChild3(new BigInteger("1")); assertEquals("5" + @@ -60,15 +55,16 @@ public void testSimpleAnonymous() throws Throwable { } } + @Test public void testMixedAnonymous() throws Throwable { NamedMixedEltDocument doc = NamedMixedEltDocument.Factory.newInstance(); MixedT testElt = doc.getNamedMixedElt(); - assertEquals(null, testElt); + assertNull(testElt); testElt = doc.addNewNamedMixedElt(); - assertEquals(null, testElt.getChild1()); - assertEquals(null, testElt.xgetChild1()); + assertNull(testElt.getChild1()); + assertNull(testElt.xgetChild1()); testElt.setChild2(new BigInteger("5")); assertEquals(5, testElt.getChild2().intValue()); XmlInteger expected = XmlInteger.Factory.newInstance(); diff --git a/src/test/java/scomp/contentType/complex/modelGroup/detailed/AllTest.java b/src/test/java/scomp/contentType/complex/modelGroup/detailed/AllTest.java new file mode 100644 index 0000000..c6b4e7e --- /dev/null +++ b/src/test/java/scomp/contentType/complex/modelGroup/detailed/AllTest.java @@ -0,0 +1,81 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package scomp.contentType.complex.modelGroup.detailed; + +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlException; +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.contentType.modelGroup.AllEltDocument; +import xbean.scomp.contentType.modelGroup.AllT; + +import java.math.BigInteger; + +import static org.junit.Assert.assertTrue; + +public class AllTest extends BaseCase { + + /** + * Instance should be valid w/ child1 missing + */ + @Test + public void testChild1Optional() { + doc = AllEltDocument.Factory.newInstance(); + AllT elt = doc.addNewAllElt(); + elt.setChild2("doo"); + elt.setChild3(BigInteger.ONE); + assertTrue(doc.validate(validateOptions)); + } + + /** + * All group doesn't care about field order + */ + @Test + public void testOrder() throws XmlException { + String input = + "" + + "52bar" + + ""; + doc = AllEltDocument.Factory.parse(input); + assertTrue(doc.validate(validateOptions)); + } + + /** + * maxOccurs is always 1 + */ + @Test + public void testIllegal() throws XmlException { + String input = + "" + + "52bar" + + ""; + doc = AllEltDocument.Factory.parse(input); + assertTrue(!doc.validate(validateOptions)); + showErrors(); + //$TODO: QUESTIONABLE ERRORS: if 2 is replaced by 2 + //all will be good: why 2 errors? + String[] errExpected = { + XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT, +// XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_NOT_ALLOWED, +// XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_ELEMENT + }; + assertTrue(compareErrorCodes(errExpected)); + + } + + + private AllEltDocument doc; +} diff --git a/test/src/scomp/contentType/complex/modelGroup/detailed/ChoiceTest.java b/src/test/java/scomp/contentType/complex/modelGroup/detailed/ChoiceTest.java similarity index 95% rename from test/src/scomp/contentType/complex/modelGroup/detailed/ChoiceTest.java rename to src/test/java/scomp/contentType/complex/modelGroup/detailed/ChoiceTest.java index 6487fd2..d14cc24 100644 --- a/test/src/scomp/contentType/complex/modelGroup/detailed/ChoiceTest.java +++ b/src/test/java/scomp/contentType/complex/modelGroup/detailed/ChoiceTest.java @@ -15,25 +15,23 @@ package scomp.contentType.complex.modelGroup.detailed; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; +import scomp.common.BaseCase; import xbean.scomp.contentType.modelGroup.ChoiceEltDocument; import xbean.scomp.contentType.modelGroup.ChoiceT; import xbean.scomp.contentType.modelGroup.MixedChoiceEltDocument; import xbean.scomp.contentType.modelGroup.MixedChoiceT; -import scomp.common.BaseCase; import java.math.BigInteger; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlErrorCodes; - -/** - * - * - * - */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; //TODO: assert that order of elements in a choice group doesn't matter public class ChoiceTest extends BaseCase { + @Test public void testValidCase() throws Throwable { ChoiceEltDocument doc = ChoiceEltDocument.Factory.newInstance(); ChoiceT elt = doc.addNewChoiceElt(); @@ -49,6 +47,7 @@ public void testValidCase() throws Throwable { //more than 1 from choice group //TODO: test should pass but error message not good + @Test public void testChoiceViolation() throws Throwable { ChoiceEltDocument doc = ChoiceEltDocument.Factory.newInstance(); ChoiceT elt = doc.addNewChoiceElt(); diff --git a/test/src/scomp/contentType/complex/modelGroup/detailed/NestSequenceChoiceTest.java b/src/test/java/scomp/contentType/complex/modelGroup/detailed/NestSequenceChoiceTest.java similarity index 97% rename from test/src/scomp/contentType/complex/modelGroup/detailed/NestSequenceChoiceTest.java rename to src/test/java/scomp/contentType/complex/modelGroup/detailed/NestSequenceChoiceTest.java index cc4bd72..39a9b70 100644 --- a/test/src/scomp/contentType/complex/modelGroup/detailed/NestSequenceChoiceTest.java +++ b/src/test/java/scomp/contentType/complex/modelGroup/detailed/NestSequenceChoiceTest.java @@ -14,20 +14,19 @@ */ package scomp.contentType.complex.modelGroup.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.contentType.modelGroup.NestedChoiceInSequenceDocument; import xbean.scomp.contentType.modelGroup.NestedChoiceInSequenceT; -import org.apache.xmlbeans.XmlErrorCodes; -/** - * - * - * - */ +import static org.junit.Assert.assertTrue; + public class NestSequenceChoiceTest extends BaseCase { /** * Choice group is optional */ + @Test public void testChoiceMissing() throws Throwable { NestedChoiceInSequenceDocument doc = NestedChoiceInSequenceDocument.Factory.newInstance(); @@ -42,9 +41,9 @@ public void testChoiceMissing() throws Throwable { showErrors(); throw t; } - } + @Test public void testAllPresent() throws Throwable { NestedChoiceInSequenceDocument doc = NestedChoiceInSequenceDocument.Factory.newInstance(); @@ -85,6 +84,7 @@ public void testAllPresent() throws Throwable { /** * Missing elt. from the sequence in the choice */ + @Test public void testIllegal() throws Throwable { NestedChoiceInSequenceDocument doc = NestedChoiceInSequenceDocument.Factory.newInstance(); @@ -110,12 +110,12 @@ public void testIllegal() throws Throwable { showErrors(); throw t; } - } /** * Incorrect order in inner sequence */ + @Test public void testIllegalOrderInner() throws Throwable { String input = "" + @@ -42,10 +42,9 @@ public void testWrongOrder() throws Throwable { String[] errExpected = new String[]{ XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT}; assertTrue(compareErrorCodes(errExpected)); - - } + @Test public void testWrongCardinality() { SequenceEltDocument doc = SequenceEltDocument.Factory.newInstance(); SequenceT elt = doc.addNewSequenceElt(); diff --git a/test/src/scomp/contentType/simple/detailed/BuiltInType.java b/src/test/java/scomp/contentType/simple/detailed/BuiltInType.java similarity index 96% rename from test/src/scomp/contentType/simple/detailed/BuiltInType.java rename to src/test/java/scomp/contentType/simple/detailed/BuiltInType.java index 6a61cda..a85c8d6 100644 --- a/test/src/scomp/contentType/simple/detailed/BuiltInType.java +++ b/src/test/java/scomp/contentType/simple/detailed/BuiltInType.java @@ -15,27 +15,24 @@ package scomp.contentType.simple.detailed; +import org.apache.xmlbeans.*; +import org.junit.Test; import scomp.common.BaseCase; -import xbean.scomp.contentType.builtIn.string.*; -import xbean.scomp.contentType.builtIn.number.*; import xbean.scomp.contentType.builtIn.date.*; -import org.apache.xmlbeans.*; +import xbean.scomp.contentType.builtIn.number.*; +import xbean.scomp.contentType.builtIn.string.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; -/** - * - * - * - */ +import static org.junit.Assert.*; + public class BuiltInType extends BaseCase { /** * testing types String, normalizedString and token - * - * @throws Throwable */ + @Test public void testStringBasedTypes1() throws Throwable { String[] exp = new String[]{ "\tLead tab,A string on\n 2 lines with 2 spaces", @@ -79,10 +76,9 @@ public void testStringBasedTypes1() throws Throwable { /** * testing types Name, NCName, Language - * - * @throws Throwable */ - public void testStringBasedTypes2() throws Throwable { + @Test + public void testStringBasedTypes2() { NameEltDocument nameDoc = NameEltDocument.Factory.newInstance(); nameDoc.setNameElt("_eltName"); assertTrue(nameDoc.validate(validateOptions)); @@ -133,7 +129,7 @@ public void testStringBasedTypes2() throws Throwable { } private String buildString(String Elt, boolean leadSpace) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("<" + Elt); sb.append(" xmlns=\"http://xbean/scomp/contentType/builtIn/String\">"); if (leadSpace) @@ -144,6 +140,7 @@ private String buildString(String Elt, boolean leadSpace) { return sb.toString(); } + @Test public void testNumericypes() throws Throwable { FloatEltDocument flDoc = FloatEltDocument @@ -152,11 +149,11 @@ public void testNumericypes() throws Throwable { ">12.34e+5"); assertTrue(flDoc.validate(validateOptions)); flDoc.setFloatElt(13.5f); - assertTrue(13.5f == flDoc.getFloatElt()); + assertEquals(13.5f, flDoc.getFloatElt(), 0.0); DoubleEltDocument doubDoc = DoubleEltDocument.Factory.newInstance(); - assertTrue(0 == doubDoc.getDoubleElt()); + assertEquals(0, doubDoc.getDoubleElt(), 0.0); XmlDouble val = XmlDouble.Factory.newInstance(); val.setDoubleValue(13.4d); doubDoc.xsetDoubleElt(val); @@ -169,7 +166,7 @@ public void testNumericypes() throws Throwable { assertTrue(decDoc.validate(validateOptions)); BigDecimal bdval = new BigDecimal(new BigInteger("10")); decDoc.setDecimalElt(bdval); - assertTrue(bdval == decDoc.getDecimalElt()); + assertSame(bdval, decDoc.getDecimalElt()); IntegerEltDocument integerDoc = IntegerEltDocument.Factory.parse("124353"); assertTrue(decDoc.validate(validateOptions)); integerDoc.setIntegerElt(BigInteger.ONE); - assertTrue(BigInteger.ONE == integerDoc.getIntegerElt()); + assertSame(BigInteger.ONE, integerDoc.getIntegerElt()); LongEltDocument longDoc = LongEltDocument.Factory.newInstance(); @@ -199,7 +196,7 @@ public void testNumericypes() throws Throwable { " xmlns=\"http://xbean/scomp/contentType/builtIn/Number\"" + ">-32768"); assertTrue(shDoc.validate(validateOptions)); - assertTrue(-32768 == shDoc.xgetShortElt().getShortValue()); + assertEquals(-32768, shDoc.xgetShortElt().getShortValue()); //largest short is 32767. Don't use set--it would wrap around shDoc = ShortEltDocument.Factory.parse("-0000000"); - assertTrue(0 == nonposIntDoc.getNonPosIntElt().intValue()); + assertEquals(0, nonposIntDoc.getNonPosIntElt().intValue()); assertTrue(nonposIntDoc.validate(validateOptions)); //should be valid but javac complains is setter is called nonposIntDoc = @@ -277,6 +274,7 @@ public void testNumericypes() throws Throwable { } + @Test public void testDateTime() throws Throwable { DateEltDocument date = DateEltDocument.Factory.newInstance(); diff --git a/test/src/scomp/contentType/simple/detailed/ListType.java b/src/test/java/scomp/contentType/simple/detailed/ListType.java similarity index 97% rename from test/src/scomp/contentType/simple/detailed/ListType.java rename to src/test/java/scomp/contentType/simple/detailed/ListType.java index e9b2ac0..0272044 100644 --- a/test/src/scomp/contentType/simple/detailed/ListType.java +++ b/src/test/java/scomp/contentType/simple/detailed/ListType.java @@ -15,24 +15,21 @@ package scomp.contentType.simple.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlSimpleList; +import org.apache.xmlbeans.impl.values.XmlValueNotSupportedException; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.contentType.list.*; -import java.util.List; -import java.util.LinkedList; import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.apache.xmlbeans.impl.values.XmlValueNotSupportedException; -import org.apache.xmlbeans.XmlSimpleList; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.*; -/** - * - * - * - */ public class ListType extends BaseCase { + @Test public void testListTypeAnonymous() throws Throwable { ListEltTokenDocument doc = ListEltTokenDocument.Factory.newInstance(); @@ -67,6 +64,7 @@ public void testListTypeAnonymous() throws Throwable { } + @Test public void testListTypeGlobal() throws Throwable { String input = "" + + " Bob25G" + + ""); + + assertTrue(!doc.validate(validateOptions)); + showErrors(); + } + + @Test + public void testElementConcrete() throws Throwable { + EltConcreteDocument doc = EltConcreteDocument.Factory.parse( + "" + + " Bob25G" + + ""); + assertTrue(!doc.validate(validateOptions)); + showErrors(); + } +} diff --git a/test/src/scomp/derivation/detailed/BlockTest.java b/src/test/java/scomp/derivation/detailed/BlockTest.java similarity index 97% rename from test/src/scomp/derivation/detailed/BlockTest.java rename to src/test/java/scomp/derivation/detailed/BlockTest.java index 250a921..2b01532 100644 --- a/test/src/scomp/derivation/detailed/BlockTest.java +++ b/src/test/java/scomp/derivation/detailed/BlockTest.java @@ -14,19 +14,18 @@ */ package scomp.derivation.detailed; -import xbean.scomp.derivation.finalBlockDefault.EltNoBlockDocument; -import xbean.scomp.derivation.finalBlockDefault.EltDefaultBlockDocument; -import xbean.scomp.derivation.block.*; -import scomp.common.BaseCase; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.derivation.block.*; +import xbean.scomp.derivation.finalBlockDefault.EltDefaultBlockDocument; +import xbean.scomp.derivation.finalBlockDefault.EltNoBlockDocument; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -/** - * - * - * - */ public class BlockTest extends BaseCase { String restrContentValid = "Bobby20"; String restrContentInvalid = "Bobby40"; @@ -36,7 +35,7 @@ public String getInstance(String elt, String type, boolean ext, boolean valid) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("\n" + " \n" + @@ -211,6 +209,7 @@ public void testFinalAll() { } + @Test public void testFinalExtension() { String inputXsd = " \n" + " \n" + @@ -247,6 +246,7 @@ public void testFinalExtension() { } } + @Test public void testFinalRestriction() { String inputXsd = " \n" + " \n" + @@ -282,6 +282,7 @@ public void testFinalRestriction() { } } + @Test public void testFinalRestrExt() { String inputXsd = " \n" + " \n" + @@ -341,7 +342,5 @@ public void testFinalRestrExt() { System.out.println("Err:" + eacherr.getMessage()); assertNotNull(eacherr.getErrorCode()); assertEquals(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$FINAL, eacherr.getErrorCode()); - } - } diff --git a/test/src/scomp/derivation/extension/detailed/EmptyContentExtension.java b/src/test/java/scomp/derivation/extension/detailed/EmptyContentExtension.java similarity index 95% rename from test/src/scomp/derivation/extension/detailed/EmptyContentExtension.java rename to src/test/java/scomp/derivation/extension/detailed/EmptyContentExtension.java index a5fd331..090bf70 100644 --- a/test/src/scomp/derivation/extension/detailed/EmptyContentExtension.java +++ b/src/test/java/scomp/derivation/extension/detailed/EmptyContentExtension.java @@ -14,16 +14,15 @@ */ package scomp.derivation.extension.detailed; +import org.junit.Test; +import scomp.common.BaseCase; import xbean.scomp.derivation.emtpy.ExtendedEmptyEltDocument; import xbean.scomp.derivation.emtpy.ExtendedEmptyT; -import scomp.common.BaseCase; -/** - * @owner: ykadiysk - * Date: Jul 21, 2004 - * Time: 10:18:48 AM - */ +import static org.junit.Assert.assertTrue; + public class EmptyContentExtension extends BaseCase{ + @Test public void testEmptyElementContent() throws Throwable{ ExtendedEmptyEltDocument doc=ExtendedEmptyEltDocument.Factory.newInstance(); ExtendedEmptyT elt=doc.addNewExtendedEmptyElt(); diff --git a/test/src/scomp/derivation/extension/detailed/MixedContentExtension.java b/src/test/java/scomp/derivation/extension/detailed/MixedContentExtension.java similarity index 96% rename from test/src/scomp/derivation/extension/detailed/MixedContentExtension.java rename to src/test/java/scomp/derivation/extension/detailed/MixedContentExtension.java index 8caed6c..24ede6a 100644 --- a/test/src/scomp/derivation/extension/detailed/MixedContentExtension.java +++ b/src/test/java/scomp/derivation/extension/detailed/MixedContentExtension.java @@ -15,22 +15,20 @@ package scomp.derivation.extension.detailed; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.derivation.complexExtension.ExtendedMixedEltDocument; import xbean.scomp.derivation.complexExtension.ExtendedMixedT; import java.math.BigInteger; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -/** - * - * - * - */ public class MixedContentExtension extends BaseCase { - + @Test public void testMixedContentInvalid() throws Throwable { ExtendedMixedEltDocument doc = ExtendedMixedEltDocument. Factory.newInstance(); @@ -73,7 +71,7 @@ public void testMixedContentInvalid() throws Throwable { } - + @Test public void testMixedContentValid() throws Throwable { ExtendedMixedEltDocument doc = ExtendedMixedEltDocument. Factory.newInstance(); diff --git a/test/src/scomp/derivation/extension/detailed/SimpleTypeExtensionTest.java b/src/test/java/scomp/derivation/extension/detailed/SimpleTypeExtensionTest.java similarity index 97% rename from test/src/scomp/derivation/extension/detailed/SimpleTypeExtensionTest.java rename to src/test/java/scomp/derivation/extension/detailed/SimpleTypeExtensionTest.java index edf5e4f..d4edf71 100644 --- a/test/src/scomp/derivation/extension/detailed/SimpleTypeExtensionTest.java +++ b/src/test/java/scomp/derivation/extension/detailed/SimpleTypeExtensionTest.java @@ -15,18 +15,17 @@ package scomp.derivation.extension.detailed; +import org.junit.Test; import xbean.scomp.derivation.simpleExtension.SimpleExtensionEltDocument; import xbean.scomp.derivation.simpleExtension.SimpleExtensionT; import scomp.common.BaseCase; import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -/** - * - * - * - */ +import static org.junit.Assert.*; + public class SimpleTypeExtensionTest extends BaseCase { + @Test public void testExtension() throws Throwable { SimpleExtensionEltDocument doc = SimpleExtensionEltDocument.Factory.newInstance(); SimpleExtensionT elt = doc.addNewSimpleExtensionElt(); diff --git a/test/src/scomp/derivation/restriction/detailed/AttrWCRestriction.java b/src/test/java/scomp/derivation/restriction/detailed/AttrWCRestriction.java similarity index 98% rename from test/src/scomp/derivation/restriction/detailed/AttrWCRestriction.java rename to src/test/java/scomp/derivation/restriction/detailed/AttrWCRestriction.java index 5c1ac56..9c6fb6c 100644 --- a/test/src/scomp/derivation/restriction/detailed/AttrWCRestriction.java +++ b/src/test/java/scomp/derivation/restriction/detailed/AttrWCRestriction.java @@ -15,19 +15,20 @@ package scomp.derivation.restriction.detailed; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.derivation.attributeWCRestriction.*; import org.apache.xmlbeans.XmlErrorCodes; -/** - * - */ +import static org.junit.Assert.assertTrue; + public class AttrWCRestriction extends BaseCase { String input; /** * Replace a wildcard with a concrete attribute * No other attr should be valid here */ + @Test public void testAny2Instance() throws Throwable{ input=" @@ -45,6 +47,7 @@ public class ElementRestriction extends BaseCase { * * */ + @Test public void testRestrictedElement() throws Throwable { ElementDocument doc = ElementDocument.Factory.newInstance(); RestrictedEltT elt = doc.addNewElement(); @@ -69,7 +72,7 @@ public void testRestrictedElement() throws Throwable { XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_VALID_MIXED_CONTENT, XmlErrorCodes.DATATYPE_FRACTION_DIGITS_VALID, }; - assertTrue(compareErrorCodes(errExpected)); + assertTrue(compareErrorCodes(errExpected)); elt.removeA(2); diff --git a/test/src/scomp/derivation/restriction/detailed/ElementWCRestriction.java b/src/test/java/scomp/derivation/restriction/detailed/ElementWCRestriction.java similarity index 95% rename from test/src/scomp/derivation/restriction/detailed/ElementWCRestriction.java rename to src/test/java/scomp/derivation/restriction/detailed/ElementWCRestriction.java index 0e94218..2351a2e 100644 --- a/test/src/scomp/derivation/restriction/detailed/ElementWCRestriction.java +++ b/src/test/java/scomp/derivation/restriction/detailed/ElementWCRestriction.java @@ -15,9 +15,14 @@ package scomp.derivation.restriction.detailed; -import scomp.common.BaseCase; -import xbean.scomp.derivation.elementWCRestriction.*; import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.derivation.elementWCRestriction.ConcreteEltDocument; +import xbean.scomp.derivation.elementWCRestriction.OtherLaxDocument; +import xbean.scomp.derivation.elementWCRestriction.UriSkipDocument; + +import static org.junit.Assert.assertTrue; /** * @@ -27,6 +32,7 @@ public class ElementWCRestriction extends BaseCase { // max occurs is now 2, not 3 //NS restricted from any to other + @Test public void testMaxOccurs() throws Throwable { String input = "\n" + "\n" + diff --git a/test/src/scomp/derivation/restriction/detailed/GroupRestrictionTest.java b/src/test/java/scomp/derivation/restriction/detailed/GroupRestrictionTest.java similarity index 97% rename from test/src/scomp/derivation/restriction/detailed/GroupRestrictionTest.java rename to src/test/java/scomp/derivation/restriction/detailed/GroupRestrictionTest.java index 523a719..e70b802 100644 --- a/test/src/scomp/derivation/restriction/detailed/GroupRestrictionTest.java +++ b/src/test/java/scomp/derivation/restriction/detailed/GroupRestrictionTest.java @@ -14,18 +14,21 @@ */ package scomp.derivation.restriction.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.derivation.groupRestriction.*; import java.math.BigInteger; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertTrue; /** * */ public class GroupRestrictionTest extends BaseCase { + @Test public void testRestrictSequence() throws Throwable { RestrictedSequenceEltDocument doc = RestrictedSequenceEltDocument.Factory .newInstance(); @@ -51,6 +54,7 @@ public void testRestrictSequence() throws Throwable { } + @Test public void testRestrictChoice() throws Throwable { RestrictedChoiceEltDocument doc = RestrictedChoiceEltDocument.Factory .newInstance(); @@ -73,6 +77,7 @@ public void testRestrictChoice() throws Throwable { } + @Test public void testRestrictAll() throws Throwable { RestrictedAllEltDocument doc = RestrictedAllEltDocument.Factory .newInstance(); @@ -95,6 +100,7 @@ public void testRestrictAll() throws Throwable { } } + @Test public void testAllToSequence() throws Throwable { All2SeqEltDocument doc = All2SeqEltDocument.Factory.newInstance(); All2SequenceT elt = doc.addNewAll2SeqElt(); @@ -117,6 +123,7 @@ public void testAllToSequence() throws Throwable { } + @Test public void testChoiceToSequence() throws Throwable { Choice2SeqEltDocument doc = Choice2SeqEltDocument.Factory.newInstance(); Choice2SequenceT elt = doc.addNewChoice2SeqElt(); diff --git a/test/src/scomp/derivation/restriction/detailed/MixedContentRestriction.java b/src/test/java/scomp/derivation/restriction/detailed/MixedContentRestriction.java similarity index 98% rename from test/src/scomp/derivation/restriction/detailed/MixedContentRestriction.java rename to src/test/java/scomp/derivation/restriction/detailed/MixedContentRestriction.java index a00225f..8968a04 100644 --- a/test/src/scomp/derivation/restriction/detailed/MixedContentRestriction.java +++ b/src/test/java/scomp/derivation/restriction/detailed/MixedContentRestriction.java @@ -14,6 +14,7 @@ */ package scomp.derivation.restriction.detailed; +import org.junit.Test; import xbean.scomp.derivation.mixedContentRestriction.*; import scomp.common.BaseCase; @@ -23,11 +24,10 @@ import org.apache.xmlbeans.XmlErrorCodes; import org.apache.xmlbeans.impl.values.XmlValueNotSupportedException; -/** - * - */ -public class MixedContentRestriction extends BaseCase{ +import static org.junit.Assert.*; +public class MixedContentRestriction extends BaseCase{ + @Test public void testRestrictedMixed() throws Throwable{ MixedEltDocument doc=MixedEltDocument.Factory.newInstance(); RestrictedMixedT elt=doc.addNewMixedElt(); @@ -49,8 +49,9 @@ public void testRestrictedMixed() throws Throwable{ assertEquals("" + "10My chars0" + "", elt.xmlText()); - } + + @Test public void testRestrictedEltOnly() throws Throwable{ ElementOnlyEltDocument doc=ElementOnlyEltDocument.Factory.newInstance(); RestrictedEltT elt=doc.addNewElementOnlyElt(); @@ -87,8 +88,9 @@ public void testRestrictedEltOnly() throws Throwable{ } + //seems that this is not a valid example p.329 top - //public void testRestrictedMixedToSimple() throws Throwable{} + @Test public void testRestrictedMixedToEmpty() throws Throwable{ Mixed2EmptyEltDocument doc=Mixed2EmptyEltDocument.Factory.newInstance(); Mixed2EmptyT elt=doc.addNewMixed2EmptyElt(); diff --git a/test/src/scomp/derivation/restriction/detailed/SimpleContentRestrictionTest.java b/src/test/java/scomp/derivation/restriction/detailed/SimpleContentRestrictionTest.java similarity index 95% rename from test/src/scomp/derivation/restriction/detailed/SimpleContentRestrictionTest.java rename to src/test/java/scomp/derivation/restriction/detailed/SimpleContentRestrictionTest.java index bae117b..ba2a40d 100644 --- a/test/src/scomp/derivation/restriction/detailed/SimpleContentRestrictionTest.java +++ b/src/test/java/scomp/derivation/restriction/detailed/SimpleContentRestrictionTest.java @@ -14,15 +14,16 @@ */ package scomp.derivation.restriction.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; +import scomp.common.BaseCase; import xbean.scomp.derivation.simpleExtension.SimpleRestrictionEltDocument; import xbean.scomp.derivation.simpleExtension.SimpleRestrictionT; -import scomp.common.BaseCase; -import org.apache.xmlbeans.XmlErrorCodes; -/** - * - */ +import static org.junit.Assert.assertTrue; + public class SimpleContentRestrictionTest extends BaseCase { + @Test public void testLegalValues() throws Throwable { SimpleRestrictionEltDocument doc = SimpleRestrictionEltDocument.Factory.newInstance(); SimpleRestrictionT elt = doc.addNewSimpleRestrictionElt(); @@ -33,9 +34,9 @@ public void testLegalValues() throws Throwable { showErrors(); throw t; } - } + @Test public void testIllegalValues() throws Throwable { SimpleRestrictionEltDocument doc = SimpleRestrictionEltDocument.Factory.newInstance(); SimpleRestrictionT elt = doc.addNewSimpleRestrictionElt(); @@ -48,7 +49,5 @@ public void testIllegalValues() throws Throwable { XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID }; assertTrue(compareErrorCodes(errExpected)); - - } } diff --git a/test/src/scomp/derivation/restriction/detailed/SimpleTypeRestriction.java b/src/test/java/scomp/derivation/restriction/detailed/SimpleTypeRestriction.java similarity index 84% rename from test/src/scomp/derivation/restriction/detailed/SimpleTypeRestriction.java rename to src/test/java/scomp/derivation/restriction/detailed/SimpleTypeRestriction.java index 2ec7dbb..d4afce1 100644 --- a/test/src/scomp/derivation/restriction/detailed/SimpleTypeRestriction.java +++ b/src/test/java/scomp/derivation/restriction/detailed/SimpleTypeRestriction.java @@ -16,35 +16,33 @@ package scomp.derivation.restriction.detailed; +import org.junit.Test; import scomp.common.BaseCase; -import xbean.scomp.derivation.simpleTypeRestriction.SmallPantSizeEltDocument; -import xbean.scomp.derivation.facets.dateTimePattern.DateTimesDocument; import xbean.scomp.derivation.facets.dateTimePattern.DateTimes; -import xbean.scomp.contentType.simpleType.PantSizeEltDocument; -import xbean.scomp.contentType.simpleType.PantSize; +import xbean.scomp.derivation.facets.dateTimePattern.DateTimesDocument; +import xbean.scomp.derivation.simpleTypeRestriction.SmallPantSizeEltDocument; import java.util.Calendar; import java.util.GregorianCalendar; -/** - * - */ +import static org.junit.Assert.assertTrue; + public class SimpleTypeRestriction extends BaseCase{ + @Test public void testPatternRestriction()throws Throwable{ - SmallPantSizeEltDocument doc=SmallPantSizeEltDocument.Factory.newInstance(); - doc.setSmallPantSizeElt(8); - //doc.setSmallPantSizeElt(6); - try { + SmallPantSizeEltDocument doc = SmallPantSizeEltDocument.Factory.newInstance(); + doc.setSmallPantSizeElt(8); + //doc.setSmallPantSizeElt(6); + try { assertTrue(doc.validate(validateOptions)); - } - catch (Throwable t) { + } catch (Throwable t) { showErrors(); throw t; } } - //user-list inspired + @Test public void testDateTimeRestriction() throws Throwable{ DateTimesDocument doc= DateTimesDocument.Factory.newInstance(); diff --git a/src/test/java/scomp/derivation/restriction/detailed/SubstitutionTest.java b/src/test/java/scomp/derivation/restriction/detailed/SubstitutionTest.java new file mode 100644 index 0000000..429ed32 --- /dev/null +++ b/src/test/java/scomp/derivation/restriction/detailed/SubstitutionTest.java @@ -0,0 +1,66 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package scomp.derivation.restriction.detailed; + +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.contentType.modelGroup.ChoiceEltDocument; +import xbean.scomp.contentType.simpleType.PantSizeEltDocument; + +import static org.junit.Assert.assertTrue; + +public class SubstitutionTest extends BaseCase { + @Test + public void testSubstitution() throws Throwable{ + ChoiceEltDocument doc= + ChoiceEltDocument.Factory.parse( + "" + + "50" + + "" + ); + try { + assertTrue(doc.validate(validateOptions)); + } + catch (Throwable t) { + showErrors(); + throw t; + } + } + + @Test + public void testSimpleTypeSubstitution() throws Throwable{ + PantSizeEltDocument doc = + PantSizeEltDocument.Factory.parse( + "" + + "8" + + "" + ); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + } +} diff --git a/src/test/java/scomp/derivation/restriction/facets/detailed/FacetRestrictionTest.java b/src/test/java/scomp/derivation/restriction/facets/detailed/FacetRestrictionTest.java new file mode 100644 index 0000000..a1a1a7f --- /dev/null +++ b/src/test/java/scomp/derivation/restriction/facets/detailed/FacetRestrictionTest.java @@ -0,0 +1,261 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package scomp.derivation.restriction.facets.detailed; + +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.derivation.facets.facetRestriction.*; + +import java.math.BigDecimal; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class FacetRestrictionTest extends BaseCase { + @Test + public void testMinMaxInclusiveElt() throws Throwable { + MinMaxInclusiveEltDocument doc = + MinMaxInclusiveEltDocument.Factory.newInstance(); + doc.setMinMaxInclusiveElt(3); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID}; + + doc.setMinMaxInclusiveElt(2); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + + clearErrors(); + errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID}; + doc.setMinMaxInclusiveElt(10); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + + } + + @Test + public void testMinMaxInclusiveDateElt() throws Throwable { + MinMaxInclusiveDateEltDocument doc = + MinMaxInclusiveDateEltDocument.Factory.newInstance(); + TimeZone tz = TimeZone.getDefault(); + Calendar c = new GregorianCalendar(tz); + c.set(2003, 11, 22); + doc.setMinMaxInclusiveDateElt(c); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + c = new GregorianCalendar(2003, 11, 24); + doc.setMinMaxInclusiveDateElt(c); + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID}; + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + } + + @Test + public void testMinMaxExclusiveElt() throws Throwable { + MinMaxExclusiveEltDocument doc = + MinMaxExclusiveEltDocument.Factory.newInstance(); + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID}; + + doc.setMinMaxExclusiveElt(3); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + clearErrors(); + + doc.setMinMaxExclusiveElt(4); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + doc.setMinMaxExclusiveElt(8); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + + } + + @Test + public void testMinMaxExclusiveDateElt() throws Throwable { + MinMaxExclusiveDateEltDocument doc = MinMaxExclusiveDateEltDocument.Factory.newInstance(); + Calendar c = new GregorianCalendar(2003, 11, 24); + doc.setMinMaxExclusiveDateElt(c); + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID}; + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + clearErrors(); + c = new GregorianCalendar(2003, 11, 23); + doc.setMinMaxExclusiveDateElt(c); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + } + + @Test + public void testMinMaxLengthElt() throws Throwable { + MinMaxLengthEltDocument doc = MinMaxLengthEltDocument.Factory.newInstance(); + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING}; + + doc.setMinMaxLengthElt("fooba"); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + + doc.setMinMaxLengthElt("fo"); + errExpected = new String[]{ + XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING}; + clearErrors(); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + + doc.setMinMaxLengthElt("foo"); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + doc.setMinMaxLengthElt("foob"); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + + } + + @Test + public void testDigitsElt() throws Throwable { + DigitsEltDocument doc = DigitsEltDocument.Factory.newInstance(); + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID}; + + doc.setDigitsElt(new BigDecimal("122.2")); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + + doc.setDigitsElt(new BigDecimal("12.3")); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + clearErrors(); + errExpected = new String[]{ + XmlErrorCodes.DATATYPE_FRACTION_DIGITS_VALID}; + doc.setDigitsElt(new BigDecimal("2.45")); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + } + + @Test + public void testWSElt() throws Throwable { + + // whiteSpace="replace" case + WSReplaceEltDocument doc = WSReplaceEltDocument.Factory.parse("" + + " This is a test.\nThe resulting string should convert tabs \t, line feeds \n and carriage returns into a single space \n" + + ""); + + // whiteSpace="collapse " case + WSCollapseEltDocument doc2 = WSCollapseEltDocument.Factory.parse("" + + " This is a test.\nThe resulting string should convert tabs \t, line feeds \n and carriage returns into a single space \n" + + ""); + + try { + assertTrue(doc.validate(validateOptions)); + assertTrue(doc2.validate(validateOptions)); + } + catch (Throwable t) { + showErrors(); + throw t; + } + + String replaceExpected = " This is a test. The resulting string should convert tabs , line feeds and carriage returns into a single space "; + assertEquals(replaceExpected, doc.getWSReplaceElt()); + + String collapseExpected = "This is a test. The resulting string should convert tabs , line feeds and carriage returns into a single space"; + assertEquals(collapseExpected, doc2.getWSCollapseElt()); + + } + + @Test + public void testEnumElt() throws Throwable { + EnumEltDocument doc = EnumEltDocument.Factory.newInstance(); + doc.setEnumElt(EnumT.A); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + doc = EnumEltDocument.Factory.parse("" + + "b" + + ""); + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_ENUM_VALID}; + + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + + } + + @Test + public void testPatternElt() throws Throwable { + + // base pattern is (a[^bc]d){3}, derived pattern is (a[^ef]d){3} + PatternEltDocument doc = PatternEltDocument.Factory.newInstance(); + doc.setPatternElt("axdaydazd"); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + String[] errExpected = new String[]{ + XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID}; + + doc.setPatternElt("aedafdagd"); + assertTrue(!doc.validate(validateOptions)); + assertTrue(compareErrorCodes(errExpected)); + } +} diff --git a/test/src/scomp/derivation/restriction/facets/detailed/FacetsTest.java b/src/test/java/scomp/derivation/restriction/facets/detailed/FacetsTest.java similarity index 93% rename from test/src/scomp/derivation/restriction/facets/detailed/FacetsTest.java rename to src/test/java/scomp/derivation/restriction/facets/detailed/FacetsTest.java index 3917be3..8bf91b9 100644 --- a/test/src/scomp/derivation/restriction/facets/detailed/FacetsTest.java +++ b/src/test/java/scomp/derivation/restriction/facets/detailed/FacetsTest.java @@ -14,30 +14,23 @@ */ package scomp.derivation.restriction.facets.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.derivation.facets.facets.*; -import xbean.scomp.derivation.facets.facets.DigitsEltDocument; -import xbean.scomp.derivation.facets.facets.EnumEltDocument; -import xbean.scomp.derivation.facets.facets.EnumT; -import xbean.scomp.derivation.facets.facets.LengthEltDocument; -import xbean.scomp.derivation.facets.facets.MinMaxExclusiveDateEltDocument; -import xbean.scomp.derivation.facets.facets.MinMaxExclusiveEltDocument; -import xbean.scomp.derivation.facets.facets.MinMaxInclusiveDateEltDocument; -import xbean.scomp.derivation.facets.facets.MinMaxInclusiveEltDocument; -import xbean.scomp.derivation.facets.facets.MinMaxLengthEltDocument; -import xbean.scomp.derivation.facets.facets.PatternEltDocument; import java.math.BigDecimal; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** */ public class FacetsTest extends BaseCase { - + @Test public void testMinMaxInclusiveElt() throws Throwable { MinMaxInclusiveEltDocument doc = MinMaxInclusiveEltDocument.Factory.newInstance(); @@ -64,6 +57,7 @@ public void testMinMaxInclusiveElt() throws Throwable { } + @Test public void testMinMaxInclusiveDateElt() throws Throwable { MinMaxInclusiveDateEltDocument doc = MinMaxInclusiveDateEltDocument.Factory.newInstance(); @@ -88,6 +82,7 @@ public void testMinMaxInclusiveDateElt() throws Throwable { } //valid range should be 3-9 + @Test public void testMinMaxExclusiveElt() throws Throwable { MinMaxExclusiveEltDocument doc = MinMaxExclusiveEltDocument.Factory.newInstance(); @@ -115,6 +110,7 @@ public void testMinMaxExclusiveElt() throws Throwable { } //valid range is 12-11 12-24-2003 + @Test public void testMinMaxExclusiveDateElt() throws Throwable { MinMaxExclusiveDateEltDocument doc = MinMaxExclusiveDateEltDocument.Factory.newInstance(); Calendar c = new GregorianCalendar(2003, 11, 25); @@ -136,6 +132,7 @@ public void testMinMaxExclusiveDateElt() throws Throwable { } + @Test public void testLengthElt() throws Throwable { LengthEltDocument doc = LengthEltDocument.Factory.newInstance(); doc.setLengthElt("foobar"); @@ -159,6 +156,7 @@ public void testLengthElt() throws Throwable { } } + @Test public void testMinMaxLengthElt() throws Throwable { MinMaxLengthEltDocument doc = MinMaxLengthEltDocument.Factory.newInstance(); String[] errExpected = new String[]{ @@ -192,6 +190,7 @@ public void testMinMaxLengthElt() throws Throwable { } + @Test public void testDigitsElt() throws Throwable { DigitsEltDocument doc = DigitsEltDocument.Factory.newInstance(); String[] errExpected = new String[]{ @@ -217,6 +216,7 @@ public void testDigitsElt() throws Throwable { } + @Test public void testWSElt() throws Throwable { WSPreserveEltDocument doc = WSPreserveEltDocument.Factory.parse("" + @@ -236,6 +236,7 @@ public void testWSElt() throws Throwable { assertEquals(expected, doc.getWSPreserveElt()); } + @Test public void testEnumElt() throws Throwable { EnumEltDocument doc = EnumEltDocument.Factory.newInstance(); @@ -257,6 +258,7 @@ public void testEnumElt() throws Throwable { } + @Test public void testPatternElt() throws Throwable { PatternEltDocument doc = PatternEltDocument.Factory.newInstance(); doc.setPatternElt("aedaedaed"); diff --git a/test/src/scomp/derivation/restriction/facets/detailed/ListRestriction.java b/src/test/java/scomp/derivation/restriction/facets/detailed/ListRestriction.java similarity index 97% rename from test/src/scomp/derivation/restriction/facets/detailed/ListRestriction.java rename to src/test/java/scomp/derivation/restriction/facets/detailed/ListRestriction.java index f2e531c..f12d9fd 100644 --- a/test/src/scomp/derivation/restriction/facets/detailed/ListRestriction.java +++ b/src/test/java/scomp/derivation/restriction/facets/detailed/ListRestriction.java @@ -14,17 +14,21 @@ */ package scomp.derivation.restriction.facets.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.derivation.facets.list.*; -import java.util.List; import java.util.ArrayList; +import java.util.List; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** */ public class ListRestriction extends BaseCase { + @Test public void testLengthFacet() throws Throwable { LengthEltDocument doc = LengthEltDocument.Factory.newInstance(); List vals = new ArrayList(); @@ -59,6 +63,7 @@ public void testLengthFacet() throws Throwable { } + @Test public void testMinLengthFacet() throws Throwable { String input = "" + @@ -96,6 +101,7 @@ public void testMinLengthFacet() throws Throwable { } + @Test public void testMaxLengthFacet() throws Throwable { String input = "" + @@ -125,9 +131,8 @@ public void testMaxLengthFacet() throws Throwable { /** * Walmsley, p. 215... - * - * @throws Throwable */ + @Test public void testEnum() throws Throwable { EnumEltDocument doc = EnumEltDocument.Factory.newInstance(); List vals = new ArrayList(); @@ -166,6 +171,7 @@ public void testEnum() throws Throwable { } + @Test public void testPattern() throws Throwable { PatternEltDocument doc = PatternEltDocument.Factory.newInstance(); List vals = new ArrayList(); diff --git a/test/src/scomp/derivation/restriction/facets/detailed/UnionRestriction.java b/src/test/java/scomp/derivation/restriction/facets/detailed/UnionRestriction.java similarity index 97% rename from test/src/scomp/derivation/restriction/facets/detailed/UnionRestriction.java rename to src/test/java/scomp/derivation/restriction/facets/detailed/UnionRestriction.java index b028bf0..7d27cf1 100644 --- a/test/src/scomp/derivation/restriction/facets/detailed/UnionRestriction.java +++ b/src/test/java/scomp/derivation/restriction/facets/detailed/UnionRestriction.java @@ -15,6 +15,7 @@ package scomp.derivation.restriction.facets.detailed; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.derivation.facets.union.UnionPatternEltDocument; import xbean.scomp.derivation.facets.union.SmallPatternUnion; @@ -22,12 +23,15 @@ import xbean.scomp.derivation.facets.union.SmallEnumUnion; import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertTrue; + /** * Only pattern and enumeration restrictions possible * Compile time tests for the rest */ public class UnionRestriction extends BaseCase { + @Test public void testPatternRestriction() throws Throwable { UnionPatternEltDocument doc = UnionPatternEltDocument.Factory.newInstance(); @@ -61,10 +65,9 @@ public void testPatternRestriction() throws Throwable { XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID }; assertTrue(compareErrorCodes(errExpected)); - - } + @Test public void testEnumRestriction() throws Throwable { UnionEnumEltDocument doc = UnionEnumEltDocument.Factory.newInstance(); doc.setUnionEnumElt("small"); @@ -97,7 +100,5 @@ public void testEnumRestriction() throws Throwable { XmlErrorCodes.DATATYPE_ENUM_VALID }; assertTrue(compareErrorCodes(errExpected)); - - } } diff --git a/test/src/scomp/elements/detailed/AnyTest.java b/src/test/java/scomp/elements/detailed/AnyTest.java similarity index 94% rename from test/src/scomp/elements/detailed/AnyTest.java rename to src/test/java/scomp/elements/detailed/AnyTest.java index 42c6254..fc14650 100644 --- a/test/src/scomp/elements/detailed/AnyTest.java +++ b/src/test/java/scomp/elements/detailed/AnyTest.java @@ -14,6 +14,7 @@ */ package scomp.elements.detailed; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.element.any.AnyEltDocument; import xbean.scomp.element.any.AnySimpleDocument; @@ -24,12 +25,11 @@ import java.math.BigInteger; import java.util.GregorianCalendar; -/** - * - * - */ +import static org.junit.Assert.assertTrue; + public class AnyTest extends BaseCase { + @Test public void testAny() throws Throwable { AnyEltDocument doc = AnyEltDocument.Factory.newInstance(); BusinessShirtType bst = BusinessShirtType.Factory.newInstance(); @@ -45,8 +45,9 @@ public void testAny() throws Throwable { showErrors(); throw t; } + clearErrors(); - + doc = AnyEltDocument.Factory.newInstance(); XmlString val = XmlString.Factory.newInstance(); val.setStringValue("foobar"); doc.setAnyElt(val); @@ -58,10 +59,9 @@ public void testAny() throws Throwable { showErrors(); throw t; } - - } + @Test public void testAnySimple() throws Throwable { AnySimpleDocument doc = AnySimpleDocument.Factory.newInstance(); diff --git a/src/test/java/scomp/elements/detailed/GlobalEltDefault.java b/src/test/java/scomp/elements/detailed/GlobalEltDefault.java new file mode 100644 index 0000000..171e534 --- /dev/null +++ b/src/test/java/scomp/elements/detailed/GlobalEltDefault.java @@ -0,0 +1,63 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package scomp.elements.detailed; + +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.element.globalEltDefault.GlobalEltDefaultIntDocument; +import xbean.scomp.element.globalEltDefault.GlobalEltDefaultStrDocument; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class GlobalEltDefault extends BaseCase { + //empty string is OK considered , so default value is ignored + @Test + public void testStringType() throws Throwable { + GlobalEltDefaultStrDocument testDoc = GlobalEltDefaultStrDocument + .Factory.newInstance(); + assertEquals(null, testDoc.getGlobalEltDefaultStr()); +/*try{ + assertTrue(testDoc.validate(validateOptions)); +}catch(Throwable t){ + showErrors(); + throw t; +} */ + testDoc.setGlobalEltDefaultStr("foo"); + try { + assertTrue(testDoc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + + } + + //default value is used + @Test + public void testIntType() throws Throwable { + GlobalEltDefaultIntDocument testDoc + = GlobalEltDefaultIntDocument.Factory + .newInstance(); + assertEquals(0, testDoc.getGlobalEltDefaultInt()); + try { + assertTrue(testDoc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + } +} diff --git a/test/src/scomp/elements/detailed/GlobalEltFixed.java b/src/test/java/scomp/elements/detailed/GlobalEltFixed.java similarity index 95% rename from test/src/scomp/elements/detailed/GlobalEltFixed.java rename to src/test/java/scomp/elements/detailed/GlobalEltFixed.java index 72057c9..c6e39c7 100644 --- a/test/src/scomp/elements/detailed/GlobalEltFixed.java +++ b/src/test/java/scomp/elements/detailed/GlobalEltFixed.java @@ -15,17 +15,17 @@ package scomp.elements.detailed; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.element.globalEltFixed.GlobalEltFixedIntDocument; import xbean.scomp.element.globalEltFixed.GlobalEltFixedStrDocument; import org.apache.xmlbeans.XmlErrorCodes; -/** - * - * - */ -public class GlobalEltFixed extends BaseCase { +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +public class GlobalEltFixed extends BaseCase { + @Test public void testValidPresent() throws Exception { GlobalEltFixedIntDocument testEltInt = GlobalEltFixedIntDocument.Factory.parse("1" + ""); assertTrue(!testDoc.validate(validateOptions)); - assertEquals(1,errorList.size()); + assertEquals(1, errorList.size()); showErrors(); String[] errExpected = new String[]{ XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_ELEMENT }; - assertTrue(compareErrorCodes(errExpected)); + assertTrue(compareErrorCodes(errExpected)); } // maxOccursOne occurs 2ce + @Test public void testInstanceGTMaxOccurs() throws Exception { MinMaxOccursDocDocument testDoc = MinMaxOccursDocDocument .Factory.parse("1" + "1" + ""); - assertEquals(0,errorList.size()); - assertTrue(!testDoc.validate(validateOptions)); - assertEquals(1,errorList.size()); - //TODO: why is this not element not allowed? + assertEquals(0, errorList.size()); + assertTrue(!testDoc.validate(validateOptions)); + assertEquals(1, errorList.size()); + //TODO: why is this not element not allowed? String[] errExpected = new String[]{ XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT}; - assertTrue(compareErrorCodes(errExpected)); + assertTrue(compareErrorCodes(errExpected)); - //fail("Error is incorrect: the dev infers the cause... incorrectly"); - showErrors(); + //fail("Error is incorrect: the dev infers the cause... incorrectly"); + showErrors(); } } diff --git a/src/test/java/scomp/elements/detailed/NamedModelGroupsTest.java b/src/test/java/scomp/elements/detailed/NamedModelGroupsTest.java new file mode 100644 index 0000000..573c3b3 --- /dev/null +++ b/src/test/java/scomp/elements/detailed/NamedModelGroupsTest.java @@ -0,0 +1,50 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package scomp.elements.detailed; + +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.element.namedModelGroup.EmployeePerf; +import xbean.scomp.element.namedModelGroup.EmployeePerformanceDocument; +import xbean.scomp.element.namedModelGroup.ManagerDocument; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.GregorianCalendar; + +import static org.junit.Assert.assertTrue; + +public class NamedModelGroupsTest extends BaseCase{ + @Test + public void testValid() throws Throwable{ + EmployeePerformanceDocument doc = + EmployeePerformanceDocument.Factory.newInstance(); + EmployeePerf elt = doc.addNewEmployeePerformance(); + ManagerDocument.Manager m = elt.addNewManager(); + m.setDepartment("Marketing"); + m.setLastName("Smith"); + + elt.setComment("Horrible performance by employee Potatohead"); + elt.setDate(new GregorianCalendar(2004, 8, 12)); + elt.setGrade(new BigDecimal(new BigInteger("10"))); + elt.setManager(m); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + } +} diff --git a/test/src/scomp/elements/detailed/NillTest.java b/src/test/java/scomp/elements/detailed/NillTest.java similarity index 98% rename from test/src/scomp/elements/detailed/NillTest.java rename to src/test/java/scomp/elements/detailed/NillTest.java index 426a784..b105f7e 100644 --- a/test/src/scomp/elements/detailed/NillTest.java +++ b/src/test/java/scomp/elements/detailed/NillTest.java @@ -14,12 +14,13 @@ */ package scomp.elements.detailed; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.values.XmlValueNotNillableException; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.element.nillTest.*; -import org.apache.xmlbeans.impl.values.XmlValueNotNillableException; -import org.apache.xmlbeans.XmlOptions; -import java.math.BigInteger; +import static org.junit.Assert.*; /** @@ -37,6 +38,7 @@ public class NillTest extends BaseCase { * element, will also add the "xsi:nil" attribute. */ // for all nillable tests, the validation falls thro only if the ValidateOnSet option is turned on + @Test public void testNotNillableLocalElem() { XmlOptions options = new XmlOptions(); @@ -68,6 +70,7 @@ public void testNotNillableLocalElem() { } + @Test public void testNotNillableGlobalElem() { XmlOptions options = new XmlOptions(); options.setValidateOnSet(); @@ -98,6 +101,7 @@ public void testNotNillableGlobalElem() { cityNameWithValidateOff.xmlText()); } + @Test public void testNillableGlobalElement() { XmlOptions options = new XmlOptions(); @@ -134,10 +138,9 @@ public void testNillableGlobalElement() "xmlns:nil=\"http://xbean/scomp/element/NillTest\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>", testElt.xmlText()); - - } + @Test public void testNillableLocalElement() { XmlOptions options = new XmlOptions(); @@ -172,10 +175,9 @@ public void testNillableLocalElement() "xsi:nil=\"true\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>", contactWithValidationOff.xmlText()); - - } + @Test public void testDefaultValElement() { XmlOptions options = new XmlOptions(); @@ -195,6 +197,7 @@ public void testDefaultValElement() } } + @Test public void testNotNillableFixedValueElement() { XmlOptions options = new XmlOptions(); diff --git a/test/src/scomp/idConstraint/detailed/KeyKeyref.java b/src/test/java/scomp/idConstraint/detailed/KeyKeyref.java similarity index 98% rename from test/src/scomp/idConstraint/detailed/KeyKeyref.java rename to src/test/java/scomp/idConstraint/detailed/KeyKeyref.java index 7703897..acd2788 100644 --- a/test/src/scomp/idConstraint/detailed/KeyKeyref.java +++ b/src/test/java/scomp/idConstraint/detailed/KeyKeyref.java @@ -15,18 +15,17 @@ package scomp.idConstraint.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.apache.xmlbeans.XmlString; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.idConstraint.constraint.*; -import org.apache.xmlbeans.XmlString; -import org.apache.xmlbeans.XmlErrorCodes; -/** - * - * - * - */ +import static org.junit.Assert.assertTrue; + public class KeyKeyref extends BaseCase { + @Test public void testUnique() throws Throwable { String input = "" + @@ -52,9 +51,8 @@ public void testUnique() throws Throwable { /** * field combo not unique in instance (a and c are the same) - * - * @throws Throwable */ + @Test public void testUniqueIllegal() throws Throwable { ProductListDocument doc = ProductListDocument.Factory.newInstance(); ProductListType products = ProductListType.Factory.newInstance(); @@ -90,9 +88,8 @@ public void testUniqueIllegal() throws Throwable { /** * Selector selects a non-unique field in instance * Only one dept can appear in the first product - * - * @throws Throwable */ + @Test public void testUniqueIllegal2() throws Throwable { String input = "" + @@ -115,6 +112,7 @@ public void testUniqueIllegal2() throws Throwable { } + @Test public void testKey() throws Throwable { String input = "" + @@ -139,9 +137,8 @@ public void testKey() throws Throwable { /** * null key in instance:missing dept in first product - * - * @throws Throwable */ + @Test public void testKeyIllegal() throws Throwable { String input = "" + @@ -168,6 +165,7 @@ public void testKeyIllegal() throws Throwable { } + @Test public void testKeyRef() throws Throwable { String input = "" + @@ -209,6 +207,7 @@ public void testKeyRef() throws Throwable { // Invalid xml instance with 2 problems : // a) the values for the key & key ref elems are not the same // b) The keyref/key elems are duplicated + @Test public void testKeyRefIllegal() throws Throwable { String input = diff --git a/test/src/scomp/namespace/checkin/PreserveNamespaces.java b/src/test/java/scomp/namespace/checkin/PreserveNamespaces.java similarity index 87% rename from test/src/scomp/namespace/checkin/PreserveNamespaces.java rename to src/test/java/scomp/namespace/checkin/PreserveNamespaces.java index 22f29d6..b211efa 100644 --- a/test/src/scomp/namespace/checkin/PreserveNamespaces.java +++ b/src/test/java/scomp/namespace/checkin/PreserveNamespaces.java @@ -15,27 +15,32 @@ package scomp.namespace.checkin; -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Before; +import org.junit.Test; import org.xmlsoap.schemas.soap.envelope.EnvelopeDocument; import tools.xml.XmlComparator; + import javax.xml.namespace.QName; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + -public class PreserveNamespaces extends TestCase +public class PreserveNamespaces { public static XmlOptions options; public static final String EOL = System.getProperty("line.separator"); - public void setUp() - { + @Before + public void setUp() { options = new XmlOptions().setSavePrettyPrint().setSaveOuter(); } //tests for preserving/copying namespace declarations when doing an XmlObject.set() - public void testDroppedXsdNSDecl() throws Exception - { + @Test + public void testDroppedXsdNSDecl() throws Exception { // Test for XSD namespace declaration dropped EnvelopeDocument env1 = EnvelopeDocument.Factory.parse(" if (env2Cursor.toFirstChild()) // { - assertTrue("Element name mismatch!", env2Cursor.getName().equals(new QName("","dFahrenheit"))); + assertEquals("Element name mismatch!", env2Cursor.getName(), new QName("", "dFahrenheit")); assertEquals("Element val mismatch!", "88", env2Cursor.getTextValue()); assertEquals("XSD Namespace has been dropped", "http://www.w3.org/2001/XMLSchema", env2Cursor.namespaceForPrefix("xsd")); } } - public void testsModifiedXsdNSPrefix() throws Exception - { + @Test + public void testsModifiedXsdNSPrefix() throws Exception { // XSD namespace used in QName values and elements EnvelopeDocument env1 = EnvelopeDocument.Factory.parse(" if (env2Cursor.toFirstChild()) // { - assertTrue("Element name mismatch!", env2Cursor.getName().equals(new QName("http://www.w3.org/2001/XMLSchema","element"))); + assertEquals("Element name mismatch!", env2Cursor.getName(), new QName("http://www.w3.org/2001/XMLSchema", "element")); assertEquals("XSD Namespace has been dropped", "http://www.w3.org/2001/XMLSchema", env2Cursor.namespaceForPrefix("xsd")); } } - public void testsFaultCodeNSUpdate() throws Exception - { + @Test + public void testsFaultCodeNSUpdate() throws Exception { EnvelopeDocument env1 = EnvelopeDocument.Factory.parse("\n" + " \n" + @@ -129,7 +134,7 @@ public void testsFaultCodeNSUpdate() throws Exception assertTrue(env2Cursor.toFirstChild()); // if (env2Cursor.toFirstChild()) // { - assertTrue("Element name mismatch!", env2Cursor.getName().equals(new QName("","faultcode"))); + assertEquals("Element name mismatch!", env2Cursor.getName(), new QName("", "faultcode")); assertEquals("soap Namespace has been dropped", "http://schemas.xmlsoap.org/soap/envelope/", env2Cursor.namespaceForPrefix("soap")); } diff --git a/src/test/java/scomp/namespace/detailed/AttrFormDefault.java b/src/test/java/scomp/namespace/detailed/AttrFormDefault.java new file mode 100644 index 0000000..00d19c6 --- /dev/null +++ b/src/test/java/scomp/namespace/detailed/AttrFormDefault.java @@ -0,0 +1,74 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package scomp.namespace.detailed; + +import org.apache.xmlbeans.XmlAnySimpleType; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.namespace.attributeFormDefault.AttributeFormDefaultEltDocument; +import xbean.scomp.namespace.attributeFormDefault.ElementT; + +import static org.junit.Assert.assertTrue; + +/** + * + */ +public class AttrFormDefault extends BaseCase { + @Test + public void testValid() throws Throwable { + AttributeFormDefaultEltDocument doc = + AttributeFormDefaultEltDocument.Factory.parse(""); + + try { + doc.validate(validateOptions); + } + catch (Throwable t) { + showErrors(); + throw t; + } + } + + @Test + public void testInvalid() throws Throwable { + AttributeFormDefaultEltDocument doc = + AttributeFormDefaultEltDocument.Factory.newInstance(); + ElementT elt = doc.addNewAttributeFormDefaultElt(); + XmlAnySimpleType val = XmlAnySimpleType.Factory.newInstance(); + val.setStringValue("345"); + elt.setLocalAttr(val); + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + + doc = + AttributeFormDefaultEltDocument.Factory.parse(""); + assertTrue(!doc.validate(validateOptions)); + showErrors(); + String[] errExpected = new String[]{ + XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD + }; + assertTrue(compareErrorCodes(errExpected)); + + } +} diff --git a/test/src/scomp/namespace/detailed/AttributeWC.java b/src/test/java/scomp/namespace/detailed/AttributeWC.java similarity index 96% rename from test/src/scomp/namespace/detailed/AttributeWC.java rename to src/test/java/scomp/namespace/detailed/AttributeWC.java index 9efdb7d..ab63201 100644 --- a/test/src/scomp/namespace/detailed/AttributeWC.java +++ b/src/test/java/scomp/namespace/detailed/AttributeWC.java @@ -15,28 +15,31 @@ package scomp.namespace.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Ignore; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.namespace.attributeWC.*; -import org.apache.xmlbeans.XmlErrorCodes; -/** - * - * - * - */ +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + public class AttributeWC extends BaseCase { + @Test public void testAnyLaxLegal() throws Throwable { AnyLaxDocument doc = AnyLaxDocument.Factory.parse(""); assertTrue(doc.validate(validateOptions)); } + @Test public void testAnyLaxIllegal() throws Throwable { AnyLaxDocument doc = AnyLaxDocument.Factory.parse(""); assertTrue(doc.validate(validateOptions)); } + @Test public void testAnySkipLegal() throws Throwable { AnySkipDocument doc = AnySkipDocument.Factory.parse(""); @@ -49,6 +52,7 @@ public void testAnySkipLegal() throws Throwable { * } */ //no NS is legal too + @Test public void testAnyStrictLegal() throws Throwable { AnyStrictDocument doc = AnyStrictDocument.Factory .parse(""); @@ -70,6 +75,7 @@ public void testAnyStrictIllegal() throws Throwable { } + @Test public void testOtherLaxLegal() throws Throwable { OtherLaxDocument doc = OtherLaxDocument.Factory .parse("" + " " + @@ -163,8 +165,8 @@ public class MultipleRedefines extends BaseCase private static final String[] CIRCULAR_SCHEMAS_NAME = { "A.xsd", "B.xsd", "C.xsd", "D.xsd"}; - public void testMultipleRedefines() throws Exception - { + @Test + public void testMultipleRedefines() throws Exception { int N = MULTIPLE_SCHEMAS.length; SchemaDocument[] sdocs = new SchemaDocument[N]; for (int i = 0; i < N; i++) @@ -175,25 +177,26 @@ public void testMultipleRedefines() throws Exception SchemaTypeSystem ts = XmlBeans.compileXsd(sdocs, XmlBeans.getBuiltinTypeSystem(), validateOptions); - Assert.assertNotNull(ts); + assertNotNull(ts); SchemaType t = ts.findType(new QName("", "T")); - Assert.assertNotNull(t); + assertNotNull(t); SchemaParticle p = t.getContentModel(); - Assert.assertNotNull(p); - Assert.assertEquals(p.getParticleType(), SchemaParticle.SEQUENCE); + assertNotNull(p); + assertEquals(p.getParticleType(), SchemaParticle.SEQUENCE); SchemaParticle[] elts = p.getParticleChildren(); - Assert.assertEquals(elts.length, 4); + assertEquals(elts.length, 4); for (int i = 0; i < elts.length; i++) - Assert.assertEquals(elts[i].getParticleType(), SchemaParticle.ELEMENT); + assertEquals(elts[i].getParticleType(), SchemaParticle.ELEMENT); - Assert.assertEquals("A", elts[0].getName().getLocalPart()); - Assert.assertEquals("B", elts[1].getName().getLocalPart()); - Assert.assertEquals("D", elts[2].getName().getLocalPart()); - Assert.assertEquals("E", elts[3].getName().getLocalPart()); + assertEquals("A", elts[0].getName().getLocalPart()); + assertEquals("B", elts[1].getName().getLocalPart()); + assertEquals("D", elts[2].getName().getLocalPart()); + assertEquals("E", elts[3].getName().getLocalPart()); } + @Test public void testCircularRedefines() throws Exception { int N =CIRCULAR_SCHEMAS.length; @@ -219,9 +222,9 @@ public void testCircularRedefines() throws Exception Assert.assertFalse(it.hasNext()); String message = err.getMessage(); // TODO check an error code instead - Assert.assertTrue(message.toLowerCase().indexOf("circular") >= 0); + assertTrue(message.toLowerCase().indexOf("circular") >= 0); } clearErrors(); - Assert.assertTrue("Compilation should fail", caught); + assertTrue("Compilation should fail", caught); } } diff --git a/src/test/java/scomp/redefine/detailed/SimpleRedefine.java b/src/test/java/scomp/redefine/detailed/SimpleRedefine.java new file mode 100644 index 0000000..3a486d8 --- /dev/null +++ b/src/test/java/scomp/redefine/detailed/SimpleRedefine.java @@ -0,0 +1,64 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package scomp.redefine.detailed; + +import org.junit.Test; +import scomp.common.BaseCase; +import xbean.scomp.redefine.simpleRedefined.NewSizeEltDocument; +import xbean.scomp.redefine.simpleRedefined.OldColorEltDocument; +import xbean.scomp.redefine.simpleRedefined.OldSizeEltDocument; + +import static org.junit.Assert.assertTrue; + +public class SimpleRedefine extends BaseCase { + + /** + * test that fields from the old type def are not + * visible anymore: only valid range for sizeT should be 3-20 + */ + @Test + public void testCodeGeneration() throws Throwable{ + NewSizeEltDocument doc = NewSizeEltDocument.Factory.newInstance(); + OldColorEltDocument doc1 = OldColorEltDocument.Factory.newInstance(); + OldSizeEltDocument doc2 = OldSizeEltDocument.Factory.newInstance(); + + doc.setNewSizeElt(3); + + try { + assertTrue(doc.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + doc.setNewSizeElt(21); + assertTrue(!doc.validate(validateOptions)); + showErrors(); + clearErrors(); + + doc2.setOldSizeElt(21); + assertTrue(!doc.validate(validateOptions)); + showErrors(); + clearErrors(); + + doc1.setOldColorElt("white"); + + try { + assertTrue(doc1.validate(validateOptions)); + } catch (Throwable t) { + showErrors(); + throw t; + } + } +} diff --git a/src/test/java/scomp/simple/SimplePersonTest.java b/src/test/java/scomp/simple/SimplePersonTest.java new file mode 100755 index 0000000..48d0610 --- /dev/null +++ b/src/test/java/scomp/simple/SimplePersonTest.java @@ -0,0 +1,113 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package scomp.simple; + +import common.Common; +import org.junit.Test; +import org.openuri.mytest.CustomerDocument; +import org.openuri.mytest.Person; + +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import static org.junit.Assert.assertEquals; + +public class SimplePersonTest { + @Test + public void test() throws Exception { + CustomerDocument doc = + CustomerDocument.Factory.parse( + Common.xbeanCase("xbean/simple/person/person.xml"), null); + + // Move from the root to the root customer element + Person person = doc.getCustomer(); + assertEquals("Howdy", person.getFirstname()); + assertEquals(4, person.sizeOfNumberArray()); + assertEquals(436, person.getNumberArray(0)); + assertEquals(123, person.getNumberArray(1)); + assertEquals(44, person.getNumberArray(2)); + assertEquals(933, person.getNumberArray(3)); + assertEquals(2, person.sizeOfBirthdayArray()); + Calendar cal = person.getBirthdayArray(0); + cal.set(1998, 7, 25, 17, 0); + assertEquals(1998, cal.get(Calendar.YEAR)); + assertEquals(7, cal.get(Calendar.MONTH)); + assertEquals(25, cal.get(Calendar.DATE)); + assertEquals(17, cal.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, cal.get(Calendar.MINUTE)); + assertEquals(0, cal.get(Calendar.SECOND)); + + Person.Gender.Enum g = person.getGender(); + assertEquals(Person.Gender.MALE, g); + + assertEquals("EGIQTWYZJ", new String(person.getHex())); + assertEquals("This string is base64Binary encoded!", + new String(person.getBase64())); + + assertEquals("GGIQTWYGG", new String(person.getHexAtt())); + assertEquals("This string is base64Binary encoded!", + new String(person.getBase64Att())); + + person.setFirstname("George"); + assertEquals("George", person.getFirstname()); + + person.setHex("hex encoding".getBytes()); + assertEquals("hex encoding", new String(person.getHex())); + + person.setBase64("base64 encoded".getBytes()); + assertEquals("base64 encoded", + new String(person.getBase64())); + + //person.setHexAtt("hex encoding in attributes".getBytes()); + //Assert.assertEquals("hex encoding in attributes", + // new String(person.getHexAtt())); + + //person.setBase64Att("base64 encoded in attributes".getBytes()); + //Assert.assertEquals("base64 encoded in attributes", + // new String(person.getBase64Att())); +// +// XmlCursor cp = person.newXmlCursor(); +// Root.dump( cp ); + +// XmlCursor c = person.xgetBirthdayArray(0).newXmlCursor(); + +// Root.dump( c ); + +// person.setBirthday(0,new Date("Tue Aug 25 16:00:00 PDT 2001")); + +// Root.dump( c ); + +// c.toNextToken(); + +// System.out.println( "---" + c.getText() + "---" ); + +// Root.dump( c ); + +// Assert.assertEquals(person.getBirthdayArray(0), new Date("Tue Aug 25 16:00:00 PDT 2002")); +// +// person.setFirstname("George"); +// Assert.assertEquals(person.getFirstname(), "George"); +// +// person.addNumber( (short) 69 ); +// Assert.assertEquals(person.countNumber(), 5); +// Assert.assertEquals(person.getNumberArray(4), 69); +// +// +// while ( c.hasNextToken() ) +// c.toNextToken(); + } +} diff --git a/test/src/scomp/substGroup/detailed/Deep.java b/src/test/java/scomp/substGroup/detailed/Deep.java similarity index 99% rename from test/src/scomp/substGroup/detailed/Deep.java rename to src/test/java/scomp/substGroup/detailed/Deep.java index 7478849..2a618bf 100644 --- a/test/src/scomp/substGroup/detailed/Deep.java +++ b/src/test/java/scomp/substGroup/detailed/Deep.java @@ -22,6 +22,8 @@ import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertTrue; + /** */ public class Deep extends BaseCase { diff --git a/test/src/scomp/substGroup/detailed/OneLevel.java b/src/test/java/scomp/substGroup/detailed/OneLevel.java similarity index 97% rename from test/src/scomp/substGroup/detailed/OneLevel.java rename to src/test/java/scomp/substGroup/detailed/OneLevel.java index 2109256..9ad52a3 100644 --- a/test/src/scomp/substGroup/detailed/OneLevel.java +++ b/src/test/java/scomp/substGroup/detailed/OneLevel.java @@ -14,18 +14,18 @@ */ package scomp.substGroup.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; import xbean.scomp.substGroup.oneLevel.*; import java.math.BigInteger; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertTrue; -/** - */ public class OneLevel extends BaseCase { + @Test public void testValidSubstParse() throws Throwable { String input = "" + @@ -61,9 +61,8 @@ public void testValidSubstParse() throws Throwable { /** * Test error message. 1 product too many - * - * @throws Throwable */ + @Test public void testValidSubstParseInvalid() throws Throwable { String input = "" + @@ -100,9 +99,9 @@ public void testValidSubstParseInvalid() throws Throwable { }; assertTrue(compareErrorCodes( errExpected)); - } + @Test public void testValidSubstBuild() throws Throwable { ItemsDocument doc = ItemsDocument.Factory.newInstance(); ItemType items = doc.addNewItems(); diff --git a/test/src/scomp/substGroup/detailed/UserReportedTest.java b/src/test/java/scomp/substGroup/detailed/UserReportedTest.java similarity index 95% rename from test/src/scomp/substGroup/detailed/UserReportedTest.java rename to src/test/java/scomp/substGroup/detailed/UserReportedTest.java index 7b1d97c..3d34736 100644 --- a/test/src/scomp/substGroup/detailed/UserReportedTest.java +++ b/src/test/java/scomp/substGroup/detailed/UserReportedTest.java @@ -15,17 +15,17 @@ package scomp.substGroup.detailed; +import org.junit.Test; import scomp.common.BaseCase; -import xbean.scomp.substGroup.userReported.RootDocument; -import xbean.scomp.substGroup.userReported.T; import xbean.scomp.substGroup.userReported.ADocument; import xbean.scomp.substGroup.userReported.BDocument; -import org.apache.xmlbeans.XmlObject; +import xbean.scomp.substGroup.userReported.RootDocument; +import xbean.scomp.substGroup.userReported.T; import javax.xml.namespace.QName; -/** - */ +import static org.junit.Assert.assertTrue; + public class UserReportedTest extends BaseCase{ String input="" + " " + @@ -34,7 +34,8 @@ public class UserReportedTest extends BaseCase{ " " + " " + ""; - public void testGoal()throws Throwable{ + @Test + public void testGoal()throws Throwable{ RootDocument doc=RootDocument.Factory.parse(input); try{ @@ -45,6 +46,7 @@ public void testGoal()throws Throwable{ } } + @Test public void testBuild()throws Throwable{ T[] arr = new T[5]; diff --git a/test/src/scomp/substGroup/detailed/Wide.java b/src/test/java/scomp/substGroup/detailed/Wide.java similarity index 96% rename from test/src/scomp/substGroup/detailed/Wide.java rename to src/test/java/scomp/substGroup/detailed/Wide.java index 82f2520..1d0080f 100644 --- a/test/src/scomp/substGroup/detailed/Wide.java +++ b/src/test/java/scomp/substGroup/detailed/Wide.java @@ -15,20 +15,21 @@ package scomp.substGroup.detailed; +import org.apache.xmlbeans.XmlErrorCodes; +import org.junit.Test; import scomp.common.BaseCase; -import xbean.scomp.substGroup.wide.*; import xbean.scomp.substGroup.deep.ItemType; -import xbean.scomp.substGroup.deep.ProductType; import xbean.scomp.substGroup.deep.ItemsDocument; +import xbean.scomp.substGroup.deep.ProductType; +import xbean.scomp.substGroup.wide.BeachUmbrellaT; +import xbean.scomp.substGroup.wide.BusinessShirtType; import java.math.BigInteger; -import org.apache.xmlbeans.XmlErrorCodes; +import static org.junit.Assert.assertTrue; -/** - */ public class Wide extends BaseCase { - + @Test public void testValidSubstParse() throws Throwable { String input = "\n"; + + public static String base = asl_header + "" + + "abc" + + "123" + + "" + + ""; + public static String base_expected_russian = "" + + "" + + " \n" + + " Copyright 2004 The Apache Software Foundation\n" + + "\n" + + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " you may not use this file except in compliance with the License.\n" + + " You may obtain a copy of the License at\n" + + "\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + "\n" + + " Unless required by applicable law or agreed to in writing, software\n" + + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " See the License for the specific language governing permissions and\n" + + " limitations under the License. \n" + + " \n" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + + public static String base_expected_salami = "" + + "" + + "" + + " \n" + + " Copyright 2004 The Apache Software Foundation\n" + + "\n" + + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " you may not use this file except in compliance with the License.\n" + + " You may obtain a copy of the License at\n" + + "\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + "\n" + + " Unless required by applicable law or agreed to in writing, software\n" + + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " See the License for the specific language governing permissions and\n" + + " limitations under the License. \n" + + " \n" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + + public static String base_expected_venetian = "" + + "" + + " \n" + + " Copyright 2004 The Apache Software Foundation\n" + + "\n" + + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " you may not use this file except in compliance with the License.\n" + + " You may obtain a copy of the License at\n" + + "\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + "\n" + + " Unless required by applicable law or agreed to in writing, software\n" + + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " See the License for the specific language governing permissions and\n" + + " limitations under the License. \n" + + " \n" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + +} diff --git a/src/test/java/tools/inst2xsd/common/Inst2XsdTestBase.java b/src/test/java/tools/inst2xsd/common/Inst2XsdTestBase.java new file mode 100644 index 0000000..00b365e --- /dev/null +++ b/src/test/java/tools/inst2xsd/common/Inst2XsdTestBase.java @@ -0,0 +1,430 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package tools.inst2xsd.common; + +import common.Common; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd; +import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import tools.xml.XmlComparator; + +import java.util.ArrayList; +import java.util.Collection; + +import static org.junit.Assert.assertNotNull; + +public class Inst2XsdTestBase extends Common { + + public static tools.inst2xsd.common.Inst2XsdCommon common; + private static boolean _verbose = true; + + private static String caseroot = XBEAN_CASE_ROOT; + //location of files under "cases folder" + private static String miscDir = caseroot + P + "tools"; + private static String inst2xsdDir = miscDir + P + "inst2xsd" + P; + protected static String OPTION_CASES_DIR = inst2xsdDir + P + "options" + P; + protected static String SCHEMA_CASES_DIR = inst2xsdDir + P + "schema" + P; + protected static final String BASEXML = OPTION_CASES_DIR + "base.xml"; + protected static final String EXPBASEXML = OPTION_CASES_DIR + "base0.xsd"; + + + protected XmlObject getTypeXml(String val) throws Exception { + return XmlObject.Factory.parse(setTypeVal(val)); + } + + private String setTypeVal(String val) { + String base_start = ""; + String base_end = ""; + return base_start + val + base_end; + } + + protected XmlObject getAttrTypeXml(String val) throws Exception { + return XmlObject.Factory.parse(setAttrVal(val)); + } + + private String setAttrVal(String val) { + String attr_base_end = "\" />"; + String attr_base_start = "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + } + + private String getAttrTypeXmlRDandSS(String type) { + return "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + } + + protected void runAttrTypeChecking(XmlObject act, String expType) throws Exception { + + log("=== Venetian options ==="); + runAttrTypeChecking(act, expType, Inst2XsdCommon.getVenetianOptions()); + log("=== Russian options ==="); + runAttrTypeChecking(act, expType, Inst2XsdCommon.getRussianOptions()); + log("=== Salami options ==="); + runAttrTypeChecking(act, expType, Inst2XsdCommon.getSalamiOptions()); + log("=== Default options ==="); + runAttrTypeChecking(act, expType, Inst2XsdCommon.getDefaultInstOptions()); + } + + private void runAttrTypeChecking(XmlObject act, String expType, Inst2XsdOptions opt) throws Exception { + SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); + checkLength(venetian, 1); + + if (opt.getDesign() == Inst2XsdOptions.DESIGN_RUSSIAN_DOLL || + opt.getDesign() == Inst2XsdOptions.DESIGN_SALAMI_SLICE) + compare(venetian[0], XmlObject.Factory.parse(getAttrTypeXmlRDandSS(expType))); + else if (opt.getDesign() == Inst2XsdOptions.DESIGN_VENETIAN_BLIND) + compare(venetian[0], XmlObject.Factory.parse(getAttrTypeXmlVenetian(expType))); + else + throw new Exception("Design style was not found"); + + checkInstance(venetian, new XmlObject[]{act}); + + } + + //element value test methods + protected void runTypeChecking(XmlObject act, String expType) throws Exception { + log("=== Venetian options ==="); + runTypeChecking(act, expType, Inst2XsdCommon.getVenetianOptions()); + log("=== Russian options ==="); + runTypeChecking(act, expType, Inst2XsdCommon.getRussianOptions()); + log("=== Salami options ==="); + runTypeChecking(act, expType, Inst2XsdCommon.getSalamiOptions()); + log("=== Default options ==="); + runTypeChecking(act, expType, Inst2XsdCommon.getDefaultInstOptions()); + } + + + private void runTypeChecking(XmlObject act, String expType, Inst2XsdOptions opt) throws Exception { + SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); + checkLength(venetian, 1); + log("actual: " + act); + log("expType: " + expType); + checkInstance(venetian, new XmlObject[]{act}); + compare(venetian[0], XmlObject.Factory.parse(getExpTypeXml(expType))); + } + + private String getExpTypeXml(String type) { + return "" + + "" + + ""; + } + + //type coercion/LCD test methods + protected void runLCDTypeCheckTest(String val1, String val2, String expType) throws Exception { + log("=== Venetian options ==="); + runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getVenetianOptions()); + log("=== Russian options ==="); + runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getRussianOptions()); + log("=== Salami options ==="); + runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getSalamiOptions()); + log("=== Default options ==="); + runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getDefaultInstOptions()); + } + + private void runLCDTypeChecking(String val1, String val2, String expType, Inst2XsdOptions opt) throws Exception { + XmlObject act = getTypeCoerceXml(val1, val2); + SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); + checkLength(venetian, 1); + log("instance: " + act); + log("expType: " + expType); + checkInstance(venetian, new XmlObject[]{act}); + + if (opt.getDesign() == Inst2XsdOptions.DESIGN_VENETIAN_BLIND) + compare(venetian[0], getExpLCDXml_vb(expType)); + else if (opt.getDesign() == Inst2XsdOptions.DESIGN_SALAMI_SLICE) + compare(venetian[0], getExpLCDXml_ss(expType)); + else if (opt.getDesign() == Inst2XsdOptions.DESIGN_RUSSIAN_DOLL) + compare(venetian[0], getExpLCDXml_rd(expType)); + else + compare(venetian[0], getExpLCDXml_vb(expType)); + } + + private String getTypeCoerceXmlString(String val1, String val2) { + return "" + + " " + val1 + "" + + " " + val2 + "" + + ""; + } + + private XmlObject getTypeCoerceXml(String val1, String val2) throws XmlException { + return XmlObject.Factory.parse(getTypeCoerceXmlString(val1, val2)); + } + + + private XmlObject getExpLCDXml_vb(String type) throws XmlException { + return XmlObject.Factory.parse("\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""); + } + + private XmlObject getExpLCDXml_ss(String type) throws XmlException { + return XmlObject.Factory.parse("\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""); + } + + private XmlObject getExpLCDXml_rd(String type) throws XmlException { + return XmlObject.Factory.parse("\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""); + } + + + protected static XmlObject[] runInst2Xsd(XmlObject inst, Inst2XsdOptions options) { + return Inst2Xsd.inst2xsd(new XmlObject[]{inst}, options); + } + + protected static XmlObject[] runInst2Xsd(XmlObject[] inst, Inst2XsdOptions options) { + return Inst2Xsd.inst2xsd(inst, options); + } + + + protected static SchemaDocument[] getSchemaDoc(XmlObject[] inst) throws XmlException { + SchemaDocument[] docs = new SchemaDocument[inst.length]; + for (int i = 0; i < docs.length; i++) { + docs[i] = SchemaDocument.Factory.parse(inst[i].xmlText()); + } + return docs; + + } + + protected static void runSchemaBuild(XmlObject inst, Inst2XsdOptions opts, XmlObject exp) throws Exception { + XmlObject[] genSchema = runInst2Xsd(inst, opts); + log(genSchema); + checkInstanceToAll(genSchema, inst, exp); + checkLength(genSchema, 1); + compare(genSchema[0], exp); + + } + + protected static void runSchemaBuild(XmlObject inst, Inst2XsdOptions opts, XmlObject[] exp) throws XmlException { + XmlObject[] genSchema = runInst2Xsd(inst, opts); + log(genSchema); + checkInstanceToAll(genSchema, new XmlObject[]{inst}, exp); + checkLength(genSchema, exp.length); + compare(genSchema, exp); + + } + + //TODO: Make this error narrowed + protected static void checkLength(Object[] obj, int val) throws XmlException { + log("Length = " + obj.length + " exp: " + val); + + if (obj.length < val) { + throw new XmlException("Actual was smaller than expected"); + } else if (obj.length > val) { + throw new XmlException("Actual was larger than expected"); + } + } + + + public static void compare(XmlObject[] act, XmlObject[] exp) throws XmlException { + checkLength(act, exp.length); + //Arrays.sort(act); + //Arrays.sort(exp); + //if (Arrays.equals(act, exp)){ + // return; + //}else{ + for (int i = 0; i < act.length; i++) { + compare(act[i], exp[i]); + } + + } + + public static void compare(XmlObject act, XmlObject exp) throws XmlException { + XmlComparator.Diagnostic diag = XmlComparator.lenientlyCompareTwoXmlStrings( + act.xmlText(Inst2XsdCommon.getXmlOptions()), + exp.xmlText(Inst2XsdCommon.getXmlOptions())); + if (diag.hasMessage()) { + log("Expected: \n" + exp.xmlText(Inst2XsdCommon.getXmlOptions())); + log("Actual: \n" + act.xmlText(Inst2XsdCommon.getXmlOptions())); + throw new XmlException("Xml Comparison Failed:\n" + diag.toString()); + } + } + + public static void log(XmlObject[] doc) { + if (_verbose) { + for (int i = 0; i < doc.length; i++) { + log("Schema[" + i + "] - " + doc[i].xmlText(Inst2XsdCommon.getXmlOptions())); + } + } + } + + public static void log(String msg) { + if (_verbose) + System.out.println(msg); + } + + public static void log(XmlObject obj) { + if (_verbose) + System.out.println(obj.xmlText(Inst2XsdCommon.getXmlOptions())); + } + + + private static void checkInstanceToAll(XmlObject[] actSchemaDoc, XmlObject inst, + XmlObject expSchemas) throws Exception { + checkInstanceToAll(getSchemaDoc(actSchemaDoc), new XmlObject[]{inst}, getSchemaDoc(new XmlObject[]{expSchemas})); + } + + private static void checkInstanceToAll(XmlObject[] actSchemaDoc, XmlObject[] inst, + XmlObject[] expSchemas) throws XmlException { + checkInstanceToAll(getSchemaDoc(actSchemaDoc), inst, getSchemaDoc(expSchemas)); + } + + private static void checkInstanceToAll(SchemaDocument[] actSchemaDoc, XmlObject[] inst, + SchemaDocument[] expSchemas) throws XmlException { + log("-= Comparing Actual to instance=-"); + if (checkInstance(actSchemaDoc, inst)) + log("-= Instance validated actual =-"); + + log("-= Comparing Expected to instance=-"); + if (checkInstance(expSchemas, inst)) + log("-= Instance validated Expected =-"); + + } + + private static boolean checkInstance(SchemaDocument[] sDocs, XmlObject[] inst) throws XmlException { + if (validateInstances(sDocs, inst)) { + return true; + } else { + throw new XmlException("Instance Failed to validate"); + } + } + + /** + * Copied from inst2Xsd as option may be removed + */ + private static boolean validateInstances(SchemaDocument[] sDocs, XmlObject[] instances) { + + SchemaTypeLoader sLoader; + Collection compErrors = new ArrayList(); + XmlOptions schemaOptions = new XmlOptions(); + schemaOptions.setErrorListener(compErrors); + try { + sLoader = XmlBeans.loadXsd(sDocs, schemaOptions); + } catch (Exception e) { + if (compErrors.isEmpty() || !(e instanceof XmlException)) { + e.printStackTrace(System.out); + } + System.out.println("Schema invalid"); + for (Object compError : compErrors) System.out.println(compError); + return false; + } + + boolean result = true; + + for (int i = 0; i < instances.length; i++) { + String instance = instances[i].toString(); + + XmlObject xobj; + + try { + assertNotNull(sLoader); + xobj = sLoader.parse(instance, null, new XmlOptions().setLoadLineNumbers()); + } catch (XmlException e) { + System.out.println("Error:\n" + instance + " not loadable: " + e); + e.printStackTrace(System.out); + result = false; + continue; + } + + Collection errors = new ArrayList(); + + if (xobj.schemaType() == XmlObject.type) { + System.out.println(instance + " NOT valid. "); + System.out.println(" Document type not found."); + result = false; + } else if (xobj.validate(new XmlOptions().setErrorListener(errors))) + System.out.println("Instance[" + i + "] valid."); + else { + System.out.println("Instance[" + i + "] NOT valid."); + for (Object error : errors) { + System.out.println(" " + error); + } + result = false; + } + } + + return result; + } + +} diff --git a/test/src/tools/inst2xsd/detailed/ComplexDetailedTest.java b/src/test/java/tools/inst2xsd/detailed/ComplexDetailedTest.java similarity index 98% rename from test/src/tools/inst2xsd/detailed/ComplexDetailedTest.java rename to src/test/java/tools/inst2xsd/detailed/ComplexDetailedTest.java index 45ba8bd..6c0d2fb 100644 --- a/test/src/tools/inst2xsd/detailed/ComplexDetailedTest.java +++ b/src/test/java/tools/inst2xsd/detailed/ComplexDetailedTest.java @@ -14,20 +14,18 @@ */ package tools.inst2xsd.detailed; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.junit.Ignore; +import org.junit.Test; import tools.inst2xsd.common.Inst2XsdTestBase; import java.io.File; -import java.io.IOException; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +@Ignore public class ComplexDetailedTest extends Inst2XsdTestBase { - public ComplexDetailedTest(String name) { - super(name); - } - + @Test public void test_complex_enum() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "enum.xml")); @@ -42,6 +40,7 @@ public void test_complex_enum() throws Exception { XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "enum2_ss0.xsd"))); } + @Test public void test_complex_enum_never() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "enum.xml")); @@ -57,9 +56,9 @@ public void test_complex_enum_never() throws Exception { log("-= SCS Options =-"); runSchemaBuild(inst, opts, XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "enum_vb_scs_enum0.xsd"))); - } + @Test public void test_complex_qname_enum() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "enumQName.xml")); @@ -74,6 +73,7 @@ public void test_complex_qname_enum() throws Exception { XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "enumQName_vb_eN0.xsd"))); } + @Test public void test_complex_nestedNSArray() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "nestedNSArray" + P + "nestedNSArray.xml")); @@ -100,6 +100,7 @@ public void test_complex_nestedNSArray() throws Exception { }); } + @Test public void test_example_po() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "examples" + P + "po" + P + "po.xml")); @@ -144,6 +145,7 @@ public void test_example_po() throws Exception { /** * java.lang.IllegalStateException: Not on a container */ + @Test public void test_complex_attrenum() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "complex" + P + "enum" + P + "attr"+P+"attrenum.xml")); diff --git a/test/src/tools/inst2xsd/detailed/DetailedLCDTest.java b/src/test/java/tools/inst2xsd/detailed/DetailedLCDTest.java similarity index 98% rename from test/src/tools/inst2xsd/detailed/DetailedLCDTest.java rename to src/test/java/tools/inst2xsd/detailed/DetailedLCDTest.java index b710edb..01135d2 100644 --- a/test/src/tools/inst2xsd/detailed/DetailedLCDTest.java +++ b/src/test/java/tools/inst2xsd/detailed/DetailedLCDTest.java @@ -14,15 +14,14 @@ */ package tools.inst2xsd.detailed; +import org.junit.Ignore; +import org.junit.Test; import tools.inst2xsd.common.Inst2XsdTestBase; import org.apache.xmlbeans.XmlObject; +@Ignore public class DetailedLCDTest extends Inst2XsdTestBase { - public DetailedLCDTest(String name) { - super(name); - } - // List of precedence for smart simple primitive type determination // byte, short, int, long, integer, float, double, decimal, // boolean @@ -67,6 +66,7 @@ public void test_lcd_duration() throws Exception { runLCDTypeCheckTest("P1347Y", "-P1347M", "duration"); } */ + @Test public void test_lcd_anyuri() throws Exception { runLCDTypeCheckTest("abc", "http://www.math.uio.no/faq/compression-faq/part1.html", "string"); @@ -76,6 +76,7 @@ public void test_lcd_anyuri() throws Exception { //runLCDTypeCheckTest("ftp://ftp.is.co.za/rfc/rfc1808.txt", "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", "anyURI"); } + @Test public void test_lcd_byte() throws Exception { runLCDTypeCheckTest("122", "123", "byte"); runLCDTypeCheckTest("-1", "+100", "byte"); @@ -100,9 +101,9 @@ public void test_lcd_byte() throws Exception { runLCDTypeCheckTest("1267.43233E12", "-1", "float"); runLCDTypeCheckTest("INF", "0", "float"); runLCDTypeCheckTest("abc", "127", "string"); - } + @Test public void test_lcd_short() throws Exception { runLCDTypeCheckTest("32767","-129", "short"); runLCDTypeCheckTest("-32768","128", "short"); @@ -126,6 +127,7 @@ public void test_lcd_short() throws Exception { runLCDTypeCheckTest("abc", "-3000", "string"); } + @Test public void test_lcd_int() throws Exception { runLCDTypeCheckTest("32768","39000", "int"); runLCDTypeCheckTest("32768","32768", "int"); @@ -150,6 +152,7 @@ public void test_lcd_int() throws Exception { runLCDTypeCheckTest("abc", "32768", "string"); } + @Test public void test_lcd_long() throws Exception { runLCDTypeCheckTest("-9223372036854775808","2147483648", "long"); runLCDTypeCheckTest("-9223372036854775808","-2147483649", "long"); @@ -168,6 +171,7 @@ public void test_lcd_long() throws Exception { runLCDTypeCheckTest("abc", "2150000000", "string"); } + @Test public void test_lcd_integer() throws Exception { runLCDTypeCheckTest("9223372036854775808","9300000000000000000", "integer"); runLCDTypeCheckTest("9223372036854775808","-9300000000000000000", "integer"); @@ -182,6 +186,7 @@ public void test_lcd_integer() throws Exception { runLCDTypeCheckTest("abc", "9223372036854775808", "string"); } + @Test public void test_lcd_float() throws Exception { runLCDTypeCheckTest("+100000.00","12.78e-2", "float"); runLCDTypeCheckTest("+100000.00","1267.43233E12", "float"); @@ -227,12 +232,13 @@ public void test_lcd_float() throws Exception { //runLCDTypeCheckTest("","1999"), "gYear"); //} - + @Test public void test_lcd_date() throws Exception { runLCDTypeCheckTest("abc", "1999-05-31", "string"); runLCDTypeCheckTest("1999-06-15","1999-05-31", "date"); } + @Test public void test_lcd_dateTime() throws Exception { runLCDTypeCheckTest("abc", "1999-05-31T13:20:00-05:00", "string"); runLCDTypeCheckTest("1999-05-31T13:20:00-08:00","1999-05-31T13:20:00-05:00", "dateTime"); @@ -240,6 +246,7 @@ public void test_lcd_dateTime() throws Exception { runLCDTypeCheckTest("1999-05-15T13:20:00-05:00","2000-03-04T23:00:00+03:00", "dateTime"); } + @Test public void test_lcd_time() throws Exception { runLCDTypeCheckTest("abc", "13:20:00-05:00", "string"); runLCDTypeCheckTest("00:00:00","13:20:00-05:00", "time"); @@ -258,7 +265,4 @@ public void test_lcd_time() throws Exception { runAttrTypeChecking(xsdString, "QName"); runAttrTypeChecking(foobaz, "QName"); }*/ - - - } diff --git a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedAttrTest.java b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedAttrTest.java similarity index 98% rename from test/src/tools/inst2xsd/detailed/Inst2XsdDetailedAttrTest.java rename to src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedAttrTest.java index 56957ce..3e5f3d4 100644 --- a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedAttrTest.java +++ b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedAttrTest.java @@ -14,15 +14,12 @@ */ package tools.inst2xsd.detailed; +import org.junit.Test; import tools.inst2xsd.common.Inst2XsdTestBase; import org.apache.xmlbeans.XmlObject; public class Inst2XsdDetailedAttrTest extends Inst2XsdTestBase { - public Inst2XsdDetailedAttrTest(String name) { - super(name); - } - // List of precedence for smart simple primitive type determination // byte, short, int, long, integer, float, double, decimal, // boolean @@ -72,6 +69,7 @@ public void test_attrgMonth() throws Exception { //runAttrTypeChecking(getAttrTypeXml("1999"), "gYear"); //} + @Test public void test_attranyuri() throws Exception { runAttrTypeChecking(getAttrTypeXml("http://www.math.uio.no/faq/compression-faq/part1.html"), "anyURI"); runAttrTypeChecking(getAttrTypeXml("http://www.example.com/doc.html#ID5"), "anyURI"); @@ -88,6 +86,7 @@ public void test_attranyuri() throws Exception { * 0, and 1 get picked up by byte * true, false are strings */ + @Test public void test_attrboolean() throws Exception { runAttrTypeChecking(getAttrTypeXml("true"), "string"); runAttrTypeChecking(getAttrTypeXml("false"), "string"); @@ -96,11 +95,7 @@ public void test_attrboolean() throws Exception { //runAttrTypeChecking(getAttrTypeXml("false"), "boolean"); } - - - - - + @Test public void test_attrQName() throws Exception { XmlObject xsdString = XmlObject.Factory.parse(""); @@ -111,7 +106,4 @@ public void test_attrQName() throws Exception { runAttrTypeChecking(xsdString, "QName"); runAttrTypeChecking(foobaz, "QName"); } - - - } diff --git a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedOptionsTest.java b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedOptionsTest.java similarity index 93% rename from test/src/tools/inst2xsd/detailed/Inst2XsdDetailedOptionsTest.java rename to src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedOptionsTest.java index 08f7555..8ca801c 100644 --- a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedOptionsTest.java +++ b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedOptionsTest.java @@ -14,23 +14,19 @@ */ package tools.inst2xsd.detailed; -import tools.inst2xsd.common.Inst2XsdTestBase; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd; - +import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Ignore; +import org.junit.Test; +import tools.inst2xsd.common.Inst2XsdTestBase; import java.io.File; -import java.io.IOException; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; public class Inst2XsdDetailedOptionsTest extends Inst2XsdTestBase { - public Inst2XsdDetailedOptionsTest(String name) { - super(name); - } - + @Test public void test_simpleContentString_Russian() throws Exception { Inst2XsdOptions opt = common.getRussianOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING); @@ -54,6 +50,8 @@ public void test_simpleContentString_Russian() throws Exception { } + @Test + @Ignore public void test_simpleContentString_Salami() throws Exception { Inst2XsdOptions opt = common.getSalamiOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING); @@ -75,6 +73,7 @@ public void test_simpleContentString_Salami() throws Exception { compare(api[0], exp); } + @Test public void test_simpleContentString_Venetian() throws Exception { Inst2XsdOptions opt = common.getVenetianOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING); @@ -97,7 +96,7 @@ public void test_simpleContentString_Venetian() throws Exception { compare(api[0], exp); } - + @Test public void test_simpleContentSmart_Russian() throws Exception { Inst2XsdOptions opt = common.getRussianOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART); @@ -119,6 +118,8 @@ public void test_simpleContentSmart_Russian() throws Exception { compare(api[0], exp); } + @Test + @Ignore public void test_simpleContentSmart_Salami() throws Exception { Inst2XsdOptions opt = common.getSalamiOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART); @@ -140,6 +141,7 @@ public void test_simpleContentSmart_Salami() throws Exception { compare(api[0], exp); } + @Test public void test_simpleContentSmart_Venetian() throws Exception { Inst2XsdOptions opt = common.getVenetianOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART); @@ -161,7 +163,7 @@ public void test_simpleContentSmart_Venetian() throws Exception { compare(api[0], exp); } - + @Test public void test_simpleContentSmart_NeverEnum_Russian() throws Exception { Inst2XsdOptions opt = common.getRussianOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART); @@ -185,6 +187,8 @@ public void test_simpleContentSmart_NeverEnum_Russian() throws Exception { compare(api[0], exp); } + @Test + @Ignore public void test_simpleContentSmart_NeverEnum_Salami() throws Exception { Inst2XsdOptions opt = common.getSalamiOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART); @@ -208,6 +212,7 @@ public void test_simpleContentSmart_NeverEnum_Salami() throws Exception { compare(api[0], exp); } + @Test public void test_simpleContentSmart_NeverEnum_Venetian() throws Exception { Inst2XsdOptions opt = common.getVenetianOptions(); opt.setUseEnumerations(Inst2XsdOptions.ENUMERATION_NEVER); @@ -231,6 +236,7 @@ public void test_simpleContentSmart_NeverEnum_Venetian() throws Exception { compare(api[0], exp); } + @Test public void test_simpleContentString_NeverEnum_Russian() throws Exception { Inst2XsdOptions opt = common.getRussianOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING); @@ -254,6 +260,8 @@ public void test_simpleContentString_NeverEnum_Russian() throws Exception { compare(api[0], exp); } + @Test + @Ignore public void test_simpleContentString_NeverEnum_Salami() throws Exception { Inst2XsdOptions opt = common.getSalamiOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING); @@ -277,6 +285,7 @@ public void test_simpleContentString_NeverEnum_Salami() throws Exception { compare(api[0], exp); } + @Test public void test_simpleContentString_NeverEnum_Venetian() throws Exception { Inst2XsdOptions opt = common.getVenetianOptions(); opt.setUseEnumerations(Inst2XsdOptions.ENUMERATION_NEVER); @@ -302,6 +311,7 @@ public void test_simpleContentString_NeverEnum_Venetian() throws Exception { //TODO: move to checkin - cursor issue + @Test public void test_simpleContentSmart() throws Exception { Inst2XsdOptions opt = common.getDefaultInstOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART); @@ -322,6 +332,7 @@ public void test_simpleContentSmart() throws Exception { } //TODO: move to checkin - cursor issue + @Test public void test_neverEnum() throws Exception { Inst2XsdOptions opt = common.getVenetianOptions(); opt.setUseEnumerations(Inst2XsdOptions.ENUMERATION_NEVER); @@ -340,6 +351,7 @@ public void test_neverEnum() throws Exception { } //TODO: move to checkin - cursor issue + @Test public void test_simpleContentString() throws Exception { Inst2XsdOptions opt = common.getDefaultInstOptions(); opt.setSimpleContentTypes(Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING); @@ -348,7 +360,23 @@ public void test_simpleContentString() throws Exception { checkLength(sDoc, 1); String stringContent = "" + - "" + + "" + + " \n" + + " Copyright 2004 The Apache Software Foundation\n" + + "\n" + + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " you may not use this file except in compliance with the License.\n" + + " You may obtain a copy of the License at\n" + + "\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + "\n" + + " Unless required by applicable law or agreed to in writing, software\n" + + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " See the License for the specific language governing permissions and\n" + + " limitations under the License. \n" + + " \n" + + ""+ "" + "" + "" + @@ -371,6 +399,7 @@ public void test_simpleContentString() throws Exception { } //TODO: move to checkin - cursor issue + @Test public void test_RussianDesign() throws Exception { SchemaDocument[] sDoc = getSchemaDoc(runInst2Xsd(XmlObject.Factory.parse(common.base), common.getRussianOptions())); @@ -389,6 +418,8 @@ public void test_RussianDesign() throws Exception { } //TODO: move to checkin - cursor issue + @Test + @Ignore public void test_SalamiDesign() throws Exception { SchemaDocument[] sDoc = getSchemaDoc(runInst2Xsd(XmlObject.Factory.parse(common.base), common.getSalamiOptions())); @@ -407,6 +438,7 @@ public void test_SalamiDesign() throws Exception { } //TODO: move to checkin - cursor issue + @Test public void test_VenetianDesign() throws Exception { SchemaDocument[] sDoc = getSchemaDoc(runInst2Xsd(new XmlObject[]{XmlObject.Factory.parse(common.base)}, common.getVenetianOptions())); diff --git a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedTest.java b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedTest.java similarity index 98% rename from test/src/tools/inst2xsd/detailed/Inst2XsdDetailedTest.java rename to src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedTest.java index b387299..f677e7b 100644 --- a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedTest.java +++ b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedTest.java @@ -14,21 +14,19 @@ */ package tools.inst2xsd.detailed; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.junit.Ignore; +import org.junit.Test; import tools.inst2xsd.common.Inst2XsdTestBase; import java.io.File; -import java.io.IOException; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +@Ignore public class Inst2XsdDetailedTest extends Inst2XsdTestBase { - public Inst2XsdDetailedTest(String name) { - super(name); - } - //TODO: move to checkin + @Test public void test_ns_duplicate_salami() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "namespaces" + P + "duplicatedNS.xml")); log("-= Salami =-"); @@ -37,6 +35,7 @@ public void test_ns_duplicate_salami() throws Exception { } //TODO: move to checkin + @Test public void test_ns_duplicate_venetian() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "namespaces" + P + "duplicatedNS.xml")); log("-= venetian =-"); @@ -46,6 +45,7 @@ public void test_ns_duplicate_venetian() throws Exception { } //TODO: move to checkin QName:bug + @Test public void test_examples_xmlnews() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "examples" + P + "xmlnews.xml")); @@ -61,6 +61,7 @@ public void test_examples_xmlnews() throws Exception { } //TODO: move to checkin QName:bug + @Test public void test_examples_slashdotrdf() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "examples" + P + "slashdot.rdf.xml")); @@ -82,6 +83,7 @@ public void test_examples_slashdotrdf() throws Exception { } //TODO: move to checkin QName:bug + @Test public void test_examples_xsl() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "examples" + P + "xsl_example.xml")); @@ -103,6 +105,7 @@ public void test_examples_xsl() throws Exception { } //TODO: move to checkin QName:bug + @Test public void test_examples_rss092() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "examples" + P + "sampleRss092.xml")); @@ -117,6 +120,7 @@ public void test_examples_rss092() throws Exception { XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "examples" + P + "sampleRss092_ss0.xsd"))); } + @Test public void test_types_comments() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "types" + P + "comments.xml")); @@ -131,6 +135,7 @@ public void test_types_comments() throws Exception { XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "types" + P + "comments_ss0.xsd"))); } + @Test public void test_types_commentschoice() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "types" + P + "commentschoice.xml")); Inst2XsdOptions opts = common.getRussianOptions(); @@ -152,6 +157,7 @@ public void test_types_commentschoice() throws Exception { } /** This case fails validation because comment is not recognized */ + @Test public void test_types_innercomment() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "types" + P + "innercomment.xml")); @@ -159,6 +165,7 @@ public void test_types_innercomment() throws Exception { XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "types" + P + "innercomment_vb0.xsd"))); } + @Test public void test_types_nillable() throws Exception { XmlObject inst = XmlObject.Factory.parse(new File(SCHEMA_CASES_DIR + "types" + P + "xsinil.xml")); diff --git a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedTypeTest.java b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedTypeTest.java similarity index 98% rename from test/src/tools/inst2xsd/detailed/Inst2XsdDetailedTypeTest.java rename to src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedTypeTest.java index 0562706..b4c1586 100644 --- a/test/src/tools/inst2xsd/detailed/Inst2XsdDetailedTypeTest.java +++ b/src/test/java/tools/inst2xsd/detailed/Inst2XsdDetailedTypeTest.java @@ -14,15 +14,12 @@ */ package tools.inst2xsd.detailed; -import tools.inst2xsd.common.Inst2XsdTestBase; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.inst2xsd.common.Inst2XsdTestBase; public class Inst2XsdDetailedTypeTest extends Inst2XsdTestBase { - public Inst2XsdDetailedTypeTest(String name) { - super(name); - } - // List of precedence for smart simple primitive type determination // byte, short, int, long, integer, float, double, decimal, // boolean @@ -67,6 +64,7 @@ public void test_duration() throws Exception { // runTypeChecking(getTypeXml("0FB7"), "hexBinary"); //} + @Test public void test_anyuri() throws Exception { runTypeChecking(getTypeXml("http://www.math.uio.no/faq/compression-faq/part1.html"), "anyURI"); runTypeChecking(getTypeXml("http://www.example.com/doc.html#ID5"), "anyURI"); @@ -86,6 +84,7 @@ public void test_anyuri() throws Exception { * true and false are strings * */ + @Test public void test_boolean() throws Exception { //runTypeChecking(getTypeXml("true"), "boolean"); //runTypeChecking(getTypeXml("false"), "boolean"); @@ -94,6 +93,7 @@ public void test_boolean() throws Exception { } + @Test public void test_QName() throws Exception { XmlObject xsdString = XmlObject.Factory.parse("xsd:string"); @@ -109,8 +109,4 @@ public void test_QName() throws Exception { runTypeChecking(xsiint, "QName"); runTypeChecking(foobaz, "QName"); } - - - - } diff --git a/test/src/tools/inst2xsd/detailed/Inst2XsdMiscTest.java b/src/test/java/tools/inst2xsd/detailed/Inst2XsdMiscTest.java similarity index 82% rename from test/src/tools/inst2xsd/detailed/Inst2XsdMiscTest.java rename to src/test/java/tools/inst2xsd/detailed/Inst2XsdMiscTest.java index 0afcf68..7d01544 100644 --- a/test/src/tools/inst2xsd/detailed/Inst2XsdMiscTest.java +++ b/src/test/java/tools/inst2xsd/detailed/Inst2XsdMiscTest.java @@ -14,26 +14,36 @@ */ package tools.inst2xsd.detailed; -import tools.inst2xsd.common.Inst2XsdTestBase; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd; -import org.apache.xmlbeans.impl.common.IOUtil; -import org.apache.xmlbeans.impl.tool.CommandLine; - +import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Test; +import tools.inst2xsd.common.Inst2XsdTestBase; -import java.io.File; -import java.io.IOException; import java.io.FileReader; -import java.io.PrintStream; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; public class Inst2XsdMiscTest extends Inst2XsdTestBase { public static final String EXPBASEXML = "\n" + "\n" + - " \n" + + " \n" + + " \n" + + " Copyright 2004 The Apache Software Foundation\n" + + "\n" + + " Licensed under the Apache License, Version 2.0 (the \"License\");\n" + + " you may not use this file except in compliance with the License.\n" + + " You may obtain a copy of the License at\n" + + "\n" + + " http://www.apache.org/licenses/LICENSE-2.0\n" + + "\n" + + " Unless required by applicable law or agreed to in writing, software\n" + + " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " See the License for the specific language governing permissions and\n" + + " limitations under the License. \n" + + " \n" + + " \n" + " \n" + " \n" + " \n" + @@ -43,10 +53,7 @@ public class Inst2XsdMiscTest extends Inst2XsdTestBase { " \n" + ""; - public Inst2XsdMiscTest(String name) { - super(name); - } - + @Test public void test_usingReader() throws Exception { FileReader[] fReader = new FileReader[]{new FileReader(BASEXML)}; SchemaDocument[] doc = Inst2Xsd.inst2xsd( fReader, common.getDefaultInstOptions()); @@ -56,6 +63,7 @@ public void test_usingReader() throws Exception { compare(doc[0],XmlObject.Factory.parse(EXPBASEXML) ); } + @Test public void test_nulloptions() throws Exception { FileReader[] fReader = new FileReader[]{new FileReader(BASEXML)}; SchemaDocument[] doc = Inst2Xsd.inst2xsd(fReader, null); @@ -64,6 +72,7 @@ public void test_nulloptions() throws Exception { compare(doc[0], XmlObject.Factory.parse(EXPBASEXML)); } + @Test public void test_notverboseoptions() throws Exception { FileReader[] fReader = new FileReader[]{new FileReader(BASEXML)}; Inst2XsdOptions opts = common.getDefaultInstOptions(); diff --git a/src/test/java/tools/util/JarUtil.java b/src/test/java/tools/util/JarUtil.java new file mode 100755 index 0000000..26979bd --- /dev/null +++ b/src/test/java/tools/util/JarUtil.java @@ -0,0 +1,85 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package tools.util; + +import java.io.*; +import java.nio.charset.StandardCharsets; + +/** + * A utility class for getting data from jar files + */ +public class JarUtil { + + /** + * returns an File Object within the given jarFile as a String. jarFile must exist in classpath + * pre: jar containing resource is in the classpath + */ + public static File getResourceFromJarasFile(String pathToResource) + throws IOException { + + String[] tokens = pathToResource.split("/"); + String fileName = tokens[tokens.length - 1]; + tokens = fileName.split("\\."); + String extension = (tokens.length < 2) ? null : "." + tokens[1]; + String prefix = (tokens[0].length() < 3) ? tokens[0] + "abc" : tokens[0]; + File temp = File.createTempFile(prefix, extension); + temp.deleteOnExit(); + try (PrintWriter pr = new PrintWriter(new FileWriter(temp))) { + String content = getResourceFromJar(pathToResource); + pr.write(content); + } + return temp; + } + + + /** + * returns the resource as String + */ + public static String getResourceFromJar(String pathToResource) + throws IOException { + + BufferedReader in = null; + try { + InputStream is = getResourceFromJarasStream(pathToResource); + in = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + char[] buf = new char[1024]; + for (int readChr; (readChr = in.read(buf)) > -1; ) { + sb.append(buf, 0, readChr); + } + return sb.toString(); + } finally { + if (in != null) { + in.close(); + } + } + } + + /** + * returns an item within the given jarFile as a Stream + */ + + public static InputStream getResourceFromJarasStream(String pathToResource) + throws IOException { + InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream( + pathToResource); + if (resource == null) { + throw new IOException(" Resource " + pathToResource + " was not found. " + + "Make sure Jar w/ resource is on classpath"); + } + return resource; + } +} + diff --git a/src/test/java/tools/util/Util.java b/src/test/java/tools/util/Util.java new file mode 100755 index 0000000..b3a06c6 --- /dev/null +++ b/src/test/java/tools/util/Util.java @@ -0,0 +1,54 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package tools.util; + +import java.io.PrintWriter; +import java.io.StringWriter; + +/** + * Utilities to copy files, directories, etc. + */ +public class Util { + /** + * Helper to get the stack trace of an Exception as a String. + * + * @param t Use the stack trace of this exception. + * @return The stack trace as a String. + */ + public static String getStackTrace(Throwable t) { + if (t == null) { + return null; + } + + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + + /** + * Checks if a string is entirely whitespace + */ + public static boolean isWhiteSpace(String s) { + for (int i = 0; i < s.length(); i++) { + if (!Character.isWhitespace(s.charAt(i))) { + return false; + } + } + + return true; + } +} + + diff --git a/test/tools/src/tools/xml/Utils.java b/src/test/java/tools/xml/Utils.java similarity index 100% rename from test/tools/src/tools/xml/Utils.java rename to src/test/java/tools/xml/Utils.java diff --git a/test/tools/src/tools/xml/XmlComparator.java b/src/test/java/tools/xml/XmlComparator.java similarity index 96% rename from test/tools/src/tools/xml/XmlComparator.java rename to src/test/java/tools/xml/XmlComparator.java index bed1b23..2a5d1ee 100755 --- a/test/tools/src/tools/xml/XmlComparator.java +++ b/src/test/java/tools/xml/XmlComparator.java @@ -24,24 +24,24 @@ public class XmlComparator { public static class Diagnostic { - private StringBuffer message = null; + private StringBuilder message = null; private void add(String s) { - if (message==null) - message = new StringBuffer(); + if (message == null) + message = new StringBuilder(); message.append(s).append("\n"); } public boolean hasMessage() { - return message!=null; + return message != null; } public String toString() { - return (message==null ? null : message.toString()); + return (message == null ? null : message.toString()); } public static void add(Diagnostic diag, String s) diff --git a/src/test/java/xmlcursor/checkin/AddToSelectionTest.java b/src/test/java/xmlcursor/checkin/AddToSelectionTest.java new file mode 100755 index 0000000..76bd460 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/AddToSelectionTest.java @@ -0,0 +1,111 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + + +public class AddToSelectionTest extends BasicCursorTestCase { + + private static String sXml = "0123456"; + + @Test + public void testAddToSelectionEnd() { + m_xc.toEndDoc(); + m_xc.addToSelection(); + assertEquals(1, m_xc.getSelectionCount()); + } + + @Test + public void testAddToSelectionStart() { + m_xc.toStartDoc(); + m_xc.addToSelection(); + assertEquals(1, m_xc.getSelectionCount()); + } + + @Test + public void testAddToSelectionAll() throws Exception { + sXml = ""; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + XmlCursor.TokenType tok; + m_xc.addToSelection(); + while ((tok = m_xc.toNextToken()) != XmlCursor.TokenType.NONE) { + System.err.println(tok); + m_xc.addToSelection(); + } + assertEquals(4, m_xc.getSelectionCount()); + + //check results + XmlCursor m_xc1 = XmlObject.Factory.parse(sXml).newCursor(); + m_xc.toSelection(0); //reset cursor + int i = m_xc.getSelectionCount(); + while ((tok = m_xc1.toNextToken()) != XmlCursor.TokenType.NONE) { + //assertEquals(true,m_xc.hasNextSelection()); + assertEquals(m_xc.toNextToken(), tok); + m_xc.toNextSelection(); + } + //second cursor should be at the end of selections too... + assertFalse(m_xc.toNextSelection()); + m_xc1.dispose(); + } + + @Test + public void testAddToSelectionSet() { + //not set but bag semantics + int expRes = 100; + + m_xc.clearSelections(); + for (int i = 0; i < 100; i++) { + m_xc.toStartDoc(); + m_xc.addToSelection(); + } + assertEquals(expRes, m_xc.getSelectionCount()); + } + + @Test(expected = Throwable.class) + public void testAddAfterDispose() { + m_xc.dispose(); + m_xc.addToSelection(); + + } + + @Before + public void setUp() throws Exception { + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + } + + @After + public void tearDown() { + if (m_xc == null) return; + try { + m_xc.clearSelections(); + super.tearDown(); + } catch (IllegalStateException e) { //cursor disposed + } catch (Exception e) { + + } + } +} + diff --git a/src/test/java/xmlcursor/checkin/AnnotationsTests.java b/src/test/java/xmlcursor/checkin/AnnotationsTests.java new file mode 100755 index 0000000..0dd8e02 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/AnnotationsTests.java @@ -0,0 +1,62 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class AnnotationsTests { + private static class TestBookmark extends XmlCursor.XmlBookmark { + } + + // + // Basic load up a file and iterate through it + // + @Test + public void testBasicXml() throws Exception { + XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); + + TestBookmark a1 = new TestBookmark(); + + c.setBookmark(a1); + + TestBookmark a2 = new TestBookmark(); + + c.toNextToken(); + c.toNextToken(); + + c.setBookmark(a2); + + c.toPrevToken(); + c.toPrevToken(); + + assertEquals(c.getBookmark(TestBookmark.class), a1); + + c.toNextToken(); + c.toNextToken(); + + assertEquals(c.getBookmark(TestBookmark.class), a2); + + c.toNextToken(); + + assertNull(c.getBookmark(TestBookmark.class)); + } +} diff --git a/src/test/java/xmlcursor/checkin/BeginElementTest.java b/src/test/java/xmlcursor/checkin/BeginElementTest.java new file mode 100755 index 0000000..a0cf9a9 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/BeginElementTest.java @@ -0,0 +1,88 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + + +public class BeginElementTest extends BasicCursorTestCase { + + private String sLocalName="localName"; + private String sUri="fakeURI"; + private String sDefaultPrefix=sUri.substring(0,3); //$BUGBUG:WHY??? + private String sExpectedStart="<"+sDefaultPrefix+":localName xmlns:"+sDefaultPrefix+"=\"fakeURI\"/>"; + + private String sInputDoc=Common.XML_FOO_DIGITS; + + + @Test + public void testBeginElementStr() throws Exception { + //same for string API + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + m_xc.beginElement(sLocalName, sUri); + toPrevTokenOfType(m_xc, TokenType.START); + assertEquals(m_xc.xmlText(), sExpectedStart); + } + + @Test + public void testBeginElementQName() throws Exception { + //Qname call + + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + //insert new under the first element + toNextTokenOfType(m_xc, TokenType.START); + QName qName = new QName(sUri, sLocalName); + m_xc.beginElement(qName); + checkResult(qName); + } + + @Test + public void testBeginElementQNamePrefix() throws Exception { + //Qname with prefix + String sPrefix = "pre"; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + QName qName = new QName(sUri, sLocalName, sPrefix); + System.out.println("Java prefix Qname: " + qName); + m_xc.beginElement(qName); + checkResult(qName); + } + + //pre: cursor is not moved after beginElt call + private void checkResult(QName qName) { + TokenType tok = m_xc.toPrevToken(); + assertEquals(m_xc.getName(), qName); + } + + public void testBeginElementStartDoc(String sLocalName, String sUri) throws Exception { + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + m_xc.beginElement(sLocalName, sUri); + m_xc.toPrevToken(); + m_xc.toPrevToken(); + assertTrue(m_xc.isStartdoc()); + } +} diff --git a/test/src/xmlcursor/checkin/ClearBookmarkTest.java b/src/test/java/xmlcursor/checkin/ClearBookmarkTest.java similarity index 94% rename from test/src/xmlcursor/checkin/ClearBookmarkTest.java rename to src/test/java/xmlcursor/checkin/ClearBookmarkTest.java index 693e52c..4097a36 100755 --- a/test/src/xmlcursor/checkin/ClearBookmarkTest.java +++ b/src/test/java/xmlcursor/checkin/ClearBookmarkTest.java @@ -15,35 +15,22 @@ package xmlcursor.checkin; -import junit.framework.*; - - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.XmlBookmark; - - +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -/** - * - * - */ public class ClearBookmarkTest extends BasicCursorTestCase { private Bookmark0 _theAnnotation0 = new Bookmark0("value0"); private Bookmark1 _theAnnotation1 = new Bookmark1("value1"); private Bookmark2 _theAnnotation2 = new Bookmark2("value2"); - public ClearBookmarkTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ClearBookmarkTest.class); - } - + @Test public void testClearIndependent() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -66,6 +53,7 @@ public void testClearIndependent() throws Exception { assertEquals("value2", ann2.text); } + @Test public void testClearNullKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -75,6 +63,7 @@ public void testClearNullKey() throws Exception { assertEquals("value0", ann0.text); } + @Test public void testClearSuperClass() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -84,6 +73,7 @@ public void testClearSuperClass() throws Exception { assertEquals("value0", ann0.text); } + @Test public void testClearInvalidClass() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); diff --git a/test/src/xmlcursor/checkin/ClearSelectionTest.java b/src/test/java/xmlcursor/checkin/ClearSelectionTest.java similarity index 86% rename from test/src/xmlcursor/checkin/ClearSelectionTest.java rename to src/test/java/xmlcursor/checkin/ClearSelectionTest.java index 0ae65a0..0b93edc 100755 --- a/test/src/xmlcursor/checkin/ClearSelectionTest.java +++ b/src/test/java/xmlcursor/checkin/ClearSelectionTest.java @@ -16,26 +16,16 @@ package xmlcursor.checkin; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; -/** - * - * - */ public class ClearSelectionTest extends BasicCursorTestCase { - public ClearSelectionTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ClearSelectionTest.class); - } - + @Test public void testClearSelection() throws Exception { //m_xo = XmlObject.Factory.parse(Common.XML_PURCHASEORDER); m_xo = XmlObject.Factory.parse( @@ -48,17 +38,17 @@ public void testClearSelection() throws Exception { assertEquals("Mill Valley", m_xc.getTextValue()); assertEquals("Mill Valley", m_xc.xmlText()); m_xc.clearSelections(); - assertEquals(false, m_xc.toNextSelection()); + assertFalse(m_xc.toNextSelection()); assertEquals("Mill Valley", m_xc.getTextValue()); assertEquals("Mill Valley", m_xc.xmlText()); } + @Test public void testClearSelectionNoSelection() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); m_xc = m_xo.newCursor(); m_xc.clearSelections(); } - } diff --git a/test/src/xmlcursor/checkin/ComparePositionTest.java b/src/test/java/xmlcursor/checkin/ComparePositionTest.java similarity index 85% rename from test/src/xmlcursor/checkin/ComparePositionTest.java rename to src/test/java/xmlcursor/checkin/ComparePositionTest.java index 2847c6c..8f14d57 100755 --- a/test/src/xmlcursor/checkin/ComparePositionTest.java +++ b/src/test/java/xmlcursor/checkin/ComparePositionTest.java @@ -19,25 +19,15 @@ import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; -/** - * - * - */ -public class ComparePositionTest extends BasicCursorTestCase { - public ComparePositionTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ComparePositionTest.class); - } +public class ComparePositionTest extends BasicCursorTestCase { + @Test public void testComparePositionThis() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -45,6 +35,7 @@ public void testComparePositionThis() throws Exception { assertEquals(0, m_xc.comparePosition(m_xc)); } + @Test(expected = IllegalArgumentException.class) public void testComparePositionDifferentDocs() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); @@ -52,23 +43,19 @@ public void testComparePositionDifferentDocs() throws Exception { xc0.toFirstChild(); try { m_xc.comparePosition(xc0); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { } finally { xc0.dispose(); } } + @Test(expected = IllegalArgumentException.class) public void testComparePositionNull() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); m_xc.toFirstChild(); - try { - m_xc.comparePosition(null); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { - } + m_xc.comparePosition(null); } + @Test public void testComparePositionRightInTEXT() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = m_xc.newCursor(); @@ -82,6 +69,7 @@ public void testComparePositionRightInTEXT() throws Exception { } } + @Test public void testComparePositionLeftInTEXT() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = m_xc.newCursor(); @@ -95,6 +83,7 @@ public void testComparePositionLeftInTEXT() throws Exception { } } + @Test public void testComparePositionENDandENDDOC() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = m_xc.newCursor(); diff --git a/src/test/java/xmlcursor/checkin/CopyTest.java b/src/test/java/xmlcursor/checkin/CopyTest.java new file mode 100755 index 0000000..db29601 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/CopyTest.java @@ -0,0 +1,215 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; + + +public class CopyTest extends BasicCursorTestCase { + @Test(expected = IllegalArgumentException.class) + public void testCopyToNull() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.copyXml(null); + } + + @Test + public void testCopyDifferentStoresLoadedByParse() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + XmlObject xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + XmlCursor xc1 = xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + toNextTokenOfType(xc1, TokenType.TEXT); + m_xc.copyXml(xc1); + xc1.toParent(); + // verify xc1 + assertEquals("01234text", xc1.getTextValue()); + xc1.dispose(); + // verify m_xc + assertEquals("01234", m_xc.getChars()); + } + + /** + * Method testCopyDifferentStoresLoadedFromFile + * + * Tests copy from document w/ namespaces to doc w/o + */ + @Test + public void testCopyDifferentStoresLoadedFromFile() throws Exception { + // load the documents and obtain a cursor + XmlObject xobj0 = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + XmlObject xobj1 = XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + + XmlCursor xc0 = xobj0.newCursor(); + XmlCursor xc1 = xobj1.newCursor(); + + xc0.selectPath(Common.CLM_NS_XQUERY_DEFAULT + " .//Initial"); + xc0.toNextSelection(); + String sQuery= + "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "+ + ".//po:zip"; + xc1.selectPath( sQuery ); + xc1.toNextSelection(); + + xc0.copyXml(xc1); // should copy the GATX element plus the default namespace + xc1.toPrevSibling(); + // verify xc1 + String sExpected = "" + + "GATX"; + assertEquals(sExpected, xc1.xmlText()); + // verify xc0 + // should contain all the namespaces for the document + assertEquals( + "GATX", + xc0.xmlText()); + xc0.dispose(); + xc1.dispose(); + + } + + /** + * Method testCopyDifferentStoresLoadedFromFile2 + * + * Tests copy from document w/o namespaces to document with namespaces + */ + @Test + public void testCopyDifferentStoresLoadedFromFile2() throws Exception { + // load the documents and obtain a cursor + XmlObject xobj0 = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + XmlObject xobj1 = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + + XmlCursor xc0 = xobj0.newCursor(); + XmlCursor xc1 = xobj1.newCursor(); + + xc0.selectPath(Common.CLM_NS_XQUERY_DEFAULT + " .//Initial"); + xc0.toNextSelection(); + + String sQuery= + "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "+ + ".//po:zip"; + xc1.selectPath( sQuery ); + xc1.selectPath( sQuery ); + xc1.toNextSelection(); + + xc1.copyXml(xc0); // should copy the 90952 element + // verify xc1 + assertEquals( + "90952", + xc1.xmlText()); + // verify xc0 + // should contain all the namespaces for the document + xc0.toPrevSibling(); + // assertEquals("90952", xc0.xmlText()); + String sExpected = "" + + "90952"; + + assertEquals(sExpected, xc0.xmlText()); + xc0.dispose(); + xc1.dispose(); + + } + + @Test + public void testCopySameLocation() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + toNextTokenOfType(xc1, TokenType.TEXT); + m_xc.copyXml(xc1); + xc1.dispose(); + m_xc.toParent(); + assertEquals("0123401234", m_xc.getTextValue()); + } + + @Test + public void testCopyNewLocation() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + + String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "; + m_xc = m_xo.newCursor(); + XmlCursor xc1 = m_xo.newCursor(); + m_xc.selectPath(ns+" .//po:shipTo/po:city"); + m_xc.toNextSelection(); + xc1.selectPath(ns +" .//po:billTo/po:city"); + xc1.toNextSelection(); + m_xc.copyXml(xc1); + xc1.toPrevToken(); + xc1.toPrevToken(); + // verify xc1 + assertEquals("Mill Valley", xc1.getChars()); + xc1.dispose(); + // verify m_xc + assertEquals("Mill Valley", m_xc.getTextValue()); + + } + + @Test + public void testCopyElementToMiddleOfTEXT() throws Exception { + String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "; + String exp_ns="xmlns:po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = m_xo.newCursor(); + m_xc.selectPath(ns+" .//po:shipTo/po:city"); + m_xc.toNextSelection(); + xc1.selectPath(ns+" .//po:billTo/po:city"); + xc1.toNextSelection(); + xc1.toNextToken(); + xc1.toNextChar(4); // should be at 'T' in "Old Town" + m_xc.copyXml(xc1); // should be "Old Mill ValleyTown" + // verify xc1 + xc1.toPrevToken(); + assertEquals(TokenType.END, xc1.currentTokenType()); + xc1.toPrevToken(); + assertEquals("Mill Valley", xc1.getChars()); + xc1.toPrevToken(); + assertEquals(TokenType.START, xc1.currentTokenType()); + assertEquals(new QName("city").getLocalPart(), + xc1.getName().getLocalPart()); + xc1.toPrevToken(); + assertEquals("Old ", xc1.getChars()); + // verify m_xc + assertEquals("Mill Valley", m_xc.xmlText()); + } +} diff --git a/src/test/java/xmlcursor/checkin/CopyXmlContentsTest.java b/src/test/java/xmlcursor/checkin/CopyXmlContentsTest.java new file mode 100755 index 0000000..de6fdbb --- /dev/null +++ b/src/test/java/xmlcursor/checkin/CopyXmlContentsTest.java @@ -0,0 +1,153 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class CopyXmlContentsTest extends BasicCursorTestCase { + @Test(expected = IllegalArgumentException.class) + public void testCopyToNull() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_DIGITS).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.copyXmlContents(null); + } + + @Test(expected = IllegalStateException.class) + public void testCopyDifferentStoresLoadedByParseInvalidDest() throws Exception { + String sDoc1 = Common.XML_FOO_DIGITS; + String sDoc2 = Common.XML_FOO_2ATTR_TEXT; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + toNextTokenOfType(xc1, TokenType.START); + xc1.dispose(); + m_xc.copyXmlContents(xc1); + } + + @Test + public void testCopyDifferentStoresLoadedByParse() throws Exception { + String sDoc1 = Common.XML_FOO_DIGITS; + String sDoc2 = Common.XML_FOO_2ATTR_TEXT; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + toNextTokenOfType(xc1, TokenType.TEXT); + m_xc.copyXmlContents(xc1); + xc1.toParent(); + // verify xc1 + assertEquals("01234text", xc1.getTextValue()); + xc1.dispose(); + + // verify m_xc + toNextTokenOfType(m_xc, TokenType.TEXT); //get to the text + assertEquals("01234", m_xc.getChars()); + } + + /* the source is not a container*/ + @Test + public void testCopyDifferentStoresLoadedByParseInvalidSrc() throws Exception { + String sDoc1 = Common.XML_FOO_DIGITS; + String sDoc2 = Common.XML_FOO_2ATTR_TEXT; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + toNextTokenOfType(xc1, TokenType.START); + boolean result = m_xc.copyXmlContents(xc1); + assertFalse(result); + } + + @Test + @Ignore + public void testCopyOntoItself() throws Exception { + String sDoc1 = Common.XML_FOO_DIGITS; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + String sExpectedXml = m_xc.xmlText(); + boolean result = m_xc.copyXmlContents(m_xc); + + //cursor is left immediately before copied material + assertEquals(sExpectedXml, m_xc.getTextValue()); + } + + @Test + public void testCopySelf() throws Exception { + String sDoc1 = Common.XML_FOO_DIGITS; + m_xo = XmlObject.Factory.parse(sDoc1); + m_xc = m_xo.newCursor(); + + toNextTokenOfType(m_xc, TokenType.START); + String sExpectedXml = "0123401234"; + boolean result = m_xc.copyXmlContents(m_xc); + + //cursor is left immediately before copied material + m_xc.toStartDoc(); + //assertEquals(sExpectedXml.length(),m_xc.xmlText().length()); + assertEquals(sExpectedXml, m_xc.xmlText()); + } + + + /** + Can't really copy the whole doc, so copy all the contents + into a false root */ + @Test + public void testCopyWholeDoc() throws Exception { + String sDoc1 = Common.XML_FOO_BAR_WS_TEXT; + String sDoc2 = ""; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); + xc1.toFirstChild(); + String sExpectedXml = m_xc.xmlText(); + boolean result = m_xc.copyXmlContents(xc1); + toPrevTokenOfType(xc1, TokenType.STARTDOC); + toNextTokenOfType(xc1, TokenType.START); + assertEquals(sExpectedXml, xc1.xmlText()); + + //namespaces are not copied + sDoc1 = Common.XML_FOO_NS_PREFIX; + sDoc2 = ""; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); + sExpectedXml = m_xc.xmlText(); + xc1.toFirstChild(); + + result = m_xc.copyXmlContents(xc1); + toPrevTokenOfType(xc1, TokenType.STARTDOC); + assertNotEquals(sExpectedXml, xc1.xmlText()); + + //attributes are not copied + sDoc1 = Common.XML_FOO_2ATTR; + sDoc2 = ""; + m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); + xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); + sExpectedXml = m_xc.xmlText(); + xc1.toFirstChild(); + + result = m_xc.copyXmlContents(xc1); + toPrevTokenOfType(xc1, TokenType.STARTDOC); + assertNotEquals(sExpectedXml, xc1.xmlText()); + } +} diff --git a/src/test/java/xmlcursor/checkin/CurrentTokenTypeTest.java b/src/test/java/xmlcursor/checkin/CurrentTokenTypeTest.java new file mode 100755 index 0000000..c3cc56d --- /dev/null +++ b/src/test/java/xmlcursor/checkin/CurrentTokenTypeTest.java @@ -0,0 +1,112 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertEquals; + + +public class CurrentTokenTypeTest extends BasicCursorTestCase { + + String sInputDoc; + + /** + ATTR + COMMENT + END + ENDDOC + NAMESPACE + NONE + PROCINST + START + STARTDOC + TEXT + */ + + @Test + public void testAttrType() throws XmlException{ + sInputDoc = Common.XML_FOO_2ATTR_TEXT; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + assertEquals(m_xc.currentTokenType(), XmlCursor.TokenType.STARTDOC); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.START); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.ATTR); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.ATTR); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.TEXT); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.END); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.ENDDOC); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.NONE); + } + + @Test + public void testCommentType() throws XmlException { + sInputDoc = Common.XML_FOO_COMMENT; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + assertEquals(m_xc.currentTokenType(), XmlCursor.TokenType.STARTDOC); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.COMMENT); + } + + @Test + public void testNamespaceType()throws XmlException{ + sInputDoc = Common.XML_FOO_NS_PREFIX; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + + assertEquals(m_xc.currentTokenType(), XmlCursor.TokenType.STARTDOC); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.START); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.NAMESPACE); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.COMMENT); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.TEXT); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.START); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.ATTR); + } + + @Test + public void testNoneType()throws XmlException{ + sInputDoc = ""; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + m_xc.toEndDoc(); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.NONE); + } + + @Test + public void testProcinstType()throws XmlException{ + sInputDoc = Common.XML_FOO_PROCINST; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + assertEquals(m_xc.currentTokenType(), XmlCursor.TokenType.STARTDOC); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.PROCINST); + } + + @Test + public void testTextType()throws XmlException{ + sInputDoc = "blahtest and some more test" + "\u042F\u0436\n\r"; + m_xc = XmlObject.Factory.parse(sInputDoc).newCursor(); + assertEquals(m_xc.currentTokenType(), XmlCursor.TokenType.STARTDOC); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.START); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.TEXT); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.START); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.TEXT); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.END); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.TEXT); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.END); + assertEquals(m_xc.toNextToken(), XmlCursor.TokenType.ENDDOC); + } +} diff --git a/src/test/java/xmlcursor/checkin/DisposeTest.java b/src/test/java/xmlcursor/checkin/DisposeTest.java new file mode 100755 index 0000000..2b4865e --- /dev/null +++ b/src/test/java/xmlcursor/checkin/DisposeTest.java @@ -0,0 +1,35 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + + +public class DisposeTest extends BasicCursorTestCase { + + @Test + public void testMultipleDispose() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO); + m_xc = m_xo.newCursor(); + m_xc.dispose(); + m_xc.dispose(); + } +} + diff --git a/test/src/xmlcursor/checkin/GetAllBookmarkRefsTest.java b/src/test/java/xmlcursor/checkin/GetAllBookmarkRefsTest.java similarity index 77% rename from test/src/xmlcursor/checkin/GetAllBookmarkRefsTest.java rename to src/test/java/xmlcursor/checkin/GetAllBookmarkRefsTest.java index 3275a28..294cee5 100755 --- a/test/src/xmlcursor/checkin/GetAllBookmarkRefsTest.java +++ b/src/test/java/xmlcursor/checkin/GetAllBookmarkRefsTest.java @@ -16,44 +16,23 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import java.net.URL; import java.util.Vector; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -/** - * - * - */ public class GetAllBookmarkRefsTest extends BasicCursorTestCase { private Bookmark0 _theBookmark0 = new Bookmark0("value0"); private Bookmark1 _theBookmark1 = new Bookmark1("value1"); private Bookmark2 _theBookmark2 = new Bookmark2("value2"); - public GetAllBookmarkRefsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetAllBookmarkRefsTest.class); - } - + @Test public void testGetAll() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -69,6 +48,7 @@ public void testGetAll() throws Exception { assertEquals("value2", ((Bookmark2) v.elementAt(2)).text); } + @Test public void testGetAllNullListToFill() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -82,7 +62,7 @@ public void testGetAllNullListToFill() throws Exception { public class Bookmark0 extends XmlCursor.XmlBookmark { public String text; - public Bookmark0(String text) { + Bookmark0(String text) { this.text = text; } } @@ -90,7 +70,7 @@ public Bookmark0(String text) { public class Bookmark1 extends XmlCursor.XmlBookmark { public String text; - public Bookmark1(String text) { + Bookmark1(String text) { this.text = text; } } @@ -98,11 +78,9 @@ public Bookmark1(String text) { public class Bookmark2 extends XmlCursor.XmlBookmark { public String text; - public Bookmark2(String text) { + Bookmark2(String text) { this.text = text; } } - - } diff --git a/test/src/xmlcursor/checkin/GetAllNamespacesTest.java b/src/test/java/xmlcursor/checkin/GetAllNamespacesTest.java similarity index 75% rename from test/src/xmlcursor/checkin/GetAllNamespacesTest.java rename to src/test/java/xmlcursor/checkin/GetAllNamespacesTest.java index 46a012e..dc16dcb 100755 --- a/test/src/xmlcursor/checkin/GetAllNamespacesTest.java +++ b/src/test/java/xmlcursor/checkin/GetAllNamespacesTest.java @@ -16,61 +16,30 @@ package xmlcursor.checkin; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import java.util.HashMap; +import java.util.Map; -import java.util.*; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class GetAllNamespacesTest extends BasicCursorTestCase { - static String sTestXml = "" + - "Cheaper by the Dozen" + - "1568491379" + - "" + - "nestedText" + - ""; - - - public GetAllNamespacesTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetAllNamespacesTest.class); - } - - + @Test(expected = Exception.class) public void testCursorNotContainer() { //lousy message toNextTokenOfType(m_xc, XmlCursor.TokenType.TEXT); Map myHash = new HashMap(); - try { - m_xc.getAllNamespaces(myHash); - fail("Cursor not on a container"); - } - catch (Exception e) { - System.err.println(e.getMessage()); - } - /* - Iterator it=myHash.values().iterator(); - while(it.hasNext()){ - System.out.println(it.next()); - } - */ - + m_xc.getAllNamespaces(myHash); } + @Test public void testGetAllNamespaces() { //parse in setUp int nExpectedNamespaces = 2;//2 distinct namespaces but 3 @@ -84,6 +53,7 @@ public void testGetAllNamespaces() { "urn:ISBN:0-395-36341-6"); } + @Test public void testGetAllNamespacesIllegalCursorPos() { int nExpectedNamespaces = 0; Map namespaceMap = new HashMap(); @@ -91,6 +61,7 @@ public void testGetAllNamespacesIllegalCursorPos() { assertEquals(namespaceMap.entrySet().size(), nExpectedNamespaces); } + @Test public void testGetAllNamespacesNull() { toNextTokenOfType(m_xc, XmlCursor.TokenType.START); @@ -101,6 +72,7 @@ public void testGetAllNamespacesNull() { /** * cursor is positioned below the namespace declaration but in its scope */ + @Test public void testGetAllNamespacesInternal() { int nExpectedNamespaces = 2; Map namespaceMap = new HashMap(); @@ -116,20 +88,15 @@ public void testGetAllNamespacesInternal() { } + @Before public void setUp() throws Exception { + String sTestXml = "" + + "Cheaper by the Dozen" + + "1568491379" + + "" + + "nestedText" + + ""; m_xc = XmlObject.Factory.parse(sTestXml).newCursor(); } - - public static void main(String[] rgs) { - try { - GetAllNamespacesTest t = (new GetAllNamespacesTest("")); - t.setUp(); - t.testGetAllNamespacesNull(); - } - catch (Exception e) { - System.err.println(e.getMessage()); - } - } - - } diff --git a/test/src/xmlcursor/checkin/GetAttributeTextTest.java b/src/test/java/xmlcursor/checkin/GetAttributeTextTest.java similarity index 80% rename from test/src/xmlcursor/checkin/GetAttributeTextTest.java rename to src/test/java/xmlcursor/checkin/GetAttributeTextTest.java index 3306da4..2840c58 100755 --- a/test/src/xmlcursor/checkin/GetAttributeTextTest.java +++ b/src/test/java/xmlcursor/checkin/GetAttributeTextTest.java @@ -18,28 +18,19 @@ import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; import javax.xml.namespace.QName; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -/** - * - * - */ -public class GetAttributeTextTest extends BasicCursorTestCase { - public GetAttributeTextTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetAttributeTextTest.class); - } +public class GetAttributeTextTest extends BasicCursorTestCase { + @Test public void testGetAttributeTextFromSTARTwith2ATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -47,34 +38,37 @@ public void testGetAttributeTextFromSTARTwith2ATTR() throws Exception { assertEquals("val1", m_xc.getAttributeText(new QName("attr1"))); } + @Test public void testGetAttributeTextFromSTARTwithInvalid() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); m_xc.toFirstChild(); - assertEquals(null, m_xc.getAttributeText(new QName("invalid"))); + assertNull(m_xc.getAttributeText(new QName("invalid"))); } + @Test public void testGetAttributeTextFromSTARTChildHasAttr() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); m_xc = m_xo.newCursor(); m_xc.selectPath("$this//items"); - assertEquals(null, m_xc.getAttributeText(new QName("partNum"))); + assertNull(m_xc.getAttributeText(new QName("partNum"))); } + @Test public void testGetAttributeTextFromSTARTDOCChildHasAttr() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); m_xc = m_xo.newCursor(); - assertEquals(null, m_xc.getAttributeText(new QName("partNum"))); + assertNull(m_xc.getAttributeText(new QName("partNum"))); } + @Test public void testGetAttributeTextFromATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(null, m_xc.getAttributeText(new QName("attr1"))); + assertNull(m_xc.getAttributeText(new QName("attr1"))); } - } diff --git a/test/src/xmlcursor/checkin/GetBookmarkTest.java b/src/test/java/xmlcursor/checkin/GetBookmarkTest.java similarity index 85% rename from test/src/xmlcursor/checkin/GetBookmarkTest.java rename to src/test/java/xmlcursor/checkin/GetBookmarkTest.java index 75fd8aa..4417c26 100755 --- a/test/src/xmlcursor/checkin/GetBookmarkTest.java +++ b/src/test/java/xmlcursor/checkin/GetBookmarkTest.java @@ -16,43 +16,24 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; import org.apache.xmlbeans.XmlCursor.XmlBookmark; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -/** - * - * - */ public class GetBookmarkTest extends BasicCursorTestCase { private Bookmark0 _theBookmark0 = new Bookmark0("value0"); private Bookmark1 _theBookmark1 = new Bookmark1("value1"); private Bookmark2 _theBookmark2 = new Bookmark2("value2"); - public GetBookmarkTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetBookmarkTest.class); - } + @Test public void testGetBookmarkIndependentKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -67,6 +48,7 @@ public void testGetBookmarkIndependentKey() throws Exception { assertEquals("value2", ann2.text); } + @Test public void testGetBookmarkNullKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -75,6 +57,7 @@ public void testGetBookmarkNullKey() throws Exception { assertNull(xa); } + @Test public void testGetBookmarkInvalidKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -83,6 +66,7 @@ public void testGetBookmarkInvalidKey() throws Exception { assertNull(xa); } + @Test public void testGetBookmarkNotAtCursor() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); diff --git a/test/src/xmlcursor/checkin/GetCharsTest.java b/src/test/java/xmlcursor/checkin/GetCharsTest.java similarity index 78% rename from test/src/xmlcursor/checkin/GetCharsTest.java rename to src/test/java/xmlcursor/checkin/GetCharsTest.java index d7a579d..213692a 100755 --- a/test/src/xmlcursor/checkin/GetCharsTest.java +++ b/src/test/java/xmlcursor/checkin/GetCharsTest.java @@ -16,38 +16,17 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class GetCharsTest extends BasicCursorTestCase { - public GetCharsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetCharsTest.class); - } - - + @Test public void testGetCharFromTEXTOffset() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -56,6 +35,7 @@ public void testGetCharFromTEXTOffset() throws Exception { assertEquals("1234", m_xc.getChars()); } + @Test public void testGetCharFromATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -63,6 +43,7 @@ public void testGetCharFromATTR() throws Exception { assertEquals("", m_xc.getChars()); } + @Test public void testGetCharFromCOMMENT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); m_xc = m_xo.newCursor(); diff --git a/test/src/xmlcursor/checkin/GetCharsType2Test.java b/src/test/java/xmlcursor/checkin/GetCharsType2Test.java similarity index 89% rename from test/src/xmlcursor/checkin/GetCharsType2Test.java rename to src/test/java/xmlcursor/checkin/GetCharsType2Test.java index edf414e..65a906b 100755 --- a/test/src/xmlcursor/checkin/GetCharsType2Test.java +++ b/src/test/java/xmlcursor/checkin/GetCharsType2Test.java @@ -16,37 +16,17 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class GetCharsType2Test extends BasicCursorTestCase { - public GetCharsType2Test(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetCharsType2Test.class); - } - + @Test public void testGetCharsType2LessThanBufLength() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -57,6 +37,7 @@ public void testGetCharsType2LessThanBufLength() throws Exception { assertEquals("012\0\0", s); } + @Test public void testGetCharsType2GTBufLengthMinusOffset() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -70,6 +51,7 @@ public void testGetCharsType2GTBufLengthMinusOffset() throws Exception { assertEquals('1', buf[4]); } + @Test public void testGetCharsType2FromATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -78,6 +60,7 @@ public void testGetCharsType2FromATTR() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -86,6 +69,7 @@ public void testGetCharsType2FromSTART() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -93,6 +77,7 @@ public void testGetCharsType2FromSTARTDOC() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -101,6 +86,7 @@ public void testGetCharsType2FromNAMESPACE() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -109,6 +95,7 @@ public void testGetCharsType2FromPROCINST() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromEND() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -117,6 +104,7 @@ public void testGetCharsType2FromEND() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -125,6 +113,7 @@ public void testGetCharsType2FromENDDOC() throws Exception { assertEquals(0, m_xc.getChars(buf, 3, 4)); } + @Test public void testGetCharsType2FromCOMMENT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); m_xc = m_xo.newCursor(); @@ -132,6 +121,5 @@ public void testGetCharsType2FromCOMMENT() throws Exception { char[] buf = new char[5]; assertEquals(0, m_xc.getChars(buf, 3, 4)); } - } diff --git a/test/src/xmlcursor/checkin/GetDocChangeStampTest.java b/src/test/java/xmlcursor/checkin/GetDocChangeStampTest.java similarity index 89% rename from test/src/xmlcursor/checkin/GetDocChangeStampTest.java rename to src/test/java/xmlcursor/checkin/GetDocChangeStampTest.java index 1ee489c..75090a4 100755 --- a/test/src/xmlcursor/checkin/GetDocChangeStampTest.java +++ b/src/test/java/xmlcursor/checkin/GetDocChangeStampTest.java @@ -18,26 +18,16 @@ import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; -/** - * - * - */ -public class GetDocChangeStampTest extends BasicCursorTestCase { - public GetDocChangeStampTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetDocChangeStampTest.class); - } +public class GetDocChangeStampTest extends BasicCursorTestCase { + @Test public void testGetDocChangeStampHasChanged() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -53,6 +43,7 @@ public void testGetDocChangeStampHasChanged() throws Exception { assertEquals(true, cs0.hasChanged()); } + @Test public void testGetDocChangeStampNotChanged() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); diff --git a/test/src/xmlcursor/checkin/GetNameTest.java b/src/test/java/xmlcursor/checkin/GetNameTest.java similarity index 94% rename from test/src/xmlcursor/checkin/GetNameTest.java rename to src/test/java/xmlcursor/checkin/GetNameTest.java index afbf85d..16c6ca6 100755 --- a/test/src/xmlcursor/checkin/GetNameTest.java +++ b/src/test/java/xmlcursor/checkin/GetNameTest.java @@ -18,22 +18,17 @@ import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -public class GetNameTest extends BasicCursorTestCase { - public GetNameTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetNameTest.class); - } +public class GetNameTest extends BasicCursorTestCase { + @Test public void testGetNameFromSTARTDOC() throws Exception { // String test="Alice Smith123 Maple StreetMill ValleyCA90952Hurry, my lawn is going wild!2 Lawnmower 10Baby Monitor1"; String test="\n" + @@ -73,9 +68,10 @@ public void testGetNameFromSTARTDOC() throws Exception { Common.TRANXML_FILE_XMLCURSOR_PO)); */ m_xc = m_xo.newCursor(); - assertEquals(null, m_xc.getName()); + assertNull(m_xc.getName()); } + @Test public void testGetNameFromPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -83,6 +79,7 @@ public void testGetNameFromPROCINST() throws Exception { assertEquals("xml-stylesheet", m_xc.getName().getLocalPart()); } + @Test public void testGetNameFromSTART() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -94,14 +91,16 @@ public void testGetNameFromSTART() throws Exception { assertEquals("city", m_xc.getName().getLocalPart()); } + @Test public void testGetNameFromEND() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); m_xc.selectPath(".//bar"); toNextTokenOfType(m_xc, TokenType.END); - assertEquals(null, m_xc.getName()); + assertNull(m_xc.getName()); } + @Test public void testGetNameFromATTR() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -114,13 +113,15 @@ public void testGetNameFromATTR() throws Exception { assertEquals("country", m_xc.getName().getLocalPart()); } + @Test public void testGetNameFromCOMMENT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.COMMENT); - assertEquals(null, m_xc.getName()); + assertNull(m_xc.getName()); } + @Test public void testGetNameElementWithDefaultNamespace() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -131,6 +132,7 @@ public void testGetNameElementWithDefaultNamespace() throws Exception { assertEquals(Common.CLM_NS, m_xc.getName().getNamespaceURI()); } + @Test public void testGetNameAttrWithDefaultNamespace() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS_PREFIX); m_xc = m_xo.newCursor(); diff --git a/src/test/java/xmlcursor/checkin/GetObjectTest.java b/src/test/java/xmlcursor/checkin/GetObjectTest.java new file mode 100755 index 0000000..2e73deb --- /dev/null +++ b/src/test/java/xmlcursor/checkin/GetObjectTest.java @@ -0,0 +1,117 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlNMTOKEN; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + + +public class GetObjectTest extends BasicCursorTestCase { + @Test + public void testGetObjectFromSTARTDOC() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + assertTrue(m_xc.getObject() instanceof CarLocationMessageDocument); + } + + @Test + public void testGetObjectFromSTART() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.toFirstChild(); + assertTrue(m_xc.getObject() instanceof CarLocationMessageDocument.CarLocationMessage); + } + + @Test + public void testGetObjectFromATTR() throws Exception { + m_xo = + XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + m_xc = m_xo.newCursor(); + String sQuery = + "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; " + + "$this//po:shipTo"; + m_xc.selectPath(sQuery); + m_xc.toNextSelection(); + m_xc.toFirstAttribute(); + assertTrue(m_xc.getObject() instanceof XmlNMTOKEN); + } + + @Test + public void testGetObjectFromEND() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.END); + assertNull(m_xc.getObject()); + } + + @Test + public void testGetObjectFromENDDOC() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.toEndDoc(); + assertNull(m_xc.getObject()); + } + + @Test + public void testGetObjectFromNAMESPACE() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.NAMESPACE); + assertNull(m_xc.getObject()); + } + + @Test + public void testGetObjectFromPROCINST() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.PROCINST); + assertNull(m_xc.getObject()); + } + + @Test + public void testGetObjectFromCOMMENT() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.COMMENT); + assertNull(m_xc.getObject()); + } + + @Test + public void testGetObjectFromTEXT() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertNull(m_xc.getObject()); + } +} + diff --git a/src/test/java/xmlcursor/checkin/InsertAttributeTest.java b/src/test/java/xmlcursor/checkin/InsertAttributeTest.java new file mode 100755 index 0000000..2ad7cad --- /dev/null +++ b/src/test/java/xmlcursor/checkin/InsertAttributeTest.java @@ -0,0 +1,242 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; + + +public class InsertAttributeTest extends BasicCursorTestCase { + @Test + public void testInsertAttributeAtSTART() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.insertAttributeWithValue("name", "uri", "value"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test + public void testInsertAttributeAtATTR() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + m_xc.insertAttributeWithValue("name", null, "value"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test + public void testInsertAttributeAt2ndATTR() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + toNextTokenOfType(m_xc, TokenType.ATTR); + m_xc.insertAttributeWithValue("name", null, "value"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeAtPROCINST() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.PROCINST); + m_xc.toNextToken(); + m_xc.insertAttributeWithValue("name", null, "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeAtSTARTwithEmptyStringName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + m_xc.insertAttributeWithValue("", "uri", "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeAtSTARTwithNullName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + m_xc.insertAttributeWithValue(null, "uri", "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeWithNullQName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + QName name = new QName(null); + m_xc.insertAttribute(name); + } + + @Test + public void testInsertAttributeAtSTARTwithEmptyStringUri() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.insertAttributeWithValue("name", "", "value"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test(expected = Exception.class) + public void testInsertAttributeAtSTARTwithNameXml() throws Exception { + /* +m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); +m_xc = m_xo.newCursor(); +toNextTokenOfType(m_xc, TokenType.TEXT); +try +{ +m_xc.insertAttributeWithValue("xml", null, "value"); +fail("Expected IllegalArgumentException"); +} +catch (IllegalArgumentException iae) +{ +} +assertEquals(true,true); + */ + + m_xo = XmlObject.Factory.parse("text"); + m_xc = m_xo.newCursor(); + m_xc.insertAttributeWithValue("xml", null, "value"); + } + + @Test + public void testInsertAttributeAtSTARTwithValueXml() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.insertAttributeWithValue("name", null, "xml"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeAtSTARTwithLTcharInName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.insertAttributeWithValue("text", m_xc.xmlText()); + } + + @Test + public void testInsertAttributeAtSTARTwithAmpCharInValue() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.insertAttributeWithValue("name", null, "&value"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeAtSTARTwithAmpCharInName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + m_xc.insertAttributeWithValue("&bar", null, "value"); + } + + // tests below use the XMLName form of the parameter signature + @Test + public void testInsertAttributeType2AtATTR() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + QName name = new QName("name"); + m_xc.insertAttributeWithValue(name, "value"); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test + public void testInsertAttributeType2AfterSTART() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + QName name = new QName("name"); + m_xc.insertAttributeWithValue(name, null); + m_xc.toStartDoc(); + assertEquals("text", m_xc.xmlText()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeType2WithXMLinName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + QName name = new QName(""); + m_xc.insertAttributeWithValue(name, "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeType2WithLeadingSpaceinName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + QName name = new QName(" any"); + m_xc.insertAttributeWithValue(name, "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeType2ContainingSpaceinName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + QName name = new QName("any any"); + m_xc.insertAttributeWithValue(name, "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeType2WithTrailingSpaceinName() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + QName name = new QName("any "); + m_xc.insertAttributeWithValue(name, "value"); + } + + @Test(expected = IllegalArgumentException.class) + public void testInsertAttributeType2WithXMLinNameCase() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + QName name = new QName(""); + m_xc.insertAttributeWithValue(name, "value"); + } +} + diff --git a/test/src/xmlcursor/checkin/InsertCharsTest.java b/src/test/java/xmlcursor/checkin/InsertCharsTest.java similarity index 84% rename from test/src/xmlcursor/checkin/InsertCharsTest.java rename to src/test/java/xmlcursor/checkin/InsertCharsTest.java index 9d83f9a..e3b36d2 100755 --- a/test/src/xmlcursor/checkin/InsertCharsTest.java +++ b/src/test/java/xmlcursor/checkin/InsertCharsTest.java @@ -16,37 +16,17 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class InsertCharsTest extends BasicCursorTestCase { - public InsertCharsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertCharsTest.class); - } - + @Test public void testInsertCharsAtSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -58,6 +38,7 @@ public void testInsertCharsAtSTART() throws Exception { assertEquals(" new chars ", m_xc.getChars()); } + @Test public void testInsertCharsAtSTARTnonEmptyPriorTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_WS_ONLY); m_xc = m_xo.newCursor(); @@ -69,6 +50,7 @@ public void testInsertCharsAtSTARTnonEmptyPriorTEXT() throws Exception { assertEquals(" new chars ", m_xc.getChars()); } + @Test public void testInsertCharsAtENDnonEmptyPriorTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_WS_ONLY); m_xc = m_xo.newCursor(); @@ -79,6 +61,7 @@ public void testInsertCharsAtENDnonEmptyPriorTEXT() throws Exception { assertEquals(" new chars ", m_xc.getChars()); } + @Test public void testInsertCharsInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -91,6 +74,7 @@ public void testInsertCharsInMiddleOfTEXT() throws Exception { assertEquals("tenew chars xt", m_xc.getTextValue()); } + @Test public void testInsertCharsNullInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -103,6 +87,7 @@ public void testInsertCharsNullInMiddleOfTEXT() throws Exception { assertEquals("text", m_xc.getTextValue()); } + @Test public void testInsertCharsEmptyInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -115,16 +100,12 @@ public void testInsertCharsEmptyInMiddleOfTEXT() throws Exception { assertEquals("text", m_xc.getTextValue()); } + @Test(expected = IllegalStateException.class) public void testInsertCharsInNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.NAMESPACE); - try { - m_xc.insertChars("fred"); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } - assertEquals(true, true); + m_xc.insertChars("fred"); } } diff --git a/test/src/xmlcursor/checkin/InsertCommentTest.java b/src/test/java/xmlcursor/checkin/InsertCommentTest.java similarity index 90% rename from test/src/xmlcursor/checkin/InsertCommentTest.java rename to src/test/java/xmlcursor/checkin/InsertCommentTest.java index c04df35..9d74318 100755 --- a/test/src/xmlcursor/checkin/InsertCommentTest.java +++ b/src/test/java/xmlcursor/checkin/InsertCommentTest.java @@ -16,37 +16,18 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; -/** - * - * - */ public class InsertCommentTest extends BasicCursorTestCase { - public InsertCommentTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertCommentTest.class); - } - + @Test public void testInsertCommentAtSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -57,6 +38,7 @@ public void testInsertCommentAtSTART() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -68,6 +50,7 @@ public void testInsertCommentInMiddleOfTEXT() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentAtEND() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -77,6 +60,7 @@ public void testInsertCommentAtEND() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentWithLTChar() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -86,6 +70,7 @@ public void testInsertCommentWithLTChar() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentWithDoubleDash() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -95,6 +80,7 @@ public void testInsertCommentWithDoubleDash() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentWithDoubleDashNoWS() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -104,6 +90,7 @@ public void testInsertCommentWithDoubleDashNoWS() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentWithEndDash() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -113,7 +100,7 @@ public void testInsertCommentWithEndDash() throws Exception { assertEquals("text", m_xc.xmlText()); } - + @Test public void testInsertCommentWithEmptyString() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -123,6 +110,7 @@ public void testInsertCommentWithEmptyString() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentWithNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -132,6 +120,7 @@ public void testInsertCommentWithNull() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertCommentAtSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); diff --git a/test/src/xmlcursor/checkin/InsertElementTest.java b/src/test/java/xmlcursor/checkin/InsertElementTest.java similarity index 83% rename from test/src/xmlcursor/checkin/InsertElementTest.java rename to src/test/java/xmlcursor/checkin/InsertElementTest.java index b5c8af4..3184674 100755 --- a/test/src/xmlcursor/checkin/InsertElementTest.java +++ b/src/test/java/xmlcursor/checkin/InsertElementTest.java @@ -18,50 +18,31 @@ import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class InsertElementTest extends BasicCursorTestCase { - public InsertElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertElementTest.class); - } - + @Test(expected = IllegalArgumentException.class) public void testInsertElementNullName() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.START); - try { - m_xc.insertElementWithText(null, "uri", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); + m_xc.insertElementWithText(null, "uri", "value"); } + @Test(expected = IllegalArgumentException.class) public void testInsertElementEmptyStringName() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.START); - try { - m_xc.insertElementWithText("", "uri", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); + m_xc.insertElementWithText("", "uri", "value"); } + @Test public void testInsertElementNullUri() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -71,6 +52,7 @@ public void testInsertElementNullUri() throws Exception { assertEquals("value", m_xc.xmlText()); } + @Test public void testInsertElementNullText() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -80,6 +62,7 @@ public void testInsertElementNullText() throws Exception { assertEquals("", m_xc.xmlText()); } + @Test public void testInsertElementEmptyStringText() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -89,6 +72,7 @@ public void testInsertElementEmptyStringText() throws Exception { assertEquals("", m_xc.xmlText()); } + @Test public void testInsertElementInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -100,6 +84,7 @@ public void testInsertElementInMiddleOfTEXT() throws Exception { assertEquals("tevaluext", m_xc.xmlText()); } + @Test public void testInsertElementAtEND() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -109,17 +94,14 @@ public void testInsertElementAtEND() throws Exception { assertEquals("textvalue", m_xc.xmlText()); } + @Test(expected = IllegalArgumentException.class) public void testInsertElementAtSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); - try { - m_xc.insertElementWithText("name", null, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - assertEquals(true, true); + m_xc.insertElementWithText("name", null, "value"); } + @Test public void testInsertElementAtENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -129,6 +111,7 @@ public void testInsertElementAtENDDOC() throws Exception { assertEquals(Common.wrapInXmlFrag("textvalue"), m_xc.xmlText()); } + @Test public void testInsertElementInStoreWithNamespace() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); diff --git a/test/src/xmlcursor/checkin/InsertProcInstTest.java b/src/test/java/xmlcursor/checkin/InsertProcInstTest.java similarity index 76% rename from test/src/xmlcursor/checkin/InsertProcInstTest.java rename to src/test/java/xmlcursor/checkin/InsertProcInstTest.java index dbdce4f..77593b7 100755 --- a/test/src/xmlcursor/checkin/InsertProcInstTest.java +++ b/src/test/java/xmlcursor/checkin/InsertProcInstTest.java @@ -16,78 +16,42 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - - -import java.net.URL; - -import org.apache.xmlbeans.XmlOptions; -import xmlcursor.common.*; - -import java.util.HashMap; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class InsertProcInstTest extends BasicCursorTestCase { - public InsertProcInstTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertProcInstTest.class); - } - + @Test(expected = IllegalArgumentException.class) public void testInsertProcInstWithNullTarget() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.insertProcInst(null, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); + m_xc.insertProcInst(null, "value"); } + @Test(expected = IllegalArgumentException.class) public void testInsertProcInstWithEmptyStringTarget() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.insertProcInst("", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); + m_xc.insertProcInst("", "value"); } + @Test(expected = IllegalArgumentException.class) public void testInsertProcInstWithLTcharInTarget() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); m_xc.selectPath("$this//bar"); m_xc.toNextSelection(); - try { - m_xc.insertProcInst("text", m_xc.xmlText()); } + @Test public void testInsertProcInstWithEmptyStringText() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -110,6 +75,7 @@ public void testInsertProcInstWithEmptyStringText() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertProcInstWithLTcharInText() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -120,6 +86,7 @@ public void testInsertProcInstWithLTcharInText() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertProcInstInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -131,6 +98,7 @@ public void testInsertProcInstInMiddleOfTEXT() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertProcInstAfterSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -141,6 +109,7 @@ public void testInsertProcInstAfterSTART() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test public void testInsertProcInstAtEND() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); @@ -150,16 +119,12 @@ public void testInsertProcInstAtEND() throws Exception { assertEquals("", m_xc.xmlText()); } + @Test(expected = IllegalArgumentException.class) public void testInsertProcInstBeforeATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); - try { - m_xc.insertProcInst("target", " value "); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { - } - assertEquals(true, true); + m_xc.insertProcInst("target", " value "); } } diff --git a/src/test/java/xmlcursor/checkin/IsAtSamePositionAsTest.java b/src/test/java/xmlcursor/checkin/IsAtSamePositionAsTest.java new file mode 100755 index 0000000..89a1425 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/IsAtSamePositionAsTest.java @@ -0,0 +1,74 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class IsAtSamePositionAsTest extends BasicCursorTestCase{ + + private static String sDoc=Common.XML_FOO_DIGITS; + + @Test + public void testNormalCase() { + XmlCursor m_xc1 = m_xo.newCursor(); + m_xc.toFirstChild(); + m_xc1.toFirstChild(); + assertTrue(m_xc.isAtSamePositionAs(m_xc1)); + } + + @Test(expected = IllegalArgumentException.class) + public void testSamePosDiffDoc() throws Exception { + XmlCursor m_xc1 = XmlObject.Factory.parse(sDoc).newCursor(); + m_xc.toFirstChild(); + m_xc1.toFirstChild(); + m_xc.isAtSamePositionAs(m_xc1); + } + + @Test + public void testDiffPosSameDoc() throws Exception { + XmlCursor m_xc1 = m_xo.newCursor(); + m_xc.toFirstChild(); + m_xc1.toFirstChild(); + m_xc1.toFirstAttribute(); + assertFalse(m_xc.isAtSamePositionAs(m_xc1)); + } + + @Test(expected = Exception.class) + public void testNull() { + m_xc.isAtSamePositionAs(null); + } + + @Test + public void testSelf() { + m_xc.toFirstChild(); + assertEquals(true, m_xc.isAtSamePositionAs(m_xc)); + } + + @Before + public void setUp() throws Exception { + m_xo = XmlObject.Factory.parse(sDoc); + m_xc = m_xo.newCursor(); + } +} diff --git a/test/src/xmlcursor/checkin/IsInSameDocumentTest.java b/src/test/java/xmlcursor/checkin/IsInSameDocumentTest.java similarity index 76% rename from test/src/xmlcursor/checkin/IsInSameDocumentTest.java rename to src/test/java/xmlcursor/checkin/IsInSameDocumentTest.java index a5de77f..01cada4 100755 --- a/test/src/xmlcursor/checkin/IsInSameDocumentTest.java +++ b/src/test/java/xmlcursor/checkin/IsInSameDocumentTest.java @@ -16,71 +16,66 @@ package xmlcursor.checkin; -import junit.framework.Test; -import junit.framework.TestSuite; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -/** - * - * - */ -public class IsInSameDocumentTest extends BasicCursorTestCase { - public IsInSameDocumentTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(IsInSameDocumentTest.class); - } +public class IsInSameDocumentTest extends BasicCursorTestCase { + @Test public void testSameDocSTARTDOCandENDDOC() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = m_xc.newCursor(); xc0.toEndDoc(); try { - assertEquals(true, m_xc.isInSameDocument(xc0)); - assertEquals(true, xc0.isInSameDocument(m_xc)); + assertTrue(m_xc.isInSameDocument(xc0)); + assertTrue(xc0.isInSameDocument(m_xc)); } finally { xc0.dispose(); } } + @Test public void testSameDocNAMESPACEandATTR() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_DIGITS).newCursor(); XmlCursor xc0 = m_xc.newCursor(); try { toNextTokenOfType(m_xc, TokenType.NAMESPACE); toNextTokenOfType(xc0, TokenType.ATTR); - assertEquals(true, m_xc.isInSameDocument(xc0)); - assertEquals(true, xc0.isInSameDocument(m_xc)); + assertTrue(m_xc.isInSameDocument(xc0)); + assertTrue(xc0.isInSameDocument(m_xc)); } finally { xc0.dispose(); } } + @Test public void testSameDocNull() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - assertEquals(false, m_xc.isInSameDocument(null)); + assertFalse(m_xc.isInSameDocument(null)); } + @Test public void testSameDocDifferentDocs() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); toNextTokenOfType(xc0, TokenType.TEXT); try { - assertEquals(false, m_xc.isInSameDocument(xc0)); - assertEquals(false, xc0.isInSameDocument(m_xc)); + assertFalse(m_xc.isInSameDocument(xc0)); + assertFalse(xc0.isInSameDocument(m_xc)); } finally { xc0.dispose(); } } + @Test public void testSameDocTEXTpositional() throws Exception { m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); XmlCursor xc0 = m_xc.newCursor(); @@ -88,12 +83,10 @@ public void testSameDocTEXTpositional() throws Exception { toNextTokenOfType(xc0, TokenType.TEXT); xc0.toNextChar(2); try { - assertEquals(true, m_xc.isInSameDocument(xc0)); - assertEquals(true, xc0.isInSameDocument(m_xc)); + assertTrue(m_xc.isInSameDocument(xc0)); + assertTrue(xc0.isInSameDocument(m_xc)); } finally { xc0.dispose(); } } - } - diff --git a/test/src/xmlcursor/checkin/MoveCharsTest.java b/src/test/java/xmlcursor/checkin/MoveCharsTest.java similarity index 82% rename from test/src/xmlcursor/checkin/MoveCharsTest.java rename to src/test/java/xmlcursor/checkin/MoveCharsTest.java index 0d44f5a..9bd8432 100755 --- a/test/src/xmlcursor/checkin/MoveCharsTest.java +++ b/src/test/java/xmlcursor/checkin/MoveCharsTest.java @@ -16,37 +16,19 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; -/** - * - * - */ public class MoveCharsTest extends BasicCursorTestCase { - public MoveCharsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(MoveCharsTest.class); - } - + @Test public void testMoveCharsOverlap() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -64,6 +46,7 @@ public void testMoveCharsOverlap() throws Exception { } } + @Test public void testMoveCharsNoOverlap() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -87,18 +70,15 @@ public void testMoveCharsNoOverlap() throws Exception { } } + @Test(expected = IllegalArgumentException.class) public void testMoveCharsToNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.moveChars(4, null); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { - } - assertEquals(true, true); + m_xc.moveChars(4, null); } + @Test(expected = IllegalStateException.class) public void testMoveCharsSibling() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -107,7 +87,7 @@ public void testMoveCharsSibling() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(4, xc1.moveChars(4, xc0)); assertEquals("0123", xc0.getChars()); xc0.toPrevToken(); @@ -115,18 +95,14 @@ public void testMoveCharsSibling() throws Exception { System.out.println("we are here"); assertEquals(TokenType.END, xc1.currentTokenType()); - - try { - xc1.getTextValue(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } + xc1.getTextValue(); } finally { xc0.dispose(); xc1.dispose(); } } + @Test(expected = IllegalStateException.class) public void testMoveCharsNegative() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -135,24 +111,20 @@ public void testMoveCharsNegative() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(4, xc1.moveChars(-1, xc0)); assertEquals("0123", xc0.getChars()); xc0.toPrevToken(); assertEquals("WXYZ0123", xc0.getTextValue()); assertEquals(TokenType.END, xc1.currentTokenType()); - try { - xc1.getTextValue(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } - + xc1.getTextValue(); } finally { xc0.dispose(); xc1.dispose(); } } + @Test public void testMoveCharsZero() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -161,35 +133,33 @@ public void testMoveCharsZero() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(0, xc1.moveChars(0, xc0)); assertEquals("0123", xc0.getChars()); xc0.toPrevToken(); assertEquals("0123", xc0.getTextValue()); assertEquals(TokenType.TEXT, xc1.currentTokenType()); assertEquals("WXYZ", xc1.getChars()); - - } finally { xc0.dispose(); xc1.dispose(); } } + @Test(expected = IllegalArgumentException.class) public void testMoveCharsToSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); XmlCursor xc0 = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { + try{ m_xc.moveChars(4, xc0); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { } finally { xc0.dispose(); } } + @Test public void testMoveCharsToPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -206,6 +176,7 @@ public void testMoveCharsToPROCINST() throws Exception { } } + @Test(expected = IllegalStateException.class) public void testMoveCharsGTmax() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -214,7 +185,7 @@ public void testMoveCharsGTmax() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(4, xc1.moveChars(1000, xc0)); assertEquals("0123", xc0.getChars()); xc0.toPrevToken(); @@ -222,17 +193,14 @@ public void testMoveCharsGTmax() throws Exception { assertEquals(TokenType.END, xc1.currentTokenType()); - try { - xc1.getTextValue(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } + xc1.getTextValue(); } finally { xc0.dispose(); xc1.dispose(); } } + @Test public void testMoveCharsToNewDocument() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); diff --git a/test/src/xmlcursor/checkin/MoveTest.java b/src/test/java/xmlcursor/checkin/MoveTest.java similarity index 92% rename from test/src/xmlcursor/checkin/MoveTest.java rename to src/test/java/xmlcursor/checkin/MoveTest.java index 6b12387..485bafa 100755 --- a/test/src/xmlcursor/checkin/MoveTest.java +++ b/src/test/java/xmlcursor/checkin/MoveTest.java @@ -16,47 +16,30 @@ package xmlcursor.checkin; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - - +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import tools.util.Util; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; +import javax.xml.namespace.QName; -/** - * - * - */ -public class MoveTest extends BasicCursorTestCase { - public MoveTest(String sName) { - super(sName); - } +import static org.junit.Assert.*; - public static Test suite() { - return new TestSuite(MoveTest.class); - } +public class MoveTest extends BasicCursorTestCase { + @Test(expected = IllegalArgumentException.class) public void testMoveToNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.moveXml(null); - fail( - "Expected IllegalArgumentException. Can't move to foreign document"); - } - catch (IllegalArgumentException e) { - } + m_xc.moveXml(null); } + @Test public void testMoveDifferentStoresLoadedByParse() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -73,6 +56,7 @@ public void testMoveDifferentStoresLoadedByParse() throws Exception { assertEquals(TokenType.END, m_xc.currentTokenType()); } + @Test public void testMoveDifferentStoresLoadedFromFile() throws Exception { // load the documents and obtain a cursor XmlObject xobj0 = XmlObject.Factory.parse( @@ -113,6 +97,7 @@ public void testMoveDifferentStoresLoadedFromFile() throws Exception { } + @Test public void testMoveSameLocation() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -124,6 +109,7 @@ public void testMoveSameLocation() throws Exception { assertEquals("01234", m_xc.getChars()); } + @Test public void testMoveNewLocation() throws Exception { m_xo=XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -148,6 +134,7 @@ public void testMoveNewLocation() throws Exception { assertEquals("CA", m_xc.getTextValue()); } + @Test public void testMoveElementToMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -182,11 +169,9 @@ public void testMoveElementToMiddleOfTEXT() throws Exception { /** * Method testMoveFromSTARTDOC - *

      * Also used to verify radar bug 16160 - * - * @throws Exception */ + @Test(expected = IllegalArgumentException.class) public void testMoveFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO); m_xc = m_xo.newCursor(); @@ -199,10 +184,8 @@ public void testMoveFromSTARTDOC() throws Exception { String sTrace = Util.getStackTrace(e); int i = sTrace.indexOf("splay.bitch"); assertTrue(i < 0); + throw e; } - assertTrue(true); } - - } diff --git a/src/test/java/xmlcursor/checkin/PrevTokenTypeTest.java b/src/test/java/xmlcursor/checkin/PrevTokenTypeTest.java new file mode 100755 index 0000000..72b981a --- /dev/null +++ b/src/test/java/xmlcursor/checkin/PrevTokenTypeTest.java @@ -0,0 +1,103 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.*; + + +public class PrevTokenTypeTest extends BasicCursorTestCase { + + @org.junit.Test + public void testAllTokensTest(){ + m_xc.toEndDoc(); + assertTrue(m_xc.isEnddoc()); + assertTrue(m_xc.isFinish()); + assertEquals(TokenType.END, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isEnd()); + assertTrue(m_xc.isFinish()); + assertEquals(TokenType.END, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + + assertTrue(m_xc.isEnd()); + assertEquals(TokenType.TEXT, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isText()); + assertFalse(m_xc.isContainer()); + assertEquals(TokenType.ATTR, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isAttr()); + assertTrue(m_xc.isAnyAttr()); + assertEquals(TokenType.ATTR, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isAttr()); + assertTrue(m_xc.isAnyAttr()); + assertEquals(TokenType.START, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isStart()); + assertTrue(m_xc.isContainer()); + assertEquals(TokenType.TEXT, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isText()); + assertEquals(TokenType.COMMENT, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isComment()); + assertEquals(TokenType.PROCINST, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isProcinst()); + assertEquals(TokenType.NAMESPACE, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isNamespace()); + assertTrue(m_xc.isAnyAttr()); + assertFalse(m_xc.isAttr()); + assertEquals(TokenType.START, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isStart()); + assertTrue(m_xc.isContainer()); + assertEquals(TokenType.STARTDOC, m_xc.prevTokenType()); + m_xc.toPrevToken(); + + assertTrue(m_xc.isStartdoc()); + assertTrue(m_xc.isContainer()); + assertEquals(TokenType.NONE, m_xc.prevTokenType()); + //assert won't move further + assertEquals(TokenType.NONE, m_xc.toPrevToken()); + assertEquals(true, m_xc.isStartdoc()); + } + + @Before + public void setUp() throws Exception{ + String sDoc = " 32.18"; + m_xc = XmlObject.Factory.parse(sDoc).newCursor(); + } +} diff --git a/src/test/java/xmlcursor/checkin/RemoveAttributeTest.java b/src/test/java/xmlcursor/checkin/RemoveAttributeTest.java new file mode 100755 index 0000000..8cf5452 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/RemoveAttributeTest.java @@ -0,0 +1,86 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.*; + + +public class RemoveAttributeTest extends BasicCursorTestCase { + @Test + public void testRemoveAttributeValidAttrFromSTART() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + QName name = new QName("attr1"); + assertTrue(m_xc.removeAttribute(name)); + assertNull(m_xc.getAttributeText(name)); + } + + @Test + public void testRemoveAttributeInvalidAttrFromSTART() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + QName name = new QName("invalid"); + assertFalse(m_xc.removeAttribute(name)); + } + + @Test(expected = IllegalArgumentException.class) + public void testRemoveAttributeNullAttrFromSTART() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + QName name = new QName("dummy"); + m_xc.removeAttribute(null); + } + + @Test + public void testRemoveAttributeFromPROCINST() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.PROCINST); + QName name = new QName("type"); + assertFalse(m_xc.removeAttribute(name)); + } + + @Test + public void testRemoveAttributeXMLNS() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + QName name = new QName("xmlns"); + assertFalse(m_xc.removeAttribute(name)); + } + + @Test + public void testRemoveAttributeFromEND() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.END); + QName name = new QName("attr1"); + assertFalse(m_xc.removeAttribute(name)); + } +} + diff --git a/test/src/xmlcursor/checkin/RemoveCharsTest.java b/src/test/java/xmlcursor/checkin/RemoveCharsTest.java similarity index 85% rename from test/src/xmlcursor/checkin/RemoveCharsTest.java rename to src/test/java/xmlcursor/checkin/RemoveCharsTest.java index b880a48..f4ae4d8 100755 --- a/test/src/xmlcursor/checkin/RemoveCharsTest.java +++ b/src/test/java/xmlcursor/checkin/RemoveCharsTest.java @@ -16,37 +16,17 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class RemoveCharsTest extends BasicCursorTestCase { - public RemoveCharsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(RemoveCharsTest.class); - } - + @Test public void testRemoveCharsLTLengthFromTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -55,6 +35,7 @@ public void testRemoveCharsLTLengthFromTEXT() throws Exception { assertEquals("34", m_xc.getChars()); } + @Test public void testRemoveCharsGTLengthFromTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -63,6 +44,7 @@ public void testRemoveCharsGTLengthFromTEXT() throws Exception { assertEquals(TokenType.END, m_xc.currentTokenType()); } + @Test public void testRemoveCharsNegativeFromTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -71,6 +53,7 @@ public void testRemoveCharsNegativeFromTEXT() throws Exception { assertEquals(TokenType.END, m_xc.currentTokenType()); } + @Test public void testRemoveCharsZeroFromTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -79,6 +62,7 @@ public void testRemoveCharsZeroFromTEXT() throws Exception { assertEquals("01234", m_xc.getChars()); } + @Test public void testRemoveCharsFromPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -86,13 +70,12 @@ public void testRemoveCharsFromPROCINST() throws Exception { assertEquals(0, m_xc.removeChars(3)); } + @Test public void testRemoveCharsFromNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.NAMESPACE); assertEquals(0, m_xc.removeChars(3)); } - - } diff --git a/test/src/xmlcursor/checkin/RemoveTest.java b/src/test/java/xmlcursor/checkin/RemoveTest.java similarity index 83% rename from test/src/xmlcursor/checkin/RemoveTest.java rename to src/test/java/xmlcursor/checkin/RemoveTest.java index 8e9b69a..bbc7342 100755 --- a/test/src/xmlcursor/checkin/RemoveTest.java +++ b/src/test/java/xmlcursor/checkin/RemoveTest.java @@ -17,42 +17,27 @@ package xmlcursor.checkin; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor.TokenType; - -import xmlcursor.common.*; - -import test.xbean.xmlcursor.purchaseOrder.USAddress; +import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.impl.values.XmlValueDisconnectedException; +import org.junit.Test; +import test.xbean.xmlcursor.purchaseOrder.USAddress; import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -/** - * - * - */ public class RemoveTest extends BasicCursorTestCase { - public RemoveTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(RemoveTest.class); - } - + @Test(expected = IllegalStateException.class) public void testRemoveFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); - try { - m_xc.removeXml(); - fail("Expected IllegalStateException"); - } - catch (IllegalStateException e) { - } + m_xc.removeXml(); } + @Test public void testRemoveFromFirstChild() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -61,6 +46,7 @@ public void testRemoveFromFirstChild() throws Exception { assertEquals(TokenType.ENDDOC, m_xc.currentTokenType()); } + @Test public void testRemoveAllText() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -71,6 +57,7 @@ public void testRemoveAllText() throws Exception { assertEquals("", m_xc.xmlText()); } + @Test public void testRemovePartialText() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); m_xc = m_xo.newCursor(); @@ -83,6 +70,7 @@ public void testRemovePartialText() throws Exception { assertEquals("te", m_xc.xmlText()); } + @Test public void testRemoveFromATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -93,6 +81,7 @@ public void testRemoveFromATTR() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test(expected = XmlValueDisconnectedException.class) public void testRemoveAffectOnXmlObjectGetXXX() throws Exception { // m_xo =XmlObject.Factory.parse(JarUtil.getResourceFromJar( // Common.XMLCASES_JAR, Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -108,17 +97,11 @@ public void testRemoveAffectOnXmlObjectGetXXX() throws Exception { XmlObject xo = m_xc.getObject(); USAddress usa = (USAddress) xo; m_xc.removeXml(); - try { - usa.getCity(); - fail("Expected XmlValueDisconnectedException"); - } - catch (XmlValueDisconnectedException xvde) { - } - assertTrue(true); + usa.getCity(); } + @Test(expected = XmlValueDisconnectedException.class) public void testRemoveAffectOnXmlObjectNewCursor() throws Exception { - // m_xo = XmlObject.Factory.parse(Common.XML_PURCHASEORDER); m_xo = XmlObject.Factory.parse(JarUtil.getResourceFromJar( "xbean/xmlcursor/po.xml")); @@ -132,13 +115,7 @@ public void testRemoveAffectOnXmlObjectNewCursor() throws Exception { USAddress usa = (USAddress) xo; m_xc.removeXml(); assertNotNull("USAddress object expected non-null, but is null", usa); - try { - m_xc = usa.newCursor(); - fail("Expected XmlValueDisconnectedException"); - } - catch (XmlValueDisconnectedException npe) { - } - assertTrue(true); + m_xc = usa.newCursor(); } } diff --git a/src/test/java/xmlcursor/checkin/SelectPathTest.java b/src/test/java/xmlcursor/checkin/SelectPathTest.java new file mode 100755 index 0000000..2a2bc6e --- /dev/null +++ b/src/test/java/xmlcursor/checkin/SelectPathTest.java @@ -0,0 +1,114 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Test; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertEquals; + + +public class SelectPathTest extends BasicCursorTestCase { + /** + * $BUGBUG: Eric's engine doesn't send to Jaxen appropriately + */ + @Test + @Ignore + public void testSelectPathFromEND() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + String ns = "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, XmlCursor.TokenType.END); + m_xc.selectPath(ns + " $this//city"); + assertEquals(0, m_xc.getSelectionCount()); + } + + @Test + @Ignore + public void testSelectPathFromENDDOC() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xc = m_xo.newCursor(); + String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; + toNextTokenOfType(m_xc, XmlCursor.TokenType.ENDDOC); + m_xc.selectPath(ns+" .//po:city"); + assertEquals(0, m_xc.getSelectionCount()); + } + + @Test + public void testSelectPathNamespace() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + String sLocalPath =".//FleetID"; + m_xc.selectPath(sLocalPath); + assertEquals(0, m_xc.getSelectionCount()); + m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + sLocalPath); + assertEquals(1, m_xc.getSelectionCount()); + } + + @Test + public void testSelectPathCaseSensitive() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xc = m_xo.newCursor(); + String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\";"; + m_xc.selectPath(ns+" .//po:ciTy"); + assertEquals(0, m_xc.getSelectionCount()); + m_xc.selectPath(ns+" .//po:city"); + assertEquals(2, m_xc.getSelectionCount()); + } + + @Test + public void testSelectPathReservedKeyword() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xc = m_xo.newCursor(); + String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\";"; + m_xc.selectPath(ns+" .//po:item"); + assertEquals(2, m_xc.getSelectionCount()); + } + + @Test(expected = RuntimeException.class) + public void testSelectPathNull() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xc = m_xo.newCursor(); + // TODO: surround with appropriate t-c once ericvas creates the exception type + // see bugs 18009 and/or 18718 + m_xc.selectPath(null); + } + + @Test(expected = RuntimeException.class) + public void testSelectPathInvalidXPath() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xc = m_xo.newCursor(); + // TODO: surround with appropriate t-c once ericvas creates the exception type + // see bugs 18009 and/or 18718 + m_xc.selectPath("&GARBAGE"); + m_xc.getSelectionCount(); + } +} + diff --git a/test/src/xmlcursor/checkin/SetAttributeTextTest.java b/src/test/java/xmlcursor/checkin/SetAttributeTextTest.java similarity index 76% rename from test/src/xmlcursor/checkin/SetAttributeTextTest.java rename to src/test/java/xmlcursor/checkin/SetAttributeTextTest.java index 519afa2..595a185 100755 --- a/test/src/xmlcursor/checkin/SetAttributeTextTest.java +++ b/src/test/java/xmlcursor/checkin/SetAttributeTextTest.java @@ -16,75 +16,58 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; import javax.xml.namespace.QName; -import xmlcursor.common.*; -import tools.util.JarUtil; - -import java.net.URL; +import static org.junit.Assert.*; -/** - * - * - */ public class SetAttributeTextTest extends BasicCursorTestCase { - public SetAttributeTextTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SetAttributeTextTest.class); - } - + @Test public void testSetAttributeTextFromSTARTOn2ndATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.START); QName name = new QName("attr2"); - assertEquals(true, m_xc.setAttributeText(name, "newval2")); + assertTrue(m_xc.setAttributeText(name, "newval2")); assertEquals("newval2", m_xc.getAttributeText(name)); } + @Test public void testSetAttributeTextNewName() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.START); QName name = new QName("newname"); - assertEquals(true, m_xc.setAttributeText(name, "newval2")); + assertTrue(m_xc.setAttributeText(name, "newval2")); assertEquals("newval2", m_xc.getAttributeText(name)); } + @Test public void testSetAttributeTextFromSTARTChildHasATTR() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); m_xc = m_xo.newCursor(); m_xc.selectPath("$this//purchaseOrder"); QName name = new QName("country"); - assertEquals(true, m_xc.setAttributeText(name, "Finland")); + assertTrue(m_xc.setAttributeText(name, "Finland")); assertEquals("Finland", m_xc.getAttributeText(name)); } + @Test public void testSetAttributeTextFromATTR() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); QName name = new QName("orderDate"); - assertEquals(false, m_xc.setAttributeText(name, "2003-01-10")); + assertFalse(m_xc.setAttributeText(name, "2003-01-10")); } - - } diff --git a/test/src/xmlcursor/checkin/SetBookmarkTest.java b/src/test/java/xmlcursor/checkin/SetBookmarkTest.java similarity index 89% rename from test/src/xmlcursor/checkin/SetBookmarkTest.java rename to src/test/java/xmlcursor/checkin/SetBookmarkTest.java index 1959713..87431eb 100755 --- a/test/src/xmlcursor/checkin/SetBookmarkTest.java +++ b/src/test/java/xmlcursor/checkin/SetBookmarkTest.java @@ -16,42 +16,22 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import java.net.URL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -/** - * - * - */ public class SetBookmarkTest extends BasicCursorTestCase { private SimpleBookmark _theBookmark = new SimpleBookmark("value"); private SimpleBookmark _theBookmark1 = new SimpleBookmark("value1"); - public SetBookmarkTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SetBookmarkTest.class); - } - + @Test public void testSetBookmarkAtSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -60,6 +40,7 @@ public void testSetBookmarkAtSTARTDOC() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkDuplicateKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -70,6 +51,7 @@ public void testSetBookmarkDuplicateKey() throws Exception { assertEquals("value1", sa.text); } + @Test public void testSetBookmarkDuplicateKeyDifferentLocation() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -83,6 +65,7 @@ public void testSetBookmarkDuplicateKeyDifferentLocation() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkAtSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -92,6 +75,7 @@ public void testSetBookmarkAtSTART() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkAtATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR); m_xc = m_xo.newCursor(); @@ -101,6 +85,7 @@ public void testSetBookmarkAtATTR() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkAtPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -110,6 +95,7 @@ public void testSetBookmarkAtPROCINST() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkInMiddleOfTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -120,6 +106,7 @@ public void testSetBookmarkInMiddleOfTEXT() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkAtENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR); m_xc = m_xo.newCursor(); @@ -129,6 +116,7 @@ public void testSetBookmarkAtENDDOC() throws Exception { assertEquals("value", sa.text); } + @Test public void testSetBookmarkNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR); m_xc = m_xo.newCursor(); @@ -138,6 +126,7 @@ public void testSetBookmarkNull() throws Exception { assertNull(sa); } + @Test public void testXmlDocumentProperties() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR); m_xo.documentProperties().put("fredkey", "fredvalue"); @@ -149,7 +138,7 @@ public void testXmlDocumentProperties() throws Exception { public class SimpleBookmark extends XmlCursor.XmlBookmark { public String text; - public SimpleBookmark(String text) { + SimpleBookmark(String text) { this.text = text; } } diff --git a/src/test/java/xmlcursor/checkin/SetNameTest.java b/src/test/java/xmlcursor/checkin/SetNameTest.java new file mode 100755 index 0000000..cb9a862 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/SetNameTest.java @@ -0,0 +1,79 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + + +public class SetNameTest extends BasicCursorTestCase{ + + @Test + public void testNormalCase(){ + m_xc.toFirstChild(); + QName newName = new QName("newBook"); + m_xc.setName(newName); + assertEquals(m_xc.getName(), newName); + + newName = new QName("uri:newUri", "newBook"); + m_xc.setName(newName); + assertEquals(m_xc.getName(), newName); + + + newName = new QName("uri:newUri", "newBook", "prefix"); + m_xc.setName(newName); + assertEquals(m_xc.getName(), newName); + + //should work for attrs too... + m_xc.toFirstAttribute(); + newName = new QName("uri:newUri", "newBook", "prefix"); + m_xc.setName(newName); + assertEquals(m_xc.getName(), newName); + } + + @Test + public void testNoUri(){ + m_xc.toFirstChild(); + QName newName = new QName(null, "newBook"); + m_xc.setName(newName); + assertEquals(m_xc.getName().getLocalPart(), "newBook"); + } + + @Test + public void testNull() { + m_xc.toFirstChild(); + try { + m_xc.setName(null); + fail("QName null"); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } + + @Before + public void setUp()throws Exception{ + String sTestXml = "text0"; + m_xc=XmlObject.Factory.parse(sTestXml).newCursor(); + } +} diff --git a/test/src/xmlcursor/checkin/SetTextTest.java b/src/test/java/xmlcursor/checkin/SetTextTest.java similarity index 81% rename from test/src/xmlcursor/checkin/SetTextTest.java rename to src/test/java/xmlcursor/checkin/SetTextTest.java index 6dd6582..8621620 100755 --- a/test/src/xmlcursor/checkin/SetTextTest.java +++ b/src/test/java/xmlcursor/checkin/SetTextTest.java @@ -16,37 +16,16 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class SetTextTest extends BasicCursorTestCase { - public SetTextTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SetTextTest.class); - } - + @Test public void testSetTextFromCOMMENT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); m_xc = m_xo.newCursor(); @@ -55,6 +34,7 @@ public void testSetTextFromCOMMENT() throws Exception { assertEquals("fred", m_xc.getTextValue()); } + @Test public void testSetTextFromPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -63,6 +43,7 @@ public void testSetTextFromPROCINST() throws Exception { assertEquals("new procinst text", m_xc.getTextValue()); } + @Test public void testSetTextFromPROCINSTInputNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -71,55 +52,42 @@ public void testSetTextFromPROCINSTInputNull() throws Exception { assertEquals("", m_xc.getTextValue()); } + @Test(expected = IllegalStateException.class) public void testSetTextFromEND() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.END); - try { - m_xc.setTextValue("fred"); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } + m_xc.setTextValue("fred"); } + @Test(expected = IllegalStateException.class) public void testSetTextFromENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); m_xc.toEndDoc(); - try { - m_xc.setTextValue("fred"); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } + m_xc.setTextValue("fred"); } + @Test(expected = IllegalStateException.class) public void testSetTextFromTEXTbegin() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); assertEquals("01234", m_xc.getChars()); - try { - m_xc.setTextValue("new text"); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } - assertEquals(true, true); + m_xc.setTextValue("new text"); } + @Test(expected = IllegalStateException.class) public void testSetTextFromTEXTmiddle() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); m_xc.toNextChar(2); assertEquals("234", m_xc.getChars()); - try { - m_xc.setTextValue("new text"); - fail("Expected IllegalStateException"); - } catch (IllegalStateException e) { - } - assertEquals(true, true); + m_xc.setTextValue("new text"); } + @Test public void testSetTextFromSTARTnotNested() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -129,6 +97,7 @@ public void testSetTextFromSTARTnotNested() throws Exception { assertEquals("new text", m_xc.getTextValue()); } + @Test public void testSetTextFromSTARTnotNestedInputNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -138,6 +107,7 @@ public void testSetTextFromSTARTnotNestedInputNull() throws Exception { assertEquals("", m_xc.getTextValue()); } + @Test public void testSetTextFromSTARTnested() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); m_xc = m_xo.newCursor(); @@ -147,6 +117,7 @@ public void testSetTextFromSTARTnested() throws Exception { assertEquals("new text", m_xc.xmlText()); } + @Test public void testSetTextFromSTARTnestedInputNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); m_xc = m_xo.newCursor(); @@ -156,6 +127,7 @@ public void testSetTextFromSTARTnestedInputNull() throws Exception { assertEquals("", m_xc.xmlText()); } + @Test public void testSetTextFromATTRnested() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); m_xc = m_xo.newCursor(); @@ -165,6 +137,7 @@ public void testSetTextFromATTRnested() throws Exception { assertEquals("new text", m_xc.getTextValue()); } + @Test public void testSetTextFromSTARTDOCnested() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); m_xc = m_xo.newCursor(); @@ -172,7 +145,5 @@ public void testSetTextFromSTARTDOCnested() throws Exception { m_xc.setTextValue("new text"); assertEquals(Common.wrapInXmlFrag("new text"), m_xc.xmlText()); } - - } diff --git a/src/test/java/xmlcursor/checkin/StoreTests.java b/src/test/java/xmlcursor/checkin/StoreTests.java new file mode 100755 index 0000000..61afdd1 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/StoreTests.java @@ -0,0 +1,1992 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.checkin; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlCursor.XmlBookmark; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Ignore; +import org.junit.Test; +import org.xml.sax.*; +import org.xml.sax.ext.LexicalHandler; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import java.io.StringReader; +import java.util.*; + +import static org.junit.Assert.*; + +public class StoreTests { + + static String[] _args; + static String _test; + + + private void streamTest(String xml) + throws Exception { + XmlObject x1 = XmlObject.Factory.parse(xml); + XmlObject x2 = XmlObject.Factory.parse(x1.newCursor().newXMLStreamReader()); + + String x1Text = x1.xmlText(); + String x2Text = x2.xmlText(); + + assertEquals(x1Text, x2Text); + } + + @Test + public void testXMLStreamReader() throws Exception { + streamTest(""); + streamTest(""); + streamTest("foo"); + streamTest("foodsfdf"); + streamTest(""); + streamTest("xz"); + streamTest("moo"); + streamTest("asasdsdaazadsasd"); + streamTest(""); + streamTest(""); + streamTest(""); + streamTest("1"); + streamTest(""); + streamTest("abcde"); + streamTest(""); + streamTest(""); + } + + @Test + public void testReplaceContents() throws Exception { + XmlObject xDst = XmlObject.Factory.newInstance(); + XmlObject xSrc = XmlObject.Factory.parse(""); + XmlObject newDst = xDst.set(xSrc); + assertEquals("", newDst.xmlText()); + + xDst = XmlObject.Factory.parse(""); + xSrc = XmlObject.Factory.parse(""); + XmlCursor c = xDst.newCursor(); + c.toNextToken(); + xDst = c.getObject(); + xDst.set(xSrc); + c.toStartDoc(); + xDst = c.getObject(); + assertEquals("", xDst.xmlText()); + + xDst = XmlObject.Factory.parse(""); + xSrc = XmlObject.Factory.parse("moo"); + c = xDst.newCursor(); + c.toNextToken(); + c.toNextToken(); + xDst = c.getObject(); + xDst.set(xSrc); + c.toStartDoc(); + xDst = c.getObject(); + assertEquals("", xDst.xmlText()); + } + + @Test(expected = Exception.class) + public void testSniffing() throws Exception { + XmlObject x; + + x = XmlObject.Factory.parse(""); + assertSame(x.schemaType(), XmlBeans.NO_TYPE); + + x = XmlObject.Factory.parse( + ""); + assertSame(x.schemaType(), SchemaDocument.type); + + x = XmlObject.Factory.parse( + ""); + assertSame(x.schemaType(), XmlBeans.NO_TYPE); + + x = XmlObject.Factory.parse( + ""); + assertSame(x.schemaType(), SchemaDocument.type); + + x = org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Factory.parse( + ""); + assertSame(x.schemaType(), SchemaDocument.type); + + org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Factory.parse( + ""); + } + + @Test + public void testCursorStack() throws Exception { + XmlObject x = XmlObject.Factory.parse(""); + XmlCursor c = x.newCursor(); + c.push(); + c.toNextToken(); + c.push(); + c.toNextToken(); + assertTrue(c.isAttr()); + c.pop(); + assertTrue(c.isStart()); + c.pop(); + assertTrue(c.isStartdoc()); + } + + @Test + public void testImplicitNamespaces() { + Map namespaces = new HashMap<>(); + namespaces.put("foo", "foo.com"); + namespaces.put("bar", "bar.com"); + namespaces.put("", "default.com"); + + XmlOptions options = new XmlOptions(); + options.setSaveImplicitNamespaces(namespaces); + + XmlObject x = XmlObject.Factory.newInstance(); + XmlCursor c = x.newCursor(); + + c.toNextToken(); + + c.beginElement("a", "foo.com"); + c.beginElement("b", "default.com"); + c.beginElement("c", "bar.com"); + + assertEquals("", x.xmlText(options)); + } + + private static class Content implements ContentHandler, LexicalHandler { + public void startDocument() { + add("START_DOCUMENT"); + } + + public void endDocument() { + add("END_DOCUMENT"); + } + + public void startElement( + String namespaceURI, String localName, + String qName, Attributes atts) { + add("START_ELEMENT"); + add(" namespaceURI: " + namespaceURI); + add(" localName: " + localName); +// add( " qName: " + qName ); + + TreeSet sortedAttrs = new TreeSet<>(); + + for (int i = 0; i < atts.getLength(); i++) { + String ln = atts.getLocalName(i); + String uri = atts.getURI(i); + String qname = atts.getQName(i); + + if (ln.equals("xmlns")) { + continue; + } + if (qname.startsWith("xmlns")) { + continue; + } + +// if (ln.equals( "xmlns" )) +// ln = ""; +// +// if (uri.equals( "xmlns" )) +// uri = ""; + + sortedAttrs.add( + uri + "-" + ln + "-" + + atts.getQName(i) + "-" + atts.getType(i) + "-" + + atts.getValue(i)); + } + + for (String sortedAttr : sortedAttrs) { + add(" Attr: " + sortedAttr); + } + } + + public void endElement( + String namespaceURI, String localName, String qName) { + add("END_ELEMENT"); + add(" namespaceURI: " + namespaceURI); + add(" localName: " + localName); +// add( " qName: " + qName ); + } + + public void characters(char[] ch, int start, int length) { + if (length > 0) { + add("CHARACTERS"); + add(ch, start, length); + } + } + + public void comment(char[] ch, int start, int length) { + add("COMMENT"); + add(" Comment: ", ch, start, length); + } + + public void processingInstruction(String target, String data) { + add("PROCESSING_INSTRUCTION"); + add("target: " + target); + add("data: " + data); + } + + public void ignorableWhitespace(char[] ch, int start, int length) { + if (length > 0) { + add("IGNORABLE_WHITESPACE"); + add(" whitespace: ", ch, start, length); + } + } + + public void startPrefixMapping(String prefix, String uri) { + add("START_PREFIX_MAPPING"); +// add( " prefix: " + prefix ); + add(" uri: " + uri); + } + + public void endPrefixMapping(String prefix) { + add("END_PREFIX_MAPPING"); +// add( " prefix: " + prefix ); + } + + public void startCDATA() { + add("START_CDATA"); + } + + public void endCDATA() { + add("END_CDATA"); + } + + public void startDTD(String name, String publicId, String systemId) { + add("START_DTD"); + add(" name: " + name); + add(" publicId: " + publicId); + add(" systemId: " + systemId); + } + + public void endDTD() { + add("END_DTD"); + } + + public void startEntity(String name) { + add("START_ENTITY"); + add(" name: " + name); + } + + public void endEntity(String name) { + add("END_ENTITY"); + add(" name: " + name); + } + + public void setDocumentLocator(Locator locator) { + // add( "START_DOCUMENT_LOCATOR" ); + } + + public void skippedEntity(String name) { + add("SKIPPED_ENTITY"); + add(" name: " + name); + } + + private void add(String s) { + _sb.append(s); + _sb.append("\n"); + } + + private void add(String s, char[] buf, int off, int cch) { + _sb.append(s); + if (buf != null) { + _sb.append(buf, off, cch); + } + _sb.append("\n"); + } + + private void add(char[] buf, int off, int cch) { + _sb.append(buf, off, cch); + _sb.append("\n"); + } + + public boolean equals(Object that) { + return toString().equals(that.toString()); + } + + public String toString() { + return _sb.toString(); + } + + private final StringBuilder _sb = new StringBuilder(); + } + + private void doTestSaxSaver(String xml) + throws Exception { + // ME + + Content content2 = new Content(); + + XmlObject x = XmlObject.Factory.parse(xml); + + x.save(content2, content2); + + // THEM + + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser sp = spf.newSAXParser(); + + XMLReader xr = sp.getXMLReader(); + + Content content1 = new Content(); + + xr.setProperty("http://xml.org/sax/properties/lexical-handler", content1); + xr.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + xr.setFeature("http://xml.org/sax/features/namespaces", true); + xr.setFeature("http://xml.org/sax/features/validation", false); + + xr.setContentHandler(content1); + + InputSource is = new InputSource(new StringReader(xml)); + + xr.parse(is); + + assertEquals(content1, content2); + } + + @Test + public void testSaxSaver() + throws Exception { + doTestSaxSaver(""); + doTestSaxSaver("xz"); + doTestSaxSaver("moo"); + doTestSaxSaver("asasdsdaazadsasd"); + doTestSaxSaver(""); + doTestSaxSaver(""); + doTestSaxSaver(""); + } + + @Test + @Ignore + public void testParsing() throws Exception { + Random r = new Random(1); + + for (int i = 0; i < 100000; i++) { + String xml = makeRandomDocument(r); + XmlObject.Factory.parse(xml); + } + } + + private void doTestLineNumbers(String xml) + throws Exception { + int line = 1; + int col = 1; + + XmlCursor c = + XmlObject.Factory.parse( + xml, new XmlOptions().setLoadLineNumbers()). + newCursor(); + + for (int i = 0; i < xml.length(); i++) { + char ch = xml.charAt(i); + + if (ch == '<' && Character.isLetter(xml.charAt(i + 1))) { + while (!c.currentTokenType().isStart()) { + c.toNextToken(); + } + + assertTrue(c.currentTokenType().isStart()); + + XmlLineNumber ln = + (XmlLineNumber) + c.getBookmark(XmlLineNumber.class); + + assertNotNull(ln); + + assertTrue(ln.getLine() == -1 || ln.getLine() == line); + assertTrue(ln.getColumn() == -1 || ln.getColumn() == col); + assertTrue(ln.getOffset() == -1 || ln.getOffset() == i); + + c.toNextToken(); + } + + if (ch == '\n') { + line++; + col = 1; + } else { + col++; + } + } + } + + @Test + @Ignore + public void testLineNumbers() throws Exception { + Random r = new Random(1); + + for (int i = 0; i < 1000; i++) { + String xml = makeRandomDocument(r); + doTestLineNumbers(xml); + } + } + + private static class DocBuilder { + Random r; + StringBuilder sb; + + DocBuilder(Random _r, StringBuilder _sb) { + r = _r; + sb = _sb; + } + + void append(char ch) { + sb.append(ch); + } + + void append(String s) { + sb.append(s); + } + + public void whitespace() { + int p = r.nextInt(100); + + if (p < 20) { + append('\t'); + } else if (p < 40) { + append('\n'); + } else { + append(' '); + } + } + + void whitespaces() { + for (int i = r.nextInt(8); i > 0; i--) { + whitespace(); + } + } + + char makeLetter() { + return (char) (((int) 'a') + r.nextInt(26)); + } + + public void letter() { + append(makeLetter()); + } + + void charEntity() { + switch (r.nextInt(5)) { + case 0: + append("<"); + break; + case 1: + append(">"); + break; + case 2: + append("&"); + break; + case 3: + append("'"); + break; + case 4: + append("""); + break; + } + } + + public void text() { + for (int i = r.nextInt(20); i > 0; i--) { + int p = r.nextInt(100); + + if (p < 70) { + letter(); + } else if (p < 74) { + charEntity(); + } else { + whitespace(); + } + } + } + + String makeNcName() { + StringBuilder name = new StringBuilder(); + + for (; ; ) { + char ch = makeLetter(); + + if (ch == 'x' || ch == 'X') { + continue; + } + + name.append(ch); + + break; + } + + for (int i = r.nextInt(20); i > 0; i--) { + name.append(makeLetter()); + } + + return name.toString(); + } + + void ncName() { + append(makeNcName()); + } + + public void comment() { + append(""); + } + + public void procinst() { + append(""); + } + + void whiteContent() { + for (; ; ) { + int p = r.nextInt(100); + + if (p < 20) { + break; + } else if (p < 50) { + whitespaces(); + } else if (p < 70) { + comment(); + } else { + procinst(); + } + } + } + + void xmlDecl() { + append(""); + } + + public void content(int depth) { + for (int i = r.nextInt(10); i > 0; i--) { + switch (r.nextInt(4)) { + case 0: + elementContent(depth + 1); + break; + + case 1: + text(); + break; + case 2: + comment(); + break; + case 3: + procinst(); + break; + } + } + } + + public void attribute() { + ncName(); + + if (r.nextInt(100) == 0) { + whitespaces(); + } + + append('='); + + if (r.nextInt(100) == 0) { + whitespaces(); + } + + char q = r.nextInt(2) == 0 ? '\'' : '"'; + + append(q); + + text(); + + append(q); + } + + void elementContent(int depth) { + // If depth == 0, guarantee an element, otherwise, as depth + // increases, the probablility we'll spit out an element + // gets smaller. + + if (r.nextInt(depth + 1) <= 1) { + String name = makeNcName(); + + append('<'); + append(name); + + if (r.nextInt(100) == 0) { + whitespaces(); + } + + HashMap attrs = new HashMap<>(); + + for (int i = r.nextInt(3); i > 0; i--) { + append(' '); + + String aname; + + do { + aname = makeNcName(); + + } while (attrs.containsKey(aname)); + + attrs.put(aname, null); + + append(aname); + + if (r.nextInt(100) == 0) { + whitespaces(); + } + + append('='); + + if (r.nextInt(100) == 0) { + whitespaces(); + } + + char q = r.nextInt(2) == 0 ? '\'' : '"'; + + append(q); + + text(); + + append(q); + + if (r.nextInt(10) == 0) { + whitespaces(); + } + } + + append('>'); + + content(depth); + + append("'); + } + } + + public void document() { + if (r.nextInt(2) == 0) { + xmlDecl(); + } + + whiteContent(); + + elementContent(0); + + whiteContent(); + } + } + + private String makeRandomDocument(Random r) { + StringBuilder sb = new StringBuilder(); + + DocBuilder db = new DocBuilder(r, sb); + + db.document(); + + return sb.toString(); + } + + private static class MyMark extends XmlBookmark { + } + + @Test + public void testBookmarks() + throws Exception { + XmlObject x = XmlObject.Factory.parse("abcdefgxy"); + + XmlCursor c = x.newCursor(); + MyMark m1 = new MyMark(); + c.setBookmark(m1); + + c.toNextToken(); + MyMark m2 = new MyMark(); + c.setBookmark(m2); + + c.toNextToken(); + MyMark m3 = new MyMark(); + c.setBookmark(m3); + + c.toNextToken(); + MyMark m4 = new MyMark(); + c.setBookmark(m4); + + c.toNextChar(1); + MyMark m5 = new MyMark(); + c.setBookmark(m5); + + c.toNextChar(3); + MyMark m6 = new MyMark(); + c.setBookmark(m6); + + c.toNextToken(); + c.toNextToken(); + c.toNextToken(); + MyMark m7 = new MyMark(); + c.setBookmark(m7); + + c.toNextToken(); + MyMark m8 = new MyMark(); + c.setBookmark(m8); + + c.toStartDoc(); + + assertSame(c.getBookmark(MyMark.class), m1); + assertSame(c.toNextBookmark(MyMark.class), m2); + assertSame(c.toNextBookmark(MyMark.class), m3); + assertSame(c.toNextBookmark(MyMark.class), m4); + assertSame(c.toNextBookmark(MyMark.class), m5); + assertSame(c.toNextBookmark(MyMark.class), m6); + assertSame(c.toNextBookmark(MyMark.class), m7); + assertSame(c.toNextBookmark(MyMark.class), m8); + assertNull(c.toNextBookmark(MyMark.class)); + + c.toEndDoc(); + + assertSame(c.getBookmark(MyMark.class), m8); + assertSame(c.toPrevBookmark(MyMark.class), m7); + assertSame(c.toPrevBookmark(MyMark.class), m6); + assertSame(c.toPrevBookmark(MyMark.class), m5); + assertSame(c.toPrevBookmark(MyMark.class), m4); + assertSame(c.toPrevBookmark(MyMark.class), m3); + assertSame(c.toPrevBookmark(MyMark.class), m2); + assertSame(c.toPrevBookmark(MyMark.class), m1); + assertNull(c.toPrevBookmark(MyMark.class)); + } + + @Test + public void testSetName() + throws Exception { + XmlObject x = XmlObject.Factory.parse(""); + XmlCursor c = x.newCursor(); + c.toNextToken(); + c.setName(new QName("bar")); + c.toNextToken(); + c.setName(new QName("y")); + + assertEquals("", x.xmlText()); + } + + // + // Basic load up a file and iterate through it + // + @Test + public void testBasicXml() + throws Exception { + XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); + + int n = 0; + + for (; ; ) { + TokenType t = c.toNextToken(); + + n++; + + if (t == TokenType.NONE) { + break; + } + } + + assertEquals(6, n); + } + + // + // Make sure the tokens going forward the the reverse of the tokens + // going backward + // + @Test + public void testConsistentTokenOrder() + throws Exception { + ArrayList l = new ArrayList<>(); + + XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); + + + do { + // System.err.println(c.currentTokenType()); + l.add(c.currentTokenType()); + + } while (c.toNextToken() != TokenType.NONE); + + c.toEndDoc(); + // System.err.println("Reversing"); + + for (int i = l.size() - 1; ; i--) { + // System.err.println(c.currentTokenType()); + assertEquals(l.get(i), c.currentTokenType()); + + if (c.toPrevToken() == TokenType.NONE) { + break; + } + } + } + + // Make sure you can't insert text before the doc begin + // going backward + @Test(expected = IllegalStateException.class) + public void testIllegalTextInsert() + throws Exception { + XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); + c.insertChars("Ho ho ho"); + } + + // Make sure getText works in a basic way + @Test + public void testgetText() + throws Exception { + XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); + assertEquals("ab", c.getTextValue()); // Doc node + + c.toNextToken(); + assertEquals("ab", c.getTextValue()); // Doc elem + + c.toNextToken(); + assertEquals("y", c.getTextValue()); // Attr x + + c.toNextToken(); + assertEquals("ab", c.getChars()); // Text + + c.toNextChar(1); + assertEquals("b", c.getChars()); // Text + + c.toNextToken(); + assertEquals(0, c.getChars().length()); // End tag + + c.toNextToken(); + assertEquals(0, c.getChars().length()); // End doc + } + + // + // Text XMLInputStream support + // + + private void doSaverTest(String xml) throws Exception { + XmlCursor c = XmlObject.Factory.parse(xml).newCursor(); + assertEquals(xml, c.xmlText()); + } + + private void doSaveTest(String xml) throws Exception { + doSaverTest(xml); + } + + @Test + public void testCDATA() throws Exception { + // https://issues.apache.org/jira/browse/XMLBEANS-404 + String xml = "Unable to render embedded object: >>>>>>><<<<<<<<<<<]]>"; + String expected = ">>>>>>><<<<<<<<<<<]]>"; + XmlOptions options = new XmlOptions().setSaveCDataLengthThreshold(0); + XmlCursor c = XmlObject.Factory.parse(xml, options).newCursor(); + assertEquals(expected, c.xmlText(options)); + } + + @Test + public void testSaving() throws Exception { + doSaveTest("1"); + doSaveTest(""); + doSaveTest("abcde"); + doSaveTest(""); + doSaveTest(""); + + String s = "aaabbb"; + s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s; + s = "xxxx" + s + ""; + + doSaveTest(s); + + XmlObject x = + XmlObject.Factory.parse(""); + + XmlCursor c = x.newCursor(); + + c.toFirstChild(); + c.toFirstChild(); + + assertEquals("", c.xmlText()); + + x = XmlObject.Factory.parse(""); + + c = x.newCursor(); + + c.toFirstChild(); + c.toFirstChild(); + + assertEquals("", c.xmlText()); + } + + + private XmlCursor navDoc(XmlObject x, String dirs) { + return navCursor(x.newCursor(), dirs); + } + + private XmlCursor navNewCursor(XmlCursor c, String dirs) { + return navCursor(c.newCursor(), dirs); + } + + // + // Format: + // + // ( [-][N] type ) * + // + // type: + // + // c - character + // t - token + // p - parent element + // s - sibling element + // d - descendent (child) element + // r - end of the doc (root) + // b - begin of the doc + // + + private XmlCursor navCursor(XmlCursor c, String dirs) { + int n = 0; + boolean prev = false; + + for (int i = 0; i < dirs.length(); i++) { + char ch = dirs.charAt(i); + + if (ch == '-') { + prev = !prev; + continue; + } else if (ch >= '0' && ch <= '9') { + n = n * 10 + (ch - '0'); + continue; + } + + if (n == 0) { + n = 1; + } + + if (ch == 'c') { + if (prev) { + assertEquals(c.toPrevChar(n), n); + } else { + assertEquals(c.toNextChar(n), n); + } + } else if (ch == 't') { + while (n-- > 0) { + if (prev) { + assertNotSame(c.toPrevToken(), TokenType.NONE); + } else { + assertNotSame(c.toNextToken(), TokenType.NONE); + } + } + } else if (ch == 'p') { + assertFalse(prev); + + while (n-- > 0) { + assertTrue(c.toParent()); + } + } else if (ch == 'r') { + assertFalse(prev); + assertEquals(1, n); + + c.toEndDoc(); + } else if (ch == 'b') { + assertFalse(prev); + assertEquals(1, n); + + c.toStartDoc(); + } else if (ch == 's') { + while (n-- > 0) { + if (prev) { + assertTrue(c.toPrevSibling()); + } else { + assertTrue(c.toNextSibling()); + } + } + } else if (ch == 'd') { + assertFalse(prev); + + while (n-- > 0) { + assertTrue(c.toFirstChild()); + } + } else { + fail(); + } + + n = 0; + prev = false; + } + + return c; + } + + @Test + public void testOps() + throws Exception { + XmlObject x, x2, y; + XmlCursor cFrom, cTo, cTemp, cTemp2, c, d; + XmlBookmark anno; + + // + + x = XmlObject.Factory.parse("abcdef"); + cFrom = navDoc(x, "d"); + cTo = navNewCursor(cFrom, ""); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + XmlOptions options = new XmlOptions(); + + options.setSaveSyntheticDocumentElement(new QName(null, "bar")); + + assertTrue( + x.xmlText(options).equals("[TO]abcdef[FROM]") || + x.xmlText(options).equals("[FROM]abcdef[TO]")); + + // + + x = XmlObject.Factory.parse("abcdef"); + + cFrom = navDoc(x, "d"); + cTo = navNewCursor(cFrom, "ttt"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertTrue( + x.xmlText(options).equals("abcdef[FROM][TO]") || + x.xmlText(options).equals("abcdef[TO][FROM]")); + + // + + x = XmlObject.Factory.parse("abcdef"); + + cFrom = navDoc(x, "d"); + cTo = navNewCursor(cFrom, "t3c"); + assertFalse(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]abc[TO]def", x.xmlText(options)); + + // + + x = XmlObject.Factory.parse("xyzpqr"); + + cFrom = navDoc(x, "dd"); + cTo = navNewCursor(cFrom, "r-1t"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]pqrxyz[TO]", x.xmlText()); + + // + + x = XmlObject.Factory.parse("xyzpqrAB"); + + cFrom = navDoc(x, "dd"); + cTo = navNewCursor(cFrom, "r-1t-1c"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]pqrAxyz[TO]B", x.xmlText()); + + // + + x = XmlObject.Factory.parse("xyzpqrAB"); + + cFrom = navDoc(x, "dd"); + cTo = navNewCursor(cFrom, "stc"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]pxyz[TO]qrAB", x.xmlText()); + + // + + x = XmlObject.Factory.parse("xyzpqrAB"); + + cFrom = navDoc(x, "dd"); + cTo = navDoc(x, "d"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + testTextFrag(x.xmlText(), "xyz[TO][FROM]pqrAB"); + + // + + x = XmlObject.Factory.parse("xyzpqrAB"); + + cFrom = navDoc(x, "dd"); + cTo = navDoc(x, "r"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]pqrABxyz[TO]", x.xmlText(options)); + + // + + x = XmlObject.Factory.parse("xyz"); + x2 = XmlObject.Factory.parse(""); + + cFrom = navDoc(x, "dd"); + cTo = navDoc(x2, "dt"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]", x.xmlText()); + assertEquals("xyz[TO]", x2.xmlText()); + + // + + x = XmlObject.Factory.parse("pq"); + + cFrom = navDoc(x, "dd"); + cTo = navDoc(x, "ddst"); + cTemp = navDoc(x, "ddt1c"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + cTemp.insertChars("[TEMP]"); + + assertEquals("[FROM][TEMP]pq[TO]", x.xmlText()); + + // + + x = XmlObject.Factory.parse("abcdef"); + + cFrom = navDoc(x, "2t2c"); + cTo = navNewCursor(cFrom, "-1c"); + cFrom.moveChars(2, cTo); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("acd[TO]b[FROM]ef", x.xmlText()); + + // + + x = XmlObject.Factory.parse("abcdef"); + + cFrom = navDoc(x, "2t2c"); + cTo = navNewCursor(cFrom, "3c"); + cFrom.moveChars(2, cTo); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("ab[FROM]ecd[TO]f", x.xmlText()); + + // + + x = XmlObject.Factory.parse("abcdef123456"); + + cFrom = navDoc(x, "3t2c"); + cTo = navNewCursor(cFrom, "3t3c"); + cFrom.moveChars(2, cTo); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("ab[FROM]ef123cd[TO]456", x.xmlText()); + + // + + x = XmlObject.Factory.parse("abcdef123456"); + + cFrom = navDoc(x, "2d"); + cTo = navDoc(x, "2dst2c"); + assertTrue(cFrom.copyXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals(x.xmlText(), + "[FROM]abcdef12" + + "abcdef[TO]3456"); + + // + + x = XmlObject.Factory.parse("xyz"); + x2 = XmlObject.Factory.parse(""); + + cFrom = navDoc(x, "dd"); + cTo = navDoc(x2, "dt"); + assertTrue(cFrom.copyXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]xyz", x.xmlText()); + assertEquals("xyz[TO]", x2.xmlText()); + + // + + x = XmlObject.Factory.parse( + "abcdefblah123456"); + + cFrom = navDoc(x, "2d"); + cTo = navDoc(x, "2dst2c"); + assertTrue(cFrom.copyXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals(x.xmlText(), "[FROM]abcdefblah12" + + "abcdef[TO]3456"); + + // + + x = XmlObject.Factory.parse( + "abcdef1234567890"); + + cFrom = navDoc(x, "2dt"); + cTo = navDoc(x, "2dst"); + cTemp = navDoc(x, "2dst3c"); + cTemp2 = navDoc(x, "2ds3t2c"); + assertTrue(cFrom.copyXml(cTo)); + cTemp.insertChars("[TEMP]"); + cTemp2.insertChars("[TEMP2]"); + + assertEquals(x.xmlText(), + "abcdef" + + "123[TEMP]45678[TEMP2]90"); + + // + + x = XmlObject.Factory.parse( + "xyabcdefpqr123456"); + + cFrom = navDoc(x, "2d"); + cTo = navDoc(x, "2ds-2c"); + + assertTrue(cFrom.removeXml()); + + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("xy[FROM]p[TO]qr123456", x.xmlText()); + + // + + x = XmlObject.Factory.parse( + "xyabcdefpqr123456"); + + cFrom = navDoc(x, "2d2t2c"); + cTo = navDoc(x, "2d2t5c"); + + cFrom.removeChars(2); + + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals(x.xmlText(), + "xyab[FROM]e[TO]f" + + "pqr123456"); + + // + + x = XmlObject.Factory.parse("abc"); + + cFrom = navDoc(x, "tt"); + cTo = navDoc(x, "tttc"); + + assertTrue(cFrom.removeXml()); + + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + + assertEquals("[FROM]a[TO]bc", x.xmlText()); + + // + + x = XmlObject.Factory.newInstance(); + + cTo = navDoc(x, "t"); + cTo.insertElement("boo"); + cTo.toPrevToken(); + cTo.insertElement("moo"); + cTo.toPrevToken(); + cTo.insertElement("goo"); + + assertEquals("", x.xmlText()); + + // + + x = XmlObject.Factory.newInstance(); + + cTo = navDoc(x, "t"); + cTo.insertElement("boo"); + cTo.toPrevToken(); + cTo.insertElement("moo"); + cTo.toPrevToken(); + cTo.insertAttributeWithValue("x", "y"); + + assertEquals("", x.xmlText()); + + // + + x = XmlObject.Factory.parse("abc"); + cTo = navDoc(x, "tt"); + cTo.insertAttributeWithValue("p", "q"); + + assertEquals("abc", x.xmlText()); + + // Text XmlBookmark + + x = XmlObject.Factory.parse("abc"); + cFrom = navDoc(x, "tt"); + anno = new Anno(); + cFrom.setBookmark(anno); + cTo = navDoc(x, "6t"); + assertTrue(cFrom.moveXml(cTo)); + cFrom.insertChars("[FROM]"); + cTo.insertChars("[TO]"); + anno.createCursor().insertChars("[ANNO]"); + + assertEquals("[FROM][ANNO]abc[TO]", x.xmlText()); + + // Test content ops + + x = XmlObject.Factory.parse("abc"); + y = XmlObject.Factory.newInstance(); + d = y.newCursor(); + d.toNextToken(); + x.newCursor().moveXmlContents(d); + assertEquals("abc", y.xmlText()); + + x = XmlObject.Factory.parse("abc"); + y = XmlObject.Factory.newInstance(); + c = x.newCursor(); + c.toNextToken(); + d = y.newCursor(); + d.toNextToken(); + c.moveXmlContents(d); + assertEquals("abc", y.xmlText()); + + x = XmlObject.Factory.parse("abc"); + c = x.newCursor(); + c.toNextToken(); + c.removeXmlContents(); + assertEquals("", x.xmlText()); + + x = XmlObject.Factory.parse("abc"); + y = XmlObject.Factory.newInstance(); + d = y.newCursor(); + d.toNextToken(); + x.newCursor().copyXmlContents(d); + assertEquals("abc", y.xmlText()); + } + + private static class Anno extends XmlBookmark { + } + + @Test + public void testSave() throws Exception { + XmlObject x; + XmlCursor cTo; + + // + + x = XmlObject.Factory.parse("abcdef"); + + assertEquals("abcdef", x.xmlText()); + + // + + x = XmlObject.Factory.parse("a<b&c"); + + assertEquals("a<b&c", x.xmlText()); + + // + + x = XmlObject.Factory.parse(""); + + cTo = navDoc(x, "dt"); + cTo.insertChars("&<"); + + assertEquals("&<", x.xmlText()); + + // + + x = XmlObject.Factory.parse("bar"); + + cTo = navDoc(x, "dt"); + + assertEquals("bar", cTo.xmlText()); + + // + + x = XmlObject.Factory.parse("bar"); + + cTo = navDoc(x, "dt"); + + assertEquals("bar", cTo.xmlText()); + + // Tests fragment saving and loading + + x = XmlObject.Factory.parse("Eric"); + + cTo = navDoc(x, "dt"); + + x = XmlObject.Factory.parse(cTo.xmlText()); + + cTo = navDoc(x, ""); + + assertEquals("Eric", cTo.getTextValue()); + + // test save where I replace the name of an element + + x = XmlObject.Factory.parse("Eric"); + + cTo = navDoc(x, "d"); + + XmlOptions options = new XmlOptions(); + + options.setSaveSyntheticDocumentElement(new QName(null, "bar")); + + x = XmlObject.Factory.parse(cTo.xmlText(options)); + + cTo = navDoc(x, ""); + + assertEquals("Eric", cTo.xmlText()); + + // test save where I replace the name of the document + + x = XmlObject.Factory.parse("Eric"); + + cTo = navDoc(x, ""); + + options = new XmlOptions(); + + options.setSaveSyntheticDocumentElement(new QName(null, "bar")); + + x = XmlObject.Factory.parse(cTo.xmlText(options)); + + cTo = navDoc(x, ""); + + assertEquals("Eric", cTo.xmlText()); + + x = XmlObject.Factory.parse(""); + + XmlCursor c = x.newCursor(); + + c.toFirstContentToken(); + c.toFirstContentToken(); + + c.insertElement("b"); + c.toPrevSibling(); + assertEquals("b", c.getName().getLocalPart()); + assertEquals(0, c.getName().getNamespaceURI().length()); + + x = XmlObject.Factory.parse(x.xmlText()); + + c = x.newCursor(); + + c.toFirstContentToken(); + c.toFirstContentToken(); + + assertEquals("b", c.getName().getLocalPart()); + assertEquals(0, c.getName().getNamespaceURI().length()); + } + + private void testTextFrag(String actual, String expected) { + String pre = ""; + + String post = ""; + + assertTrue(actual.startsWith(pre)); + assertTrue(actual.endsWith(post)); + + assertEquals(expected, actual.substring( + pre.length(), actual.length() - post.length())); + } + + @Test + public void testSaveFrag() { + XmlObject x; + XmlCursor c; + + x = XmlObject.Factory.newInstance(); + + c = x.newCursor(); + + c.toNextToken(); + + c.insertChars("Eric"); + + testTextFrag(x.xmlText(), "Eric"); + + // + + x = XmlObject.Factory.newInstance(); + + c = x.newCursor(); + + c.toNextToken(); + + c.insertComment(""); + c.insertChars("x"); + + testTextFrag(x.xmlText(), "x"); + + // + + x = XmlObject.Factory.newInstance(); + + c = x.newCursor(); + + c.toNextToken(); + + c.insertElement("foo"); + c.insertChars("x"); + + testTextFrag(x.xmlText(), "x"); + + // + + x = XmlObject.Factory.newInstance(); + + c = x.newCursor(); + + c.toNextToken(); + + c.insertElement("foo"); + c.insertElement("bar"); + + testTextFrag(x.xmlText(), ""); + } + + @Test + public void testLoad() throws Exception { + XmlObject x; + + XmlOptions options = new XmlOptions(); + options.setLoadReplaceDocumentElement(null); + + x = + XmlObject.Factory.parse( + "abxycd", options); + + XmlCursor c = navDoc(x, "t"); + + assertSame(c.currentTokenType(), TokenType.ATTR); + + String open = "xmlns:open='http://www.openuri.org/fragment'"; + + x = + XmlObject.Factory.parse( + "abxycd"); + + c = navDoc(x, "t"); + + assertSame(c.currentTokenType(), TokenType.ATTR); + } + + @Test + public void testCompare() throws Exception { + XmlObject x; + XmlCursor cFrom, cTo; + + // Forward navigation + + x = XmlObject.Factory.parse("abxycd"); + + cFrom = navDoc(x, ""); + cTo = navDoc(x, ""); + + for (; ; ) { + assertEquals(0, cFrom.comparePosition(cTo)); + assertTrue(cFrom.isAtSamePositionAs(cTo)); + + TokenType tt = cFrom.currentTokenType(); + + if (tt == TokenType.ENDDOC) { + break; + } else if (tt == TokenType.TEXT) { + cFrom.toNextChar(1); + cTo.toNextChar(1); + } else { + cFrom.toNextToken(); + cTo.toNextToken(); + } + } + + // Backward navigation + + x = XmlObject.Factory.parse("abxycd"); + + cFrom = navDoc(x, "r"); + cTo = navDoc(x, "r"); + + for (; ; ) { + assertEquals(0, cFrom.comparePosition(cTo)); + assertTrue(cFrom.isAtSamePositionAs(cTo)); + + if (cFrom.toPrevChar(1) == 1) { + cTo.toPrevChar(1); + } else if (cFrom.toPrevToken() != TokenType.NONE) { + cTo.toPrevToken(); + } else { + break; + } + } + + // + + x = XmlObject.Factory.parse( + "abxycxyd"); + + cFrom = navDoc(x, ""); + + for (; ; ) { + boolean passed = false; + + cTo = navDoc(x, ""); + + for (; ; ) { + if (cTo.isAtSamePositionAs(cFrom)) { + assertFalse(passed); + passed = true; + } else if (cTo.isLeftOf(cFrom)) { + assertFalse(passed); + } else { + assertTrue(passed); + assertTrue(cTo.isRightOf(cFrom)); + } + + if (cTo.toNextChar(1) != 1) { + if (cTo.toNextToken() == TokenType.ENDDOC) { + break; + } + } + } + + if (cFrom.toNextChar(1) != 1) { + if (cFrom.toNextToken() == TokenType.ENDDOC) { + break; + } + } + } + } + + @Test + public void testAttrSetter() + throws Exception { + XmlObject x = XmlObject.Factory.parse(""); + XmlCursor c = x.newCursor(); + c.toNextToken(); + c.setAttributeText(new QName(null, "x"), "hardehar"); + assertEquals("", x.xmlText()); + } + + @Test + public void testNavigation() + throws Exception { + XmlObject x = XmlObject.Factory.parse(""); + XmlCursor c = x.newCursor(); + assertFalse(c.toNextSibling()); + assertFalse(c.toPrevSibling()); + assertFalse(c.toFirstAttribute()); + assertFalse(c.toLastAttribute()); + c.toNextToken(); + c.toNextToken(); + assertTrue(c.toNextSibling()); + assertEquals("y", c.getName().getLocalPart()); + assertTrue(c.toNextSibling()); + assertEquals("z", c.getName().getLocalPart()); + assertFalse(c.toNextSibling()); + + x = XmlObject.Factory.parse(""); + c = x.newCursor(); + c.toNextToken(); + c.toNextToken(); + assertTrue(c.currentTokenType().isAttr()); + assertFalse(c.toPrevSibling()); + assertTrue(c.currentTokenType().isAttr()); + assertTrue(c.toNextSibling()); + assertEquals("x", c.getName().getLocalPart()); + + c.toEndDoc(); + c.toPrevToken(); + assertTrue(c.toPrevSibling()); + assertEquals("z", c.getName().getLocalPart()); + assertTrue(c.toPrevSibling()); + assertEquals("y", c.getName().getLocalPart()); + assertTrue(c.toPrevSibling()); + assertEquals("x", c.getName().getLocalPart()); + assertFalse(c.toPrevSibling()); + + c.toEndDoc(); + c.toPrevToken(); + assertTrue(c.toParent()); + assertEquals("a", c.getName().getLocalPart()); + + c.toEndDoc(); + assertTrue(c.toParent()); + assertTrue(c.currentTokenType().isStartdoc()); + + x = XmlObject.Factory.parse("moofoo"); + c = x.newCursor(); + c.toStartDoc(); + c.toNextToken(); + c.toNextToken(); + c.toNextToken(); + assertTrue(c.toParent()); + assertEquals("a", c.getName().getLocalPart()); + + c.toStartDoc(); + c.toNextToken(); + c.toNextToken(); + c.toNextToken(); + c.toNextToken(); + assertTrue(c.toParent()); + assertEquals("a", c.getName().getLocalPart()); + + c.toStartDoc(); + c.toNextToken(); + c.toNextToken(); + c.toNextToken(); + c.toNextToken(); + c.toNextChar(2); + assertTrue(c.toParent()); + assertEquals("a", c.getName().getLocalPart()); + + x = XmlObject.Factory.parse("earlytextzap"); + c = x.newCursor(); + c.toNextToken(); + c.toNextToken(); + assertTrue(c.toFirstChild()); + assertEquals("zap", c.getTextValue()); + } + + @Test + public void testGetName() + throws Exception { + XmlObject x = XmlObject.Factory.parse("eric"); + XmlCursor c = x.newCursor(); + assertNull(c.getName()); + assertFalse(c.toNextToken().isNone()); + assertEquals("a", c.getName().getLocalPart()); + assertEquals(0, c.getName().getNamespaceURI().length()); + assertFalse(c.toNextToken().isNone()); + assertEquals("x", c.getName().getLocalPart()); + assertEquals(0, c.getName().getNamespaceURI().length()); + assertFalse(c.toNextToken().isNone()); + assertNull(c.getName()); + assertFalse(c.toNextToken().isNone()); + assertNull(c.getName()); + assertFalse(c.toNextToken().isNone()); + assertEquals("moo", c.getName().getLocalPart()); + assertEquals(0, c.getName().getNamespaceURI().length()); + assertFalse(c.toNextToken().isNone()); + assertNull(c.getName()); + assertFalse(c.toNextToken().isNone()); + assertNull(c.getName()); + assertTrue(c.toNextToken().isNone()); + } + + @Test + public void testGetChars() + throws Exception { + XmlObject x = XmlObject.Factory.parse("abcdefghijkl"); + XmlCursor c = x.newCursor(); + c.toNextToken(); + c.toNextToken(); + c.toNextChar(2); + + char[] buf = new char[3]; + int n = c.getChars(buf, 0, 400); + + assertEquals(3, n); + assertEquals('c', buf[0]); + assertEquals('d', buf[1]); + assertEquals('e', buf[2]); + } + + @Test + public void testNamespaceSubstitution() + throws Exception { + HashMap subs = new HashMap<>(); + subs.put("foo", "moo"); + subs.put("a", "b"); + + XmlOptions options = new XmlOptions(); + options.setLoadSubstituteNamespaces(subs); + + XmlObject x = XmlObject.Factory.parse("", options); + + XmlCursor c = x.newCursor(); + + c.toNextToken(); + assertEquals("moo", c.getName().getNamespaceURI()); + + c.toNextToken(); + assertEquals("moo", c.getName().getNamespaceURI()); + + c.toNextToken(); + assertEquals("b", c.getName().getNamespaceURI()); + + c.toNextToken(); + assertEquals("b", c.getName().getNamespaceURI()); + } + + @Test + public void testNamespaceInsertion() { + XmlObject x = XmlObject.Factory.newInstance(); + + XmlCursor c = x.newCursor(); + + c.toNextToken(); + c.insertElement("foo", "http://p.com"); + c.toPrevToken(); + c.insertNamespace("p", "http://p.com"); + + assertEquals("", x.xmlText()); + } + + private void dotestParser(String xml, String xmlResult) + throws Exception { + XmlObject x = XmlObject.Factory.parse(xml); + String result = x.xmlText(); + assertEquals(xmlResult, result); + } + + private void dotestParserErrors(String xml) { + try { + XmlObject.Factory.parse(xml); + } catch (Throwable t) { + return; + } + + fail(); + } + + @Test + public void testNil() + throws Exception { + XmlObject x = noNamespace.CanBeNilDocument.Factory.parse(""); + XmlCursor c = x.newCursor(); + c.toFirstChild(); + XmlObject fc = c.getObject(); + assertFalse(fc.isNil()); + fc.setNil(); + assertTrue(fc.isNil()); + assertEquals("", x.xmlText()); + c.toNextToken(); + assertTrue(c.isAttr()); + c.removeXml(); + assertEquals("", x.xmlText()); + assertFalse(fc.isNil()); + } + + @Test + public void testParser() + throws Exception { + dotestParserErrors("66"); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(" "); + + dotestParserErrors("har"); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + dotestParserErrors(""); + + dotestParser("", ""); + } + + @Test + public void testSaxParser() + throws Exception { + String xml = "xz"; + + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser sp = spf.newSAXParser(); + XMLReader xr = sp.getXMLReader(); + InputSource is = new InputSource(new StringReader(xml)); + XmlSaxHandler sh = XmlObject.Factory.newXmlSaxHandler(); + + xr.setFeature( + "http://xml.org/sax/features/namespace-prefixes", + true); + + xr.setFeature( + "http://xml.org/sax/features/namespaces", true); + + xr.setFeature( + "http://xml.org/sax/features/validation", false); + + xr.setContentHandler(sh.getContentHandler()); + + xr.setProperty( + "http://xml.org/sax/properties/lexical-handler", + sh.getLexicalHandler()); + + xr.parse(is); + + XmlObject x1 = sh.getObject(); + + XmlObject x2 = XmlObject.Factory.parse(xml); + + assertEquals(x1.xmlText(), x2.xmlText()); + } + + @Test + public void testAdditionalNamespaces() + throws Exception { + String xml = ""; + + Map map = new LinkedHashMap<>(); + map.put("b", "bNS"); + map.put("c", "cNS"); + map.put("a", "not-aNS"); + + XmlOptions options = new XmlOptions(); + options.setLoadAdditionalNamespaces(map); + + XmlObject x = XmlObject.Factory.parse(xml, options); + + // 'a' prefix namespace is not remapped + + xml = ""; + + map = new LinkedHashMap<>(); + map.put("b", "bNS"); + map.put("c", "cNS"); + map.put("", "not-aNS"); + + options = new XmlOptions(); + options.setLoadAdditionalNamespaces(map); + + x = XmlObject.Factory.parse(xml, options); + + // default namespace is not remapped + String expect = ""; + assertEquals(expect, x.xmlText()); + + } + + +} diff --git a/src/test/java/xmlcursor/checkin/ToCursorTest.java b/src/test/java/xmlcursor/checkin/ToCursorTest.java new file mode 100755 index 0000000..de3e12d --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToCursorTest.java @@ -0,0 +1,78 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class ToCursorTest extends BasicCursorTestCase { + @Test + public void testToCursorMoves() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + XmlCursor xc0 = m_xc.newCursor(); + xc0.toEndDoc(); + try { + assertTrue(m_xc.toCursor(xc0)); + assertTrue(xc0.isAtSamePositionAs(m_xc)); + } finally { + xc0.dispose(); + } + } + + /** + * FIXED: toCursor(null) does not return a boolean but throws an exception. + */ + @Test(expected = IllegalArgumentException.class) + public void testToCursorNull() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + m_xc.toFirstChild(); + m_xc.toCursor(null); + } + + @Test + public void testToCursorDifferentDocs() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + XmlCursor xc0 = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + String s = m_xc.xmlText(); + toNextTokenOfType(xc0, TokenType.TEXT); + try { + assertFalse(m_xc.toCursor(xc0)); + assertEquals(s, m_xc.xmlText()); + } finally { + xc0.dispose(); + } + } + + @Test + public void testToCursorThis() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + m_xc.toFirstChild(); + String s = m_xc.xmlText(); + assertTrue(m_xc.toCursor(m_xc)); + assertEquals(s, m_xc.xmlText()); + } + +} + diff --git a/src/test/java/xmlcursor/checkin/ToFirstAttributeTest.java b/src/test/java/xmlcursor/checkin/ToFirstAttributeTest.java new file mode 100755 index 0000000..91f5c76 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToFirstAttributeTest.java @@ -0,0 +1,78 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class ToFirstAttributeTest extends BasicCursorTestCase { + @Test + public void testToFirstAttrSTARTDOC() throws Exception { + m_xc = XmlObject.Factory.parse("text").newCursor(); + m_xc.toFirstChild(); + m_xc.insertAttributeWithValue("attr0", "val0"); + m_xc.toStartDoc(); + assertTrue(m_xc.toFirstAttribute()); + assertEquals("val0", m_xc.getTextValue()); + } + + @Test + public void testToFirstAttrSTARTmoreThan1ATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertTrue(m_xc.toFirstAttribute()); + assertEquals("val0", m_xc.getTextValue()); + } + + @Test + public void testToFirstAttrFrom2ndATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertFalse(m_xc.toFirstAttribute()); + } + + @Test + public void testToFirstAttrZeroATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertFalse(m_xc.toFirstAttribute()); + } + + @Test + public void testToFirstAttrFromTEXT() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertEquals(TokenType.TEXT, m_xc.currentTokenType()); + assertEquals("text", m_xc.getChars()); + assertFalse(m_xc.toFirstAttribute()); + } + + @Test + public void testToFirstAttrWithXMLNS() throws Exception { + m_xc = XmlObject.Factory.parse("text").newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertFalse(m_xc.toFirstAttribute()); + } +} + diff --git a/src/test/java/xmlcursor/checkin/ToFirstChildElementTest.java b/src/test/java/xmlcursor/checkin/ToFirstChildElementTest.java new file mode 100755 index 0000000..03199e2 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToFirstChildElementTest.java @@ -0,0 +1,76 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.*; + + +public class ToFirstChildElementTest extends BasicCursorTestCase { + @Test + public void testToFirstChildElemSTARTnested() throws Exception { + m_xc = XmlObject.Factory.parse("earlytext").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertTrue(m_xc.toFirstChild()); + assertEquals("text", m_xc.getTextValue()); + } + + @Test + public void testToFirstChildElemFromLastChild() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertTrue(m_xc.toFirstChild()); + assertFalse(m_xc.toFirstChild()); + assertEquals("text", m_xc.getTextValue()); + } + + @Test + public void testToFirstChildElemFromTEXTnested() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertEquals("early", m_xc.getChars()); + assertTrue(m_xc.toFirstChild()); + assertEquals("zap", m_xc.getTextValue()); + } + + @Test + public void testToFirstChildElemFromATTRnested() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertEquals("val0", m_xc.getTextValue()); + assertTrue(m_xc.toFirstChild()); + } + + @Test + public void testToFirstChildElemFromSTARTnoChild() throws Exception { + m_xc = XmlObject.Factory.parse("early").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertFalse(m_xc.toFirstChild()); + } + + @Test + public void testToFirstChildElemFromSTARTDOC() throws Exception { + m_xc = XmlObject.Factory.parse("early").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertEquals(TokenType.START, m_xc.currentTokenType()); + } +} + diff --git a/test/src/xmlcursor/checkin/ToFirstContentTokenTest.java b/src/test/java/xmlcursor/checkin/ToFirstContentTokenTest.java similarity index 87% rename from test/src/xmlcursor/checkin/ToFirstContentTokenTest.java rename to src/test/java/xmlcursor/checkin/ToFirstContentTokenTest.java index 5dc18d1..b3415d9 100755 --- a/test/src/xmlcursor/checkin/ToFirstContentTokenTest.java +++ b/src/test/java/xmlcursor/checkin/ToFirstContentTokenTest.java @@ -16,39 +16,16 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class ToFirstContentTokenTest extends BasicCursorTestCase { - public ToFirstContentTokenTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToFirstContentTokenTest.class); - } + @Test public void testToFirstContentTokenFromSTARTDOC() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); m_xc.toFirstChild(); @@ -59,6 +36,7 @@ public void testToFirstContentTokenFromSTARTDOC() throws Exception { assertEquals("earlytext", m_xc.getTextValue()); } + @Test public void testToFirstContentTokenFromATTR() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); @@ -67,6 +45,7 @@ public void testToFirstContentTokenFromATTR() throws Exception { assertEquals("val0", m_xc.getTextValue()); } + @Test public void testToFirstContentTokenFromNAMESPACE() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.NAMESPACE); @@ -76,6 +55,7 @@ public void testToFirstContentTokenFromNAMESPACE() throws Exception { assertEquals(m_xc.getTextValue(),"nsuri"); } + @Test public void testToFirstContentTokenFromSTARTwithContent() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.START); @@ -83,6 +63,7 @@ public void testToFirstContentTokenFromSTARTwithContent() throws Exception { assertEquals("early", m_xc.getChars()); } + @Test public void testToFirstContentTokenFromSTARTnoContent() throws Exception { m_xc = XmlObject.Factory.parse("").newCursor(); toNextTokenOfType(m_xc, TokenType.START); @@ -91,12 +72,14 @@ public void testToFirstContentTokenFromSTARTnoContent() throws Exception { assertEquals(TokenType.ENDDOC, m_xc.currentTokenType()); } + @Test public void testToFirstContentTokenEmptyDocument() throws Exception { m_xc = XmlObject.Factory.newInstance().newCursor(); assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); assertEquals(TokenType.ENDDOC, m_xc.toFirstContentToken()); } + @Test public void testToFirstContentTokenFromTEXT() throws Exception { m_xc = XmlObject.Factory.parse("text").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -104,6 +87,7 @@ public void testToFirstContentTokenFromTEXT() throws Exception { assertEquals("text", m_xc.getChars()); } + @Test public void testToFirstContentTokenFromTEXTmiddle() throws Exception { m_xc = XmlObject.Factory.parse("text").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -111,6 +95,5 @@ public void testToFirstContentTokenFromTEXTmiddle() throws Exception { assertEquals(TokenType.NONE, m_xc.toFirstContentToken()); assertEquals("xt", m_xc.getChars()); } - } diff --git a/src/test/java/xmlcursor/checkin/ToLastAttributeTest.java b/src/test/java/xmlcursor/checkin/ToLastAttributeTest.java new file mode 100755 index 0000000..016e155 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToLastAttributeTest.java @@ -0,0 +1,77 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class ToLastAttributeTest extends BasicCursorTestCase { + + @Test + public void testToLastAttrSTARTDOC() throws Exception { + m_xc = XmlObject.Factory.parse("text").newCursor(); + m_xc.toLastChild(); + m_xc.insertAttributeWithValue("attr0", "val0"); + m_xc.insertAttributeWithValue("attr1", "val1"); + m_xc.toStartDoc(); + assertTrue(m_xc.toLastAttribute()); + assertEquals("val1", m_xc.getTextValue()); + } + + @Test + public void testToLastAttrSTARTmoreThan1ATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertTrue(m_xc.toLastAttribute()); + assertEquals("val1", m_xc.getTextValue()); + } + + @Test + public void testToLastAttrFrom1stATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertFalse(m_xc.toLastAttribute()); + } + + @Test + public void testToLastAttrZeroATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertFalse(m_xc.toLastAttribute()); + } + + @Test + public void testToLastAttrFromTEXT() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertFalse(m_xc.toLastAttribute()); + } + + @Test + public void testToLastAttrWithXMLNS() throws Exception { + m_xc = XmlObject.Factory.parse("text").newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertFalse(m_xc.toLastAttribute()); + } +} + diff --git a/src/test/java/xmlcursor/checkin/ToLastChildElementTest.java b/src/test/java/xmlcursor/checkin/ToLastChildElementTest.java new file mode 100755 index 0000000..73d5d83 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToLastChildElementTest.java @@ -0,0 +1,86 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.*; + + +public class ToLastChildElementTest extends BasicCursorTestCase { + @Test + public void testToLastChildElemSTARTnestedSiblings() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertTrue(m_xc.toLastChild()); + assertEquals("zap", m_xc.getTextValue()); + } + + @Test + public void testToLastChildElemSTARTnestedSiblingsTwice() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertTrue(m_xc.toLastChild()); + assertTrue(m_xc.toLastChild()); + assertEquals("yap", m_xc.getTextValue()); + } + + @Test + public void testToLastChildElemFromTEXTnested() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzapyap").newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertEquals("early", m_xc.getChars()); + XmlCursor xc0 = m_xc.newCursor(); + xc0.toNextSibling(); + try { + assertEquals("textzapyap", xc0.getTextValue()); + xc0.toLastChild(); + assertEquals("yap", xc0.getTextValue()); + assertTrue(m_xc.toLastChild()); + assertEquals("yap", m_xc.getTextValue()); + } finally { + xc0.dispose(); + } + } + + @Test + public void testToLastChildElemFromATTRnested() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzapyap").newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertEquals("val0", m_xc.getTextValue()); + assertTrue(m_xc.toLastChild()); + } + + @Test + public void testToLastChildElemFromSTARTnoChild() throws Exception { + m_xc = XmlObject.Factory.parse("early").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertFalse(m_xc.toLastChild()); + } + + @Test + public void testToLastChildElemFromSTARTDOC() throws Exception { + m_xc = XmlObject.Factory.parse("early").newCursor(); + assertTrue(m_xc.toLastChild()); + assertEquals(TokenType.START, m_xc.currentTokenType()); + } +} + diff --git a/src/test/java/xmlcursor/checkin/ToNextAttributeTest.java b/src/test/java/xmlcursor/checkin/ToNextAttributeTest.java new file mode 100755 index 0000000..702631d --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToNextAttributeTest.java @@ -0,0 +1,79 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class ToNextAttributeTest extends BasicCursorTestCase { + @Test + public void testToNextAttrFromSTART() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertFalse(m_xc.toNextAttribute()); + } + + @Test + public void testToNextAttrFromSingleATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertFalse(m_xc.toNextAttribute()); + assertEquals("val0", m_xc.getTextValue()); + } + + @Test + public void testToNextAttrWithSiblings() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertTrue(m_xc.toNextAttribute()); + assertEquals("val1", m_xc.getTextValue()); + } + + @Test + public void testToNextAttrFromLastSibling() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertFalse(m_xc.toNextAttribute()); + assertEquals("val1", m_xc.getTextValue()); + } + + @Test + public void testToNextAttrWithXMLNS() throws Exception { + m_xc = XmlObject.Factory.parse("text").newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertEquals("val0", m_xc.getTextValue()); + assertTrue(m_xc.toNextAttribute()); + assertEquals("val1", m_xc.getTextValue()); + assertFalse(m_xc.toNextAttribute()); + } + + @Test + public void testToNextAttrFromTEXT() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertFalse(m_xc.toNextAttribute()); + } + +} + diff --git a/test/src/xmlcursor/checkin/ToNextBookmarkTest.java b/src/test/java/xmlcursor/checkin/ToNextBookmarkTest.java similarity index 77% rename from test/src/xmlcursor/checkin/ToNextBookmarkTest.java rename to src/test/java/xmlcursor/checkin/ToNextBookmarkTest.java index c7a88cf..d833c99 100755 --- a/test/src/xmlcursor/checkin/ToNextBookmarkTest.java +++ b/src/test/java/xmlcursor/checkin/ToNextBookmarkTest.java @@ -16,43 +16,22 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import java.net.URL; +import static org.junit.Assert.*; -/** - * - * - */ public class ToNextBookmarkTest extends BasicCursorTestCase { private SimpleBookmark _theBookmark = new SimpleBookmark("value"); private SimpleBookmark _theBookmark1 = new SimpleBookmark("value1"); private DifferentBookmark _difBookmark = new DifferentBookmark("diff"); - public ToNextBookmarkTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToNextBookmarkTest.class); - } - + @Test public void testToNextBookmarkSameKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -65,16 +44,17 @@ public void testToNextBookmarkSameKey() throws Exception { m_xc.toStartDoc(); try { assertEquals(_theBookmark, m_xc.toNextBookmark(SimpleBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc0)); + assertTrue(m_xc.isAtSamePositionAs(xc0)); assertEquals(_theBookmark1, m_xc.toNextBookmark(SimpleBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc1)); - assertEquals(null, m_xc.toNextBookmark(SimpleBookmark.class)); + assertTrue(m_xc.isAtSamePositionAs(xc1)); + assertNull(m_xc.toNextBookmark(SimpleBookmark.class)); } finally { xc0.dispose(); xc1.dispose(); } } + @Test public void testToNextBookmarkInvalidKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -83,9 +63,10 @@ public void testToNextBookmarkInvalidKey() throws Exception { toNextTokenOfType(m_xc, TokenType.END); m_xc.setBookmark(_theBookmark1); m_xc.toStartDoc(); - assertEquals(null, m_xc.toNextBookmark(Object.class)); + assertNull(m_xc.toNextBookmark(Object.class)); } + @Test public void testToNextBookmarkDifferentKeys() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -98,16 +79,17 @@ public void testToNextBookmarkDifferentKeys() throws Exception { m_xc.toStartDoc(); try { assertEquals(_theBookmark, m_xc.toNextBookmark(SimpleBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc0)); - assertEquals(null, m_xc.toNextBookmark(SimpleBookmark.class)); + assertTrue(m_xc.isAtSamePositionAs(xc0)); + assertNull(m_xc.toNextBookmark(SimpleBookmark.class)); assertEquals(_difBookmark, m_xc.toNextBookmark(DifferentBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc1)); + assertTrue(m_xc.isAtSamePositionAs(xc1)); } finally { xc0.dispose(); xc1.dispose(); } } + @Test public void testToNextBookmarkPostRemoveChars() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -121,7 +103,7 @@ public void testToNextBookmarkPostRemoveChars() throws Exception { XmlCursor xc1 = m_xc.newCursor(); xc1.toStartDoc(); try { - assertEquals(null, xc1.toNextBookmark(SimpleBookmark.class)); + assertNull(xc1.toNextBookmark(SimpleBookmark.class)); assertEquals(TokenType.STARTDOC, xc1.currentTokenType()); } finally { xc1.dispose(); @@ -131,7 +113,7 @@ public void testToNextBookmarkPostRemoveChars() throws Exception { public class SimpleBookmark extends XmlCursor.XmlBookmark { public String text; - public SimpleBookmark(String text) { + SimpleBookmark(String text) { this.text = text; } } @@ -139,7 +121,7 @@ public SimpleBookmark(String text) { public class DifferentBookmark extends XmlCursor.XmlBookmark { public String text; - public DifferentBookmark(String text) { + DifferentBookmark(String text) { this.text = text; } } diff --git a/test/src/xmlcursor/checkin/ToNextCharTest.java b/src/test/java/xmlcursor/checkin/ToNextCharTest.java similarity index 83% rename from test/src/xmlcursor/checkin/ToNextCharTest.java rename to src/test/java/xmlcursor/checkin/ToNextCharTest.java index b957f2f..10664ee 100755 --- a/test/src/xmlcursor/checkin/ToNextCharTest.java +++ b/src/test/java/xmlcursor/checkin/ToNextCharTest.java @@ -16,39 +16,15 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class ToNextCharTest extends BasicCursorTestCase { - public ToNextCharTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToNextCharTest.class); - } - + @Test public void testToNextCharNegative() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -58,6 +34,7 @@ public void testToNextCharNegative() throws Exception { assertEquals("text", m_xc.getTextValue()); } + @Test public void testToNextCharGTLength() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -67,6 +44,7 @@ public void testToNextCharGTLength() throws Exception { assertEquals("text", m_xc.getTextValue()); } + @Test public void testToNextCharLTLength() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -76,6 +54,7 @@ public void testToNextCharLTLength() throws Exception { assertEquals("ly", m_xc.getChars()); } + @Test public void testToNextCharZero() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -85,6 +64,7 @@ public void testToNextCharZero() throws Exception { assertEquals("early", m_xc.getChars()); } + @Test public void testToNextCharFromATTR() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); diff --git a/src/test/java/xmlcursor/checkin/ToNextElementTest.java b/src/test/java/xmlcursor/checkin/ToNextElementTest.java new file mode 100755 index 0000000..d739c96 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToNextElementTest.java @@ -0,0 +1,62 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.*; + +public class ToNextElementTest extends BasicCursorTestCase { + @Test + public void testToNextElementFromSTARTDOC() throws Exception { + m_xc = XmlObject.Factory.parse("earlytext").newCursor(); + assertFalse(m_xc.toNextSibling()); + assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); + } + + @Test + public void testToNextElementSiblings() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); + assertTrue(m_xc.toFirstChild()); + assertTrue(m_xc.toFirstChild()); + assertEquals("text", m_xc.getTextValue()); + assertTrue(m_xc.toNextSibling()); + assertEquals("zapwapyap", m_xc.getTextValue()); + assertFalse(m_xc.toNextSibling()); + } + + @Test + public void testToNextElementFromATTR() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertEquals("val0", m_xc.getTextValue()); + assertTrue(m_xc.toNextSibling()); + } + + @Test + public void testToNextElementFromTEXT() throws Exception { + m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertEquals("early", m_xc.getChars()); + assertTrue(m_xc.toNextSibling()); + assertEquals("text", m_xc.getTextValue()); + } +} + diff --git a/src/test/java/xmlcursor/checkin/ToNextSelectionTest.java b/src/test/java/xmlcursor/checkin/ToNextSelectionTest.java new file mode 100755 index 0000000..0c87f7d --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToNextSelectionTest.java @@ -0,0 +1,132 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.*; + +public class ToNextSelectionTest extends BasicCursorTestCase { + @Test + public void testToNextSelectionMultipleReturns() throws Exception { + String sXml = "0123456"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + m_xc.selectPath("$this//b"); + m_xc.toNextSelection(); + for (int i = 0; i < 6; i++) { + assertEquals("" + i, m_xc.getTextValue()); + assertTrue(m_xc.toNextSelection()); + } + assertEquals("6", m_xc.getTextValue()); + assertFalse(m_xc.toNextSelection()); + } + + @Test + public void testToNextSelectionAfterClear() throws Exception { + String sXml = "0123456"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + m_xc.selectPath("$this//b"); + m_xc.toNextSelection(); + for (int i = 0; i < 3; i++) { + assertEquals("" + i, m_xc.getTextValue()); + assertTrue(m_xc.toNextSelection()); + } + m_xc.clearSelections(); + assertEquals("3", m_xc.getTextValue()); + assertFalse(m_xc.toNextSelection()); + } + + @Test + public void testToNextSelectionBeforeSelect() throws Exception { + String sXml = "0123456"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + assertFalse(m_xc.toNextSelection()); + m_xc.selectPath("$this//b"); + m_xc.toNextSelection(); + for (int i = 0; i < 6; i++) { + assertEquals("" + i, m_xc.getTextValue()); + assertTrue(m_xc.toNextSelection()); + } + assertEquals("6", m_xc.getTextValue()); + assertFalse(m_xc.toNextSelection()); + } + + @Test + public void testToNextSelectionOtherCursor() throws Exception { + String sXml = "0123456"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + XmlCursor xc0 = m_xc.newCursor(); + try { + m_xc.selectPath("$this//b"); + assertFalse(xc0.toNextSelection()); + } finally { + xc0.dispose(); + } + } + + @Test + public void testToNextSelectionTwoCursorsDifferentSelections() throws Exception { + String sXml = "X0Y1Z2"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + XmlCursor xc0 = m_xc.newCursor(); + try { + xc0.selectPath("$this//a"); + xc0.toNextSelection(); + assertEquals(3, xc0.getSelectionCount()); + m_xc.selectPath("$this//b"); + m_xc.toNextSelection(); + assertEquals(3, m_xc.getSelectionCount()); + assertTrue(xc0.toNextSelection()); + assertEquals("Y", xc0.getTextValue()); + assertTrue(m_xc.toNextSelection()); + assertEquals("1", m_xc.getTextValue()); + } finally { + xc0.dispose(); + } + } + + @Test + public void testToNextSelectionTwoCursorsSameSelections() throws Exception { + String sXml = "X0Y1Z2"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + XmlCursor xc0 = m_xc.newCursor(); + try { + xc0.selectPath("$this//b"); + xc0.toNextSelection(); + assertEquals(3, xc0.getSelectionCount()); + m_xc.selectPath("$this//b"); + m_xc.toNextSelection(); + assertEquals(3, m_xc.getSelectionCount()); + assertTrue(xc0.toNextSelection()); + assertEquals("1", xc0.getTextValue()); + assertTrue(m_xc.toNextSelection()); + assertEquals("1", m_xc.getTextValue()); + assertTrue(xc0.toNextSelection()); + assertEquals("2", xc0.getTextValue()); + assertTrue(m_xc.toNextSelection()); + assertEquals("2", m_xc.getTextValue()); + assertFalse(xc0.toNextSelection()); + assertFalse(m_xc.toNextSelection()); + } finally { + xc0.dispose(); + } + } +} + diff --git a/test/src/xmlcursor/checkin/ToNextSiblingTest.java b/src/test/java/xmlcursor/checkin/ToNextSiblingTest.java similarity index 85% rename from test/src/xmlcursor/checkin/ToNextSiblingTest.java rename to src/test/java/xmlcursor/checkin/ToNextSiblingTest.java index cf56dba..982aab3 100644 --- a/test/src/xmlcursor/checkin/ToNextSiblingTest.java +++ b/src/test/java/xmlcursor/checkin/ToNextSiblingTest.java @@ -15,37 +15,25 @@ package xmlcursor.checkin; -import junit.framework.*; - import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; import javax.xml.namespace.QName; -import xmlcursor.common.*; +import static org.junit.Assert.*; /** * checkin tests for XmlCursor toNextSibling methods * */ -public class ToNextSiblingTest extends BasicCursorTestCase -{ - public ToNextSiblingTest(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(ToNextSiblingTest.class); - } - +public class ToNextSiblingTest extends BasicCursorTestCase { private static String xml0 = ""; private static String xml1 = ""; /** test toNextSibling(String name) where there is no namespace */ - public void testName() throws Exception - { + @Test + public void testName() throws Exception { m_xc = XmlObject.Factory.parse(xml0).newCursor(); m_xc.toNextToken(); m_xc.toChild(0); @@ -67,8 +55,8 @@ public void testName() throws Exception } /** test toNextSibling(String name) where there is a namespace */ - public void testIncompleteName() throws Exception - { + @Test + public void testIncompleteName() throws Exception { m_xc = XmlObject.Factory.parse(xml1).newCursor(); m_xc.toNextToken(); m_xc.toChild(0); @@ -82,8 +70,8 @@ public void testIncompleteName() throws Exception } /** test toNextSibling(String namespace, String localname) */ - public void testNamespaceAndLocalName0() throws Exception - { + @Test + public void testNamespaceAndLocalName0() throws Exception { m_xc = XmlObject.Factory.parse(xml0).newCursor(); m_xc.toNextToken(); m_xc.toChild(0); @@ -105,8 +93,8 @@ public void testNamespaceAndLocalName0() throws Exception } /** test toNextSibling(String namespace, String localname) */ - public void testNamespaceAndLocalName1() throws Exception - { + @Test + public void testNamespaceAndLocalName1() throws Exception { m_xc = XmlObject.Factory.parse(xml1).newCursor(); m_xc.toNextToken(); m_xc.toChild(0); @@ -128,8 +116,8 @@ public void testNamespaceAndLocalName1() throws Exception } /** test toNextSibling(QName qName) */ - public void testQName() throws Exception - { + @Test + public void testQName() throws Exception { m_xc = XmlObject.Factory.parse(xml1).newCursor(); m_xc.toNextToken(); m_xc.toChild(0); diff --git a/test/src/xmlcursor/checkin/ToParentElementTest.java b/src/test/java/xmlcursor/checkin/ToParentElementTest.java similarity index 76% rename from test/src/xmlcursor/checkin/ToParentElementTest.java rename to src/test/java/xmlcursor/checkin/ToParentElementTest.java index a156854..959eadb 100755 --- a/test/src/xmlcursor/checkin/ToParentElementTest.java +++ b/src/test/java/xmlcursor/checkin/ToParentElementTest.java @@ -16,81 +16,64 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; -import java.net.URL; +import static org.junit.Assert.*; -/** - * - * - */ public class ToParentElementTest extends BasicCursorTestCase { - public ToParentElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToParentElementTest.class); - } + @Test public void testToParentElementFromSTARTDOC() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); - assertEquals(false, m_xc.toParent()); + assertFalse(m_xc.toParent()); assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); } + @Test public void testToParentElementFromFirstChildOfSTARTDOC() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); m_xc.toFirstChild(); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); } + @Test public void testToParentElementFromPrevTokenOfENDDOC() throws Exception { m_xc = XmlObject.Factory.parse("text").newCursor(); m_xc.toEndDoc(); m_xc.toPrevToken(); assertEquals(TokenType.END, m_xc.currentTokenType()); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals(TokenType.START, m_xc.currentTokenType()); } + @Test public void testToParentElementNested() throws Exception { m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); m_xc.selectPath("$this//ear"); m_xc.toNextSelection(); assertEquals("yap", m_xc.getTextValue()); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals("zapwapyap", m_xc.getTextValue()); } + @Test public void testToParentElementFromATTR() throws Exception { m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); assertEquals("val0", m_xc.getTextValue()); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals("yap", m_xc.getTextValue()); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals("zapwapyap", m_xc.getTextValue()); } + @Test public void testToParentElementFromTEXT() throws Exception { m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); m_xc.selectPath("$this//ear"); @@ -98,9 +81,9 @@ public void testToParentElementFromTEXT() throws Exception { m_xc.toNextToken(); assertEquals(TokenType.TEXT, m_xc.currentTokenType()); assertEquals("yap", m_xc.getChars()); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals("yap", m_xc.getTextValue()); - assertEquals(true, m_xc.toParent()); + assertTrue(m_xc.toParent()); assertEquals("zapwapyap", m_xc.getTextValue()); } } diff --git a/src/test/java/xmlcursor/checkin/ToPrevAttributeTest.java b/src/test/java/xmlcursor/checkin/ToPrevAttributeTest.java new file mode 100755 index 0000000..5b22220 --- /dev/null +++ b/src/test/java/xmlcursor/checkin/ToPrevAttributeTest.java @@ -0,0 +1,78 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.checkin; + +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + +public class ToPrevAttributeTest extends BasicCursorTestCase { + @Test + public void testtoPrevAttrFromSTART() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.START); + assertFalse(m_xc.toPrevAttribute()); + } + + @Test + public void testtoPrevAttrFromSingleATTR() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertFalse(m_xc.toPrevAttribute()); + assertEquals("val0", m_xc.getTextValue()); + } + + @Test + public void testtoPrevAttrWithSiblings() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertEquals("val1", m_xc.getTextValue()); + assertTrue(m_xc.toPrevAttribute()); + assertEquals("val0", m_xc.getTextValue()); + } + + @Test + public void testtoPrevAttrFromFirstSibling() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertFalse(m_xc.toPrevAttribute()); + assertEquals("val0", m_xc.getTextValue()); + } + + @Test + public void testtoPrevAttrWithXMLNS() throws Exception { + m_xc = XmlObject.Factory.parse("text").newCursor(); + toNextTokenOfType(m_xc, TokenType.ATTR); + toNextTokenOfType(m_xc, TokenType.ATTR); + assertEquals("val1", m_xc.getTextValue()); + assertTrue(m_xc.toPrevAttribute()); + assertEquals("val0", m_xc.getTextValue()); + assertFalse(m_xc.toPrevAttribute()); + } + + @Test + public void testtoPrevAttrFromTEXT() throws Exception { + m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertFalse(m_xc.toPrevAttribute()); + } +} diff --git a/test/src/xmlcursor/checkin/ToPrevBookmarkTest.java b/src/test/java/xmlcursor/checkin/ToPrevBookmarkTest.java similarity index 81% rename from test/src/xmlcursor/checkin/ToPrevBookmarkTest.java rename to src/test/java/xmlcursor/checkin/ToPrevBookmarkTest.java index 62399d8..728ce33 100755 --- a/test/src/xmlcursor/checkin/ToPrevBookmarkTest.java +++ b/src/test/java/xmlcursor/checkin/ToPrevBookmarkTest.java @@ -16,32 +16,22 @@ package xmlcursor.checkin; -import junit.framework.*; - - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; -/** - * - * - */ public class ToPrevBookmarkTest extends BasicCursorTestCase { private SimpleBookmark _theBookmark = new SimpleBookmark("value"); private SimpleBookmark _theBookmark1 = new SimpleBookmark("value1"); private DifferentBookmark _difBookmark = new DifferentBookmark("diff"); - public ToPrevBookmarkTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToPrevBookmarkTest.class); - } - + @Test public void testToPrevBookmarkSameKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -54,16 +44,17 @@ public void testToPrevBookmarkSameKey() throws Exception { m_xc.toEndDoc(); try { assertEquals(_theBookmark1, m_xc.toPrevBookmark(SimpleBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc1)); + assertTrue(m_xc.isAtSamePositionAs(xc1)); assertEquals(_theBookmark, m_xc.toPrevBookmark(SimpleBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc0)); - assertEquals(null, m_xc.toPrevBookmark(SimpleBookmark.class)); + assertTrue(m_xc.isAtSamePositionAs(xc0)); + assertNull(m_xc.toPrevBookmark(SimpleBookmark.class)); } finally { xc0.dispose(); xc1.dispose(); } } + @Test public void testToPrevBookmarkInvalidKey() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -72,9 +63,10 @@ public void testToPrevBookmarkInvalidKey() throws Exception { toNextTokenOfType(m_xc, TokenType.END); m_xc.setBookmark(_theBookmark1); m_xc.toEndDoc(); - assertEquals(null, m_xc.toPrevBookmark(Object.class)); + assertNull(m_xc.toPrevBookmark(Object.class)); } + @Test public void testToPrevBookmarkDifferentKeys() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -87,16 +79,17 @@ public void testToPrevBookmarkDifferentKeys() throws Exception { m_xc.toEndDoc(); try { assertEquals(_difBookmark, m_xc.toPrevBookmark(DifferentBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc1)); - assertEquals(null, m_xc.toPrevBookmark(DifferentBookmark.class)); + assertTrue(m_xc.isAtSamePositionAs(xc1)); + assertNull(m_xc.toPrevBookmark(DifferentBookmark.class)); assertEquals(_theBookmark, m_xc.toPrevBookmark(SimpleBookmark.class)); - assertEquals(true, m_xc.isAtSamePositionAs(xc0)); + assertTrue(m_xc.isAtSamePositionAs(xc0)); } finally { xc0.dispose(); xc1.dispose(); } } + @Test public void testToPrevBookmarkPostSetTextValue() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -110,7 +103,7 @@ public void testToPrevBookmarkPostSetTextValue() throws Exception { m_xc.setTextValue("changed"); // changes text, should destroy bm m_xc.toEndDoc(); try { - assertEquals(null, xc1.toPrevBookmark(SimpleBookmark.class)); + assertNull(xc1.toPrevBookmark(SimpleBookmark.class)); assertEquals(TokenType.ENDDOC, xc1.currentTokenType()); } finally { xc1.dispose(); @@ -120,7 +113,7 @@ public void testToPrevBookmarkPostSetTextValue() throws Exception { public class SimpleBookmark extends XmlCursor.XmlBookmark { public String text; - public SimpleBookmark(String text) { + SimpleBookmark(String text) { this.text = text; } } @@ -128,7 +121,7 @@ public SimpleBookmark(String text) { public class DifferentBookmark extends XmlCursor.XmlBookmark { public String text; - public DifferentBookmark(String text) { + DifferentBookmark(String text) { this.text = text; } } diff --git a/test/src/xmlcursor/checkin/ToPrevCharTest.java b/src/test/java/xmlcursor/checkin/ToPrevCharTest.java similarity index 84% rename from test/src/xmlcursor/checkin/ToPrevCharTest.java rename to src/test/java/xmlcursor/checkin/ToPrevCharTest.java index 1138846..77ce52d 100755 --- a/test/src/xmlcursor/checkin/ToPrevCharTest.java +++ b/src/test/java/xmlcursor/checkin/ToPrevCharTest.java @@ -16,39 +16,16 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; -import java.net.URL; +import static org.junit.Assert.assertEquals; -/** - * - * - */ public class ToPrevCharTest extends BasicCursorTestCase { - public ToPrevCharTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToPrevCharTest.class); - } - + @Test public void testToPrevCharNegative() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -59,6 +36,7 @@ public void testToPrevCharNegative() throws Exception { assertEquals("early", m_xc.getChars()); } + @Test public void testToPrevCharGTLength() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -69,6 +47,7 @@ public void testToPrevCharGTLength() throws Exception { assertEquals("early", m_xc.getChars()); } + @Test public void testToPrevCharLTLength() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -79,6 +58,7 @@ public void testToPrevCharLTLength() throws Exception { assertEquals("rly", m_xc.getChars()); } + @Test public void testToPrevCharZero() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); @@ -89,6 +69,7 @@ public void testToPrevCharZero() throws Exception { assertEquals("text", m_xc.getTextValue()); } + @Test public void testToPrevCharFromATTR() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); diff --git a/test/src/xmlcursor/checkin/ToPrevElementTest.java b/src/test/java/xmlcursor/checkin/ToPrevElementTest.java similarity index 75% rename from test/src/xmlcursor/checkin/ToPrevElementTest.java rename to src/test/java/xmlcursor/checkin/ToPrevElementTest.java index f66efef..1b68a34 100755 --- a/test/src/xmlcursor/checkin/ToPrevElementTest.java +++ b/src/test/java/xmlcursor/checkin/ToPrevElementTest.java @@ -16,45 +16,24 @@ package xmlcursor.checkin; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; -import java.net.URL; +import static org.junit.Assert.*; -/** - * - * - */ public class ToPrevElementTest extends BasicCursorTestCase { - public ToPrevElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToPrevElementTest.class); - } - + @Test public void testToPrevElementFromSTARTDOC() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); - assertEquals(false, m_xc.toPrevSibling()); + assertFalse(m_xc.toPrevSibling()); assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); } + @Test public void testToPrevElementFromENDDOC() throws Exception { m_xc = XmlObject.Factory.parse("earlytext").newCursor(); XmlCursor xc0 = m_xc.newCursor(); @@ -62,36 +41,39 @@ public void testToPrevElementFromENDDOC() throws Exception { m_xc.toEndDoc(); m_xc.toPrevSibling(); try { - assertEquals(true, m_xc.isAtSamePositionAs(xc0)); + assertTrue(m_xc.isAtSamePositionAs(xc0)); } finally { xc0.dispose(); } } + @Test public void testToPrevElementSiblings() throws Exception { m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); m_xc.selectPath("$this//ear"); m_xc.toNextSelection(); assertEquals("yap", m_xc.getTextValue()); - assertEquals(true, m_xc.toPrevSibling()); + assertTrue(m_xc.toPrevSibling()); assertEquals("wap", m_xc.getTextValue()); - assertEquals(false, m_xc.toPrevSibling()); + assertFalse(m_xc.toPrevSibling()); } + @Test public void testToPrevElementFromATTR() throws Exception { m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); toNextTokenOfType(m_xc, TokenType.ATTR); assertEquals("val0", m_xc.getTextValue()); - assertEquals(false, m_xc.toPrevSibling()); + assertFalse(m_xc.toPrevSibling()); } + @Test public void testToPrevElementFromTEXT() throws Exception { m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); m_xc.selectPath("$this//ear"); m_xc.toNextSelection(); toNextTokenOfType(m_xc, TokenType.TEXT); assertEquals("yap", m_xc.getChars()); - assertEquals(true, m_xc.toPrevSibling()); + assertTrue(m_xc.toPrevSibling()); assertEquals("", m_xc.getTextValue()); } } diff --git a/test/src/xmlcursor/checkin/TokensTest.java b/src/test/java/xmlcursor/checkin/TokensTest.java similarity index 91% rename from test/src/xmlcursor/checkin/TokensTest.java rename to src/test/java/xmlcursor/checkin/TokensTest.java index a675569..31df92b 100755 --- a/test/src/xmlcursor/checkin/TokensTest.java +++ b/src/test/java/xmlcursor/checkin/TokensTest.java @@ -16,61 +16,56 @@ package xmlcursor.checkin; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import xmlcursor.common.*; - +import static org.junit.Assert.*; -/** - * - * - */ public class TokensTest extends BasicCursorTestCase { - public TokensTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(TokensTest.class); - } + @Test public void testHasNextToken() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(true, m_xc.hasNextToken()); + assertTrue(m_xc.hasNextToken()); } + @Test public void testHasNextTokenENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); m_xc.toEndDoc(); - assertEquals(false, m_xc.hasNextToken()); + assertFalse(m_xc.hasNextToken()); } + @Test public void testHasPrevToken() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(true, m_xc.hasPrevToken()); + assertTrue(m_xc.hasPrevToken()); } + @Test public void testHasPrevTokenSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); - assertEquals(false, m_xc.hasPrevToken()); + assertFalse(m_xc.hasPrevToken()); } + @Test public void testToEndTokenFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); assertEquals(TokenType.ENDDOC, m_xc.toEndToken()); } + @Test public void testToEndTokenFromSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -78,6 +73,7 @@ public void testToEndTokenFromSTART() throws Exception { assertEquals(TokenType.END, m_xc.toEndToken()); } + @Test public void testToEndTokenFromTEXTmiddle() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -86,6 +82,7 @@ public void testToEndTokenFromTEXTmiddle() throws Exception { assertEquals(TokenType.NONE, m_xc.toEndToken()); } + @Test public void testToFirstContentTokenFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -93,6 +90,7 @@ public void testToFirstContentTokenFromSTARTDOC() throws Exception { assertEquals(TokenType.START, m_xc.currentTokenType()); } + @Test public void testToFirstContentTokenFromATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -101,6 +99,7 @@ public void testToFirstContentTokenFromATTR() throws Exception { assertEquals(TokenType.ATTR, m_xc.currentTokenType()); } + @Test public void testToFirstContentTokenFromSTARTwithContent() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -108,6 +107,7 @@ public void testToFirstContentTokenFromSTARTwithContent() throws Exception { assertEquals(TokenType.TEXT, m_xc.toFirstContentToken()); } + @Test public void testToFirstContentTokenFromSTARTwithoutContent() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR); m_xc = m_xo.newCursor(); @@ -115,6 +115,7 @@ public void testToFirstContentTokenFromSTARTwithoutContent() throws Exception { assertEquals(TokenType.END, m_xc.toFirstContentToken()); } + @Test public void testToNextTokenFromENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -122,6 +123,7 @@ public void testToNextTokenFromENDDOC() throws Exception { assertEquals(TokenType.NONE, m_xc.toNextToken()); } + @Test public void testToNextTokenNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); @@ -129,6 +131,7 @@ public void testToNextTokenNAMESPACE() throws Exception { assertEquals(TokenType.NAMESPACE, m_xc.toNextToken()); } + @Test public void testToPrevTokenSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -136,13 +139,12 @@ public void testToPrevTokenSTARTDOC() throws Exception { assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); } + @Test public void testToPrevTokenENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); m_xc.toEndDoc(); assertEquals(TokenType.END, m_xc.toPrevToken()); } - - } diff --git a/src/test/java/xmlcursor/common/BasicCursorTestCase.java b/src/test/java/xmlcursor/common/BasicCursorTestCase.java new file mode 100755 index 0000000..38c1a5b --- /dev/null +++ b/src/test/java/xmlcursor/common/BasicCursorTestCase.java @@ -0,0 +1,96 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +package xmlcursor.common; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.After; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class BasicCursorTestCase { + protected XmlObject m_xo; + protected XmlCursor m_xc; + + @After + public void tearDown() throws Exception { + m_xo = null; + if (m_xc != null) { + m_xc.dispose(); + m_xc = null; + } + } + + public void toNextTokenOfType(XmlCursor xc, TokenType tt) throws IllegalArgumentException { + if (xc == null) { + throw new IllegalArgumentException("Invalid argument: null XmlCursor"); + } else if (tt == null) { + throw new IllegalArgumentException("Invalid argument: null TokenType"); + } + + while (xc.toNextToken() != tt) { + if (xc.currentTokenType() == TokenType.ENDDOC) + fail("Expected Token not found! " + tt.toString()); + } + assertEquals(tt, xc.currentTokenType()); + } + + public void toPrevTokenOfType(XmlCursor xc, TokenType tt) + throws IllegalArgumentException { + if (xc == null) { + throw new IllegalArgumentException("Invalid argument: null XmlCursor"); + } else if (tt == null) { + throw new IllegalArgumentException("Invalid argument: null TokenType"); + } + + while (xc.toPrevToken() != tt) { + if (xc.currentTokenType() == TokenType.STARTDOC) + fail("Expected Token not found! " + tt.toString()); + } + assertEquals(tt, xc.currentTokenType()); + } + + /** + * Method compareDocTokens + * + * TODO: should really compare values also. + * + * @param a a XmlCursor + * @param b a XmlCursor + * + * + */ + public void compareDocTokens(XmlCursor a, XmlCursor b) { + while (a.hasNextToken() && b.hasNextToken()) { + TokenType ttOrig = a.currentTokenType(); + TokenType ttRoundTrip = b.currentTokenType(); + if (ttOrig != ttRoundTrip) { + fail("Round trip failed. Original Cursor TokenType = " + + ttOrig + " Roundtrip Cursor TokenType = " + + ttRoundTrip); + + } + a.toNextToken(); + b.toNextToken(); + } + } + +} + diff --git a/src/test/java/xmlcursor/common/Common.java b/src/test/java/xmlcursor/common/Common.java new file mode 100755 index 0000000..63a73e7 --- /dev/null +++ b/src/test/java/xmlcursor/common/Common.java @@ -0,0 +1,66 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +package xmlcursor.common; + + + +public class Common { + public final static String XMLFRAG_BEGINTAG = ""; + public final static String XMLFRAG_ENDTAG = ""; + + public final static String XML_FOO = ""; + public final static String XML_FOO_1ATTR = ""; + public final static String XML_FOO_TEXT = "text"; + public final static String XML_FOO_1ATTR_TEXT = "text"; + public final static String XML_FOO_2ATTR = ""; + public final static String XML_FOO_2ATTR_TEXT = "text"; + public final static String XML_FOO_5ATTR_TEXT = "text"; + public final static String XML_FOO_BAR = ""; + public final static String XML_FOO_BAR_TEXT = "text"; + public final static String XML_FOO_BAR_TEXT_EXT = "textextended"; + public final static String XML_FOO_BAR_WS_TEXT = " text ws \\r\\n "; + public final static String XML_FOO_BAR_WS_ONLY = " "; + public final static String XML_FOO_NS = ""; + public final static String XML_FOO_NS_PREFIX = " 32.18"; + public final static String XML_FOO_BAR_NESTED_SIBLINGS = "text0nested0text1nested1"; + public final static String XML_FOO_PROCINST = "text"; + public final static String XML_FOO_COMMENT = "text"; + public final static String XML_FOO_DIGITS = "01234"; + public final static String XML_TEXT_MIDDLE = "textextendedtext1"; + + public final static String XML_ATTR_TEXT = "ab "; + + + + public final static String CLM_NS = "http://www.tranxml.org/TranXML/Version4.0"; + public final static String CLM_XSI_NS = "xmlns:xsi=\"http://www.w3.org/2000/10/XMLSchema-instance\""; + public final static String CLM_NS_XQUERY_DEFAULT = "declare default element namespace \"" + CLM_NS + "\"; "; + + public final static String TRANXML_FILE_CLM = "xbean/xmlcursor/CarLocationMessage.xml"; + public final static String TRANXML_FILE_XMLCURSOR_PO = "xbean/xmlcursor/po.xml"; + + + public final static String XML_SCHEMA_TYPE_SUFFIX = "http://www.w3.org/2001/XMLSchema"; + public final static String TRANXML_SCHEMA_TYPE_SUFFIX = CLM_NS; + + public static String wrapInXmlFrag(String text) { + return XMLFRAG_BEGINTAG + text + XMLFRAG_ENDTAG; + } + +} + diff --git a/test/src/xmlcursor/detailed/CopyCharsTest.java b/src/test/java/xmlcursor/detailed/CopyCharsTest.java similarity index 77% rename from test/src/xmlcursor/detailed/CopyCharsTest.java rename to src/test/java/xmlcursor/detailed/CopyCharsTest.java index 6fdb897..f1a644d 100755 --- a/test/src/xmlcursor/detailed/CopyCharsTest.java +++ b/src/test/java/xmlcursor/detailed/CopyCharsTest.java @@ -16,72 +16,51 @@ package xmlcursor.detailed; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import xmlcursor.common.*; - -import java.net.URL; +import static org.junit.Assert.*; -/** - * - * - */ public class CopyCharsTest extends BasicCursorTestCase { - public CopyCharsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CopyCharsTest.class); - } - + @Test(expected = IllegalArgumentException.class) public void testCopyCharsToNull() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.copyChars(4, null); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { - } - assertEquals(true, true); + m_xc.copyChars(4, null); } + @Test public void testCopyCharsNegative() throws Exception { - m_xo = XmlObject.Factory - .parse("0123WXYZ"); + m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc0 = m_xc.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); - try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + try { + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(4, xc1.copyChars(-1, xc0)); - assertEquals(TokenType.TEXT, xc0.currentTokenType()); - assertEquals("0123", xc0.getTextValue()); + assertEquals(TokenType.TEXT, xc0.currentTokenType()); + assertEquals("0123", xc0.getTextValue()); xc0.toPrevToken(); - assertEquals(TokenType.START,xc0.prevTokenType()); + assertEquals(TokenType.START, xc0.prevTokenType()); assertEquals("WXYZ0123", xc0.getTextValue()); assertEquals(TokenType.TEXT, xc1.currentTokenType()); - assertEquals(TokenType.START,xc1.prevTokenType()); - assertEquals("WXYZ", xc1.getTextValue()); - } finally { + assertEquals(TokenType.START, xc1.prevTokenType()); + assertEquals("WXYZ", xc1.getTextValue()); + } finally { xc0.dispose(); xc1.dispose(); - } + } } + @Test public void testCopyCharsZero() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -90,7 +69,7 @@ public void testCopyCharsZero() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(0, xc1.copyChars(0, xc0)); assertEquals("0123", xc0.getTextValue()); xc0.toPrevToken(); @@ -103,7 +82,7 @@ public void testCopyCharsZero() throws Exception { } } - + @Test public void testCopyCharsThis() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -111,7 +90,7 @@ public void testCopyCharsThis() throws Exception { XmlCursor xc0 = m_xc.newCursor(); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(true, xc0.isAtSamePositionAs(xc1)); + assertTrue(xc0.isAtSamePositionAs(xc1)); assertEquals(4, xc1.copyChars(4, xc0)); assertEquals("0123", xc0.getTextValue()); xc0.toPrevToken(); @@ -123,6 +102,7 @@ public void testCopyCharsThis() throws Exception { } } + @Test public void testCopyCharsGTmax() throws Exception { m_xo = XmlObject.Factory.parse("0123WXYZ"); m_xc = m_xo.newCursor(); @@ -131,7 +111,7 @@ public void testCopyCharsGTmax() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); XmlCursor xc1 = m_xc.newCursor(); try { - assertEquals(false, xc0.isAtSamePositionAs(xc1)); + assertFalse(xc0.isAtSamePositionAs(xc1)); assertEquals(4, xc1.copyChars(1000, xc0)); // verify xc0 assertEquals("0123", xc0.getTextValue()); @@ -145,6 +125,7 @@ public void testCopyCharsGTmax() throws Exception { } } + @Test public void testCopyCharsToDifferentDocument() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); @@ -161,18 +142,14 @@ public void testCopyCharsToDifferentDocument() throws Exception { assertEquals("01234", m_xc.getTextValue()); } + @Test(expected = IllegalArgumentException.class) public void testCopyCharsToEmptyDocumentSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); m_xc = m_xo.newCursor(); XmlObject xo = XmlObject.Factory.newInstance(); XmlCursor xc1 = xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); - try { - assertEquals(5, m_xc.copyChars(5, xc1)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException ise) { - } - assertEquals(true, true); + assertEquals(5, m_xc.copyChars(5, xc1)); } } diff --git a/src/test/java/xmlcursor/detailed/CopyTest.java b/src/test/java/xmlcursor/detailed/CopyTest.java new file mode 100644 index 0000000..b21c7ec --- /dev/null +++ b/src/test/java/xmlcursor/detailed/CopyTest.java @@ -0,0 +1,48 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CopyTest { + + //this is per CR128353 + @Test + @Ignore("doesn't work anymore without Piccolo Parser") + public void testCopyNamespaceMigration() throws XmlException { + String s1 = "123"; + String s2 = " ... [some content] ... "; + XmlCursor xc1 = XmlObject.Factory.parse(s1).newCursor(); + xc1.toFirstContentToken(); + xc1.toFirstChild(); + XmlCursor xc2 = XmlObject.Factory.parse(s2).newCursor(); + assertEquals(XmlCursor.TokenType.START, xc2.toFirstContentToken()); + xc2.toNextToken(); + xc1.copyXml(xc2); + xc2.toStartDoc(); + assertEquals("" + + "123" + + " ... [some content] ... ", xc2.xmlText()); + xc1.dispose(); + xc2.dispose(); + } + +} diff --git a/src/test/java/xmlcursor/detailed/CursorGeneratedTypedObjectTest.java b/src/test/java/xmlcursor/detailed/CursorGeneratedTypedObjectTest.java new file mode 100755 index 0000000..cde6922 --- /dev/null +++ b/src/test/java/xmlcursor/detailed/CursorGeneratedTypedObjectTest.java @@ -0,0 +1,207 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import org.tranxml.tranXML.version40.CodeList309; +import org.tranxml.tranXML.version40.GeographicLocationDocument; +import org.tranxml.tranXML.version40.LocationIdentifierDocument; +import person.Person; +import person.PersonDocument; +import test.xbean.xmlcursor.location.LocationDocument; +import tools.util.JarUtil; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.*; + + +public class CursorGeneratedTypedObjectTest { + @Test + public void testGetObjectValidateLocation() throws Exception { + String sNamespace = "xmlns:loc=\"http://xbean.test/xmlcursor/Location\""; + String sXml = + "" + + "DALLAS" + + "TX" + + ""; + LocationDocument locDoc = LocationDocument.Factory.parse(sXml); + XmlCursor xc = locDoc.newCursor(); + xc.toFirstChild(); + LocationDocument.Location loc = (LocationDocument.Location) xc.getObject(); + assertTrue(loc.validate()); + XmlCursor xc0 = xc.newCursor(); + + xc0.toEndDoc(); + xc0.toPrevToken(); + // xc0.insertElementWithText("SubdivisionCode", "xyz"); + xc0.insertElementWithText( + new QName("http://xbean.test/xmlcursor/Location", "SubdivisionCode", "loc"), + "xyz"); + xc0.toCursor(xc); + + + String sExpectedXML = + "" + + "DALLAS" + + "TX" + + "xyz" + + ""; + + String sOExpectedXML = + "" + + "DALLAS" + + "TX" + + "xyz" + + ""; + XmlOptions map = new XmlOptions(); + //map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); + //map.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(-1)); + try { + assertEquals(sExpectedXML, xc0.xmlText(map)); + loc = (LocationDocument.Location) xc0.getObject(); + assertEquals(sOExpectedXML, loc.xmlText()); + assertTrue(loc.validate()); + assertEquals("DALLAS", loc.getCityName()); + assertEquals("TX", loc.getStateCode()); + assertEquals("xyz", loc.getSubdivisionCode()); + } finally { + xc.dispose(); + xc0.dispose(); + } + + } + + @Test + public void testGetObjectGL() throws Exception { + String sNamespace = "xmlns=\"http://www.tranxml.org/TranXML/Version4.0\" xmlns:xsi=\"http://www.w3.org/2000/10/XMLSchema-instance\""; + CarLocationMessageDocument clm = CarLocationMessageDocument.Factory.parse( + JarUtil.getResourceFromJar( + Common.TRANXML_FILE_CLM)); + XmlCursor xc = clm.newCursor(); + xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//GeographicLocation"); + xc.toNextSelection(); + + GeographicLocationDocument.GeographicLocation gl0 = (GeographicLocationDocument.GeographicLocation) xc.getObject(); + assertTrue(gl0.validate()); + + XmlCursor xc0 = xc.newCursor(); + try { + xc0.toLastChild(); + assertEquals("TX", xc0.getTextValue()); + xc0.toNextToken(); + xc0.toNextToken(); + xc0.toNextToken(); + xc0.toNextToken(); + assertEquals(TokenType.END, xc0.currentTokenType()); + + xc0.beginElement("LocationIdentifier", + "http://www.tranxml.org/TranXML/Version4.0"); + xc0.insertAttributeWithValue("Qualifier", "FR"); + xc0.toEndToken(); + xc0.toNextToken();//move past the end token + xc0.insertElementWithText("CountrySubdivisionCode", + "http://www.tranxml.org/TranXML/Version4.0", "xyz"); + xc0.toCursor(xc); + + String sExpectedXML = + "\n" + + "\t\t\tDALLAS\n" + + "\t\t\tTX\n" + + "\t\txyz" + + ""; + + XmlOptions map = new XmlOptions(); + // map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); + // map.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(-1)); + assertEquals(sExpectedXML, xc0.xmlText()); + + String sOExpectedXML = + "\n" + + "\t\t\t" + + "DALLAS\n" + + "\t\t\t" + + "TX\n" + + "\t\t" + + "xyz" + + ""; + + GeographicLocationDocument.GeographicLocation gl = (GeographicLocationDocument.GeographicLocation) xc0.getObject(); + assertEquals(sOExpectedXML, gl.xmlText(map)); + assertTrue(gl.validate()); + + + assertEquals("DALLAS", gl.getCityName().getStringValue()); + assertEquals("TX", gl.getStateOrProvinceCode()); + LocationIdentifierDocument.LocationIdentifier li = gl.getLocationIdentifier(); + assertNotNull("LocationIdentifier unexpectedly null", li); + assertEquals(CodeList309.FR, + gl.getLocationIdentifier().getQualifier()); + assertEquals("xyz", gl.getCountrySubdivisionCode()); + } finally { + xc.dispose(); + xc0.dispose(); + } + } + + + @Test + public void testGetObjectPerson() throws Exception { + String sFF = "FredFlintstone"; + String sXml = "" + sFF + + ""; + XmlCursor xc = XmlObject.Factory.parse(sXml).newCursor(); + PersonDocument pdoc = (PersonDocument) xc.getObject(); + + xc.toFirstChild(); + XmlCursor xcPlaceHolder = xc.newCursor(); + + try { + Person p = (Person) xc.getObject(); + assertTrue(p.validate()); + // move to + xc.toEndToken(); + + xc.insertElement("Sibling", "person"); + xc.toPrevToken(); + xc.insertElement("Name", "person"); + xc.toPrevToken(); + xc.insertElementWithText("First", "person", "Barney"); + xc.insertElementWithText("Last", "person", "Rubble"); + + p = (Person) xcPlaceHolder.getObject(); + assertTrue(p.validate()); + + assertEquals("Fred", p.getName().getFirst()); + assertEquals("Flintstone", p.getName().getLast()); + Person[] ap = p.getSiblingArray(); + assertEquals(1, ap.length); + assertEquals("Barney", ap[0].getName().getFirst()); + assertEquals("Rubble", ap[0].getName().getLast()); + } finally { + xc.dispose(); + xcPlaceHolder.dispose(); + } + } +} diff --git a/src/test/java/xmlcursor/detailed/CursorLocations.java b/src/test/java/xmlcursor/detailed/CursorLocations.java new file mode 100755 index 0000000..468456b --- /dev/null +++ b/src/test/java/xmlcursor/detailed/CursorLocations.java @@ -0,0 +1,339 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; +import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderType; +import test.xbean.xmlcursor.purchaseOrder.USAddress; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import java.math.BigDecimal; + +import static org.junit.Assert.*; + +public class CursorLocations extends BasicCursorTestCase { + + private Bookmark0 _theBookmark0 = new Bookmark0("value0"); + + @Test(expected = IllegalArgumentException.class) + public void testLocation() throws Exception { + XmlCursor xc1, xc2, xc3, xc4; + XmlObject m_xo1; + + + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + m_xo1 = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); + + + xc1 = m_xo.newCursor(); + xc2 = m_xo.newCursor(); + xc3 = m_xo1.newCursor(); + + + toNextTokenOfType(xc2, TokenType.END); + toNextTokenOfType(xc3, TokenType.START); + + + //start w/ xc1 at beg of doc + //xc2 at end of first elt (po:name) + while (xc1.isLeftOf(xc2)) { + assertFalse(xc1.isRightOf(xc2)); + assertTrue(xc2.isRightOf(xc1)); + assertTrue(xc1.isInSameDocument(xc2)); + assertFalse(xc2.isAtSamePositionAs(xc1)); + assertFalse(xc1.isAtSamePositionAs(xc2)); + assertEquals(1, xc2.comparePosition(xc1)); + assertEquals(-1, xc1.comparePosition(xc2)); + // System.out.println(xc1.currentTokenType() + " " + xc2.currentTokenType()); + xc1.toNextToken(); + xc2.toPrevToken(); + } + //xc1 & xc2 @ shipTo + toNextTokenOfType(xc1,TokenType.TEXT); + toNextTokenOfType(xc2,TokenType.TEXT); + assertEquals("Current Token Type ", + xc1.currentTokenType(), + xc2.currentTokenType()); + //both @ Alice Smith + toNextTokenOfType(xc1,TokenType.TEXT); + toNextTokenOfType(xc2,TokenType.TEXT); + assertEquals(XmlCursor.TokenType.TEXT, + xc1.currentTokenType()); + //these are only equivalent if the cursor is on a TEXT token + assertEquals(xc1.getChars(), xc1.getTextValue()); + assertEquals(xc1.getChars(), xc2.getTextValue()); + + assertTrue(xc1.isAtSamePositionAs(xc2)); + xc2.toNextChar(10); + + +//comparing two cursors in the middle of text + + assertEquals(xc2.toPrevChar(4), xc1.toNextChar(4)); + assertTrue(xc2.isRightOf(xc1)); + assertFalse(xc1.isRightOf(xc2)); + assertFalse(xc2.isLeftOf(xc1)); + assertFalse(xc1.isAtSamePositionAs(xc2)); + assertEquals(1, xc2.comparePosition(xc1)); + assertTrue(xc1.isInSameDocument(xc2)); + xc1.toNextChar(2); + assertEquals(0, xc2.comparePosition(xc1)); + assertEquals(xc1.currentTokenType(), xc2.currentTokenType()); + + //Comparing the same cursor to itself + xc1.toNextChar(1); + assertFalse(xc1.isRightOf(xc1)); + assertEquals(0, xc2.comparePosition(xc2)); + assertTrue(xc2.isInSameDocument(xc2)); + assertTrue(xc2.isAtSamePositionAs(xc2)); + + xc2.toPrevToken(); + //xc2 on Alice + assertEquals(TokenType.TEXT, xc2.toPrevToken()); + //put the bookmark on S*mith + xc1.setBookmark(_theBookmark0); + + //moving xml and bookmark to a + // different location + assertTrue(xc1.moveXml(xc3)); + xc4 = _theBookmark0.createCursor(); + assertNotNull(xc4); + + XmlCursor debug=xc4.newCursor(); + XmlCursor debug1=xc1.newCursor(); + + toPrevTokenOfType(debug1,TokenType.START); + assertTrue(xc4.isInSameDocument(xc3)); + assertEquals(-1, xc4.comparePosition(xc3)); + // assertEquals(TokenType.TEXT, xc3.toPrevToken()); + assertEquals(4,xc3.toPrevChar(4)); + assertEquals(0, xc4.comparePosition(xc3)); + + //comparing in two different documents + assertFalse(xc2.isInSameDocument(xc3)); + + + try { + xc4.isLeftOf(xc2); + } finally { + xc1.dispose(); + xc2.dispose(); + xc3.dispose(); + xc4.dispose(); + } + } + + @Test + public void testLocationATTR() throws Exception { + XmlCursor xc1, xc2; + m_xo = XmlObject.Factory.parse(Common.XML_FOO_5ATTR_TEXT); + + xc1 = m_xo.newCursor(); + xc2 = m_xo.newCursor(); + + toNextTokenOfType(xc1, TokenType.ATTR); + toNextTokenOfType(xc2, TokenType.ATTR); + + int i = 0; + while (xc2.currentTokenType() == TokenType.ATTR) { + xc2.toNextToken(); + ++i; + } + + assertEquals(5, i); + xc2.toPrevToken(); + + //moving betweenAttributes. one cursor is at the last ATTR and other is at first ATTR. + while (xc1.isLeftOf(xc2)) { + assertFalse(xc1.isRightOf(xc2)); + assertTrue(xc2.isRightOf(xc1)); + assertTrue(xc1.isInSameDocument(xc2)); + assertFalse(xc2.isAtSamePositionAs(xc1)); + assertFalse(xc1.isAtSamePositionAs(xc2)); + assertEquals(1, xc2.comparePosition(xc1)); + assertEquals(-1, xc1.comparePosition(xc2)); + // System.out.println(xc1.currentTokenType() + " " + xc2.currentTokenType()); + xc1.toNextToken(); + xc2.toPrevToken(); + } + assertTrue(xc1.isAtSamePositionAs(xc2)); + + //inserting and then comparing to make sure cursors move properly. + xc2.insertAttributeWithValue("attr5", "val5"); + assertEquals(0, xc1.comparePosition(xc2)); + + xc2.toPrevToken(); + assertEquals("val5", xc2.getTextValue()); + + xc1.dispose(); + xc2.dispose(); + + } + + @Test + public void testLocationTEXTMiddle() throws Exception { + XmlCursor xc1, xc2, xc3; + m_xo = XmlObject.Factory.parse(Common.XML_TEXT_MIDDLE); + + xc1 = m_xo.newCursor(); + xc2 = m_xo.newCursor(); + xc3 = m_xo.newCursor(); + + + // while(xc2.currentTokenType() != TokenType.ENDDOC) + // { + // System.out.println(xc2.currentTokenType()); + // xc2.toNextToken(); + // } + + // moving cursor to right locations. one is in middle of mixed content. + // the others is in middle of text of first node and last node + + toNextTokenOfType(xc1, TokenType.TEXT); + toNextTokenOfType(xc2, TokenType.TEXT); + toNextTokenOfType(xc3, TokenType.START); + toNextTokenOfType(xc2, TokenType.TEXT); + xc1.toNextChar(4); + xc2.toNextChar(5); + xc3.toEndToken(); + xc3.toPrevToken(); + xc3.toPrevChar(3); + + //comparing positions + assertEquals(-1, xc2.comparePosition(xc3)); + assertTrue(xc2.isRightOf(xc1)); + assertTrue(xc1.isInSameDocument(xc2)); + assertFalse(xc2.isAtSamePositionAs(xc3)); + + //moving cursors + xc3.toPrevChar(2); + xc2.toNextChar(1); + + //comparing position once again + assertEquals(-1, xc2.comparePosition(xc3)); + assertTrue(xc2.isRightOf(xc1)); + assertTrue(xc1.isInSameDocument(xc2)); + assertFalse(xc2.isAtSamePositionAs(xc3)); + + //moving and bringing them to identical positions + xc3.toPrevToken(); + xc2.toNextChar(2); + assertTrue(xc2.isAtSamePositionAs(xc3)); + + xc1.dispose(); + xc2.dispose(); + xc3.dispose(); + } + + @Test + public void testXmlObjectUsingCursor() throws Exception { + XmlCursor xc1, xc2, xc3; + + PurchaseOrderDocument pod = PurchaseOrderDocument.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); + xc1 = pod.newCursor(); + xc2 = pod.newCursor(); + xc3 = pod.newCursor(); + + + //moving cursor location so that it comes to zip under shipto + + toNextTokenOfType(xc1, TokenType.START); + toNextTokenOfType(xc1, TokenType.START); + toNextTokenOfType(xc2, TokenType.START); + toNextTokenOfType(xc2, TokenType.START); + toNextTokenOfType(xc3, TokenType.START); + toNextTokenOfType(xc3, TokenType.START); + + xc1.toEndToken(); + xc2.toEndToken(); + xc3.toEndToken(); + + toPrevTokenOfType(xc1, TokenType.TEXT); + toPrevTokenOfType(xc1, TokenType.TEXT); + toPrevTokenOfType(xc2, TokenType.TEXT); + toPrevTokenOfType(xc2, TokenType.TEXT); + toPrevTokenOfType(xc3, TokenType.TEXT); + toPrevTokenOfType(xc3, TokenType.TEXT); + //all cursors are now at: 90952 + assertEquals(xc1.getChars(), xc2.getChars(), xc3.getChars()); + //at 52 + xc2.toNextChar(3); + //after 90952 + xc3.toNextChar(5); + assertFalse(xc2.isAtSamePositionAs(xc3)); + assertFalse(xc3.isAtSamePositionAs(xc1)); + + + //setting zip value through the object . + // once the set occurs comparing postions of cursors. + PurchaseOrderType pt = pod.getPurchaseOrder(); + USAddress usa = pt.getShipTo(); + usa.setZip(new BigDecimal(500)); + + assertEquals(500,usa.getZip().intValue()); + //Any cursors in the value of an Element/attr should be positioned + // at the end of the elem/attr after the strong setter + assertTrue(xc2.isAtSamePositionAs(xc3)); + assertTrue(xc3.isAtSamePositionAs(xc1)); + + assertEquals(TokenType.END,xc1.currentTokenType()); + + + // inserting an element through the cursor under zip and then doing + // a set of a valid value through object.. + + xc1.insertElementWithText("foo", "text"); + toPrevTokenOfType(xc1, TokenType.START); + toPrevTokenOfType(xc1, TokenType.START); + //System.out.println("here" + xc1.getTextValue()); + + toNextTokenOfType(xc1, TokenType.START); + + xc1.toNextChar(2); + usa.setZip(new BigDecimal(90852)); + + assertTrue(xc2.isAtSamePositionAs(xc3)); + assertTrue(xc3.isAtSamePositionAs(xc1)); + //cursors at the end of element + xc1.toPrevToken(); + //assertEquals(5,xc1.toPrevChar(5)); + assertEquals("90852", xc1.getChars()); + + + xc1.dispose(); + xc2.dispose(); + xc3.dispose(); + } + + + public class Bookmark0 extends XmlCursor.XmlBookmark { + public String text; + + Bookmark0(String text) { + this.text = text; + } + } +} + diff --git a/src/test/java/xmlcursor/detailed/CursorVsObjectAttributeTest.java b/src/test/java/xmlcursor/detailed/CursorVsObjectAttributeTest.java new file mode 100755 index 0000000..6b0ace6 --- /dev/null +++ b/src/test/java/xmlcursor/detailed/CursorVsObjectAttributeTest.java @@ -0,0 +1,89 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import org.tranxml.tranXML.version40.CarLocationMessageDocument.CarLocationMessage; +import tools.util.JarUtil; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + + +public class CursorVsObjectAttributeTest { + @Test + public void testAttributeSet() throws Exception { + CarLocationMessageDocument clmDoc = CarLocationMessageDocument.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + XmlCursor xc = clmDoc.newCursor(); + xc.toFirstChild(); + CarLocationMessage clm = (CarLocationMessage) xc.getObject(); + + clm.setVersion("XyZ"); + QName name = new QName("Version"); + assertEquals("XyZ", xc.getAttributeText(name)); + xc.setAttributeText(name, "012"); + assertEquals("012", clm.getVersion()); + } + + @Test + public void testAttributeUnsetRemove() throws Exception { + CarLocationMessageDocument clmDoc = + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + XmlCursor xc = clmDoc.newCursor(); + xc.toFirstChild(); + CarLocationMessage clm = (CarLocationMessage) xc.getObject(); + QName name = new QName("Version"); + assertEquals("CLM", xc.getAttributeText(name)); + clm.unsetVersion(); + assertNull(xc.getAttributeText(name)); + xc.setAttributeText(name, "012"); + assertEquals("012", clm.getVersion()); + xc.removeAttribute(name); + assertNull(clm.getVersion()); + } + + @Test + public void testAttributeInsert() throws Exception { + XmlOptions map = new XmlOptions(); + map.setLoadStripWhitespace(); + + CarLocationMessageDocument clmDoc = + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM), map); + XmlCursor xc = clmDoc.newCursor(); + xc.toFirstChild(); + CarLocationMessage clm = (CarLocationMessage) xc.getObject(); + QName name = new QName("Version"); + assertEquals("CLM", xc.getAttributeText(name)); + clm.unsetVersion(); + assertNull(xc.getAttributeText(name)); + xc.toFirstChild(); + assertEquals(TokenType.START, xc.currentTokenType()); + xc.insertAttributeWithValue(name, "012"); + assertEquals("012", clm.getVersion()); + } +} diff --git a/test/src/xmlcursor/detailed/CursorVsObjectInsertRemoveTest.java b/src/test/java/xmlcursor/detailed/CursorVsObjectInsertRemoveTest.java similarity index 79% rename from test/src/xmlcursor/detailed/CursorVsObjectInsertRemoveTest.java rename to src/test/java/xmlcursor/detailed/CursorVsObjectInsertRemoveTest.java index 978ce81..0fec7df 100755 --- a/test/src/xmlcursor/detailed/CursorVsObjectInsertRemoveTest.java +++ b/src/test/java/xmlcursor/detailed/CursorVsObjectInsertRemoveTest.java @@ -14,43 +14,26 @@ */ -package xmlcursor.detailed; +package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; -import xmlcursor.common.Common; - -import tools.util.JarUtil; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import org.tranxml.tranXML.version40.CarLocationMessageDocument; import org.tranxml.tranXML.version40.EventStatusDocument.EventStatus; import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; +import tools.util.JarUtil; +import xmlcursor.common.Common; -/** - * - * - */ -public class CursorVsObjectInsertRemoveTest extends TestCase { - public CursorVsObjectInsertRemoveTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CursorVsObjectInsertRemoveTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } +import static org.junit.Assert.*; +public class CursorVsObjectInsertRemoveTest { + @Test public void testInsertRemove() throws Exception { CarLocationMessageDocument clm = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); assertNotNull(clm); XmlCursor xc = clm.newCursor(); xc.toFirstChild(); diff --git a/test/src/xmlcursor/detailed/CursorVsObjectSetGetTextTest.java b/src/test/java/xmlcursor/detailed/CursorVsObjectSetGetTextTest.java similarity index 79% rename from test/src/xmlcursor/detailed/CursorVsObjectSetGetTextTest.java rename to src/test/java/xmlcursor/detailed/CursorVsObjectSetGetTextTest.java index 47cc07b..addfb63 100755 --- a/test/src/xmlcursor/detailed/CursorVsObjectSetGetTextTest.java +++ b/src/test/java/xmlcursor/detailed/CursorVsObjectSetGetTextTest.java @@ -16,36 +16,20 @@ package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import tools.util.JarUtil; -import xmlcursor.common.Common; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; import org.tranxml.tranXML.version40.CityNameDocument.CityName; +import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; +import tools.util.JarUtil; +import xmlcursor.common.Common; +import static org.junit.Assert.*; -/** - * - * - */ -public class CursorVsObjectSetGetTextTest extends TestCase { - public CursorVsObjectSetGetTextTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CursorVsObjectSetGetTextTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } +public class CursorVsObjectSetGetTextTest { + @Test public void testSetGet() throws Exception { CarLocationMessageDocument clm = (CarLocationMessageDocument) XmlObject.Factory.parse( @@ -74,7 +58,7 @@ public void testSetGet() throws Exception { xc.toNextSelection(); for (int i = 0; i < 3; i++) { - assertEquals(true, xc.toFirstChild()); + assertTrue(xc.toFirstChild()); assertEquals("SEATTLE", xc.getTextValue()); xc.setTextValue("PORTLAND"); xc.toNextSelection(); @@ -89,10 +73,10 @@ public void testSetGet() throws Exception { } - public class Bookmark extends XmlCursor.XmlBookmark { + class Bookmark extends XmlCursor.XmlBookmark { public String text; - public Bookmark(String text) { + Bookmark(String text) { this.text = text; } } diff --git a/test/src/xmlcursor/detailed/GetTextTest.java b/src/test/java/xmlcursor/detailed/GetTextTest.java similarity index 86% rename from test/src/xmlcursor/detailed/GetTextTest.java rename to src/test/java/xmlcursor/detailed/GetTextTest.java index bf99ae8..9378172 100755 --- a/test/src/xmlcursor/detailed/GetTextTest.java +++ b/src/test/java/xmlcursor/detailed/GetTextTest.java @@ -16,38 +16,17 @@ package xmlcursor.detailed; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import java.net.URL; +import static org.junit.Assert.assertEquals; - -/** - * - * - */ public class GetTextTest extends BasicCursorTestCase { - public GetTextTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetTextTest.class); - } - + @Test(expected = IllegalStateException.class) public void testGetTextFromEND() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -57,14 +36,10 @@ public void testGetTextFromEND() throws Exception { assertEquals(TokenType.END, m_xc.currentTokenType()); //assertEquals(null, m_xc.getTextValue()); - try { - m_xc.getTextValue(); - fail("Expecting Illegal State Exception"); - } catch (IllegalStateException ie) { - } - + m_xc.getTextValue(); } + @Test public void testGetTextFromPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); @@ -72,6 +47,7 @@ public void testGetTextFromPROCINST() throws Exception { assertEquals("type=\"text/xsl\" xmlns=\"http://openuri.org/shipping/\"", m_xc.getTextValue()); } + @Test public void testGetTextFromCOMMENT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); m_xc = m_xo.newCursor(); @@ -79,6 +55,7 @@ public void testGetTextFromCOMMENT() throws Exception { assertEquals(" comment text ", m_xc.getTextValue()); } + @Test public void testGetTextFromNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); @@ -89,24 +66,19 @@ public void testGetTextFromNAMESPACE() throws Exception { //filed bug on API String text= m_xc.getTextValue(); assertEquals("http://www.foo.org", text); - - } + @Test(expected = IllegalStateException.class) public void testGetTextFromENDDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.ENDDOC); //assertEquals(null, m_xc.getTextValue()); - try { - m_xc.getTextValue(); - fail("Expecting Illegal State Exception"); - } catch (IllegalStateException ie) { - } - + m_xc.getTextValue(); } + @Test public void testGetTextFromTEXT() throws Exception { // m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); @@ -115,13 +87,14 @@ public void testGetTextFromTEXT() throws Exception { toNextTokenOfType(m_xc, TokenType.TEXT); assertEquals(TokenType.TEXT, m_xc.currentTokenType()); assertEquals("text", m_xc.getChars()); - assertEquals("text", m_xc.getTextValue()); + assertEquals("text", m_xc.getTextValue()); - m_xc.toNextChar(2); - assertEquals(TokenType.TEXT, m_xc.currentTokenType()); + m_xc.toNextChar(2); + assertEquals(TokenType.TEXT, m_xc.currentTokenType()); assertEquals("xt", m_xc.getTextValue()); } + @Test public void testGetTextFromSTART_NotNested() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -133,6 +106,7 @@ public void testGetTextFromSTART_NotNested() throws Exception { assertEquals("FLEETNAME", m_xc.getTextValue()); } + @Test public void testGetTextFromSTART_Nested() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -142,6 +116,7 @@ public void testGetTextFromSTART_Nested() throws Exception { assertEquals("\n\t\t\tGATX\n\t\t\t123456\n\t\t\tL\n\t\t", m_xc.getTextValue()); } + @Test public void testGetTextFromSTART_TextAferEND() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT_EXT); m_xc = m_xo.newCursor(); @@ -150,6 +125,7 @@ public void testGetTextFromSTART_TextAferEND() throws Exception { assertEquals("text", m_xc.getTextValue()); } + @Test public void testGetTextFromSTART_TextAferEND_WS() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_WS_TEXT); m_xc = m_xo.newCursor(); @@ -158,6 +134,7 @@ public void testGetTextFromSTART_TextAferEND_WS() throws Exception { assertEquals(" text ", m_xc.getTextValue()); } + @Test public void testGetTextFromATTR_Nested() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); @@ -170,12 +147,14 @@ public void testGetTextFromATTR_Nested() throws Exception { assertEquals("US", m_xc.getTextValue()); } + @Test public void testGetTextFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT_EXT); m_xc = m_xo.newCursor(); assertEquals("textextended", m_xc.getTextValue()); } + @Test public void testGetTextEmptyElementSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR); m_xc = m_xo.newCursor(); @@ -183,12 +162,12 @@ public void testGetTextEmptyElementSTART() throws Exception { assertEquals("", m_xc.getTextValue()); } + @Test public void testGetTextWhitespaceOnlyFromSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_WS_ONLY); m_xc = m_xo.newCursor(); m_xc.toFirstChild(); assertEquals(" ", m_xc.getTextValue()); } - } diff --git a/test/src/xmlcursor/detailed/GetTextValueTest.java b/src/test/java/xmlcursor/detailed/GetTextValueTest.java similarity index 86% rename from test/src/xmlcursor/detailed/GetTextValueTest.java rename to src/test/java/xmlcursor/detailed/GetTextValueTest.java index 178e72d..714d97b 100755 --- a/test/src/xmlcursor/detailed/GetTextValueTest.java +++ b/src/test/java/xmlcursor/detailed/GetTextValueTest.java @@ -15,32 +15,23 @@ package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor.TokenType; -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; +import static org.junit.Assert.*; -/** - * - * - */ -public class GetTextValueTest extends BasicCursorTestCase { +public class GetTextValueTest extends BasicCursorTestCase { - String sDoc = Common.XML_FOO_NS_PREFIX; - public GetTextValueTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetTextValueTest.class); - } + private String sDoc = Common.XML_FOO_NS_PREFIX; // Depth first concatenation of all text leaves - + @Test public void testNormalCase() { String sExpected = " 32.18"; char[] buffer = new char[100]; @@ -49,24 +40,18 @@ public void testNormalCase() { assertEquals(sExpected, new String(buffer).substring(0, nCopied)); } + @Test(expected = IllegalArgumentException.class) public void testGetNull() { - try { - m_xc.getTextValue(null, 0, 10); - fail("Buffer was Null"); - } catch (IllegalArgumentException ie) { - } + m_xc.getTextValue(null, 0, 10); } + @Test(expected = IllegalArgumentException.class) public void testNegativeOffset() { char[] buffer = new char[100]; - try { - m_xc.getTextValue(buffer, -1, 100); - fail("Offset < 0"); - } catch (IllegalArgumentException ie) { - } - + m_xc.getTextValue(buffer, -1, 100); } + @Test public void testNonZeroOffset() { String sExpected = "T\0 32.18"; char[] buffer = new char[10]; @@ -79,20 +64,17 @@ public void testNonZeroOffset() { assertEquals("", new String(buffer).substring(nOffset + nCopied, buffer.length) .trim()); - } + @Test(expected = IllegalArgumentException.class) public void testLargeOffset() { char[] buffer = new char[100]; - try { - m_xc.getTextValue(buffer, 101, 1); - fail("Offset Past end"); - } catch (IllegalArgumentException ie) { - } + m_xc.getTextValue(buffer, 101, 1); } //charCount<=0: should be a noop //BUT: Assumption is that <0=infinity, so all is copies + @Test public void testNegativeCharCount() { char[] buffer = new char[100]; String sExpected = m_xc.getTextValue(); @@ -101,6 +83,7 @@ public void testNegativeCharCount() { assertEquals(sExpected, new String(buffer, 0, nCount)); } + @Test public void testZeroCharCount() { char[] buffer = new char[10]; int nCopied = m_xc.getTextValue(buffer, 0, 0); @@ -108,18 +91,20 @@ public void testZeroCharCount() { assertEquals("", new String(buffer).trim()); } + @Test public void testLargeCharCount() { String sExpected = " 32.18"; char[] buffer = new char[200]; int nCharCount = 300; - assertEquals(true, sDoc.length() < nCharCount); - assertEquals(false, buffer.length >= nCharCount); + assertTrue(sDoc.length() < nCharCount); + assertFalse(buffer.length >= nCharCount); int nCopied = m_xc.getTextValue(buffer, 0, nCharCount); assertEquals(sExpected.length(), nCopied); assertEquals(sExpected, new String(buffer).substring(0, nCopied)); } //offset+selection>buffer + @Test public void testSelectionPastEnd() { String sExpected = " 3"; char[] buffer = new char[100]; @@ -133,6 +118,7 @@ public void testSelectionPastEnd() { //End,Enddoc,Namespace should //return 0 as per spec //NB: Design changed, should work now + @Test public void testGetNonTextElement() { char[] buffer = new char[100]; toNextTokenOfType(m_xc, TokenType.NAMESPACE); @@ -154,11 +140,10 @@ public void testGetNonTextElement() { fail("Operation not allowed"); } catch (java.lang.IllegalStateException e) { } - - } //test text of comment, PI or Attr + @Test public void testCommentPIAttr() throws Exception { String sExpected = "http://ecommerce.org/schema"; int nSize = sExpected.length(); @@ -191,11 +176,10 @@ public void testCommentPIAttr() throws Exception { assertEquals(sExpected, new String(buffer) .substring(0, nCopied)); assertEquals(sExpected.length(), nCopied); - } + @Before public void setUp() throws Exception { - m_xc = XmlObject.Factory.parse(sDoc) - .newCursor(); + m_xc = XmlObject.Factory.parse(sDoc).newCursor(); } } diff --git a/src/test/java/xmlcursor/detailed/InsertAttributeTest2.java b/src/test/java/xmlcursor/detailed/InsertAttributeTest2.java new file mode 100755 index 0000000..8a7e3b9 --- /dev/null +++ b/src/test/java/xmlcursor/detailed/InsertAttributeTest2.java @@ -0,0 +1,169 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.*; + + +public class InsertAttributeTest2 extends BasicCursorTestCase { + @Test + public void testNormalCase() { + for (int i = 0; i < 50; i++) { + m_xc.insertAttribute("at" + i, "com.bea.foo"); + //System.out.println(i); + } + toPrevTokenOfType(m_xc, TokenType.ATTR); + + int i = 0; + do { + i++; + //System.out.println(m_xc.xmlText()); + } while (m_xc.toPrevAttribute()); + + assertEquals(i, 50); + } + + @Test(expected = Exception.class) + public void testIllegalCursorPos() { + //position curor at text + toNextTokenOfType(m_xc, XmlCursor.TokenType.END); + // Shoild not be able to insert at attr here + m_xc.insertAttribute("at", "com.bea.foo"); + } + + /** + No xml tag can contain 2 attrib such that: + 1. have identical names, or + 2. have qualified names with the same local part and with prefixes which have been bound to namespace names that are identical. + + ** According to Eric he will perform the insert but + * check upon serialization that only the first token with a given name is printed + */ + @Test + public void testLocalNameCollision() { + m_xc.insertAttributeWithValue("at", "v1"); + m_xc.insertAttributeWithValue("at", "v2"); + toPrevTokenOfType(m_xc, TokenType.START); + m_xc.toFirstAttribute(); + assertEquals(m_xc.getName().getLocalPart(), "at"); + assertTrue(m_xc.toNextAttribute()); + assertEquals(m_xc.getName().getLocalPart(), "at"); + } + + /** + * The idea was to try to force the following: + * + * which would be illegal + * This test case is not necessary: The implementation re-writes this as + * xmlns:com="..." and com:at0, com:at1 + * it seems impossible to force a binding of the same URI with two + * different prefixes + */ + @Test(expected = Exception.class) + @Ignore + public void testUriCollision() { + m_xc.insertAttribute("at0", "com.bea.foo"); + m_xc.insertAttribute("at1", "com.bea.foo"); + toPrevTokenOfType(m_xc, TokenType.START); + // Should not be able to insert at attr with colliding name + System.out.println(m_xc.xmlText()); + } + + @Test + public void testUriLocalNameOK() { + m_xc.insertAttribute("at", ""); + m_xc.insertAttribute("at", "com.bea.foo"); + toPrevTokenOfType(m_xc, XmlCursor.TokenType.START); + m_xc.toFirstAttribute(); + int i = 1; + while (m_xc.toNextAttribute()) i++; + assertEquals(i, 2); + } + + @Test + public void testUriNull() { + m_xc.insertAttribute("at", null); + toPrevTokenOfType(m_xc, TokenType.ATTR); + assertEquals(m_xc.getName(), new QName("at")); + } + + @Test(expected = Exception.class) + public void testLocalnameNull() { + m_xc.insertAttribute(null, ""); + } + + @Test + public void testUriEmpty() { + m_xc.insertAttribute("myat", ""); + toPrevTokenOfType(m_xc, TokenType.START); + m_xc.toFirstAttribute(); + assertEquals(m_xc.getName(), new QName(null, "myat")); + } + + @Test(expected = Exception.class) + public void testLocalnameEmpty() { + m_xc.insertAttribute("", ""); + } + + @Test + public void testInsertAttributeWithValue() { + StringBuilder sb = new StringBuilder(); + String value0 = "test" + "\n\t\r"; + String value1 = "'QuotedText'"; + String value2 = "\"QuotedText2\""; + + int nStressBound = 20000;//Integer.MAX_VALUE + for (int i = 0; i < nStressBound; i++) + sb.append('a'); + m_xc.insertAttributeWithValue("at0", value0); + m_xc.insertAttributeWithValue("at1", value1); + m_xc.insertAttributeWithValue("at2", value2); + m_xc.insertAttributeWithValue("at3", sb.toString()); + + toPrevTokenOfType(m_xc, TokenType.START); + + assertEquals(m_xc.getAttributeText(new QName("at3")).length(), nStressBound); + assertEquals(m_xc.getAttributeText(new QName("at2")), value2); + + assertEquals(m_xc.getAttributeText(new QName("at1")), value1); + assertEquals(m_xc.getAttributeText(new QName("at0")), value0); + } + + @Test + public void testInsertAttributeWithValueNull() { + m_xc.insertAttributeWithValue("at0", null); + assertNull(m_xc.getAttributeText(new QName("at0"))); + } + + @Before + public void setUp()throws Exception{ + String sDoc = Common.XML_FOO_TEXT; + m_xc= XmlObject.Factory.parse(sDoc).newCursor(); + toNextTokenOfType(m_xc,XmlCursor.TokenType.TEXT);//prepare for atts + } +} diff --git a/test/src/xmlcursor/detailed/InsertNamespaceTest.java b/src/test/java/xmlcursor/detailed/InsertNamespaceTest.java similarity index 76% rename from test/src/xmlcursor/detailed/InsertNamespaceTest.java rename to src/test/java/xmlcursor/detailed/InsertNamespaceTest.java index 8658924..825d013 100755 --- a/test/src/xmlcursor/detailed/InsertNamespaceTest.java +++ b/src/test/java/xmlcursor/detailed/InsertNamespaceTest.java @@ -16,39 +16,19 @@ package xmlcursor.detailed; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - +import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlCursor.TokenType; +import org.junit.Ignore; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import javax.xml.namespace.QName; +import static org.junit.Assert.assertEquals; -import xmlcursor.common.*; -import java.util.*; -import java.net.URL; - - -/** - * - * - */ public class InsertNamespaceTest extends BasicCursorTestCase { - public InsertNamespaceTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertNamespaceTest.class); - } - + @Test public void testInsertNamespaceAfterSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -56,10 +36,11 @@ public void testInsertNamespaceAfterSTART() throws Exception { m_xc.insertNamespace("prefix", "value"); m_xc.toStartDoc(); XmlOptions map = new XmlOptions(); - map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); + map.setSaveNamespacesFirst(true); assertEquals("text", m_xc.xmlText(map)); } + @Test public void testInsertNamespaceAfterATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -68,48 +49,37 @@ public void testInsertNamespaceAfterATTR() throws Exception { m_xc.insertNamespace("prefix", "value"); m_xc.toStartDoc(); XmlOptions map = new XmlOptions(); - map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); + map.setSaveNamespacesFirst(); assertEquals("text", m_xc.xmlText(map)); } + @Test(expected = IllegalArgumentException.class) public void testInsertNamespaceInsideTEXT() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.TEXT); m_xc.toNextChar(2); assertEquals("xt", m_xc.getChars()); - try { - m_xc.insertNamespace("prefix", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - assertTrue(true); + m_xc.insertNamespace("prefix", "value"); } + @Test(expected = IllegalArgumentException.class) public void testInsertNamespaceFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); m_xc = m_xo.newCursor(); - try { - m_xc.insertNamespace("prefix", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - assertTrue(true); + m_xc.insertNamespace("prefix", "value"); } + @Test(expected = IllegalArgumentException.class) public void testInsertNamespaceAfterPROCINST() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.PROCINST); m_xc.toNextToken(); - try { - m_xc.insertNamespace("prefix", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - assertTrue(true); + m_xc.insertNamespace("prefix", "value"); } + @Test public void testInsertNamespaceAfterNAMESPACE() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_NS); m_xc = m_xo.newCursor(); @@ -120,6 +90,7 @@ public void testInsertNamespaceAfterNAMESPACE() throws Exception { assertEquals("", m_xc.xmlText()); } + @Test public void testInsertDuplicateNamespace() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); @@ -130,6 +101,8 @@ public void testInsertDuplicateNamespace() throws Exception { assertEquals("text", m_xc.xmlText()); } + @Test + @Ignore public void testInsertNamespaceWithNullPrefix() throws Exception { // According to Eric V... This test is not valid // Eric's comments: @@ -150,29 +123,26 @@ public void testInsertNamespaceWithNullPrefix() throws Exception { // assertEquals("", m_xc.xmlText()); } + @Test public void testInsertNamespaceWithNullValue() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.END); - //EricV: this should be OK, but make sure the saver + //EricV: this should be OK, but make sure the saver // doesn't serialize it since it's not legal XML - m_xc.insertNamespace("prefix", null); - m_xc.toStartDoc(); + m_xc.insertNamespace("prefix", null); + m_xc.toStartDoc(); assertEquals("", m_xc.xmlText()); } + @Test(expected = IllegalArgumentException.class) public void testInsertEmptyNamespace() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); m_xc = m_xo.newCursor(); toNextTokenOfType(m_xc, TokenType.END); - try { - m_xc.insertNamespace("", ""); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } + m_xc.insertNamespace("", ""); } - } diff --git a/test/src/xmlcursor/detailed/MoveXmlTest2.java b/src/test/java/xmlcursor/detailed/MoveXmlTest2.java similarity index 80% rename from test/src/xmlcursor/detailed/MoveXmlTest2.java rename to src/test/java/xmlcursor/detailed/MoveXmlTest2.java index bcdbb02..26fec58 100755 --- a/test/src/xmlcursor/detailed/MoveXmlTest2.java +++ b/src/test/java/xmlcursor/detailed/MoveXmlTest2.java @@ -16,37 +16,23 @@ package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.*; - +import static org.junit.Assert.*; -/** - * - * - */ public class MoveXmlTest2 extends BasicCursorTestCase { - static String sTestXml = "text0"; - static String sTargetXml = ""; - static XmlCursor m_xc1; - - public MoveXmlTest2(String sName) - { - super(sName); - } - - public static Test suite() - { - return new TestSuite(MoveXmlTest2.class); - } - + private static String sTestXml = "text0"; + private static XmlCursor m_xc1; + @Test public void testNormalCase() { String sExpectedTrg1 = ""; @@ -87,6 +73,7 @@ public void testNormalCase() } //to here at END + @Test(expected = IllegalArgumentException.class) public void testMoveNoop() { @@ -101,17 +88,15 @@ public void testMoveNoop() toNextTokenOfType(m_xc1, TokenType.START); toNextTokenOfType(m_xc, TokenType.ENDDOC); - try { - m_xc.moveXml(m_xc1); - fail(" need IllegalArgumentException"); - } catch (IllegalArgumentException e) {} + m_xc.moveXml(m_xc1); } + @Test public void testInvalidToCursorPos() { //position the cursor within a tag ... toNextTokenOfType(m_xc, TokenType.START);//m_xc on book at0 - assertEquals(true, m_xc.toFirstAttribute()); //at0 in book + assertTrue(m_xc.toFirstAttribute()); //at0 in book toNextTokenOfType(m_xc1, TokenType.START); try { if (m_xc1.moveXml(m_xc)) { @@ -123,6 +108,7 @@ public void testInvalidToCursorPos() } } + @Test public void testMovedAttrNameCollision() throws Exception { @@ -131,13 +117,13 @@ public void testMovedAttrNameCollision() throws Exception toNextTokenOfType(m_xc1, TokenType.START); toNextTokenOfType(m_xc1, TokenType.START); //toNextTokenOfType(m_xc1,TokenType.END);//to author - assertEquals(true, m_xc1.toFirstAttribute()); - assertEquals(true, m_xc.toFirstAttribute()); //at0 in book + assertTrue(m_xc1.toFirstAttribute()); + assertTrue(m_xc.toFirstAttribute()); //at0 in book if (m_xc.moveXml(m_xc1)) { toPrevTokenOfType(m_xc1, TokenType.START); m_xc1.toFirstAttribute(); assertEquals(m_xc1.getName().getLocalPart(), "at0"); - assertEquals(true, m_xc1.toNextAttribute()); + assertTrue(m_xc1.toNextAttribute()); assertEquals(m_xc1.getName().getLocalPart(), "at0"); } m_xc1.dispose(); @@ -148,14 +134,15 @@ public void testMovedAttrNameCollision() throws Exception * seems to be illegal semantics judging from beginElement * $NOTE: legal here */ + @Test public void testInvalidXml() { toNextTokenOfType(m_xc, TokenType.START); toNextTokenOfType(m_xc1, TokenType.START); - assertEquals(true, m_xc.moveXml(m_xc1)); + assertTrue(m_xc.moveXml(m_xc1)); } - + @Test public void testNull() { toNextTokenOfType(m_xc, TokenType.START); @@ -167,7 +154,7 @@ public void testNull() } } - + @Test public void testSelf() { String sExpectedResult = m_xc.xmlText(); @@ -183,12 +170,15 @@ public void testSelf() } } + @Before public void setUp() throws Exception { m_xc = XmlObject.Factory.parse(sTestXml).newCursor(); + String sTargetXml = ""; m_xc1 = XmlObject.Factory.parse(sTargetXml).newCursor(); } + @After public void tearDown() throws Exception { super.tearDown(); @@ -197,18 +187,4 @@ public void tearDown() throws Exception m_xc1 = null; } } - - public static void main(String[] rgs) - { - try { - MoveXmlTest2 t = new MoveXmlTest2(""); - t.setUp(); - t.testSelf(); - } catch (Exception e) { - System.err.println("Error " + e.getMessage()); - e.printStackTrace(); - } - } - - } diff --git a/src/test/java/xmlcursor/detailed/MultipleCopyFromCursorTest.java b/src/test/java/xmlcursor/detailed/MultipleCopyFromCursorTest.java new file mode 100755 index 0000000..33990d3 --- /dev/null +++ b/src/test/java/xmlcursor/detailed/MultipleCopyFromCursorTest.java @@ -0,0 +1,130 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import org.tranxml.tranXML.version40.CodeList309; +import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; +import org.tranxml.tranXML.version40.LocationIdentifierDocument.LocationIdentifier; +import tools.util.JarUtil; +import xmlcursor.common.Common; + +import java.util.ArrayList; + +import static org.junit.Assert.*; + + +public class MultipleCopyFromCursorTest { + + @Test + public void testMultipleCopy() throws Exception { + CarLocationMessageDocument clm = + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + assertNotNull(clm); + XmlCursor xc = clm.newCursor(); + XmlCursor[] aCursors = new XmlCursor[3]; + try { + xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//GeographicLocation"); + xc.toNextSelection(); + for (int i = 0; i < 3; i++) { + aCursors[i] = xc.newCursor(); + xc.toNextSelection(); + } + xc.toStartDoc(); + xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//GeographicLocation"); + assertTrue(xc.getSelectionCount() > 0); + assertTrue(xc.toNextSelection()); + aCursors[0].toLastChild(); + assertEquals("TX", aCursors[0].getTextValue()); + + aCursors[0].toNextToken(); + aCursors[0].toNextToken(); + aCursors[0].toNextToken(); + aCursors[0].toNextToken(); + assertEquals(TokenType.END, aCursors[0].currentTokenType()); + + aCursors[0].beginElement("LocationIdentifier", + "http://www.tranxml.org/TranXML/Version4.0"); + aCursors[0].insertAttributeWithValue("Qualifier", "FR"); + aCursors[0].toEndToken(); + aCursors[0].toNextToken();//move past the end token + aCursors[0].insertElementWithText("CountrySubdivisionCode", + "http://www.tranxml.org/TranXML/Version4.0", + "xyz"); + aCursors[0].toCursor(xc); + GeographicLocation gl = (GeographicLocation) aCursors[0].getObject(); + XmlOptions validateOptions = new XmlOptions(); + ArrayList errors = new ArrayList(); + validateOptions.setErrorListener(errors); + try { + assertTrue(gl.validate(validateOptions)); + } catch (Throwable t) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < errors.size(); i++) { + XmlError error = (XmlError) errors.get(i); + + sb.append("Message: " + error.getMessage() + "\n"); + if (error.getCursorLocation() != null) + System.out.println("Location of invalid XML: " + + error.getCursorLocation().xmlText() + "\n"); + } + throw new Exception(" Validation failed " + sb.toString()); + } + + assertEquals("DALLAS", gl.getCityName().getStringValue()); + assertEquals("TX", gl.getStateOrProvinceCode()); + LocationIdentifier li = gl.getLocationIdentifier(); + assertNotNull("Cursor0: LocationIdentifier unexpectedly null", li); + assertEquals(CodeList309.FR, gl.getLocationIdentifier().getQualifier()); + assertEquals("xyz", gl.getCountrySubdivisionCode()); + + + for (int i = 1; i < 3; i++) { + aCursors[i].removeXml(); + aCursors[0].copyXml(aCursors[i]); + // must move to PrevElement to get to the START of the copied section. + aCursors[i].toPrevSibling(); + + gl = (GeographicLocation) aCursors[i].getObject(); + + assertEquals("DALLAS", gl.getCityName().getStringValue()); + assertEquals("TX", gl.getStateOrProvinceCode()); + li = gl.getLocationIdentifier(); + assertNotNull("Cursor " + i + ": LocationIdentifier unexpectedly null", li); + assertEquals(CodeList309.FR, gl.getLocationIdentifier().getQualifier()); + assertEquals("xyz", gl.getCountrySubdivisionCode()); + } + + } finally { + xc.dispose(); + for (int i = 0; i < 3; i++) { + aCursors[i].dispose(); + } + } + } +} + + diff --git a/test/src/xmlcursor/detailed/MultipleCopyTest.java b/src/test/java/xmlcursor/detailed/MultipleCopyTest.java similarity index 79% rename from test/src/xmlcursor/detailed/MultipleCopyTest.java rename to src/test/java/xmlcursor/detailed/MultipleCopyTest.java index 125236e..a94214e 100755 --- a/test/src/xmlcursor/detailed/MultipleCopyTest.java +++ b/src/test/java/xmlcursor/detailed/MultipleCopyTest.java @@ -14,45 +14,27 @@ */ -package xmlcursor.detailed; +package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import xmlcursor.common.*; - - -import tools.util.JarUtil; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; import org.tranxml.tranXML.version40.CodeList309; +import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; import org.tranxml.tranXML.version40.LocationIdentifierDocument.LocationIdentifier; +import tools.util.JarUtil; +import xmlcursor.common.Common; +import static org.junit.Assert.*; -/** - * - * - */ -public class MultipleCopyTest extends TestCase { - public MultipleCopyTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(MultipleCopyTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } +public class MultipleCopyTest { + @Test public void testMultipleCopy() throws Exception { CarLocationMessageDocument clm = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); assertNotNull(clm); XmlCursor xc = clm.newCursor(); XmlCursor[] aCursors = new XmlCursor[3]; diff --git a/test/src/xmlcursor/detailed/MultipleCursorSetTest.java b/src/test/java/xmlcursor/detailed/MultipleCursorSetTest.java similarity index 75% rename from test/src/xmlcursor/detailed/MultipleCursorSetTest.java rename to src/test/java/xmlcursor/detailed/MultipleCursorSetTest.java index c47a409..405ab95 100755 --- a/test/src/xmlcursor/detailed/MultipleCursorSetTest.java +++ b/src/test/java/xmlcursor/detailed/MultipleCursorSetTest.java @@ -16,35 +16,19 @@ package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlString; import org.apache.xmlbeans.XmlCursor.TokenType; -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlString; +import org.junit.Test; import tools.util.JarUtil; +import xmlcursor.common.Common; +import static org.junit.Assert.*; -/** - * - * - */ -public class MultipleCursorSetTest extends TestCase { - public MultipleCursorSetTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(MultipleCursorSetTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } +public class MultipleCursorSetTest { + @Test public void testMultipleCursorSet() throws Exception { XmlCursor xc = XmlObject.Factory.parse(JarUtil.getResourceFromJar( Common.TRANXML_FILE_CLM)).newCursor(); @@ -61,13 +45,13 @@ public void testMultipleCursorSet() throws Exception { } for (int i = 0; i < 6; i++) { for (int j = 0; j != i && j < 6; j++) { - assertEquals(false, aCursors[i].isAtSamePositionAs(aCursors[j])); + assertFalse(aCursors[i].isAtSamePositionAs(aCursors[j])); } } xs.setStringValue("XYZ"); for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { - assertEquals(true, aCursors[i].isAtSamePositionAs(aCursors[j])); + assertTrue(aCursors[i].isAtSamePositionAs(aCursors[j])); } // System.out.println(aCursors[i].currentTokenType()); // assertEquals(null, aCursors[i].getTextValue()); diff --git a/test/src/xmlcursor/detailed/NamespaceForPrefixTest.java b/src/test/java/xmlcursor/detailed/NamespaceForPrefixTest.java similarity index 83% rename from test/src/xmlcursor/detailed/NamespaceForPrefixTest.java rename to src/test/java/xmlcursor/detailed/NamespaceForPrefixTest.java index f877791..181bb35 100755 --- a/test/src/xmlcursor/detailed/NamespaceForPrefixTest.java +++ b/src/test/java/xmlcursor/detailed/NamespaceForPrefixTest.java @@ -16,45 +16,18 @@ package xmlcursor.detailed; -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlOptions; - -import java.util.Map; -import java.util.HashMap; -import javax.xml.namespace.QName; - -import java.util.Vector; - -import xmlcursor.common.*; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; -import java.net.URL; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; - -/** - * - * - */ public class NamespaceForPrefixTest extends BasicCursorTestCase { - public NamespaceForPrefixTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(NamespaceForPrefixTest.class); - } - + @Test public void testNamespaceForPrefixFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -69,6 +42,7 @@ public void testNamespaceForPrefixFromSTARTDOC() throws Exception { assertEquals("uri3", m_xc.namespaceForPrefix("pre3")); } + @Test public void testNamespaceForPrefixFromSTARTDOCInvalid() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -78,9 +52,10 @@ public void testNamespaceForPrefixFromSTARTDOCInvalid() throws Exception { m_xc.insertNamespace("pre3", "uri3"); m_xc.insertNamespace(null, "uridefault"); m_xc.toStartDoc(); - assertEquals(null, m_xc.namespaceForPrefix("pre4")); + assertNull(m_xc.namespaceForPrefix("pre4")); } + @Test public void testNamespaceForPrefixFromSTARTDOCNull() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -93,6 +68,7 @@ public void testNamespaceForPrefixFromSTARTDOCNull() throws Exception { assertEquals("uridefault", m_xc.namespaceForPrefix(null)); } + @Test public void testNamespaceForPrefixFromSTARTDOCEmptyString() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -105,6 +81,7 @@ public void testNamespaceForPrefixFromSTARTDOCEmptyString() throws Exception { assertEquals("uridefault", m_xc.namespaceForPrefix("")); } + @Test public void testNamespaceForPrefixFromSTART() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -114,6 +91,7 @@ public void testNamespaceForPrefixFromSTART() throws Exception { m_xc.namespaceForPrefix("xsi")); } + @Test public void testNamespaceForPrefixFromSTARTdefaultNamespace() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -123,6 +101,7 @@ public void testNamespaceForPrefixFromSTARTdefaultNamespace() throws Exception { m_xc.namespaceForPrefix("")); } + @Test(expected = IllegalStateException.class) public void testNamespaceForPrefixFromATTR() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -136,15 +115,12 @@ public void testNamespaceForPrefixFromATTR() throws Exception { m_xc.toNextSelection(); m_xc.toFirstAttribute(); - try { - m_xc.namespaceForPrefix(null); - fail("Expected IllegalStateException"); - } catch (IllegalStateException iae) { - } + m_xc.namespaceForPrefix(null); //assertEquals("nsa", m_xc.namespaceForPrefix(null)); // assertEquals("uri1", m_xc.namespaceForPrefix("pre1")); } + @Test(expected = IllegalStateException.class) public void testNamespaceForPrefixFromEND() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -155,11 +131,7 @@ public void testNamespaceForPrefixFromEND() throws Exception { m_xc.insertNamespace("pre3", "uri3"); m_xc.insertNamespace(null, "uridefault"); toNextTokenOfType(m_xc, TokenType.END); - try { - m_xc.namespaceForPrefix(null); - fail("Expected IllegalStateException"); - } catch (IllegalStateException iae) { - } + m_xc.namespaceForPrefix(null); // assertEquals("nsa", m_xc.namespaceForPrefix(null)); // assertEquals("uri1", m_xc.namespaceForPrefix("pre1")); } diff --git a/src/test/java/xmlcursor/detailed/ObjectCursorInteractionTest.java b/src/test/java/xmlcursor/detailed/ObjectCursorInteractionTest.java new file mode 100755 index 0000000..088be6e --- /dev/null +++ b/src/test/java/xmlcursor/detailed/ObjectCursorInteractionTest.java @@ -0,0 +1,176 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import test.xbean.xmlcursor.location.LocationDocument; +import test.xbean.xmlcursor.location.LocationDocument.Location; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class ObjectCursorInteractionTest { + @Test + public void testObjectNullEffectOnCursor() throws Exception { + String sNamespace = ""; + String sXml = + "DALLASTX" + + ""; + + // LocationDocument locDoc = (LocationDocument) XmlObject.Factory.parse(sXml); + LocationDocument locDoc = LocationDocument.Factory.parse(sXml); + Location loc = locDoc.getLocation(); + XmlCursor xc0 = loc.newCursor(); + assertEquals("DALLAS", loc.getCityName()); + loc = null; + System.gc(); + try { + Thread.sleep(1000); + xc0.toFirstChild(); + assertEquals("DALLAS", xc0.getTextValue()); + } finally { + xc0.dispose(); + } + } + + @Test + public void testCursorDisposalEffectOnObject() throws Exception { + String sNamespace = "xmlns:loc=\"http://xbean.test/xmlcursor/Location\""; + String sXml = "" + + "DALLASTX"; + LocationDocument locDoc = LocationDocument.Factory.parse( + sXml); + assertTrue(locDoc.validate()); + Location loc0 = locDoc.getLocation(); + Location loc1 = locDoc.getLocation(); + XmlCursor xc0 = loc0.newCursor(); + XmlCursor xc1 = loc1.newCursor(); + + xc0.toFirstChild(); + xc1.toFirstChild(); + xc0.setTextValue("AUSTIN"); + try { + assertEquals("AUSTIN", loc0.getCityName()); + loc1.setCityName("SAN ANTONIO"); + xc0.dispose(); + assertEquals("SAN ANTONIO", xc1.getTextValue()); + xc1.setTextValue("HOUSTON"); + xc1.dispose(); + assertEquals("HOUSTON", loc0.getCityName()); + } finally { + xc0.dispose(); + xc1.dispose(); + } + } + + @Test + public void testObjectRefAssignmentEffectOnCursor() throws Exception { + String sXml0 = + "" + + "DALLAS" + + "TX" + + ""; + String sXml1 = + "" + + "90210" + + "US" + + ""; + LocationDocument locDoc0 = LocationDocument.Factory.parse( + sXml0); + Location loc0 = locDoc0.getLocation(); + XmlCursor xc0 = loc0.newCursor(); + + LocationDocument locDoc1 = (LocationDocument) XmlObject.Factory.parse( + sXml1); + Location loc1 = locDoc1.getLocation(); + + assertEquals("DALLAS", loc0.getCityName()); + assertEquals("TX", loc0.getStateCode()); + assertNull(loc0.getPostalCode()); + assertNull(loc0.getCountryCode()); + + loc0 = loc1; + + assertNull(loc0.getCityName()); + assertNull(loc0.getStateCode()); + assertEquals("90210", loc0.getPostalCode()); + assertEquals("US", loc0.getCountryCode()); + + try { + assertEquals(sXml0, xc0.xmlText()); + xc0 = loc0.newCursor(); + assertEquals(sXml1, xc0.xmlText()); + } finally { + xc0.dispose(); + } + } + + @Test + public void testCursorRefAssignmentEffectOnObject() throws Exception { + String sXml0 = + "" + + "DALLAS" + + "TX" + + ""; + LocationDocument locDoc0 = LocationDocument.Factory.parse( + sXml0); + Location loc0 = locDoc0.getLocation(); + XmlCursor xc0 = loc0.newCursor(); + + String sXml1 = + "" + + "90210" + + "US" + + ""; + LocationDocument locDoc1 = LocationDocument.Factory.parse( + sXml1); + Location loc1 = locDoc1.getLocation(); + XmlCursor xc1 = loc1.newCursor(); + + try { + assertEquals("DALLAS", loc0.getCityName()); + assertEquals("TX", loc0.getStateCode()); + assertNull(loc0.getPostalCode()); + assertNull(loc0.getCountryCode()); + + xc0 = xc1; + + assertEquals("DALLAS", loc0.getCityName()); + assertEquals("TX", loc0.getStateCode()); + assertNull(loc0.getPostalCode()); + assertNull(loc0.getCountryCode()); + + loc0 = (Location) xc0.getObject(); + + assertNull(loc0.getCityName()); + assertNull(loc0.getStateCode()); + assertEquals("90210", loc0.getPostalCode()); + assertEquals("US", loc0.getCountryCode()); + + } finally { + xc0.dispose(); + xc1.dispose(); + } + } + +} + diff --git a/test/src/xmlcursor/detailed/PrefixForNamespaceTest.java b/src/test/java/xmlcursor/detailed/PrefixForNamespaceTest.java similarity index 86% rename from test/src/xmlcursor/detailed/PrefixForNamespaceTest.java rename to src/test/java/xmlcursor/detailed/PrefixForNamespaceTest.java index 85bdb5c..95b59d0 100755 --- a/test/src/xmlcursor/detailed/PrefixForNamespaceTest.java +++ b/src/test/java/xmlcursor/detailed/PrefixForNamespaceTest.java @@ -18,27 +18,16 @@ import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import tools.util.JarUtil; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; +import static org.junit.Assert.assertEquals; -/** - * - * - */ -public class PrefixForNamespaceTest extends BasicCursorTestCase { - - public PrefixForNamespaceTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(PrefixForNamespaceTest.class); - } +public class PrefixForNamespaceTest extends BasicCursorTestCase { + @Test public void testprefixForNamespaceFromSTARTDOC() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -53,6 +42,7 @@ public void testprefixForNamespaceFromSTARTDOC() throws Exception { assertEquals("pre3", m_xc.prefixForNamespace("uri3")); } + @Test public void testprefixForNamespaceFromSTARTDOCInvalid() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -65,26 +55,21 @@ public void testprefixForNamespaceFromSTARTDOCInvalid() throws Exception { assertEquals("uri4", m_xc.prefixForNamespace("uri4")); } + @Test(expected = IllegalArgumentException.class) public void testprefixForNamespaceFromSTARTDOCNull() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); - try { - m_xc.prefixForNamespace(null); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } + m_xc.prefixForNamespace(null); } + @Test(expected = IllegalArgumentException.class) public void testprefixForNamespaceFromSTARTDOCEmptyString() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); - try { - m_xc.prefixForNamespace(""); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } + m_xc.prefixForNamespace(""); } + @Test public void testprefixForNamespaceFromSTART() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -94,6 +79,7 @@ public void testprefixForNamespaceFromSTART() throws Exception { m_xc.prefixForNamespace("http://www.w3.org/2000/10/XMLSchema-instance")); } + @Test public void testprefixForNamespaceFromSTARTdefaultNamespace() throws Exception { m_xo = XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); @@ -103,6 +89,7 @@ public void testprefixForNamespaceFromSTARTdefaultNamespace() throws Exception { m_xc.prefixForNamespace("http://www.tranxml.org/TranXML/Version4.0")); } + @Test public void testprefixForNamespaceFromATTR() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -112,12 +99,13 @@ public void testprefixForNamespaceFromATTR() throws Exception { m_xc.insertNamespace("pre3", "uri3"); m_xc.insertNamespace(null, "uridefault"); m_xc.toStartDoc(); - m_xc.selectPath("default element namespace=\"nsa\"" + "$this//bar"); + m_xc.selectPath("declare default element namespace \"nsa\";" + "$this//bar"); m_xc.toFirstAttribute(); assertEquals("nsa", m_xc.prefixForNamespace("nsa")); assertEquals("pre1", m_xc.prefixForNamespace("uri1")); } + @Test public void testprefixForNamespaceFromEND() throws Exception { m_xo = XmlObject.Factory.parse("text"); m_xc = m_xo.newCursor(); @@ -131,7 +119,5 @@ public void testprefixForNamespaceFromEND() throws Exception { assertEquals("", m_xc.prefixForNamespace("nsa")); // assertEquals("pre1", m_xc.prefixForNamespace("uri1")); } - - } diff --git a/src/test/java/xmlcursor/detailed/PushPopTest.java b/src/test/java/xmlcursor/detailed/PushPopTest.java new file mode 100755 index 0000000..90ef0e4 --- /dev/null +++ b/src/test/java/xmlcursor/detailed/PushPopTest.java @@ -0,0 +1,53 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + + +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PushPopTest extends BasicCursorTestCase { + + private String sDoc = " 32.18 "; + + @Test + public void testPopEmpty() { + assertFalse(m_xc.pop()); + } + + @Test + public void testPushNTimes() { + int nCount = 100; + for (int i = 0; i < nCount; i++) + m_xc.push(); + boolean result = true; + for (int i = 0; i < nCount; i++) + result &= m_xc.pop(); + assertTrue(result); + assertFalse(m_xc.pop()); + } + + @Before + public void setUp() throws Exception { + m_xc = XmlObject.Factory.parse(sDoc).newCursor(); + } +} diff --git a/src/test/java/xmlcursor/detailed/SelectionsTest.java b/src/test/java/xmlcursor/detailed/SelectionsTest.java new file mode 100755 index 0000000..deb2cf8 --- /dev/null +++ b/src/test/java/xmlcursor/detailed/SelectionsTest.java @@ -0,0 +1,133 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlcursor.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import test.xbean.xmlcursor.cr196679.TestDocument; +import test.xbean.xmlcursor.cr196679.TestType; +import xmlcursor.common.BasicCursorTestCase; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + + +public class SelectionsTest extends BasicCursorTestCase { + + private static final String sXml="0123456"; + + //average case test + @Test + public void testNormalCase() throws Exception { + XmlCursor m_xc1 = m_xo.newCursor(); + int nSelectionsCount = 7; + m_xc.selectPath("$this//a"); + assertFalse(m_xc.hasNextSelection()); + assertFalse(m_xc.toNextSelection()); + assertEquals(0, m_xc.getSelectionCount()); + + m_xc.selectPath("$this//b"); + m_xc1.toFirstChild(); + m_xc1.toFirstChild(); + do { + m_xc1.addToSelection(); + } while (m_xc1.toNextSibling()); + assertEquals(nSelectionsCount, m_xc.getSelectionCount()); + int i = 0; + while (m_xc.hasNextSelection()) { + m_xc.toNextSelection(); + assertEquals("" + i, m_xc.getTextValue()); + i++; + } + int j = 0; + while (m_xc1.hasNextSelection()) { + m_xc1.toSelection(j); + assertEquals("" + j, m_xc1.getTextValue()); + j++; + } + assertEquals(nSelectionsCount, j); + assertEquals(nSelectionsCount, i); + } + + @Test + public void testToSelectionIllegalIndex() { + m_xc.selectPath("$this//b"); + boolean result = m_xc.toSelection(-1); + assertFalse(result); + + try { + result = m_xc.toSelection(m_xc.getSelectionCount() + 1); + assertFalse("Index > num selections", result); + } catch (IllegalStateException e) { + } + + assertFalse("Index < 0 ", result); + + } + + @Test + public void testClearSelections() { + m_xc.selectPath("$this//b"); + m_xc.toSelection(0); + m_xc.clearSelections(); + assertEquals("0", m_xc.xmlText()); + + } + + @Test + public void testCR196679() throws Exception { + TestDocument testDoc = null; + String input = "\n" + + " myTest" + + " 5" + + " "; + testDoc = TestDocument.Factory.parse(input); + TestType test = testDoc.getTest(); + + String queryName = + "declare namespace ns='http://xbean.test/xmlcursor/CR196679'" + + "$this/ns:name"; + + String queryValue = + "declare namespace ns='http://xbean.test/xmlcursor/CR196679'" + + "$this/ns:value"; + + XmlCursor cursor = test.newCursor(); + cursor.push(); + cursor.selectPath(queryName); + cursor.toNextSelection(); + + assertEquals("myTest", cursor.getTextValue()); + + cursor.pop(); + cursor.selectPath(queryValue); + cursor.toNextSelection(); + + assertEquals("5", cursor.getTextValue());//expected output is value=5 + + cursor.dispose(); + + } + + @Before + public void setUp() throws Exception { + m_xo = XmlObject.Factory.parse(sXml); + m_xc = m_xo.newCursor(); + } +} diff --git a/test/src/xmlcursor/detailed/SetTextValueTest.java b/src/test/java/xmlcursor/detailed/SetTextValueTest.java similarity index 87% rename from test/src/xmlcursor/detailed/SetTextValueTest.java rename to src/test/java/xmlcursor/detailed/SetTextValueTest.java index 2b73c6a..9622434 100755 --- a/test/src/xmlcursor/detailed/SetTextValueTest.java +++ b/src/test/java/xmlcursor/detailed/SetTextValueTest.java @@ -15,33 +15,26 @@ package xmlcursor.detailed; -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; import xmlcursor.common.BasicCursorTestCase; import xmlcursor.common.Common; +import static org.junit.Assert.*; + /** * * */ public class SetTextValueTest extends BasicCursorTestCase { - String sDoc = Common.XML_FOO_NS_PREFIX; - - public SetTextValueTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SetTextValueTest.class); - } - /** * Depth first concatenation of all text leaves */ + @Test public void testSTARTDOC() { String sExpected = Common.XMLFRAG_BEGINTAG + "<newdoc/>" + Common.XMLFRAG_ENDTAG; @@ -51,6 +44,7 @@ public void testSTARTDOC() { assertEquals(sExpected, m_xc.xmlText()); } + @Test public void testSTART() { String sNewVal = "new test value "; String sExpected = "" + @@ -63,6 +57,7 @@ public void testSTART() { assertEquals(sExpected, m_xc.xmlText()); } + @Test public void testAttr() { String sNewVal = "US\u0024 "; String sExpected = " " + Common.XMLFRAG_ENDTAG;//the comment string + String sXPath = "//comment()"; + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(m_xc.xmlText(), sExpected); + } + + @Test + public void testNode() throws Exception { + String sInput = " footxt"; + m_xc = XmlObject.Factory.parse(sInput).newCursor(); + String sXPath = "//foo/node()"; + String[] sExpected = { + Common.XMLFRAG_BEGINTAG + " " + Common.XMLFRAG_ENDTAG, + "foo", + Common.XMLFRAG_BEGINTAG + "txt" + Common.XMLFRAG_ENDTAG + }; + m_xc.selectPath(fixPath(sXPath)); + int i = 0; + // assertEquals("node() failed", sExpected.length, m_xc.getSelectionCount()); + while (m_xc.hasNextSelection()) { + m_xc.toNextSelection(); + //assertEquals(m_xc.xmlText(), sExpected[i++]); + } + } + + @Test + public void testPI() throws Exception { + String sInput = Common.XML_FOO_PROCINST; + m_xc = XmlObject.Factory.parse(sInput).newCursor(); + String sXPath1 = "//processing-instruction()"; + String sXPath2 = "//processing-instruction(\"xml-stylesheet\")"; + String sXPath3 = "//processing-instruction(\"xsl\")"; + String sExpected1 = Common.XMLFRAG_BEGINTAG + "" + Common.XMLFRAG_ENDTAG; + String sExpected2 = ""; + m_xc.selectPath(fixPath(sXPath1)); + assertEquals(m_xc.getSelectionCount(), 1); + m_xc.toNextSelection(); + assertEquals(m_xc.xmlText(), sExpected1); + + + m_xc.clearSelections(); + m_xc.selectPath(fixPath(sXPath2)); + assertEquals(m_xc.xmlText(), sExpected1); + + m_xc.clearSelections(); + //shouldn't select any nodes + m_xc.selectPath(fixPath(sXPath3)); + assertEquals(m_xc.getSelectionCount(), 0); + } + + @Test + public void testText() throws Exception { + String sInput = "
      footext
      "; + m_xc = XmlObject.Factory.parse(sInput).newCursor(); + String sXPath = "//text()"; + String sExpected1 = Common.XMLFRAG_BEGINTAG + "foo" + Common.XMLFRAG_ENDTAG; + String sExpected2 = Common.XMLFRAG_BEGINTAG + "text" + Common.XMLFRAG_ENDTAG; + m_xc.selectPath(sXPath); + assertEquals(m_xc.getSelectionCount(), 2); + m_xc.toNextSelection(); + assertEquals(m_xc.xmlText(), sExpected1); + m_xc.toNextSelection(); + assertEquals(m_xc.xmlText(), sExpected2); + } + + @Test + public void testTextObject() throws Exception { + String sInput = "
      footext
      "; + m_xo = XmlObject.Factory.parse(sInput); + String sXPath = "//text()"; + String sExpected1 = Common.XMLFRAG_BEGINTAG + "footext" + Common.XMLFRAG_ENDTAG; + String sExpected2 = Common.XMLFRAG_BEGINTAG + "text" + Common.XMLFRAG_ENDTAG; + XmlObject[] res = m_xo.selectPath(sXPath); + assertEquals(res.length, 2); + assertEquals(res[0].xmlText(), sExpected1); + assertEquals(res[1].xmlText(), sExpected2); + } +} + + diff --git a/src/test/java/xmlcursor/xpath/complex/checkin/ContainerCommentTest.java b/src/test/java/xmlcursor/xpath/complex/checkin/ContainerCommentTest.java new file mode 100644 index 0000000..9b43ae1 --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/checkin/ContainerCommentTest.java @@ -0,0 +1,71 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.xpath.complex.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; + +/** + * This class tests the execution of an XQuery where the + * starting point of the query is a comment + */ +public class ContainerCommentTest { + @Test + public void testFunctionPathWithCursor() throws Exception { + String sXml = + "" + + "" + + "\n" + + " \n" + + " Fred Jones\n" + + "

      \n" + + " 900 Aurora Ave.\n" + + " Seattle\n" + + " WA\n" + + " 98115\n" + + "
      \n" + + " (425)555-5665\n" + + " (206)555-5555\n" + + " (206)555-4321\n" + + " \n" + + " "; + + XmlObject employees = XmlObject.Factory.parse(sXml); + String m_namespaceDeclaration = + "declare namespace xq='http://xmlbeans.apache.org/samples/xquery/employees';"; + + XmlCursor cursor = employees.newCursor(); + cursor.toNextToken(); + + cursor.selectPath(m_namespaceDeclaration + "$this//xq:employee"); + if (cursor.getSelectionCount() > 0) { + cursor.toNextSelection(); + + String[] names = new String[cursor.getSelectionCount()]; + + for (int i = 0; i < cursor.getSelectionCount(); i++) { + XmlCursor nameCursor = cursor.newCursor(); + nameCursor.selectPath(m_namespaceDeclaration + + "$this/xq:name/text()"); + nameCursor.toNextSelection(); + names[i] = nameCursor.getTextValue(); + cursor.toNextSelection(); + System.out.println(names[i]); + } + } + } + +} diff --git a/src/test/java/xmlcursor/xpath/complex/checkin/XPathTests.java b/src/test/java/xmlcursor/xpath/complex/checkin/XPathTests.java new file mode 100755 index 0000000..32e1d81 --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/checkin/XPathTests.java @@ -0,0 +1,152 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xpath.complex.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import xmlcursor.xpath.common.XPathCommon; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +@RunWith(Parameterized.class) +public class XPathTests { + static final String XML = + "" + + "" + + "" + + "" + + " " + + " " + + "" + + " "; + + private static final String[] STEPS = { + /* 0 */ "", + /* 1 */ " ", + /* 2 */ "", + /* 3 */ " ", + /* 4 */ "", + /* 5 */ " ", + /* 6 */ "", + /* 7 */ "", + /* 8 */ "", + /* 9 */ " ", + /* 10 */ " ", + /* 11 */ " " + }; + + private static final String XMLFRAG_EMPTY = ""; + private static XmlObject doc; + + @Parameter + public String xpath = null; + @Parameter(value = 1) + public String[] expected = null; + + @BeforeClass + public static void init() throws XmlException { + doc = XmlObject.Factory.parse(XML); + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + final List data = new ArrayList<>(); + + add(data, "/doc/a/@test", STEPS[2]); + add(data, "//.", XML, STEPS[1], STEPS[2], STEPS[5], XMLFRAG_EMPTY, STEPS[10], XMLFRAG_EMPTY, STEPS[8]); + add(data, "/doc", STEPS[1]); + add(data, "/doc/a", STEPS[2]); + add(data, "//@*", STEPS[3], STEPS[6], STEPS[7]); + add(data, ".", XML); + add(data, "//ancestor-or-self::*", XML, STEPS[2], STEPS[5], STEPS[10]); + add(data, "./child::*[1]", STEPS[1]); + add(data, "//descendant-or-self::*/@*[1]", STEPS[2], STEPS[6]); + + // This is tricky: + // The expression "*" is true for the principal axis: since the axis is self, so we're looking for elements: doc + // elt node() also returns the doc elt, but also the comment nodes in the union set are returned in doc order + add(data, "//@* | * | node()", STEPS[1], STEPS[3], STEPS[6], STEPS[7], STEPS[8]); + + add(data, "//*", STEPS[1], STEPS[2], STEPS[5], STEPS[4]); + add(data, "/doc/n", (String) null); + add(data, "//descendant::comment()", STEPS[8]); + add(data, "//*[local-name()='a']", STEPS[2], STEPS[4]); + add(data, "//*/@*", STEPS[3], STEPS[6], STEPS[7]); + add(data, "//*[last()]", STEPS[1], STEPS[5], STEPS[4]); + add(data, "doc/*[last()]", STEPS[5]); + + // TODO: BUGBUG: fix this + add(data, "/doc/a/*/@*", (String) null); + + add(data, "doc/descendant::node()", STEPS[2], STEPS[5], STEPS[11], STEPS[10], STEPS[11]); + add(data, "doc/a/@*", STEPS[2]); + add(data, "doc/b/a/ancestor-or-self::*", STEPS[1], STEPS[5], STEPS[4]); + add(data, "doc/b/a/preceding::*", STEPS[2]); + add(data, "doc/a/following::*", STEPS[5], STEPS[4]); + add(data, "/doc/b/preceding-sibling::*", STEPS[2]); + add(data, "/doc/a/following-sibling::*", STEPS[5]); + + // "/doc/namespace::*", STEPS[0],DEFAULT_NS}; + + return data; + } + + private static void add(List data, String xpath, String... expected) { + data.add(new Object[]{xpath, expected}); + } + + + @Test + public void testConformance() { + XmlCursor actual = doc.newCursor(); + try { + actual.selectPath(xpath); + + if (actual.getSelectionCount() == 0) { + assertNull(expected[0]); + return; + } + + XmlObject[] expXO = Stream.of(expected).map(XPathTests::parse).toArray(XmlObject[]::new); + XPathCommon.compare(actual, expXO); + } finally { + actual.dispose(); + } + } + + private static XmlObject parse(String str) { + try { + return XmlObject.Factory.parse(str); + } catch (XmlException e) { + fail(e.getMessage()); + return null; + } + } +} diff --git a/src/test/java/xmlcursor/xpath/complex/checkin/XPathTestsMisc.java b/src/test/java/xmlcursor/xpath/complex/checkin/XPathTestsMisc.java new file mode 100644 index 0000000..64b64a1 --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/checkin/XPathTestsMisc.java @@ -0,0 +1,35 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xpath.complex.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; + +public class XPathTestsMisc { + + @Test + public void testDelete() throws Exception { + String query = "*"; + + XmlCursor xc = XmlObject.Factory.parse(XPathTests.XML).newCursor(); + xc.selectPath(query); + while (xc.toNextSelection()) { + System.out.println(xc.xmlText()); + } + } + +} diff --git a/test/src/xmlcursor/xpath/complex/detailed/DeclareNamespaceTest.java b/src/test/java/xmlcursor/xpath/complex/detailed/DeclareNamespaceTest.java similarity index 78% rename from test/src/xmlcursor/xpath/complex/detailed/DeclareNamespaceTest.java rename to src/test/java/xmlcursor/xpath/complex/detailed/DeclareNamespaceTest.java index 060c7dc..caa725e 100644 --- a/test/src/xmlcursor/xpath/complex/detailed/DeclareNamespaceTest.java +++ b/src/test/java/xmlcursor/xpath/complex/detailed/DeclareNamespaceTest.java @@ -12,22 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package xmlcursor.xpath.complex.detailed; +package xmlcursor.xpath.complex.detailed; -import org.apache.xmlbeans.*; -import junit.framework.TestCase; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlLong; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import xmlcursor.common.Common; -/** - * - */ -public class DeclareNamespaceTest - extends TestCase -{ +import static org.junit.Assert.*; - public static void testDeclareNSPath() - throws Exception - { +public class DeclareNamespaceTest { + + @Test + public void testDeclareNSPath() throws Exception { XmlObject s = XmlObject.Factory.parse( "foobar"); XmlObject[] res; @@ -50,14 +49,13 @@ public static void testDeclareNSPath() c1.toFirstContentToken(); XmlObject o = c1.getObject(); - assertTrue(o != res[0]); + assertNotSame(o, res[0]); assertEquals(res[0].xmlText(), ""); } - public static void testDefaultNSPath() - throws Exception - { + @Test + public void testDefaultNSPath() throws Exception { XmlObject s = XmlObject.Factory.parse( "foobar"); XmlObject[] res; @@ -75,13 +73,12 @@ public static void testDefaultNSPath() c1.toFirstContentToken(); XmlObject o = c1.getObject(); - assertTrue(o != res[0]); + assertNotSame(o, res[0]); assertEquals(res[0].xmlText(), "bar"); } - public void testSequence() - throws Exception - { + @Test + public void testSequence() throws Exception { XmlObject o = XmlObject.Factory.parse( "foobar"); XmlObject[] res = null; @@ -101,16 +98,14 @@ public void testSequence() a = ((XmlLong) res[0]); expXml = "10"; assertEquals(expXml, a.xmlText()); - for (int i = 1; i < 5; i++) - { + for (int i = 1; i < 5; i++) { a = ((XmlLong) res[i]); assertEquals(Common.wrapInXmlFrag(i + ""), a.xmlText()); } } - public void testSequenceUnion() - throws Exception - { + @Test + public void testSequenceUnion() throws Exception { XmlObject o = XmlObject.Factory.parse("11"); XmlObject[] res = o.selectPath("//a union //b"); assertEquals(2, res.length); @@ -123,9 +118,8 @@ public void testSequenceUnion() assertEquals("1", a.xmlText()); } - public void testSequenceIntersect() - throws Exception - { + @Test + public void testSequenceIntersect() throws Exception { XmlCursor o = XmlObject.Factory.parse("11").newCursor(); o.selectPath("//b intersect //b"); assertEquals(1, o.getSelectionCount()); @@ -133,9 +127,8 @@ public void testSequenceIntersect() assertEquals("1", o.xmlText()); } - public void testSequenceExcept() - throws Exception - { + @Test + public void testSequenceExcept() throws Exception { XmlCursor o = XmlObject.Factory.parse("11").newCursor(); o.selectPath("/a except /a"); assertEquals(0, o.getSelectionCount()); @@ -148,18 +141,10 @@ public void testSequenceExcept() //If an operand of union, intersect, or except // contains an item that is not a node, a type error is raised. - public void testSequenceTypeError() - throws Exception - { - try - { - XmlCursor o = XmlObject.Factory.parse("").newCursor(); - o.selectPath("(0 to 4) except (0 to 4)"); - fail("Type error expected"); - } - catch (Throwable t) - { - } + @Test(expected = RuntimeException.class) + public void testSequenceTypeError() throws XmlException { + XmlCursor o = XmlObject.Factory.parse("").newCursor(); + o.selectPath("(0 to 4) except (0 to 4)"); + o.toNextSelection(); } - } diff --git a/src/test/java/xmlcursor/xpath/complex/detailed/NodeCopyTest.java b/src/test/java/xmlcursor/xpath/complex/detailed/NodeCopyTest.java new file mode 100644 index 0000000..8ac7da4 --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/detailed/NodeCopyTest.java @@ -0,0 +1,109 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.xpath.complex.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlLong; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Test; +import xbean.scomp.element.globalEltDefault.GlobalEltDefaultIntDocument; + +import static org.junit.Assert.*; + +public class NodeCopyTest { + + @Test + public void testNS() throws Exception { + XmlObject s = XmlObject.Factory.parse("foobar"); + XmlObject[] res; + /* + res=s.selectPath("./a"); + assertTrue(s.selectChildren("","a")[0] == res[0] ); + assertEquals( res[0].xmlText(),"foobar"); + //"for $e in ./a return { $e } " + */ + XmlCursor s1 = s.newCursor().execQuery("./a"); + assertEquals("foobar", s1.xmlText()); + + res = s.execQuery("./a"); + XmlCursor c1 = s.newCursor(); + c1.toFirstContentToken(); + + XmlObject o = c1.getObject(); + assertNotSame(o, res[0]); + assertEquals("foobar", res[0].xmlText()); + } + + @Test + public void testText() throws Exception { + XmlObject s = XmlObject.Factory.parse("barfoo"); + XmlObject[] res; + res = s.selectPath(".//text()"); + assertEquals(2, res.length); + assertEquals("bar", res[0].xmlText()); + assertEquals("foo", res[1].xmlText()); + } + + @Test + public void testCount() throws Exception { + XmlObject s = XmlObject.Factory.parse("barfoo"); + XmlObject[] res; + res = s.selectPath("count(.//b)"); + System.out.println(res[0].xmlText()); + XmlLong i = (XmlLong) res[0]; + assertEquals((long) 1, i.getLongValue()); + // res= s.selectPath("//b"); + } + + @Test + @Ignore + public void testInt() throws Exception { + GlobalEltDefaultIntDocument d = + GlobalEltDefaultIntDocument.Factory + .parse("" + + "3" + + ""); + d.getGlobalEltDefaultInt(); + } + + @Test + public void testXmlObjectSelectPath() { + + } + + @Test + public void testDeleteMe() throws Exception { + XmlObject t = XmlObject.Factory.parse(""); + XmlCursor cursor = + t.newCursor(); + System.out.println(cursor.getObject()); + // use xpath to select elements + cursor.selectPath("*/*"); + + System.out.println("cnt " + cursor.getSelectionCount()); + // iterate over the selection + while (cursor.toNextSelection()) { + // two views of the same data: + // move back and forth between XmlObject <-> XmlCursor + XmlObject trans = cursor.getObject(); + + System.out.println("Trans " + trans.xmlText()); + System.out.println("xmlText " + cursor.xmlText()); + + } + + } +} diff --git a/src/test/java/xmlcursor/xpath/complex/detailed/TypesTest.java b/src/test/java/xmlcursor/xpath/complex/detailed/TypesTest.java new file mode 100644 index 0000000..323bf99 --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/detailed/TypesTest.java @@ -0,0 +1,128 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.xpath.complex.detailed; + +import org.apache.xmlbeans.*; +import org.junit.Before; +import org.junit.Test; + +import java.util.Calendar; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class TypesTest { + private XmlObject o; + private XmlObject[] res; + + @Before + public void setUp() + throws Exception { + o = XmlObject.Factory.parse(""); + } + + @Test + public void testDate() { + res = o.selectPath("xs:date(\"2000-01-01\")"); + assertEquals(1, res.length); + Calendar d = ((XmlDate) res[0]).getCalendarValue(); + assertEquals(2000, d.get(Calendar.YEAR)); +// assertEquals( +// "Fri Dec 31 16:00:00 PST 1999", +// d.xmlText()); + } + + @Test + public void testDecimal() { + res = o.selectPath( + "seconds-from-dateTime(xs:dateTime('1997-07-16T19:20:30+01:00'))"); + assertEquals(1, res.length); + XmlDecimal dec = ((XmlDecimal) res[0]); + assertEquals("30", dec.xmlText()); + } + + //Saxon returns string here, though the string is a valid duration + //representation + @Test + public void testDuration() { + res = o.selectPath("xs:dayTimeDuration(\"PT12H\")*4"); + assertEquals(1, res.length); + System.out.println(res[0].schemaType()); + String s = res[0].xmlText(); + System.out.println(s); + int i = s.indexOf("(\""); + int j = s.indexOf("\")"); + assertTrue(0 < i); + assertTrue(i < j); + String duration = s.substring(i + 2, j); + System.out.println(duration); + GDurationSpecification gDur = new GDurationBuilder(duration); + System.out.println(gDur.getDay()); + assertEquals(2, gDur.getDay()); + } + + @Test + public void testTypes() throws Exception { + XmlObject o = XmlObject.Factory.parse( + "foobar"); + XmlObject[] res = null; + + //Long + res = o.selectPath("hours-from-dateTime(" + + "current-dateTime()) cast as xs:integer"); + assertEquals(1, res.length); + System.out.println(res[0].schemaType()); + XmlLong xl = ((XmlLong) res[0]); + System.out.println(xl.xmlText()); + + //Java type is string... + res = o.selectPath("current-time()"); + assertEquals(1, res.length); + System.out.println(res[0].schemaType()); + System.out.println(res[0].xmlText()); + XmlTime time = XmlTime.Factory.parse(res[0].xmlText()); + System.out.println(time.xmlText()); + + /* + res = o.selectPath("subtract-dateTimes-yielding-dayTimeDuration(" + + "current-dateTime()," + + "current-dateTime())"); + assertEquals(1, res.length); + XmlDuration dur = ((XmlDuration) res[0]); + System.out.println(dur.xmlText()); + */ + //Java type is long--is query right? + res = o.selectPath("xs:byte(3)"); + assertEquals(1, res.length); + System.out.println(res[0].schemaType()); //xs:long + //XmlByte b = ((XmlByte) res[0]); + //System.out.println(b.xmlText()); + + //Java type is string + res = o.selectPath("base-uri(/a)"); + assertEquals(1, res.length); + System.out.println(res[0].schemaType()); //xs:string + XmlAnyURI u = XmlAnyURI.Factory.parse(res[0].xmlText()); + System.out.println(u.xmlText()); + + //java type is Date + res = o.selectPath("current-dateTime()"); + assertEquals(1, res.length); + System.out.println(res[0].schemaType()); + XmlDate dt = ((XmlDate) res[0]); + System.out.println(dt.xmlText()); + } + +} diff --git a/test/src/xmlcursor/xpath/complex/detailed/XPathExpressionTestImpl.java b/src/test/java/xmlcursor/xpath/complex/detailed/XPathExpressionTestImpl.java similarity index 83% rename from test/src/xmlcursor/xpath/complex/detailed/XPathExpressionTestImpl.java rename to src/test/java/xmlcursor/xpath/complex/detailed/XPathExpressionTestImpl.java index 3527073..09c9d70 100755 --- a/test/src/xmlcursor/xpath/complex/detailed/XPathExpressionTestImpl.java +++ b/src/test/java/xmlcursor/xpath/complex/detailed/XPathExpressionTestImpl.java @@ -15,54 +15,38 @@ package xmlcursor.xpath.complex.detailed; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; import xmlcursor.common.Common; import xmlcursor.xpath.common.XPathExpressionTest; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; +import static org.junit.Assert.*; /** * Verifies XPath with Expressions * http://www.w3schools.com/xpath/xpath_expressions.asp */ -public class XPathExpressionTestImpl - extends XPathExpressionTest -{ - public XPathExpressionTestImpl(String name) - { - super(name); - } - - public String getQuery(String testName, int testCase) - throws IllegalArgumentException - { - Object queries; - - if ((queries = testMap.get(testName)) == null) - throw new IllegalArgumentException("No queries for test" + - testName); - else if (((String[]) queries).length <= testCase) - throw new IllegalArgumentException("No query " + testCase + - " for test" + testName); - else - return ((String[]) queries)[testCase]; +public class XPathExpressionTestImpl extends XPathExpressionTest { + public String getQuery(String testName, int testCase) throws IllegalArgumentException { + String[] queries = testMap.get(testName); + assertNotNull("No queries for test", queries); + assertFalse("No query " + testCase + " for test" + testName, queries.length <= testCase); + return queries[testCase]; } - private void verifySelection(XmlCursor c, String[] expected) - { + private void verifySelection(XmlCursor c, String[] expected) { int count = c.getSelectionCount(); assertEquals(expected.length, count); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { c.toNextSelection(); assertEquals(expected[i], c.xmlText()); } } - public void testForExpression() - throws Exception - { + @Test + public void testForExpression() throws Exception { String sXml = "\n" + " \n" + " TCP/IP Illustrated\n" + @@ -102,9 +86,8 @@ public void testForExpression() verifySelection(c, exp); } - public void testFor_1() - throws Exception - { + @Test + public void testFor_1() throws Exception { XmlCursor c = XmlObject.Factory.parse("").newCursor(); String query = "for $i in (10, 20),\n" + " $j in (1, 2)\n" + @@ -119,9 +102,8 @@ public void testFor_1() verifySelection(c, expected); } - public void testFor_2() - throws Exception - { + @Test + public void testFor_2() throws Exception { XmlCursor c = XmlObject.Factory.parse("").newCursor(); String query = "sum (for $i in (10, 20)" + "return $i)"; @@ -131,9 +113,8 @@ public void testFor_2() assertEquals(Common.wrapInXmlFrag("30"), c.xmlText()); } - public void testIf() - throws Exception - { + @Test + public void testIf() throws Exception { XmlCursor c = XmlObject.Factory.parse("" + "Pooh" + "Pooh" + @@ -165,9 +146,8 @@ public void testIf() assertEquals("Maid", c.xmlText()); } - public void testQuantifiedExpression() - throws Exception - { + @Test + public void testQuantifiedExpression() throws Exception { XmlCursor c = XmlObject.Factory.parse("").newCursor(); String query = "some $x in (1, 2, 3), $y in (2, 3, 4) " + @@ -177,5 +157,4 @@ public void testQuantifiedExpression() c.toNextSelection(); assertEquals("true", c.xmlText()); } - } diff --git a/src/test/java/xmlcursor/xpath/complex/detailed/XPathFunctionAuxTest.java b/src/test/java/xmlcursor/xpath/complex/detailed/XPathFunctionAuxTest.java new file mode 100755 index 0000000..5f08728 --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/detailed/XPathFunctionAuxTest.java @@ -0,0 +1,256 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xpath.complex.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; +import xmlcursor.xpath.common.XPathCommon; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Verifies XPath using functions + * http://www.w3schools.com/xpath/xpath_functions.asp + */ + +public class XPathFunctionAuxTest extends BasicCursorTestCase { + + private static String fixPath(String path) { + return path; + } + + @Test + public void testFunctionCount_caseB() throws Exception { + XmlObject xDoc = XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/cdcatalog.xml")); + + String ex1Simple = "count(//cd)"; + String ex1R1 = Common.XMLFRAG_BEGINTAG + "26" + Common.XMLFRAG_ENDTAG; + XmlObject[] exXml1 = new XmlObject[]{XmlObject.Factory.parse(ex1R1)}; + + System.out.println("Test 1: " + ex1Simple); + XmlCursor x1 = xDoc.newCursor(); + x1.selectPath(ex1Simple); + XPathCommon.display(x1); + XPathCommon.compare(x1, exXml1); + x1.dispose(); + } + + @Test + public void testFunctionConcat_caseB() throws Exception { + String sXml = "3.00" + + "23.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "concat(name(//bar[position()=1]/*[position()=last()])," + + "//price[position()=1]/text())"; + String sExpected = Common.wrapInXmlFrag("price3.00"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionStringLength_caseB() throws Exception { + String sXml = "3.0023.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "string-length(name(//bar/*[last()]))"; + String sExpected = Common.wrapInXmlFrag("price".length() + ""); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionSubString_caseB() throws Exception { + String sXml = "3.0023.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "substring(name(//bar[position()=1]/*[position()=1]),3,3)"; + String sExpected = Common.wrapInXmlFrag("ice"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(XmlCursor.TokenType.TEXT, + m_xc.currentTokenType()); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionSubStringAfter_caseB() throws Exception { + String sXml = "3.0023.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "substring-after(name(//bar[position()=1]/*[position()=1]),'pr')"; + String sExpected = Common.wrapInXmlFrag("ice"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionSubStringBefore_caseB() throws Exception { + String sXml = "3.0023.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "substring-before(" + + "name(//bar[position()=1]/*[position()=1]),'ice')"; + String sExpected = Common.wrapInXmlFrag("pr"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionTranslate_caseB() throws Exception { + String sXml = "3.0023.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "translate(//bar[position()=1]/price[position()=1]/text()," + + "'200'," + + "'654')";//0 is now 5 &&4? + String sExpected = Common.wrapInXmlFrag("3.55"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionNumber_caseB() throws Exception { + String sXml = "3.003.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + String sXPath = "number(//price/text())+10"; + String sExpected = Common.wrapInXmlFrag("13.0"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionRound_caseB() throws Exception { + String sXml = "3.152.873.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "round(//bar/price[position()=1]/text())"; + String sExpected = Common.wrapInXmlFrag("3.0"); + m_xc.selectPath(fixPath(sXPath)); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionSum_caseB() throws Exception { + String sXml = "3.0023.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "sum(//bar/price)"; + String sExpected = Common.wrapInXmlFrag("5.0"); + m_xc.selectPath(sXPath); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } + + @Test + public void testFunctionBoolean_caseB_delete() throws Exception { + String sXml = "" + + "3.00" + + "2" + + "3.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + + String sXPath = "boolean(//foo/text())"; + m_xc.selectPath(sXPath); + System.out.println(m_xc.getSelectionCount()); + assertTrue(m_xc.toNextSelection()); + assertEquals(Common.wrapInXmlFrag("false"), + m_xc.xmlText()); + assertTrue(!m_xc.toNextSelection()); + System.out.println("DOC " + m_xc.xmlText()); + m_xc.clearSelections(); + m_xc.toStartDoc(); + m_xc.selectPath("boolean(//price/text())"); +// m_xc.selectPath("$this//bar"); + m_xc.toNextSelection(); + // System.out.println("HERE " + m_xc.xmlText()); + } + + @Test + public void testFunctionBoolean_caseB() throws Exception { + String sXml = "" + + "3.00" + + "2" + + "3.00"; + m_xc = XmlObject.Factory.parse(sXml).newCursor(); + XmlCursor _startPos = m_xc.newCursor(); + + String sXPath = "boolean(//foo/text())";//"boolean(//foo/text())"; + m_xc.push(); + m_xc.selectPath(sXPath); + m_xc.toNextSelection(); + assertEquals(Common.wrapInXmlFrag("false"), + m_xc.xmlText()); + m_xc.clearSelections(); + + //need to reset cursor since it's on a bool outside the doc + m_xc.pop(); + //number + m_xc.selectPath("boolean(//price/text())"); + m_xc.toNextSelection(); + assertEquals(Common.wrapInXmlFrag("true"), m_xc.xmlText()); + m_xc.clearSelections(); + + + //number + assertTrue(m_xc.toCursor(_startPos)); + //boolean of Nan is false + m_xc.selectPath("boolean(number(name(//price[position()=last()])))"); + m_xc.toNextSelection(); + assertEquals(Common.wrapInXmlFrag("false"), m_xc.xmlText()); + m_xc.clearSelections(); + + //node-set + m_xc.toCursor(_startPos); + m_xc.selectPath("boolean(//price)"); + m_xc.toNextSelection(); + assertEquals(Common.wrapInXmlFrag("true"), m_xc.xmlText()); + m_xc.clearSelections(); + + m_xc.toCursor(_startPos); + m_xc.selectPath("boolean(//barK)"); + m_xc.toNextSelection(); + assertEquals(Common.wrapInXmlFrag("false"), m_xc.xmlText()); + m_xc.clearSelections(); + } + + @Test + public void testFunctionFalse_caseB() throws Exception { + m_xc = + XmlObject.Factory.parse( + "3.00") + .newCursor(); + m_xc.selectPath("name(//*[boolean(text())=false()])"); + String sExpected = Common.wrapInXmlFrag("foo"); + m_xc.toNextSelection(); + assertEquals(sExpected, m_xc.xmlText()); + } +} diff --git a/test/src/xmlcursor/xpath/complex/detailed/XPathFunctionTestImpl.java b/src/test/java/xmlcursor/xpath/complex/detailed/XPathFunctionTestImpl.java similarity index 82% rename from test/src/xmlcursor/xpath/complex/detailed/XPathFunctionTestImpl.java rename to src/test/java/xmlcursor/xpath/complex/detailed/XPathFunctionTestImpl.java index 3cd5452..7bcda45 100755 --- a/test/src/xmlcursor/xpath/complex/detailed/XPathFunctionTestImpl.java +++ b/src/test/java/xmlcursor/xpath/complex/detailed/XPathFunctionTestImpl.java @@ -15,21 +15,22 @@ package xmlcursor.xpath.complex.detailed; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; import xmlcursor.xpath.common.XPathFunctionTest; -import org.apache.xmlbeans.XmlObject; +import static org.junit.Assert.*; /** * Queries here overwrite whatever is loaded in the query map if * the syntax is different */ -public class XPathFunctionTestImpl - extends XPathFunctionTest -{ - public XPathFunctionTestImpl(String name) - { - super(name); +public class XPathFunctionTestImpl extends XPathFunctionTest { + @Before + public void setUp() throws Exception { + super.setUp(); testMap.put("testFunctionCount", new String[]{ "count(//cd)", @@ -73,49 +74,32 @@ public XPathFunctionTestImpl(String name) "//*[boolean(@at)=true()]"}); } - public String getQuery(String testName, int testCase) - throws IllegalArgumentException - { - Object queries; - - if ((queries = testMap.get(testName)) == null) - throw new IllegalArgumentException("No queries for test" + - testName); - else if (((String[]) queries).length <= testCase) - throw new IllegalArgumentException("No query " + testCase + - " for test" + testName); - else - return ((String[]) queries)[testCase]; + public String getQuery(String testName, int testCase) throws IllegalArgumentException { + String[] queries = testMap.get(testName); + assertNotNull("No queries for test" + testName, queries); + assertFalse("No query " + testCase + " for test" + testName, queries.length <= testCase); + return queries[testCase]; } - public void testErrorMessages() - throws Exception - { + @Test + public void testErrorMessages() throws Exception { //do nothing for Jaxen } //ensure Jaxen is not in the classpath - public void testAntiJaxenTest() - { - try - { - m_xc.selectPath("//*"); - fail("XQRL shouldn't handle absolute paths"); - } - catch (Throwable t) - { - } + @Test(expected = Throwable.class) + public void testAntiJaxenTest() { + // XQRL shouldn't handle absolute paths + m_xc.selectPath("//*"); } - public void testExternalVariable() - throws Exception - { + @Test + public void testExternalVariable() throws Exception { } - public void testExternalFunction() - throws Exception - { + @Test + public void testExternalFunction() throws Exception { String query = "" + "declare function local:toc($book-or-section as element()) as element()*;" + " local:toc($book-or-section/section)"; @@ -173,5 +157,4 @@ public void testExternalFunction() assertEquals(1, res.length); assertEquals("", res[0].xmlText()); } - } diff --git a/test/src/xmlcursor/xpath/complex/detailed/XPathNodeTest.java b/src/test/java/xmlcursor/xpath/complex/detailed/XPathNodeTest.java similarity index 81% rename from test/src/xmlcursor/xpath/complex/detailed/XPathNodeTest.java rename to src/test/java/xmlcursor/xpath/complex/detailed/XPathNodeTest.java index 35b27ad..3fb770d 100644 --- a/test/src/xmlcursor/xpath/complex/detailed/XPathNodeTest.java +++ b/src/test/java/xmlcursor/xpath/complex/detailed/XPathNodeTest.java @@ -14,23 +14,20 @@ */ package xmlcursor.xpath.complex.detailed; -import javax.xml.namespace.QName; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; -import junit.framework.TestCase; +import org.junit.Test; import xmlcursor.common.Common; -/** - * - */ -public class XPathNodeTest - extends TestCase -{ - public void testNodeEquality() - throws Exception - { - XmlCursor c = XmlObject.Factory.parse("" + - "") +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; + +public class XPathNodeTest { + @Test + public void testNodeEquality() throws Exception { + XmlCursor c = XmlObject.Factory.parse( + "") .newCursor(); c.selectPath("//book[@isbn='012345'] is //book[@id='09876']"); assertEquals(1, c.getSelectionCount()); @@ -38,11 +35,10 @@ public void testNodeEquality() assertEquals(Common.wrapInXmlFrag("true"), c.xmlText()); } - public void testNodeOrder() - throws Exception - { - XmlCursor c = XmlObject.Factory.parse("" + - "") + @Test + public void testNodeOrder() throws Exception { + XmlCursor c = XmlObject.Factory.parse( + "") .newCursor(); c.selectPath("//book[@isbn='012345'] << //book[@id='09876']"); assertEquals(1, c.getSelectionCount()); @@ -55,9 +51,8 @@ public void testNodeOrder() assertEquals(Common.wrapInXmlFrag("false"), c.xmlText()); } - public void testParent() - throws Exception - { + @Test + public void testParent() throws Exception { String input = ""; XmlObject o; XmlCursor c = XmlObject.Factory.parse(input).newCursor(); @@ -71,10 +66,9 @@ public void testParent() assertEquals("", res[0].newCursor().xmlText()); } - public void testParent1() - throws Exception - { - String input = + @Test + public void testParent1() throws Exception { + String input = "" + @@ -99,5 +93,4 @@ public void testParent1() assertEquals("http://www.eurecom.fr/security/xac#", qn.getNamespaceURI()); assertEquals("Content", qn.getLocalPart()); } - } diff --git a/src/test/java/xmlcursor/xpath/complex/detailed/XPathTest.java b/src/test/java/xmlcursor/xpath/complex/detailed/XPathTest.java new file mode 100755 index 0000000..2d78a7f --- /dev/null +++ b/src/test/java/xmlcursor/xpath/complex/detailed/XPathTest.java @@ -0,0 +1,221 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xpath.complex.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.xpath.common.XPathCommon; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Verifies XPath impl using examples from + * http://www.zvon.org/xxl/XPathTutorial/Output/example1.html + * includes expanded notations as well + * + */ +@RunWith(Parameterized.class) +public class XPathTest extends BasicCursorTestCase { + + @Parameter + public int dataset; + @Parameter(value = 1) + public String xpath; + @Parameter(value = 2) + public String[] expected = null; + + @Parameterized.Parameters(name = "{index}: zvon{0}.xml {1}") + public static Collection data() { + final List data = new ArrayList<>(); + add(data, 1, "/AAA", ""); + add(data, 1, "/AAA/CCC", "", ""); + add(data, 1, "/AAA/DDD/BBB", ""); + + add(data, 2, "//BBB", "", "", "", "", ""); + add(data, 2, "//DDD/BBB", "", "", ""); + + add(data, 3, "/AAA/CCC/DDD/*", "", "", "", ""); + add(data, 3, "/*/*/*/BBB", "", "", "", "", ""); + + //according to Galax the document order is : + add(data, 3, "//*", + "", + "", "", "", "", + "", "", "", "", + "", "", "", "", "", + "", "", ""); + + add(data, 4, "/AAA/BBB[1]", ""); + add(data, 4, "/AAA/BBB[last()]", ""); + + add(data, 5, "//@id", "", ""); + add(data, 5, "//BBB[@id]", "", ""); + add(data, 5, "//BBB[@name]", ""); + add(data, 5, "//BBB[@*]", "", "", ""); + add(data, 5, "//BBB[not(@*)]", ""); + + add(data, 6, "//BBB[@id='b1']", ""); + add(data, 6, "//BBB[@name='bbb']", ""); + add(data, 6, "//BBB[normalize-space(@name)='bbb']", "", ""); + + add(data, 7, "//*[count(BBB)=2]", ""); + add(data, 7, "//*[count(*)=2]", "", ""); + add(data, 7, "//*[count(*)=3]", + "", ""); + + add(data, 8, "//*[name()='BBB']", "", "", "", "", ""); + add(data, 8, "//*[starts-with(name(),'B')]", "", + "", "", "", "", "", ""); + + // ykadiysk: Jaxen prints in BF left-to-right order but XPath wants doc order + // add(data, "zvon8.xml", "//*[starts-with(name(),'B')]", "", + // "", "", "", "", "", ""); + + add(data, 8, "//*[contains(name(),'C')]", "", "", ""); + + add(data, 9, "//*[string-length(name()) = 3]", "", ""); + add(data, 9, "//*[string-length(name()) < 3]", "", ""); + add(data, 9, "//*[string-length(name()) > 3]", "", "", ""); + + add(data, 10, "$this//CCC | $this//BBB", "", "", ""); + // Nodes are returned in document order + add(data, 10, "$this/AAA/EEE | $this//BBB", "", ""); + add(data, 10, "./AAA/EEE |.//DDD/CCC | ./AAA | .//BBB", "", + "", "", ""); + + add(data, 11, "/AAA", ""); + add(data, 11, "/child::AAA", ""); + add(data, 11, "/AAA/BBB", ""); + add(data, 11, "/child::AAA/child::BBB", ""); + add(data, 11, "/child::AAA/BBB", ""); + + add(data, 12, "/descendant::*", + "", + "", "", + "", "", "", "", + "", "", "", ""); + add(data, 12, "/AAA/BBB/descendant::*", "", + "", "", ""); + add(data, 12, "//CCC/descendant::*", "", "", "", + "", "", ""); + add(data, 12, "//CCC/descendant::DDD", "", "", ""); + + add(data, 13, "//DDD/parent::*", "", + "", "", ""); + + add(data, 14, "/AAA/BBB/DDD/CCC/EEE/ancestor::*", + "", + "", "", ""); + add(data, 14, "//FFF/ancestor::*", + "", + "", "", + "", ""); + + add(data, 15, "/AAA/BBB/following-sibling::*", + "", ""); + add(data, 15, "//CCC/following-sibling::*", "", "", ""); + + add(data, 16, "/AAA/XXX/preceding-sibling::*", ""); + add(data, 16, "//CCC/preceding-sibling::*", "", + "", "", ""); + + add(data, 17, "/AAA/XXX/following::*", "", ""); + add(data, 17, "//ZZZ/following::*", "", "", + "", + "", "", "", "", "", + "", "", "", ""); + + + // the preceding axis contains all nodes that are descendants of the root of the tree in which the context + // node is found, are not ancestors of the context node, and occur before the context node in document order + add(data, 18, "/AAA/XXX/preceding::*", "", "", + "", ""); + add(data, 18, "//GGG/preceding::*", "", "", + "", "", "", "", "", ""); + + + add(data, 19, "/AAA/XXX/descendant-or-self::*", "", + "", "", "", "", "", "", ""); + add(data, 19, "//CCC/descendant-or-self::*", "", "", "", ""); + + + add(data, 20, "/AAA/XXX/DDD/EEE/ancestor-or-self::*", + "", + "", + "", ""); + add(data, 20, "//GGG/ancestor-or-self::*", + "", + "", + "", "", ""); + + add(data, 21, "//GGG/ancestor::*", + "", + "", + "", + ""); + add(data, 21, "//GGG/descendant::*", "", "", ""); + add(data, 21, "//GGG/following::*", "", "", ""); + add(data, 21, "//GGG/preceding::*", "", "", "", "", ""); + add(data, 21, "//GGG/self::*", ""); + add(data, 21, "//GGG/ancestor::* | //GGG/descendant::* | //GGG/following::* | //GGG/preceding::* | //GGG/self::*", + "", + "", "", "", "", + "", "", + "", "", "", + "", "", "", "", "", ""); + + add(data, 22, "//BBB[position() mod 2 = 0 ]", "", "", "", ""); + add(data, 22, "//BBB[ position() = floor(last() div 2 + 0.5) or position() = ceiling(last() div 2 + 0.5) ]", + "", ""); + add(data, 22, "//CCC[ position() = floor(last() div 2 + 0.5) or position() = ceiling(last() div 2 + 0.5) ]", + ""); + + return data; + } + + private static void add(List data, int dataset, String xpath, String... expected) { + data.add(new Object[]{dataset, xpath, expected}); + } + + + @Test + public void zvonExample() throws IOException, XmlException { + XmlObject xDoc = XmlObject.Factory.parse(JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon"+dataset+".xml")); + XmlCursor x1 = xDoc.newCursor(); + try { + x1.selectPath(xpath); + + XmlObject[] exp = new XmlObject[expected.length]; + for (int i = 0; i < expected.length; i++) { + exp[i] = XmlObject.Factory.parse(expected[i]); + } + + XPathCommon.compare(x1, exp); + } finally { + x1.dispose(); + } + } +} diff --git a/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/AxesTest.java b/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/AxesTest.java new file mode 100755 index 0000000..203407a --- /dev/null +++ b/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/AxesTest.java @@ -0,0 +1,379 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xpath.xbean_xpath.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Axes Tested: + * child + * descendant + * attribute + * descendant-or-self + * self + * namespace + */ +public class AxesTest { + private final String sXmlChild = + " " + + "txt child"; + + private final XmlOptions options = new XmlOptions(); + + private final String sXmlDesc = + " " + + "txt child"; + + @Before + public void setUp() { + options.setXPathUseXmlBeans(); + } + + @Test + public void testChildAxisAbbrev() throws XmlException { + String sQuery1 = "./foo/bar"; + String sExpected = + "" + + "txt child"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + + sQuery1 = "$this/foo/child::bar"; + c.clearSelections(); + c.toStartDoc(); + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testChildAxis() throws XmlException { + String sQuery1 = "./foo/child::bar"; + String sExpected = + "" + + "txt child"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testChildAxisDot() throws XmlException { + String sQuery1 = "$this/foo/./bar"; + String sExpected = + "" + + "txt child"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testChildAxisDNE() throws XmlException { + String sQuery1 = "$this/foo/./baz"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + c.selectPath(sQuery1, options); + assertEquals(0, c.getSelectionCount()); + } + + @Test + @Ignore + public void testDescendantAxis() throws XmlException { + String sQuery1 = "./descendant::foo"; + String sExpected = "" + + "txt child"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testDescendantAxisAbbrev() throws XmlException { + String sQuery1 = ".//foo"; + String sExpected = "" + + "txt child"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testDescAxisDot() throws XmlException { + String sQuery1 = "$this/descendant::foo/."; + String sExpected = "" + + "txt child"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testDescAxisDNE() throws XmlException { + String sQuery1 = "$this/descendant::baz"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1, options); + assertEquals(0, c.getSelectionCount()); + } + + @Test + public void testChildAttribute() throws XmlException { + String sExpected = ""; + String sQuery1 = "$this/foo/bar/attribute::at0"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testChildAttributeAbbrev() throws XmlException { + String sExpected = ""; + String sQuery1 = "$this/foo/bar/@at0"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testDescAttribute() throws XmlException { + String sExpected = ""; + String sQuery1 = "$this//attribute::at0"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testDescendantOrSelfAxis() throws XmlException { + + String sQuery1 = "./descendant-or-self::foo"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + String[] sExpected = { + c.xmlText() + , "" + + "txt child" + }; + + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(2, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected[0], c.xmlText()); + c.toNextSelection(); + assertEquals(sExpected[1], c.xmlText()); + + + } + + @Test + @Ignore + public void testDescendantOrSelfAxisDot() throws XmlException { + String sQuery1 = "./descendant-or-self::foo"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + String[] sExpected = new String[] + { + c.xmlText() + , "" + + "txt child" + }; + + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1, options); + + c.selectPath(sQuery1, options); + assertEquals(2, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected[0], c.xmlText()); + c.toNextSelection(); + assertEquals(sExpected[1], c.xmlText()); + } + + @Test + @Ignore + public void testDescendantOrSelfAxisDNE() throws XmlException { + + String sQuery1 = "$this/descendant-or-self::baz"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1, options); + assertEquals(0, c.getSelectionCount()); + + } + + @Test + @Ignore + public void testSelfAxis() throws XmlException { + String sQuery1 = "$this/self::foo"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + String sExpected = + c.xmlText(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + public void testSelfAxisAbbrev() throws XmlException { + String sQuery1 = "."; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = + c.xmlText(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testSelfAxisDot() throws XmlException { + + String sQuery1 = "./self::foo"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + String sExpected = + c.xmlText(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testSelfAxisDNE() throws XmlException { + + String sQuery1 = "$this/self::baz"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1, options); + assertEquals(0, c.getSelectionCount()); + + } + + @Test + @Ignore + public void testNamespaceAxis() throws XmlException { + + String sQuery1 = "$this/namespace::http://uri.com"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + String sExpected = + c.xmlText(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals(XmlCursor.TokenType.TEXT, c.toNextToken()); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testNamespaceAxisDot() throws XmlException { + + String sQuery1 = "./*/namespace::http://uri.com"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + String sExpected = + c.xmlText(); + + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + + c.selectPath(sQuery1, options); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testNamespaceAxisDNE() throws XmlException { + + String sQuery1 = "$this/namespace::*"; + XmlCursor c = XmlObject.Factory.parse(sXmlDesc).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals(XmlCursor.TokenType.TEXT, c.toNextToken()); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + //to namespace + assertEquals(XmlCursor.TokenType.NAMESPACE, c.toNextToken()); + c.selectPath(sQuery1, options); + assertEquals(0, c.getSelectionCount()); + } +} + diff --git a/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/NodeTest.java b/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/NodeTest.java new file mode 100755 index 0000000..bbd4c6d --- /dev/null +++ b/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/NodeTest.java @@ -0,0 +1,201 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xpath.xbean_xpath.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Nodes Tested: + * + * NameTest + * "*" + * NCName:* + * QName + * NodeType + * comment + * node + * pi + * text + * PI(Literal) + */ +public class NodeTest { + + private String sXmlChild = + " " + + "txt child" + + ""; + + private String sXmlPI = + ""; + + + @Test + public void testNameTestStar() throws XmlException { + String sQuery1 = "./*"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = c.xmlText(); + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + + } + + @Test + public void testNameTestNCName() throws XmlException { + String sQuery1 = "$this//*"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = ""; + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.toNextToken(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("bar", c.getName().getLocalPart()); + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + + } + + @Test + public void testNameTestQName_1() throws XmlException { + String sQuery1 = "declare namespace pre=\"http://uri.com\"; $this//pre:*"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = + ""; + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + assertEquals("foo", c.getName().getLocalPart()); + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + + } + + //test a QName that DNE + @Test + public void testNameTestQName_2() throws XmlException { + String sQuery1 = "declare namespace pre=\"http://uri\"; $this//pre:baz"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1); + assertEquals(0, c.getSelectionCount()); + + + } + + @Test + public void testNameTestQName_3() throws XmlException { + String sQuery1 = "$this//bar"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = "" + + "txt child"; + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + + } + + @Test + public void testNodeTypeComment() { + + } + + + @Test + public void testNodeTypeNodeAbbrev() throws XmlException { + String sQuery1 = "$this/foo/*"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = "" + + "txt child"; + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + /** + * Will not support natively + */ + @Test + @Ignore + public void testNodeTypeNode() throws XmlException { + String sQuery1 = "$this/foo/node()"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = "" + + "txt child"; + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testNodeTypePI() throws XmlException { + + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = ""; + String sQuery = "./foo/processing-instruction()"; + c.selectPath(sQuery); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testNodeTypeText() throws XmlException { + String sQuery1 = "$this//text()"; + XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); + String sExpected = " "; + assertEquals(XmlCursor.TokenType.START, c.toNextToken()); + c.selectPath(sQuery1); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testPI() throws XmlException { + XmlCursor c = XmlObject.Factory.parse(sXmlPI).newCursor(); + String sExpected = ""; + String sQuery = "./foo/processing-instruction('xml-stylesheet')"; + c.selectPath(sQuery); + assertEquals(1, c.getSelectionCount()); + c.toNextSelection(); + assertEquals(sExpected, c.xmlText()); + } + + @Test + @Ignore + public void testPIDNE() throws XmlException { + XmlCursor c = XmlObject.Factory.parse(sXmlPI).newCursor(); + String sQuery = "./foo/processing-instruction('stylesheet')"; + c.selectPath(sQuery); + assertEquals(0, c.getSelectionCount()); + } +} diff --git a/test/src/xmlcursor/xpath/xbean_xpath/detailed/README.txt b/src/test/java/xmlcursor/xpath/xbean_xpath/detailed/README.txt similarity index 100% rename from test/src/xmlcursor/xpath/xbean_xpath/detailed/README.txt rename to src/test/java/xmlcursor/xpath/xbean_xpath/detailed/README.txt diff --git a/src/test/java/xmlcursor/xquery/checkin/QueryEngineTests.java b/src/test/java/xmlcursor/xquery/checkin/QueryEngineTests.java new file mode 100644 index 0000000..04d09fc --- /dev/null +++ b/src/test/java/xmlcursor/xquery/checkin/QueryEngineTests.java @@ -0,0 +1,32 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.xquery.checkin; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class QueryEngineTests { + // Execute repeated queries to test picking up of the query engine from classpath + // This test is following rev 292446 + @Test + public void testQueryEngineSelection() throws Exception { + XmlObject o = XmlObject.Factory.parse(""); + XmlObject[] res = o.execQuery("(//a/b)"); + String expectedRes = ""; + assertEquals(expectedRes, res[0].xmlText()); + } +} diff --git a/src/test/java/xmlcursor/xquery/detailed/NISTTest.java b/src/test/java/xmlcursor/xquery/detailed/NISTTest.java new file mode 100644 index 0000000..5df5213 --- /dev/null +++ b/src/test/java/xmlcursor/xquery/detailed/NISTTest.java @@ -0,0 +1,132 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.xquery.detailed; + +import common.Common; +import noNamespace.TestCase; +import noNamespace.TestSuiteDocument; +import noNamespace.TestSuiteDocument.TestSuite.TestGroup; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import static org.junit.Assert.assertEquals; + +@Ignore("Too many XMLBeans unrelated errors") +@RunWith(Parameterized.class) +public class NISTTest { + + private static ZipFile zf; + + @Rule + public final QueryFailed queryLog = new QueryFailed(); + + @SuppressWarnings("DefaultAnnotationParam") + @Parameterized.Parameter(value = 0) + public String groupName; + + @Parameterized.Parameter(value = 1) + public String testName; + + @Parameterized.Parameter(value = 2) + public TestCase testCase; + + private String query; + + @Parameterized.Parameters(name = "{index}: {0} {1}") + public static Iterable files() throws IOException, XmlException { + zf = new ZipFile(Common.getCaseLocation()+"/xbean/xmlcursor/xquery/xmlQuery.zip"); + + ZipEntry e = zf.getEntry("testSuite/NIST/files/catalog.xml"); + InputStream is = zf.getInputStream(e); + TestSuiteDocument doc = TestSuiteDocument.Factory.parse(is); + + List files = new ArrayList(); + for (TestGroup xg : doc.getTestSuite().getTestGroupArray()) { + String groupName = xg.getName(); + for (TestCase tc : xg.getTestCaseArray()) { + String testName = tc.getName(); + files.add(new Object[]{groupName, testName, tc}); + + // NIST BUG: folder is called testSuite but appears as testsuite in desc. file + String filePath = tc.getFilePath() + .replaceAll("testsuite", "testSuite") + .replace((char) 92, '/'); + tc.setFilePath(filePath); + } + } + is.close(); + + return files; + } + + @Test + public void bla() throws Exception { + //bad comment syntax in suite + query = getString(testCase.getFilePath()+testCase.getName()+".xq") + .replace("{--", "(:") + .replace("--}", ":)"); + + XmlObject obj = XmlObject.Factory.parse(""); + String inputFile = testCase.getInputFileArray(0).getStringValue(); + assertEquals("emptyDoc", inputFile); + + // String outputFile = testCase.getFilePath()+testCase.getOutputFileArray(0).getStringValue(); + // XmlObject[] expRes = { XmlObject.Factory.parse(getString(outputFile)) }; + + XmlObject[] queryRes = obj.execQuery(query); + // XPathCommon.compare(queryRes, expRes); + } + + private static String getString(String zipFile) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ZipEntry queryFile = zf.getEntry(zipFile); + InputStream is = zf.getInputStream(queryFile); + byte[] buf = new byte[4096]; + for (int readBytes; (readBytes = is.read(buf)) > -1; ) { + bos.write(buf, 0, readBytes); + } + is.close(); + return new String(bos.toByteArray(), Charset.forName("UTF-8")); + } + + + + private class QueryFailed extends TestWatcher { + @Override + protected void failed(Throwable e, Description description) { + System.out.println( + "Description:\n"+ + testCase.getQuery().getDescription().getStringValue()+ + "\n\nQuery:\n"+ + query); + } + } +} diff --git a/src/test/java/xmlcursor/xquery/detailed/StoreTestsXqrl.java b/src/test/java/xmlcursor/xquery/detailed/StoreTestsXqrl.java new file mode 100644 index 0000000..0e8e8f7 --- /dev/null +++ b/src/test/java/xmlcursor/xquery/detailed/StoreTestsXqrl.java @@ -0,0 +1,177 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlcursor.xquery.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + + +//Used to be a checkin +public class StoreTestsXqrl { + private void doTokenTest(String xml) throws Exception { + XmlCursor c = XmlObject.Factory.parse(xml).newCursor(); + //String s = c.execQuery( "$this" ).xmlText(); + String s = c.execQuery(".").xmlText(); + assertEquals(s, xml); + } + + private void doSaveTest(String xml) throws Exception { + doTokenTest(xml); + } + + @Test + public void testSaving() throws Exception { + doSaveTest("1"); + doSaveTest(""); + doSaveTest("abcde"); + doSaveTest(""); + doSaveTest(""); + + String s = "aaabbb"; + s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s; + s = "xxxx" + s + ""; + + doSaveTest(s); + + XmlObject x = + XmlObject.Factory.parse(""); + + XmlCursor c = x.newCursor(); + + c.toFirstChild(); + c.toFirstChild(); + + assertEquals("", c.xmlText()); + + x = XmlObject.Factory.parse(""); + + c = x.newCursor(); + + c.toFirstChild(); + c.toFirstChild(); + + assertEquals("", c.xmlText()); + } + + @Test + private void testTextFrag(String actual, String expected) { + String pre = ""; + + String post = ""; + + assertTrue(actual.startsWith(pre)); + assertTrue(actual.endsWith(post)); + + assertEquals(expected, actual.substring( + pre.length(), actual.length() - post.length())); + } + + // + // Make sure XQuery works (tests the saver too) + // + @Test + public void testXQuery() + throws Exception { + XmlCursor c = + XmlObject.Factory.parse( + "12").newCursor(); + + String s = + c.execQuery("for $b in //bar order by ($b) " + + "descending return $b").xmlText(); + + testTextFrag(s, "21"); + + c = XmlObject.Factory.parse("").newCursor(); + c.toNextToken(); + c.toNextToken(); + c.insertElement("boo", "boo.com"); + c.toStartDoc(); + + assertEquals("", + c.execQuery(".").xmlText()); + } + + @Test + public void testPathing() throws Exception { + XmlObject x = + XmlObject.Factory.parse( + "123"); + + XmlCursor c = x.newCursor(); + + c.selectPath("//bar"); + + assertTrue(c.toNextSelection()); + assertEquals("1", c.xmlText()); + + assertTrue(c.toNextSelection()); + assertEquals("2", c.xmlText()); + + assertTrue(c.toNextSelection()); + assertEquals("3", c.xmlText()); + + assertTrue(!c.toNextSelection()); + + x = + XmlObject.Factory.parse( + ""); + + c = x.newCursor(); + + //c.selectPath( "$this//@x" ); + c.selectPath(".//@x"); + + assertTrue(c.toNextSelection()); + assertTrue(c.currentTokenType().isAttr()); + assertEquals("1", c.getTextValue()); + + assertTrue(c.toNextSelection()); + assertTrue(c.currentTokenType().isAttr()); + assertEquals("2", c.getTextValue()); + + assertTrue(c.toNextSelection()); + assertTrue(c.currentTokenType().isAttr()); + assertEquals("3", c.getTextValue()); + + assertTrue(!c.toNextSelection()); + + x = XmlObject.Factory.parse( + "123"); + + c = x.newCursor(); + + c.selectPath("//text()"); + + assertTrue(c.toNextSelection()); + assertTrue(c.currentTokenType().isText()); + assertEquals("1", c.getChars()); + + assertTrue(c.toNextSelection()); + assertTrue(c.currentTokenType().isText()); + assertEquals("2", c.getChars()); + + assertTrue(c.toNextSelection()); + assertTrue(c.currentTokenType().isText()); + assertEquals("3", c.getChars()); + + assertTrue(!c.toNextSelection()); + } +} diff --git a/src/test/java/xmlcursor/xquery/detailed/XQueryTest.java b/src/test/java/xmlcursor/xquery/detailed/XQueryTest.java new file mode 100644 index 0000000..664e46e --- /dev/null +++ b/src/test/java/xmlcursor/xquery/detailed/XQueryTest.java @@ -0,0 +1,308 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlcursor.xquery.detailed; + +import org.apache.xmlbeans.*; +import org.junit.Ignore; +import org.junit.Test; +import test.xbean.xmlcursor.xQueryInput.EmpT; +import tools.util.JarUtil; + +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class XQueryTest { + @Test + @Ignore("XQuery on Cursor is invalid") + public void testSimple() throws XmlException, IOException { + String xq = "for $e in //employee where $e/name='Bob' return $e "; + String xq1 = "for $e in //employee return $e "; + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + + XmlObject o = XmlObject.Factory.parse(input); + XmlCursor c = o.newCursor(); + XmlCursor c1 = c.execQuery(xq); + c1.toFirstContentToken(); + assertEquals("\n" + + "\t\tBob\n" + + "\t\t1000\n" + + "\t", c1.xmlText()); + + XmlObject[] res = o.execQuery(xq); + EmpT employeeType = (EmpT) res[0]; + assertEquals("Bob", employeeType.getName()); + } + + @Test + public void testObjConstruction() throws XmlException, IOException { + String query = JarUtil.getResourceFromJar("xbean/xmlcursor/xquery/Constructor.xq"); + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + XmlObject o = XmlObject.Factory.parse(input); + //via Object + XmlObject[] reslt = o.execQuery(query); + assertEquals(3, reslt.length); + assertEquals("Bob", + reslt[0].xmlText()); + assertEquals("Beth", + reslt[1].xmlText()); + assertEquals("NotBob", + reslt[2].xmlText()); + XmlCursor c = o.newCursor(); + + //via Cursor + /*XmlCursor c1=c.execQuery(query); + c1.toFirstContentToken(); + assertEquals("Bob", + c1.xmlText() ); + c1.toNextSibling(); + assertEquals("Beth", + c1.xmlText() ); + c1.dispose(); + c.dispose(); + */ + int i = 0; + while (i++ < 2) { + //via Cursor--new + XmlCursor c1 = c.execQuery(query); + //c.dispose(); + assertEquals(XmlCursor.TokenType.STARTDOC, c1.currentTokenType()); + assertEquals(XmlCursor.TokenType.START, c1.toNextToken()); + assertEquals("Bob", + c1.xmlText()); + // assertTrue(c1.toNextSelection()); + assertTrue(c1.toNextSibling()); + assertEquals("Beth", + c1.xmlText()); + //assertTrue(c1.toNextSelection()); + assertTrue(c1.toNextSibling()); + assertEquals("NotBob", + c1.xmlText()); + c1.dispose(); + } + c.dispose(); + } + + @Test + public void testJoin() throws XmlException, IOException { + String query = JarUtil.getResourceFromJar("xbean/xmlcursor/xquery/Join.xq"); + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + XmlObject o = XmlObject.Factory.parse(input); + XmlCursor c = o.newCursor(); + XmlCursor c1 = c.execQuery(query); + + // assertEquals(3, c1.getSelectionCount()); + c1.toFirstContentToken(); + assertEquals("" + + "1000,\n" + + "\t\tBob,\n" + + "\t\tNotBob" + + "", + c1.xmlText()); +/* assertEquals("" + + "" + + "1000,\n" + + "\t\tBob,\n" + + "\t\tNotBob" + + "" + + "1001,\n" + + "\t\tBeth,\n" + + "\t\t" + + "1000,\n" + + "\t\tNotBob,\n" + + "\t\tBob" + + "" + + "", + c1.xmlText() ); */ + c1.dispose(); + c.dispose(); + + XmlObject[] res = o.execQuery(query); + assertEquals(3, res.length); + } + + @Test + public void testTextSequenceRootObject() throws XmlException, IOException { + //String query = "$this//text()"; + String query = ".//text()"; + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + XmlObject o = XmlObject.Factory.parse(input); + XmlObject[] res = o.execQuery(query); + assertEquals(19, res.length); + input.close(); + } + + @Test + @Ignore("Cursor support for //text() is invalid") + public void testTextSequenceRootCursor() throws XmlException, IOException { + String query = ".//text()"; + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + XmlObject o = XmlObject.Factory.parse(input); + XmlCursor c = o.newCursor(); + XmlCursor c1 = c.execQuery(query); + assertEquals(XmlCursor.TokenType.TEXT,c1.toNextToken()); + // assertEquals() + //assertEquals(19, c1.getSelectionCount()); + c.dispose();//make sure this doesn't screw things up + while (c1.toNextSibling()) + assertEquals(XmlCursor.TokenType.TEXT, c1.currentTokenType()); + c1.toStartDoc(); + assertEquals("Bob", + c1.xmlText()); + c1.dispose(); + c.dispose(); + } + + @Test + @Ignore("still bugged") + public void testDocumentFunc() throws XmlException, IOException { + //String query = "{$this},{count(//employee)}"; + String query = "{.},{count(//employee)}"; + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + XmlCursor c = XmlObject.Factory.parse(input).newCursor(); + XmlCursor c1 = c.execQuery(query); + assertEquals("", + c1.xmlText()); + c1.dispose(); + c.dispose(); + } + + @Test + public void testTextAtOddPlaces() throws Exception { + //String query = "{$this},{count(//employee)}"; + String query = "{.},{count(//employee)}"; + String input = "textmore text"; + XmlObject o = XmlObject.Factory.parse(input); + XmlCursor c = o.newCursor(); + + XmlObject[] res = o.execQuery("//a"); + assertEquals("textmore text", res[0].xmlText()); + + XmlCursor cur = c.execQuery("//a"); + // assertEquals(1, cur.getSelectionCount()); + cur.toFirstContentToken(); + assertEquals("textmore text", cur.xmlText()); + } + + @Test + @Ignore + public void testMultiDocJoin() throws XmlException, IOException { + String query = JarUtil.getResourceFromJar("xbean/xmlcursor/xquery/2DocJoin.xq"); + InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); + XmlCursor c = XmlObject.Factory.parse(input).newCursor(); + XmlCursor c1 = c.execQuery(query); + assertEquals("", + c1.xmlText()); + c1.dispose(); + c.dispose(); + } + + @Test + public void testFunction() throws Exception { + String query = + " declare function local:summary($emps as element(employee)*) \n" + + " as element(dept)*\n" + + "{\n" + + " for $d in fn:distinct-values($emps/deptno)\n" + + " let $e := $emps[deptno = $d]\n" + + " return\n" + + " \n" + + " {$d}\n" + + " {fn:count($e)} \n" + + " {fn:sum($e/salary)} \n" + + " \n" + + "};\n" + + "\n" + + //"local:summary($this//employee[location = \"Denver\"])"; + "local:summary(.//employee[location = \"Denver\"])"; + + String xml = + " " + + "" + + "Denver" + + "7" + + "20" + + "" + + "" + + "Seattle" + + "6" + + "30" + + "" + + "" + + "Denver" + + "5" + + "40" + + "" + + "" + + "Denver" + + "7" + + "10" + + "" + + ""; + + XmlObject o = XmlObject.Factory.parse(xml); + XmlObject[] res = o.execQuery(query); + assertEquals(2, res.length); + assertEquals("7230", + res[0].xmlText()); + assertEquals("5140", + res[1].xmlText()); + XmlCursor c = o.newCursor(); + XmlCursor c1 = c.execQuery(query); + c1.toFirstContentToken(); + assertEquals(res[0].xmlText(), + c1.xmlText()); + c1.dispose(); + c.dispose(); + } + + @Test + public void testType() throws Exception { + String xml = ""; + String query = "count(//b)"; + XmlObject o = XmlObject.Factory.parse(xml); + XmlObject[] res = o.execQuery(query); + XmlLong result = (XmlLong) res[0]; + assertEquals("2", result.getStringValue()); + assertEquals(2, result.getLongValue()); + } + + @Test + public void testQueryComment() throws Exception { + String xml = ""; + String query = "(:comment:) count(//b)"; + XmlObject o = XmlObject.Factory.parse(xml); + XmlObject[] res = o.execQuery(query); + XmlLong result = (XmlLong) res[0]; + assertEquals("2", result.getStringValue()); + assertEquals(2, result.getLongValue()); + } + + @Test + @Ignore + public void testStandaloneFunction() throws Exception { + String query = + "\n" + + " {fn:not(xs:unsignedShort(\"65535\"))}\n" + + " "; + XmlObject o = XmlObject.Factory.newInstance(); + XmlObject[] res = o.execQuery(query); + XmlLong result = (XmlLong) res[0]; + assertEquals("2", result.getStringValue()); + assertEquals(2, result.getLongValue()); + } +} diff --git a/test/src/xmlcursor/xquery/detailed/XQueryVariableBindingTest.java b/src/test/java/xmlcursor/xquery/detailed/XQueryVariableBindingTest.java similarity index 79% rename from test/src/xmlcursor/xquery/detailed/XQueryVariableBindingTest.java rename to src/test/java/xmlcursor/xquery/detailed/XQueryVariableBindingTest.java index 4d7506b..9a57318 100644 --- a/test/src/xmlcursor/xquery/detailed/XQueryVariableBindingTest.java +++ b/src/test/java/xmlcursor/xquery/detailed/XQueryVariableBindingTest.java @@ -14,15 +14,17 @@ */ package xmlcursor.xquery.detailed; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - +import common.Common; +import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlCursor; +import org.junit.Test; -import common.Common; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; /** This class tests the use of XmlOptions in binding XQuery variables */ public class XQueryVariableBindingTest extends Common @@ -31,13 +33,7 @@ public class XQueryVariableBindingTest extends Common XBEAN_CASE_ROOT + P + "xmlcursor" + P + "xquery"; public static File dir = new File(XQUERY_CASE_DIR); - public XQueryVariableBindingTest(String name) - { - super(name); - } - - private XmlCursor _testDocCursor1() throws Exception - { + private XmlCursor _testDocCursor1() throws Exception { String xml = "" + "text11" + @@ -54,8 +50,7 @@ private XmlCursor _testDocCursor1() throws Exception return xc; } - private void _verifySelection(XmlCursor xc) - { + private void _verifySelection(XmlCursor xc) { assertEquals(3, xc.getSelectionCount()); assertTrue(xc.toNextSelection()); assertEquals("", xc.xmlText()); @@ -66,8 +61,8 @@ private void _verifySelection(XmlCursor xc) } /** test the automatic binding of $this to the current node: selectPath() */ - public void testThisVariable1() throws Exception - { + @Test + public void testThisVariable1() throws Exception { XmlCursor xc = _testDocCursor1(); xc.toFirstChild(); // xc.toFirstChild(); // @@ -79,8 +74,8 @@ public void testThisVariable1() throws Exception // this fails: see JIRA issue XMLBEANS-276 /** test the binding of a variable to the current node: selectPath() */ - public void testCurrentNodeVariable1() throws Exception - { + @Test + public void testCurrentNodeVariable1() throws Exception { XmlCursor xc = _testDocCursor1(); xc.toFirstChild(); xc.toFirstChild(); @@ -94,31 +89,27 @@ public void testCurrentNodeVariable1() throws Exception xc.dispose(); } - private XmlCursor _testDocCursor2() throws Exception - { + private XmlCursor _testDocCursor2() throws Exception { File f = new File(dir, "employees.xml"); XmlObject doc = XmlObject.Factory.parse(f); - XmlCursor xc = doc.newCursor(); - return xc; + return doc.newCursor(); } - public void _verifyQueryResult(XmlCursor qc) - { + public void _verifyQueryResult(XmlCursor qc) { System.out.println(qc.xmlText()); assertTrue(qc.toFirstChild()); - assertEquals("(425)555-5665", - qc.xmlText()); + assertEquals("(425)555-5665", qc.xmlText()); assertTrue(qc.toNextSibling()); - assertEquals("(425)555-6897", - qc.xmlText()); + assertEquals("(425)555-6897", qc.xmlText()); assertFalse(qc.toNextSibling()); } /** test the automatic binding of $this to the current node: execQuery() */ + @Test public void testThisVariable2() throws Exception { XmlCursor xc = _testDocCursor2(); - xc.toNextToken(); + // xc.toNextToken(); String q = "for $e in $this/employees/employee " + "let $s := $e/address/state " + @@ -131,10 +122,10 @@ public void testThisVariable2() throws Exception } /** test the binding of a variable to the current node: execQuery() */ - public void testCurrentNodeVariable2() throws Exception - { + @Test + public void testCurrentNodeVariable2() throws Exception { XmlCursor xc = _testDocCursor2(); - xc.toNextToken(); + // xc.toNextToken(); String q = "for $e in $cur/employees/employee " + "let $s := $e/address/state " + @@ -150,17 +141,15 @@ public void testCurrentNodeVariable2() throws Exception qc.dispose(); } - private XmlObject[] _execute(XmlObject xo, Map m, String q) - { + private XmlObject[] _execute(XmlObject xo, Map m, String q) { XmlOptions opts = new XmlOptions(); opts.setXqueryVariables(m); - XmlObject[] results = xo.execQuery(q, opts); - return results; + return xo.execQuery(q, opts); } /** test the binding of a variable to an XmlTokenSource using a map */ - public void testOneVariable() throws Exception - { + @Test + public void testOneVariable() throws Exception { File f = new File(dir, "bookstore.xml"); XmlObject doc = XmlObject.Factory.parse(f); String q = @@ -168,22 +157,20 @@ public void testOneVariable() throws Exception "for $x in $rt/book " + "where $x/price > 30 " + "return $x/title"; - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("rt", doc.selectChildren("", "bookstore")[0]); XmlObject[] results = _execute(doc, m, q); assertNotNull(results); assertEquals(2, results.length); - assertEquals("XQuery Kick Start", - results[0].xmlText()); - assertEquals("Learning XML", - results[1].xmlText()); + assertEquals("XQuery Kick Start", results[0].xmlText()); + assertEquals("Learning XML", results[1].xmlText()); } - + /** test the binding of multiple variables using a map; at the same time, test the binding of a variable to a String */ - public void testMultipleVariables() throws Exception - { + @Test + public void testMultipleVariables() throws Exception { File f = new File(dir, "bookstore.xml"); XmlObject doc = XmlObject.Factory.parse(f); String q = @@ -192,14 +179,13 @@ public void testMultipleVariables() throws Exception "for $x in $rt/book " + "where $x[@category=$c] " + "return $x/title"; - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("rt", doc.selectChildren("", "bookstore")[0]); m.put("c", "CHILDREN"); XmlObject[] results = _execute(doc, m, q); assertNotNull(results); assertEquals(1, results.length); - assertEquals("Harry Potter", - results[0].xmlText()); + assertEquals("Harry Potter", results[0].xmlText()); } } diff --git a/src/test/java/xmlobject/checkin/AssortedTests.java b/src/test/java/xmlobject/checkin/AssortedTests.java new file mode 100755 index 0000000..3a84cb3 --- /dev/null +++ b/src/test/java/xmlobject/checkin/AssortedTests.java @@ -0,0 +1,228 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import com.easypo.XmlCustomerBean; +import com.easypo.XmlLineItemBean; +import com.easypo.XmlPurchaseOrderDocumentBean; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlTime; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Ignore; +import org.junit.Test; +import xint.test.PositionDocument; + +import java.math.BigInteger; + +import static org.junit.Assert.*; + +public class AssortedTests { + // bug 27489 + @Test + public void testSaverCharEscaping() throws XmlException { + XmlObject xdoc = XmlObject.Factory.parse("something"); + XmlCursor cur = xdoc.newCursor(); + cur.toFirstChild(); + // valid chars + cur.setTextValue(""); + assertEquals("<something or other:\u03C0\uD7FF>", xdoc.toString()); + + // invalid chars - control chars, FFFF/FFFE, etc + cur.setTextValue(""); + assertEquals("<something?or?other:\u0045?>", xdoc.toString()); + + String greekChars = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E\uD835\uDF4F\uD835\uDF50\uD835" + + "\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835\uDF55"; + cur.setTextValue(greekChars); + assertEquals("" + greekChars + "", xdoc.toString()); + } + + // bug 26140/26104 + @Test + public void testNoTypeInvalid() throws XmlException { + XmlObject xdoc = XmlObject.Factory.parse("something"); + assertTrue("Untyped document should be invalid", !xdoc.validate()); + + xdoc = XmlObject.Factory.parse(""); + assertTrue("Untyped document should be invalid", !xdoc.validate()); + } + + // bug 26790 + @Test + public void testComplexSetter() throws XmlException { + XmlPurchaseOrderDocumentBean xdoc = XmlPurchaseOrderDocumentBean.Factory.parse( + "" + + "" + + "David Bau" + + "
      100 Main Street
      " + + "
      " + + "2003-05-18T11:50:00" + + "" + + "Red Candy" + + "0.423" + + "4" + + "" + + "" + + "Blue Candy" + + "5.0" + + "1" + + "" + + "
      "); + // test copy-within doc + XmlLineItemBean newItem = xdoc.getPurchaseOrder().addNewLineItem(); + newItem.set(xdoc.getPurchaseOrder().getLineItemArray(0)); + assertEquals(BigInteger.valueOf(4), xdoc.getPurchaseOrder().getLineItemArray(2).getQuantity()); + xdoc.getPurchaseOrder().setLineItemArray(0, xdoc.getPurchaseOrder().getLineItemArray(1)); + assertEquals(BigInteger.valueOf(1), xdoc.getPurchaseOrder().getLineItemArray(0).getQuantity()); + + // test copy-between docs + XmlLineItemBean anotherItem = XmlLineItemBean.Factory.parse( + "" + + "Yellow Balloon" + + "0.001" + + "200" + + ""); + + assertEquals("Yellow Balloon", anotherItem.getDescription()); + xdoc.getPurchaseOrder().setLineItemArray(1, anotherItem); + + assertEquals("Yellow Balloon", xdoc.getPurchaseOrder().getLineItemArray(1).getDescription()); + assertEquals(BigInteger.valueOf(1), xdoc.getPurchaseOrder().getLineItemArray(0).getQuantity()); + assertEquals(BigInteger.valueOf(200), xdoc.getPurchaseOrder().getLineItemArray(1).getQuantity()); + assertEquals(BigInteger.valueOf(4), xdoc.getPurchaseOrder().getLineItemArray(2).getQuantity()); + + // test copy-to-self + xdoc.getPurchaseOrder().setLineItemArray(1, xdoc.getPurchaseOrder().getLineItemArray(1)); + assertEquals("Yellow Balloon", xdoc.getPurchaseOrder().getLineItemArray(1).getDescription()); + assertEquals(BigInteger.valueOf(1), xdoc.getPurchaseOrder().getLineItemArray(0).getQuantity()); + assertEquals(BigInteger.valueOf(200), xdoc.getPurchaseOrder().getLineItemArray(1).getQuantity()); + assertEquals(BigInteger.valueOf(4), xdoc.getPurchaseOrder().getLineItemArray(2).getQuantity()); + } + + // bug 45338 + @Test + public void testComplexGetter() throws Exception { + XmlPurchaseOrderDocumentBean xdoc = + XmlPurchaseOrderDocumentBean.Factory.parse( + "" + + "" + + "David Bau" + + "
      100 Main Street
      " + + "
      " + + "2003-05-18T11:50:00" + + "" + + "Blue Candy" + + "5.0" + + "1" + + "" + + "
      "); + + assertFalse(xdoc.validate()); + assertEquals(XmlPurchaseOrderDocumentBean.type, xdoc.schemaType()); + + // check type of element when xsi:type is bad + XmlCustomerBean cust = xdoc.getPurchaseOrder().getCustomer(); + assertEquals(XmlCustomerBean.type, cust.schemaType()); + + assertEquals("David Bau", cust.getName()); + } + + @Test + @Ignore + public void testPrettyPrint() throws Exception { + XmlObject xobj = XmlObject.Factory.parse("<SHOULDNOTBEATAG>simple<ALSOSHOULDNOTBEATAG>"); + // System.out.println(xobj); + System.out.println(xobj.xmlText()); + /* + XmlCursor xcur = xobj.newCursor(); + xcur.toFirstChild(); + xobj = xcur.getObject(); + String result = xobj.toString(); + System.out.println(result); + + xcur.toFirstChild(); + xcur.toFirstChild(); + xcur.toFirstContentToken(); + xcur.insertChars("this is a test"); + + System.out.println(xobj); + */ + } + + @Test + @Ignore + public void testQNameCopy() throws Exception { + SchemaDocument xobj = SchemaDocument.Factory.parse( + "" + + ""); + SchemaDocument xobj2 = SchemaDocument.Factory.parse( + ""); + xobj2.getSchema().addNewElement().set(xobj.getSchema().getElementArray(0)); + System.out.println(xobj2); + } + + // don't run on normal drt because it's too slow: about 20-30 secs + @Test + @Ignore + public void testCursorFinalize() { + XmlObject obj = XmlObject.Factory.newInstance(); + int i = 0; + try { + for (i = 0; i < 2000 * 1000; i++) { + XmlCursor cur = obj.newCursor(); + // cur.dispose(); skipping this depends on finalization or else OOM + } + } catch (OutOfMemoryError e) { + System.err.println("Did " + i + " iterations before running out of memory"); + throw e; + } + } + + @Test + public void testOutOfRange() throws Exception { + PositionDocument doc = PositionDocument.Factory.parse("43037"); + assertEquals(43, doc.getPosition().getLat()); + assertEquals(37, doc.getPosition().getLon()); + assertTrue(doc.validate()); + + doc = PositionDocument.Factory.parse("443737"); + assertEquals(443, doc.getPosition().getLat()); + assertEquals(737, doc.getPosition().getLon()); + assertTrue(!doc.validate()); + + doc.getPosition().setLat((short) -300); + doc.getPosition().setLon((short) 32767); + assertEquals(-300, doc.getPosition().getLat()); + assertEquals(32767, doc.getPosition().getLon()); + assertTrue(!doc.validate()); + + doc.getPosition().setLat((short) 43); + doc.getPosition().setLon((short) 127); + assertEquals(43, doc.getPosition().getLat()); + assertEquals(127, doc.getPosition().getLon()); + assertTrue(doc.validate()); + } + + @Test + public void testParse() throws Exception { + XmlTime xt = XmlTime.Factory.parse("12:00:00"); + assertEquals("12:00:00", xt.getCalendarValue().toString()); + } +} diff --git a/src/test/java/xmlobject/checkin/CDataTest.java b/src/test/java/xmlobject/checkin/CDataTest.java new file mode 100644 index 0000000..f2f6ce4 --- /dev/null +++ b/src/test/java/xmlobject/checkin/CDataTest.java @@ -0,0 +1,113 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xmlbeans.SystemProperties; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +/** + * Test for finner CData control feature. + */ +public class CDataTest { + private static final String NL = SystemProperties.getProperty("line.separator") != null ? + SystemProperties.getProperty("line.separator") : + (System.getProperty("line.separator") != null ? System.getProperty("line.separator") : "\n"); + + @Test + public void testCData1() throws Exception { + String xmlText = ""; + checkCData(xmlText, xmlText, xmlText); + } + + @Test + @Ignore("Bookmark doesn't seem to keep the length of the CDATA") + public void testCData2() throws Exception { + String xmlText = + "" + NL + + " regular text" + NL + + ""; + String expected1 = + "\n" + + "cdata text regular text\n" + + ""; + String expected2 = + "" + NL + + " cdata text regular text" + NL + + ""; + + checkCData(xmlText, expected1, expected2); + } + + @Test + public void testCData3() throws Exception { + String xmlText = + "\n" + + "text \n" + + ""; + String expected1 = + "\n" + + "text cdata text\n" + + ""; + String expected2 = + "" + NL + + " text cdata text" + NL + + ""; + + checkCData(xmlText, expected1, expected2); + } + + // https://issues.apache.org/jira/browse/XMLBEANS-404 + @Test + public void testXmlBeans404() + throws Exception { + String xmlText = + "\n" + + "text \n" + + ""; + String expected1 = + "\n" + + "text cdata text]]\n" + + ""; + String expected2 = + "" + NL + + " text cdata text]]" + NL + + ""; + + checkCData(xmlText, expected1, expected2); + } + + private void checkCData(String xmlText, String expected1, String expected2) + throws XmlException { + XmlOptions opts = new XmlOptions(); + opts.setUseCDataBookmarks(); + + XmlObject xo = XmlObject.Factory.parse(xmlText, opts); + + String result1 = xo.xmlText(opts); + assertEquals("xmlText", expected1, result1); + + opts.setSavePrettyPrint(); + String result2 = xo.xmlText(opts); + assertEquals("prettyPrint", expected2, result2); + } +} diff --git a/src/test/java/xmlobject/checkin/CreationTests.java b/src/test/java/xmlobject/checkin/CreationTests.java new file mode 100755 index 0000000..468f683 --- /dev/null +++ b/src/test/java/xmlobject/checkin/CreationTests.java @@ -0,0 +1,82 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import com.easypo.XmlLineItemBean; +import com.easypo.XmlPurchaseOrderDocumentBean; +import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; +import com.easypo.XmlShipperBean; +import org.junit.Test; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class CreationTests { + @Test + public void testCreatePo() { + XmlPurchaseOrderDocumentBean doc = + XmlPurchaseOrderDocumentBean.Factory.newInstance(); + + PurchaseOrder order = doc.addNewPurchaseOrder(); + order.addNewCustomer().setName("David Bau"); + order.getCustomer().setAddress("Gladwyne, PA"); + XmlLineItemBean li; + li = order.addNewLineItem(); + li.setDescription("Burnham's Celestial Handbook, Vol 1"); + li.setPrice(new BigDecimal("21.79")); + li.setQuantity(BigInteger.valueOf(2)); + li.setPerUnitOunces(new BigDecimal("5")); + li = order.addNewLineItem(); + li.setDescription("Burnham's Celestial Handbook, Vol 2"); + li.setPrice(new BigDecimal("19.89")); + li.setQuantity(BigInteger.valueOf(2)); + li.setPerUnitOunces(new BigDecimal("5")); + li = order.addNewLineItem(); + li.setDescription("Burnham's Celestial Handbook, Vol 3"); + li.setPrice(new BigDecimal("19.89")); + li.setQuantity(BigInteger.valueOf(1)); + li.setPerUnitOunces(new BigDecimal("5")); + XmlShipperBean sh = order.addNewShipper(); + sh.setName("UPS"); + sh.setPerOunceRate(new BigDecimal("0.74")); + + assertEquals("David Bau", order.getCustomer().getName()); + assertEquals("Gladwyne, PA", order.getCustomer().getAddress()); + assertEquals(3, order.sizeOfLineItemArray()); + + assertEquals("Burnham's Celestial Handbook, Vol 1", order.getLineItemArray(0).getDescription()); + assertEquals(new BigDecimal("21.79"), order.getLineItemArray(0).getPrice()); + assertEquals(new BigInteger("2"), order.getLineItemArray(0).getQuantity()); + assertEquals(new BigDecimal("5"), order.getLineItemArray(0).getPerUnitOunces()); + + assertEquals("Burnham's Celestial Handbook, Vol 2", order.getLineItemArray(1).getDescription()); + assertEquals(new BigDecimal("19.89"), order.getLineItemArray(1).getPrice()); + assertEquals(new BigInteger("2"), order.getLineItemArray(1).getQuantity()); + assertEquals(new BigDecimal("5"), order.getLineItemArray(1).getPerUnitOunces()); + + assertEquals("Burnham's Celestial Handbook, Vol 3", order.getLineItemArray(2).getDescription()); + assertEquals(new BigDecimal("19.89"), order.getLineItemArray(2).getPrice()); + assertEquals(new BigInteger("1"), order.getLineItemArray(2).getQuantity()); + assertEquals(new BigDecimal("5"), order.getLineItemArray(2).getPerUnitOunces()); + + assertTrue(order.isSetShipper()); + assertEquals("UPS", order.getShipper().getName()); + assertEquals(new BigDecimal("0.74"), order.getShipper().getPerOunceRate()); + } +} diff --git a/src/test/java/xmlobject/checkin/DumbTest.java b/src/test/java/xmlobject/checkin/DumbTest.java new file mode 100755 index 0000000..7f3aaf9 --- /dev/null +++ b/src/test/java/xmlobject/checkin/DumbTest.java @@ -0,0 +1,49 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import dumbNS.RootDocument; +import dumbNS.RootDocument.Root; +import org.apache.xmlbeans.XmlObject; +import org.junit.Before; +import org.junit.Test; +import tools.util.JarUtil; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + + +public class DumbTest { + private String instance; + + @Before + public void setUp() throws IOException { + instance = JarUtil.getResourceFromJar("xbean/simple/dumb/dumb.xml"); + } + + @Test + public void testGetB2() + throws Exception { + RootDocument rootDoc = (RootDocument) XmlObject.Factory + .parse(instance); + Root root = rootDoc.getRoot(); + + System.out.println("root.xmlText() = " + root.xmlText()); + + assertEquals("bar:b attribute != 4", 4, root.getB2().intValue()); + } +} diff --git a/src/test/java/xmlobject/checkin/EasyPoTests.java b/src/test/java/xmlobject/checkin/EasyPoTests.java new file mode 100755 index 0000000..06a70cf --- /dev/null +++ b/src/test/java/xmlobject/checkin/EasyPoTests.java @@ -0,0 +1,104 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import com.easypo.XmlPurchaseOrderDocumentBean; +import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.util.JarUtil; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import static org.junit.Assert.*; + +public class EasyPoTests { + @Test + public void testEasyPo() throws Exception { + XmlPurchaseOrderDocumentBean doc = (XmlPurchaseOrderDocumentBean) + XmlObject.Factory.parse(JarUtil.getResourceFromJarasFile( + "xbean/xmlobject/easypo1.xml")); + assertFalse(doc.isNil()); + PurchaseOrder order = doc.getPurchaseOrder(); + assertEquals("David Bau", order.getCustomer().getName()); + assertEquals("Gladwyne, PA", order.getCustomer().getAddress()); + assertEquals(3, order.sizeOfLineItemArray()); + + assertEquals("Burnham's Celestial Handbook, Vol 1", order.getLineItemArray(0).getDescription()); + assertEquals(new BigDecimal("21.79"), order.getLineItemArray(0).getPrice()); + assertEquals(new BigInteger("2"), order.getLineItemArray(0).getQuantity()); + assertEquals(new BigDecimal("5"), order.getLineItemArray(0).getPerUnitOunces()); + + assertEquals("Burnham's Celestial Handbook, Vol 2", order.getLineItemArray(1).getDescription()); + assertEquals(new BigDecimal("19.89"), order.getLineItemArray(1).getPrice()); + assertEquals(new BigInteger("2"), order.getLineItemArray(1).getQuantity()); + assertEquals(new BigDecimal("5"), order.getLineItemArray(1).getPerUnitOunces()); + + assertEquals("Burnham's Celestial Handbook, Vol 3", order.getLineItemArray(2).getDescription()); + assertEquals(new BigDecimal("19.89"), order.getLineItemArray(2).getPrice()); + assertEquals(new BigInteger("1"), order.getLineItemArray(2).getQuantity()); + assertEquals(new BigDecimal("5"), order.getLineItemArray(2).getPerUnitOunces()); + + assertTrue(order.isSetShipper()); + assertEquals("UPS", order.getShipper().getName()); + assertEquals(new BigDecimal("0.74"), order.getShipper().getPerOunceRate()); + + assertEquals(3, order.sizeOfLineItemArray()); + } + + @Test + public void testSimpleAutoValidaiton() throws Exception { + XmlPurchaseOrderDocumentBean.Factory.parse( + ""); + + try { + XmlPurchaseOrderDocumentBean.Factory.parse( + ""); + fail(); + } catch (XmlException e) { + } + + try { + XmlPurchaseOrderDocumentBean.Factory.parse( + ""); + fail(); + } catch (XmlException e) { + } + + try { + XmlPurchaseOrderDocumentBean.Factory.parse( + ""); + fail(); + } catch (XmlException e) { + } + + try { + XmlPurchaseOrderDocumentBean.Factory.parse( + ""); + fail(); + } catch (XmlException e) { + } + + try { + XmlPurchaseOrderDocumentBean.Factory.parse( + ""); + fail(); + } catch (XmlException e) { + } + } +} diff --git a/src/test/java/xmlobject/checkin/InstanceValidationTests.java b/src/test/java/xmlobject/checkin/InstanceValidationTests.java new file mode 100755 index 0000000..91730aa --- /dev/null +++ b/src/test/java/xmlobject/checkin/InstanceValidationTests.java @@ -0,0 +1,1928 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.junit.Test; +import tools.util.JarUtil; + +import javax.xml.namespace.QName; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.*; + +public class InstanceValidationTests { + static String[] _args; + static String _test; + + + private SchemaTypeLoader makeSchemaTypeLoader(String[] schemas) throws XmlException { + XmlObject[] schemaDocs = new XmlObject[schemas.length]; + + for (int i = 0; i < schemas.length; i++) { + schemaDocs[i] = XmlObject.Factory.parse(schemas[i]); + } + + return XmlBeans.loadXsd(schemaDocs); + } + + private SchemaTypeLoader makeSchemaTypeLoader(File[] schemas) throws XmlException, IOException { + XmlObject[] schemaDocs = new XmlObject[schemas.length]; + + for (int i = 0; i < schemas.length; i++) { + schemaDocs[i] = XmlObject.Factory.parse(schemas[i], new XmlOptions().setLoadLineNumbers().setLoadMessageDigest()); + } + + return XmlBeans.loadXsd(schemaDocs); + } + + + private List performValidation(String[] schemas, String instances) throws XmlException { + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + + XmlOptions options = new XmlOptions(); + + XmlObject x = stl.parse(instances, null, options); + + List xel = new ArrayList(); + options.setErrorListener(xel); + + x.validate(options); + + return xel; + } + + @Test + public void testValidationElementError() throws XmlException { + String bobSchema = "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "" + " \n" + " \n" + "" + " \n" + " \n" + "" + "\n"; + + String invalid = ""; + + String[] schemas = {bobSchema}; + + List errors = null; + + errors = performValidation(schemas, invalid); + assertNotNull(errors); + assertTrue(errors.size() > 0); + + for (Object error : errors) { + XmlValidationError xmlValError = (XmlValidationError) error; + assertEquals(xmlValError.getErrorType(), XmlValidationError.INCORRECT_ELEMENT); + assertEquals(xmlValError.getBadSchemaType().getName().getLocalPart(), "biff"); + assertEquals(xmlValError.getOffendingQName().getLocalPart(), "q"); + assertEquals(xmlValError.getMessage(), "Expected element 'a@http://openuri.org/bobschema' instead of 'q@http://openuri.org/bobschema' here in element foo@http://openuri.org/bobschema"); + } + } + + @Test + public void testValidationAttributeError() throws XmlException { + + String empSchema = + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n"; + String[] schemas = {empSchema}; + + List errors = null; + + String xmlInstance = "" + + "" + + "joe blow" + + "31" + + "" + + "" + + "test user" + + "29" + + "" + + ""; + errors = performValidation(schemas, xmlInstance); + assertNotNull(errors); + assertTrue(errors.size() > 0); + + for (Object error : errors) { + XmlValidationError xmlValError = (XmlValidationError) error; + assertEquals(xmlValError.getErrorType(), XmlValidationError.INCORRECT_ATTRIBUTE); + assertEquals(xmlValError.getBadSchemaType().getName().getLocalPart(), "personType"); + assertEquals(xmlValError.getOffendingQName().getLocalPart(), "employee"); + assertEquals(xmlValError.getMessage(), "Expected attribute: employee in element person"); + } + } + + @Test + public void testValidationIncorrectElementError() throws XmlException { + + String empSchema = + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n"; + String[] schemas = {empSchema}; + + List errors = null; + + String xmlInstance = + "" + + "" + + "31" + + "" + + "" + + "test user" + + "29" + + "" + + ""; + + errors = performValidation(schemas, xmlInstance); + assertNotNull(errors); + assertTrue(errors.size() > 0); + + Iterator it = errors.iterator(); + assertTrue(it.hasNext()); + + XmlValidationError xmlValError = (XmlValidationError) it.next(); + assertEquals(XmlValidationError.INCORRECT_ELEMENT, xmlValError.getErrorType()); + assertEquals("personType", xmlValError.getBadSchemaType().getName().getLocalPart()); + // todo debug this Assert.assertEquals(xmlValError.getOffendingQName().getLocalPart(), "age"); + assertEquals("Expected element 'name' instead of 'age' here in element person", xmlValError.getMessage()); + + assertTrue(it.hasNext()); + + xmlValError = (XmlValidationError) it.next(); + assertEquals(XmlValidationError.INCORRECT_ELEMENT, xmlValError.getErrorType()); + assertEquals("personType", xmlValError.getBadSchemaType().getName().getLocalPart()); + // todo debug this Assert.assertEquals(xmlValError.getOffendingQName().getLocalPart(), "age"); + assertEquals("Expected element 'name' before the end of the content in element person", xmlValError.getMessage()); + } + + @Test + public void testValidationElementNotAllowedError() throws XmlException { + + String empSchema = + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n"; + String[] schemas = {empSchema}; + + List errors = null; + + String xmlInstance = + "" + + "" + + "joe blow" + + "31" + + "" + + "" + + "test user" + + "29" + + "" + + ""; + errors = performValidation(schemas, xmlInstance); + assertNotNull(errors); + // todo: enable this assert Assert.assertTrue(errors.size()>0); + + for (Object error : errors) { + XmlValidationError xmlValError = (XmlValidationError) error; + + assertEquals(xmlValError.getErrorType(), XmlValidationError.ELEMENT_NOT_ALLOWED); + assertEquals(xmlValError.getBadSchemaType().getName().getLocalPart(), "personType"); + assertEquals(xmlValError.getMessage(), "Expected element(s)"); + } + } + + @Test + public void testValidationAttributeTypeError() throws XmlException { + + String empSchema = + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n"; + String[] schemas = {empSchema}; + + List errors = null; + + String xmlInstance = "" + + "" + + "joe blow" + + "31" + + "" + + "" + + "test user" + + "junk" + + "" + + ""; + errors = performValidation(schemas, xmlInstance); + assertNotNull(errors); + assertTrue(errors.size() > 0); + + for (Object error : errors) { + XmlValidationError xmlValError = (XmlValidationError) error; + assertEquals(xmlValError.getErrorType(), XmlValidationError.ATTRIBUTE_TYPE_INVALID); + assertEquals(xmlValError.getMessage(), "Invalid decimal value: unexpected char '106'"); + } + } + + @Test + public void testElementError() throws XmlException { + String bobSchema = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + "" + + " \n" + + " \n" + "" + + " \n" + + " \n" + "" + + "\n"; + + String invalid = ""; + + String[] schemas = {bobSchema}; + + List errors = performValidation(schemas, invalid); + assertNotNull(errors); + assertTrue(errors.size() > 0); + + for (Object error : errors) { + XmlError xmlError = (XmlError) error; + assertEquals(xmlError.getMessage(), "Expected element 'a@http://openuri.org/bobschema' instead of 'q@http://openuri.org/bobschema' here in element foo@http://openuri.org/bobschema"); + // todo check XmlValidationError + } + } + + @Test + public void testAttributeError() throws XmlException { + + String empSchema = + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n"; + String[] schemas = {empSchema}; + + List errors = null; + + String xmlInstance = + "" + + "" + + "joe blow" + + "31" + + "" + + "" + + "test user" + + "29" + + "" + + ""; + errors = performValidation(schemas, xmlInstance); + assertNotNull(errors); + assertTrue(errors.size() > 0); + + for (Object error : errors) { + XmlError xmlError = (XmlError) error; + assertEquals(xmlError.getMessage(), "Expected attribute: employee in element person"); + // todo check XmlValidationError + } + } + + @Test + public void testValidate0() throws Exception { + // + // The most basic schema + // + + String schema = + "\n" + + "" + + ""; + + String[] schemas = {schema}; + + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + + // + // One which uses ##targetNamespace on a wildcard + // + + schema = + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + ""; + + String[] schemas99 = {schema}; + + stl = makeSchemaTypeLoader(schemas99); + + // + // A big, nasty schema :-) + // + + File schemeFile = + JarUtil.getResourceFromJarasFile("xbean/xmlobject/store/XMLSchema.xsd"); + File xmlFile = JarUtil.getResourceFromJarasFile("xbean/xmlobject/store/XML.xsd"); + + File[] schemasF = {schemeFile, xmlFile}; + + stl = makeSchemaTypeLoader(schemasF); + + SchemaType type = + stl.findDocumentType( + new QName("http://www.w3.org/2001/XMLSchema", "schema")); + + assertNotNull(type); + + + // + // A good piece from a J2EE schema + // + + schema = + "\n" + + "\n" + + "\n" + + "\n" + + "@(#)application-client_1_4.xsds 1.7 07/08/02\n" + + "\n" + + "\n" + + "\n"; + + String[] schemas5 = {schema}; + + stl = makeSchemaTypeLoader(schemas5); + + // + // A bad schema + // + + schema = ""; + + String[] schemas2 = {schema}; + + try { + stl = makeSchemaTypeLoader(schemas2); + fail(); + } catch (Exception e) { + } + + // + // A bad schema + // + schema = + "\n" + + " \n" + + "" + + ""; + + String[] schemas3 = {schema}; + + try { + makeSchemaTypeLoader(schemas3); + + fail(); + } catch (XmlException e) { + } + } + + @Test + public void testValidate1() throws Exception { + String ericSchema = + "\n" + + "\n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + "\n"; + + String eric2Schema = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + + String eric = ""; + String eric2 = ""; + String xsi = "xmlns:eric2='http://openuri.org/ericschema2' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"; + + String[] valid = { + eric + "
      ", + eric + "", + eric + "", + eric + "", + "" + + "" + }; + + String ericSansY = + ""; + + String[] invalid = { + "", + "", + eric + "text", + eric + "text", + eric + "text", + eric + "text", + eric + "text", + eric + "", + ericSansY + "", + "" + + "" + }; + + String[] schemas = {ericSchema, eric2Schema}; + + doTest( + schemas, + new QName("http://openuri.org/ericschema", "eric"), + valid, invalid); + } + + @Test + public void testValidate2() throws Exception { + String bobSchema = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + "" + + "\n"; + + String[] valid = { + "" + }; + + String[] invalid = { + "", + "" + }; + + String[] schemas = {bobSchema}; + + doTest(schemas, null, valid, invalid); + } + + @Test + public void testValidate3() throws Exception { + String schema = + "\n" + + "" + + " \n" + + " \n" + + " for maxOccurs\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + "" + + " \n" + + " \n" + + "" + + "\n"; + + String ns = "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " + + "xmlns:xs='http://www.w3.org/2001/XMLSchema'"; + String[] valid = { + ".1", + ".12", + ".123", + + "unbounded", + "0", + "1", + + "CAFEBABE", + "abcd", + + "abcdefgh", + "Eric", + + " Zero", + "Zero", + "0", + + "1", + " 1 ", + "Two", + " Three ", + + "", + "Brian", + "Kevin", + "Kevin Brian", + "Brian Kevin", + + " 1 22 333 4444 ", + "", + "5999", + + "P1Y", + + "abcde", + "xs:abc", + "foo", + "foo", + + "1965-06-11", + "1965-06-10", + "1999-05-31T13:20:00-05:00", + "00:00:00", + "13:20:00-05:00", + + "xs:abc", + "abcde", + "xs:ab", + "3", + "11", + "+45", + "1", + "0", + "-1", + "-1", + "489743579837589743434", + "1", + "", + "12", + "1", + "0", + "false", + "0", + "Monday", + "Sunday", + " Thursday ", + + "10.1", + "9.9", + "10", + "10.1", + "10", + "9.9", + + "10.1", + "9.9", + "10", + "10.1", + "10", + "9.9", + + "10.1", + "9.9", + "10", + "10.1", + "10", + "9.9", + + "eric", + "12345", + "1234", + "12345", + "1234", + "\n\n" + }; + + String[] invalid = { + "foo", + "P", + "CAFEBABP", + "abce", + + "abcde", + "Erik", + + "One", + "Twenty", + + "Seven", + "Bob", + "", + + "1", + "Bob", + "Ralph Frank", + + " 1 22 333 Eric ", + "Eric", + "-", + + "P2Y", + + "1965-06-10", + "1985-06-10", + "xx1999-05-31T13:20:00-05:00", + "eric", + "99:99:00", + "13:20:00-99:00", + + "moo", + "ab", + + "xs:abcdefghijk", + "xs:pqr", + "foo:bar", + "12", + "6", + "foo", + ".1", + "1", + "true", + "false", + "nibble", + "2", + "blurf", + "", + "", + "Monday Sucks", + + "10.1", + "10", + "10", + "9.9", + "9.9", + "10.1", + + "10.1", + "10", + "10", + "9.9", + "9.9", + "10.1", + + "10.1", + "10", + "10", + "9.9", + "9.9", + "10.1", + + " 1234 ", + "123456", + "vasilik", + "1", + "1234567", + ".1234", + " eric ", + + "", + "\n\n" + }; + + String[] schemas = {schema}; + + doTest(schemas, null, valid, invalid); + } + + + @Test + public void testValidate5() throws Exception { + String schema = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n" + + ""; + + String[] schemas = {schema}; + + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + + XmlObject x = + stl.parse( + "66", + null, null); + + XmlCursor c = x.newCursor(); + + do { + XmlObject obj = c.getObject(); + + if (obj != null) { + obj.validate(); + } + + } while (!c.toNextToken().isNone()); + + // invalid + + x = + stl.parse( + "66", + null, null); + + assertTrue(!x.validate()); + + c = x.newCursor(); + c.toNextToken(); + c.toNextToken(); + + assertTrue(!c.getObject().validate()); + + // No schema + + x = XmlObject.Factory.parse("asasasas"); + + c = x.newCursor(); + + do { + XmlObject obj = c.getObject(); + + if (obj != null) { + obj.validate(); + } + + } while (!c.toNextToken().isNone()); + } + + @Test(expected = XmlException.class) + public void testValidate6() throws Exception { + String schema = + "\n" + + " \n" + + " \n" + + "\n" + + ""; + + String[] schemas = {schema, schema}; + + + // Should get a schema compile error + makeSchemaTypeLoader(schemas); + } + + @Test + public void testValidate7() throws Exception { + String schema = + "" + + "" + + " " + + "" + + " " + + " " + + " " + + " " + + " " + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "" + + "" + + ""; + + String[] schemas = {schema}; + + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + + XmlObject x = + stl.parse( + "", null, null); + + assertTrue(x.validate()); + + XmlCursor c = x.newCursor(); + + c.toFirstChild(); + + XmlObject base = c.getObject(); + + c.toEndToken(); + c.insertElement("bar"); + + assertTrue(!x.validate()); + + c.toPrevSibling(); + + c.removeXml(); + + assertTrue(x.validate()); + + base.changeType(stl.findType(new QName("derived"))); + + c.insertElement("bar"); + + assertTrue(x.validate()); + } + + // Tests abstract & block attributes on ComplexType + @Test + public void testValidate8() throws Exception { + String[] schemas = { + "" + + "" + + " " + + " " + + "" + + " " + + "" + + " " + + " " + + " " + + " " + + " " + + "" + + " " + + "" + + " " + + " " + + " " + + " " + + " " + + "" + + " " + + " " + + " " + + " " + + " " + + "" + + "" + + "", + }; + + String xsiType = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "; + + String[] valid = { + "", + "", + "", + }; + String[] invalid = { + "", + "", + }; + + doTest(schemas, null, valid, invalid); + } + + @Test + public void testValidate9() throws Exception { + + String[] schemas = { + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " ", + + "" + + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + + " " + + " " + + " " + + " " + + " " + + " " + + + "", + + "" + + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "", + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "", + + }; + + String[] valid = { + "" + + " " + + " " + + " 1" + + " " + + " " + + " 1" + + " " + + " " + + " " + + " " + + " 124" + + " Shirt" + + " 29.99" + + " " + + " " + + " 563 " + + " Hat" + + " 69.99" + + " " + + " " + + " 443" + + " Umbrella" + + " 49.99" + + " " + + " " + + "", + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "", + + "" + + " " + + " " + + "", + + "" + + " " + + " " + + " " + + "", + + "" + + " xyz" + + " abc def" + + " abc" + + " def" + + " xyz" + + " abc" + + " xyz abc" + + "", + }; + + String[] invalid = { + "" + + " " + + " " + + " 1" + + " " + + " " + + " 1" + + " " + + " " + + " " + + " " + + " 124" + + " Shirt" + + " 29.99" + + " " + + " " + + " 563" + + " Hat" + + " 69.99" + + " " + + " " + + " 443" + + " Umbrella" + + " 49.99" + + " " + + " " + + "", + + "" + + " " + + " " + + "", + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "", + + "" + + " " + + " " + + " " + + "", + }; + + String[] invalidOnDocOnly = { + "" + + " foo" + + " abc" + + " def" + + " xyz" + + "", + + "" + + " abc foo" + + " abc" + + " def" + + " xyz" + + "", + }; + + + doTest(schemas, null, valid, invalid, true); + doTest(schemas, null, valid, invalid, false); + + // IDRefs are validated only if starting at the very root of the world + doTest(schemas, null, new String[0], invalidOnDocOnly, true); + doTest(schemas, null, invalidOnDocOnly, new String[0], false); + } + + // Test validation of setting with the ValidateOnSet option + @Test + public void testValidate10() throws Exception { + String schema = + "\n" + + " " + + " " + + " " + + " " + + " " + + ""; + + String[] schemas = {schema}; + + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + + XmlOptions validate = new XmlOptions().setValidateOnSet(); + XmlOptions noValidate = new XmlOptions(); + + SchemaType st = stl.findType(new QName("", "dec-restriction")); + + XmlDecimal dec = (XmlDecimal) stl.newInstance(st, validate); + + try { + dec.setStringValue("200"); + fail("Expected XmlValueOutOfRangeException"); + } catch (XmlValueOutOfRangeException e) { + } + + dec = (XmlDecimal) stl.newInstance(st, noValidate); + + dec.setStringValue("200"); + } + + // tests numeral validation + @Test + public void testValidate11() throws Exception { + String schema = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + "\n"; + + String[] valid = { + "" + + " \n -10" + + " " + + "", + "" + + " \n -9" + + " " + + "", + "" + + " +0008" + + " " + + "", + "" + + " +070" + + " " + + "" + }; + + String[] invalid = { + "" + + " " + + "", + "" + + " " + + "", + "" + + " + 4 " + + "" + }; + + String[] schemas = {schema}; + + doTest( + schemas, + new QName("http://openuri.org/testNumerals", "doc"), + valid, invalid); + } + + // Bugzilla bug #26105: validate derived type from base type enumeration + @Test + public void testValidate12() throws Exception { + String[] schemas = { + "\n" + + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + "\n" + + + "\n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n", + }; + + String[] valid = { + "enum1", + }; + + String[] invalid = { + "enum2/enumDef>", + }; + + doTest(schemas, null, valid, invalid); + } + + @Test + public void testValidateNestedGroups() throws Exception { + // This is a weird Schema, inspired from JIRA bug XMLBEANS-35 + // Make sure we compile it and then validate correctly + String[] schemas = { + "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n" + + "\n"}; + + String[] valid = { + "\n" + + " \n" + + " \n" + + " " + + " \n" + + " \n" + + "\n"}; + + String[] invalid = { + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"}; + + doTest(schemas, null, valid, invalid); + } + + private void doTest( + String[] schemas, QName docType, + String[] validInstances, String[] invalidInstances) + throws Exception { + doTest(schemas, docType, validInstances, invalidInstances, true); + } + + private void doTest( + String[] schemas, QName docType, + String[] validInstances, String[] invalidInstances, boolean startOnDocument) + throws Exception { + SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); + + XmlOptions options = new XmlOptions(); + + if (docType != null) { + SchemaType docSchema = stl.findDocumentType(docType); + + assertNotNull(docSchema); + + options.setDocumentType(docSchema); + } + + for (int i = 0; i < validInstances.length; i++) { + XmlObject x = + stl.parse((String) validInstances[i], null, options); + + if (!startOnDocument) { + XmlCursor c = x.newCursor(); + c.toFirstChild(); + x = c.getObject(); + c.dispose(); + } + + List xel = new ArrayList<>(); + + options.setErrorListener(xel); + + boolean isValid = x.validate(options); + + if (!isValid) { + System.err.println("Invalid doc, expected a valid doc: "); + System.err.println("Instance(" + i + "): "); + System.err.println(x.xmlText()); + System.err.println("Errors: "); + for (Object o : xel) { + System.err.println(o); + } + System.err.println(); + } + + assertTrue(isValid); + } + + for (int i = 0; i < invalidInstances.length; i++) { + XmlObject x; + + try { + x = stl.parse((String) invalidInstances[i], null, options); + + if (!startOnDocument) { + XmlCursor c = x.newCursor(); + c.toFirstChild(); + x = c.getObject(); + c.dispose(); + } + + boolean isValid = x.validate(); + + if (isValid) { + System.err.println("Valid doc, expected a invalid doc: "); + System.err.println("Instance(" + i + "): "); + System.err.println(x.xmlText()); + System.err.println(); + } + + assertFalse(isValid); + } catch (XmlException e) { + } + } + } +} diff --git a/src/test/java/xmlobject/checkin/NameworldTest.java b/src/test/java/xmlobject/checkin/NameworldTest.java new file mode 100755 index 0000000..8521c3e --- /dev/null +++ b/src/test/java/xmlobject/checkin/NameworldTest.java @@ -0,0 +1,68 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.openuri.nameworld.Loc; +import org.openuri.nameworld.NameworldDocument; +import org.openuri.nameworld.NameworldDocument.Nameworld; +import tools.util.JarUtil; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; + + +public class NameworldTest { + @Test + public void testWorld1() throws Exception { + NameworldDocument doc = (NameworldDocument) + XmlObject.Factory.parse( + JarUtil.getResourceFromJarasFile( + "xbean/xmlobject/nameworld.xml")); + + assertEquals(new QName("http://openuri.org/nameworld", "nameworld"), doc.schemaType().getDocumentElementName()); + + QName[] contents = { + new QName("http://bar.com/", "barcity"), + new QName("http://foo.com/", "footown"), + new QName("http://bar.com/", "barvillage"), + new QName("http://bar.com/", "bartown"), + new QName("http://foo.com/", "foovillage"), + new QName("http://bar.com/", "barvillage"), + new QName("http://foo.com/", "foocity"), + new QName("http://bar.com/", "bartown"), + new QName("http://foo.com/", "foovillage"), + new QName("http://foo.com/", "footown"), + new QName("http://bar.com/", "barvillage"), + new QName("http://foo.com/", "foovillage"), + }; + int t = 0; + + Nameworld world = doc.getNameworld(); + Nameworld.Island[] islands = world.getIslandArray(); + for (int i = 0; i < islands.length; i++) { + Loc[] locs = islands[i].getLocationArray(); + for (int j = 0; j < locs.length; j++) { + Loc.Reference[] refs = locs[j].getReferenceArray(); + for (int k = 0; k < refs.length; k++) { + assertEquals(contents[t++], refs[k].getTo()); + } + } + } + } +} diff --git a/src/test/java/xmlobject/checkin/RedefineTest.java b/src/test/java/xmlobject/checkin/RedefineTest.java new file mode 100755 index 0000000..9ce83cb --- /dev/null +++ b/src/test/java/xmlobject/checkin/RedefineTest.java @@ -0,0 +1,68 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.checkin; + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlOptions; +import org.example.prod.NewSizeDocument; +import org.junit.Test; +import org.openuri.versionstest.ElementDocument; +import org.openuri.versionstest.Type; +import org.openuri.versionstest.TypeX; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; + +public class RedefineTest { + @Test + public void testRedefine() throws XmlException { + String xml = "7"; + NewSizeDocument nsDoc = NewSizeDocument.Factory.parse(xml); + + boolean valid = nsDoc.validate(); + + assertTrue(valid); + + assertEquals(7, nsDoc.getNewSize()); + + nsDoc.setNewSize(20); + + List errors = new ArrayList(); + XmlOptions options = new XmlOptions(); + options.setErrorListener(errors); + + valid = nsDoc.validate(options); + + assertFalse(valid); + + assertEquals(1, errors.size()); + } + + @Test + public void testMultipleRedefine() throws XmlException { + String xml = "" + + "AAABC" + ""; + ElementDocument doc = ElementDocument.Factory.parse(xml); + TypeX tx = doc.getElement(); + + assertTrue(tx.validate()); + assertEquals("A", tx.getA()); + assertEquals("B", tx.getB()); + assertEquals("C", tx.getC()); + assertEquals("AA", ((Type) tx).getAa()); + } +} diff --git a/src/test/java/xmlobject/checkin/SelectChldAttTests.java b/src/test/java/xmlobject/checkin/SelectChldAttTests.java new file mode 100755 index 0000000..8cca0f6 --- /dev/null +++ b/src/test/java/xmlobject/checkin/SelectChldAttTests.java @@ -0,0 +1,227 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xml.test.selectChldAtt.DocDocument; +import org.apache.xml.test.selectChldAtt.TypeExtendedC; +import org.apache.xmlbeans.*; +import org.junit.Test; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import static org.junit.Assert.assertTrue; + +public class SelectChldAttTests { + private static final String XSI_URI = "http://www.w3.org/2001/XMLSchema-instance"; + + @Test + public void testSelect() throws XmlException { + String uri = "http://xml.apache.org/test/selectChldAtt"; + + String xml = "\n" + + " 7\n" + + " ... some text ... \n" + + + " \n" + + " this is wildcard bucket \n" + + " \n" + + + " \n" + + " 2\n" + + " element in #other namespace \n" + + " \n" + + + " \n" + + " element from typeC \n" + + " element in the 'any' bucket for typeExtendedC \n" + + " element from typeExtendedC \n" + + " \n" + + ""; + + DocDocument document = DocDocument.Factory.parse(xml); + DocDocument.Doc doc = document.getDoc(); + Collection errors = new ArrayList(); + assertTrue("Valid instance", doc.validate(new XmlOptions().setErrorListener(errors))); + printErrors(errors); + + XmlObject xo; + XmlObject[] xos; + + // select a known element + xos = doc.selectChildren(new QName(uri, "int")); + //print("1 selectChildren 'int' : ", xos); + assertTrue("1 selectChildren 'int' : ", verifyResult(xos, new String[]{"7"})); + + xos = doc.selectChildren(uri, "string"); + //print("2 selectChildren 'string' : ", xos); + assertTrue("2 selectChildren 'string' : ", verifyResult(xos, new String[]{" ... some text ... "})); + + // elemA + xos = doc.selectChildren(new QName(uri, "elemA")); + //print("3 selectChildren 'elemA' : ", xos); + assertTrue("3 selectChildren 'elemA' : ", + verifyResult(xos, new String[]{"\n" + + " this is wildcard bucket \n" + + ""})); + + // select a known attribute + xo = xos[0].selectAttribute(new QName("", "price")); + //print("4 selectAttribute 'price' : ", xo); + assertTrue("4 selectAttribute 'price' : ", + verifyResult(xo, "4.321")); + + // select all attributes + QNameSet qns = QNameSet.forWildcardNamespaceString("##any", uri); + xos = xos[0].selectAttributes(qns); + //print("5 selectAttributes set'##any' :", xos); + assertTrue("5 selectAttributes set'##any' :", + verifyResult(xos, new String[]{"4.321"})); + + // elemB + xos = doc.selectChildren(new QName(uri, "elemB")); + //print("6 selectChildren 'elemB' : ", xos); + + //print("7 selectChildren set'##other' : " , xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##other", uri))); + assertTrue("7 selectChildren set'##other' : ", + verifyResult(xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##other", uri)) + , new String[]{" element in #other namespace "})); + //print("8 selectAttributes set'##other' : ", xos[0].selectAttributes(QNameSet.forWildcardNamespaceString("##other", uri))); + assertTrue("8 selectAttributes set'##other' : ", + verifyResult(xos[0].selectAttributes(QNameSet.forWildcardNamespaceString("##other", uri)), + new String[]{"attribute in #other namespace"})); + + // elemC + xos = doc.selectChildren(new QName(uri, "elemC")); + //print("9 selectChildren 'elemC' : ", xos); + //print("10 selectChildren set'##any' : " , xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##any", uri))); + assertTrue("10 selectChildren set'##any' : ", + verifyResult(xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##any", uri)) + , new String[]{" element from typeC ", + " element in the 'any' bucket for typeExtendedC ", + " element from typeExtendedC "})); + + // select elements in the any bucket by excluding the the known elements + QNameSetBuilder qnsb = new QNameSetBuilder(); + qnsb.add(new QName(uri, "someElement")); + qnsb.add(new QName(uri, "aditionalElement")); + qnsb.invert(); + + //print("11a selectChildren in the any bucket for typeExtendedC: " , xos[0].selectChildren(qnsb.toQNameSet())); + assertTrue("11a selectChildren in the any bucket for typeExtendedC: ", + verifyResult(xos[0].selectChildren(qnsb.toQNameSet()), + new String[]{" element in the 'any' bucket for typeExtendedC "})); + + //print("11b selectChildren in the any bucket for typeExtendedC: " , xos[0].selectChildren(TypeExtendedC.type.qnameSetForWildcardElements())); + assertTrue("11b selectChildren in the any bucket for typeExtendedC: ", + verifyResult(xos[0].selectChildren(TypeExtendedC.type.qnameSetForWildcardElements()), + new String[]{" element in the 'any' bucket for typeExtendedC "})); + + // select attributes in the any bucket by excluding the the known attributes + qnsb = new QNameSetBuilder(); + qnsb.add(new QName("", "att1")); + qnsb.add(new QName("", "aditionalAtt")); + qnsb.add(new QName(XSI_URI, "type")); + qnsb.invert(); + + //print("12a selectChildren in the any bucket for typeExtendedC: " , xos[0].selectAttributes(qnsb.toQNameSet())); + assertTrue("12a selectChildren in the any bucket for typeExtendedC: ", + verifyResult(xos[0].selectAttributes(qnsb.toQNameSet()), + new String[]{"attribute in any bucket"})); + //print("12b selectChildren in the any bucket for typeExtendedC: " , xos[0].selectAttributes(TypeExtendedC.type.qnameSetForWildcardAttributes())); + assertTrue("12b selectChildren in the any bucket for typeExtendedC: ", + verifyResult(xos[0].selectAttributes(TypeExtendedC.type.qnameSetForWildcardAttributes()), + new String[]{"typeExtendedC", + "attribute in any bucket"})); + } + + private static void printErrors(Collection errors) { + for (Iterator i = errors.iterator(); i.hasNext(); ) { + System.out.println("ERROR: " + i.next()); + } + } + + private static boolean verifyResult(XmlObject[] xos, String[] expected) { + if (xos == null && expected == null) + return true; + + if (xos == null || expected == null) + return false; + + if (xos.length != expected.length) + return false; + + for (int i = 0; i < xos.length; i++) { + XmlObject xo = xos[i]; + if (!equalsIgnoreNewLine(xo.toString(), expected[i])) { + System.out.println("ERROR:\n Actual:\n" + xo.toString() + "\n Expected:\n" + expected[i]); + return false; + } + } + return true; + } + + private static boolean verifyResult(XmlObject xo, String expected) { + if (xo == null && expected == null) + return true; + + if (xo == null || expected == null) + return false; + + if (!xo.toString().equals(expected)) { + System.out.println("ERROR:\n Actual:\n" + xo.toString() + "\n Expected:\n" + expected); + return false; + } else + return true; + } + + private static boolean equalsIgnoreNewLine(String s1, String s2) { + if (s1 == null && s2 == null) + return true; + + if (s1 == null || s2 == null) + return false; + + int i1 = 0, i2 = 0; + while (i1 < s1.length() || i2 < s2.length()) { + if (s1.charAt(i1) == '\n' || s1.charAt(i1) == '\r') { + i1++; + continue; + } + + if (s2.charAt(i2) == '\n' || s2.charAt(i2) == '\r') { + i2++; + continue; + } + + if (s1.charAt(i1) != s2.charAt(i2)) + return false; + + i1++; + i2++; + } + + return (i1 == s1.length()) && (i2 == s2.length()); + } +} diff --git a/src/test/java/xmlobject/checkin/SerializationTests.java b/src/test/java/xmlobject/checkin/SerializationTests.java new file mode 100755 index 0000000..27f9a0a --- /dev/null +++ b/src/test/java/xmlobject/checkin/SerializationTests.java @@ -0,0 +1,152 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.checkin; + +import com.easypo.XmlLineItemBean; +import com.easypo.XmlPurchaseOrderDocumentBean; +import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; +import com.easypo.XmlShipperBean; +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Test; +import org.xml.sax.InputSource; +import tools.util.JarUtil; + +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SerializationTests { + @Test + public void testXmlObjectSerialization() throws Exception { + String simpleDocument = "43"; + XmlObject doc = XmlObject.Factory.parse(simpleDocument); + + // baseline test + assertEquals(simpleDocument, doc.xmlText()); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(out); + oos.writeObject(doc); + oos.close(); + + byte[] byteArray = out.toByteArray(); + ByteArrayInputStream in = new ByteArrayInputStream(byteArray); + ObjectInputStream ois = new ObjectInputStream(in); + XmlObject newdoc = (XmlObject) ois.readObject(); + ois.close(); + + assertEquals(simpleDocument, newdoc.xmlText()); + } + + @Test + public void testXBeanSerialization() throws Exception { + XmlPurchaseOrderDocumentBean doc = XmlPurchaseOrderDocumentBean.Factory.newInstance(); + PurchaseOrder order = doc.addNewPurchaseOrder(); + order.addNewCustomer().setName("David Bau"); + order.getCustomer().setAddress("Gladwyne, PA"); + XmlLineItemBean li; + li = order.addNewLineItem(); + li.setDescription("Burnham's Celestial Handbook, Vol 1"); + li.setPrice(new BigDecimal("21.79")); + li.setQuantity(BigInteger.valueOf(2)); + li.setPerUnitOunces(new BigDecimal("5")); + li = order.addNewLineItem(); + li.setDescription("Burnham's Celestial Handbook, Vol 2"); + li.setPrice(new BigDecimal("19.89")); + li.setQuantity(BigInteger.valueOf(2)); + li.setPerUnitOunces(new BigDecimal("5")); + li = order.addNewLineItem(); + li.setDescription("Burnham's Celestial Handbook, Vol 3"); + li.setPrice(new BigDecimal("19.89")); + li.setQuantity(BigInteger.valueOf(1)); + li.setPerUnitOunces(new BigDecimal("5")); + XmlShipperBean sh = order.addNewShipper(); + sh.setName("UPS"); + sh.setPerOunceRate(new BigDecimal("0.74")); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(out); + oos.writeObject(doc.getPurchaseOrder().getLineItemArray(1)); + oos.writeObject(doc); + oos.writeObject(doc.getPurchaseOrder().getLineItemArray(2)); + oos.close(); + + byte[] byteArray = out.toByteArray(); + ByteArrayInputStream in = new ByteArrayInputStream(byteArray); + ObjectInputStream ois = new ObjectInputStream(in); + XmlLineItemBean newli1 = (XmlLineItemBean) ois.readObject(); + XmlPurchaseOrderDocumentBean newdoc = (XmlPurchaseOrderDocumentBean) ois.readObject(); + XmlLineItemBean newli2 = (XmlLineItemBean) ois.readObject(); + ois.close(); + + PurchaseOrder neworder = newdoc.getPurchaseOrder(); + + assertEquals(newli1, neworder.getLineItemArray(1)); + assertEquals(newli2, neworder.getLineItemArray(2)); + + assertEquals("David Bau", neworder.getCustomer().getName()); + assertEquals("Gladwyne, PA", neworder.getCustomer().getAddress()); + assertEquals(3, neworder.sizeOfLineItemArray()); + + assertEquals("Burnham's Celestial Handbook, Vol 1", neworder.getLineItemArray(0).getDescription()); + assertEquals(new BigDecimal("21.79"), neworder.getLineItemArray(0).getPrice()); + assertEquals(new BigInteger("2"), neworder.getLineItemArray(0).getQuantity()); + assertEquals(new BigDecimal("5"), neworder.getLineItemArray(0).getPerUnitOunces()); + + assertEquals("Burnham's Celestial Handbook, Vol 2", neworder.getLineItemArray(1).getDescription()); + assertEquals(new BigDecimal("19.89"), neworder.getLineItemArray(1).getPrice()); + assertEquals(new BigInteger("2"), neworder.getLineItemArray(1).getQuantity()); + assertEquals(new BigDecimal("5"), neworder.getLineItemArray(1).getPerUnitOunces()); + + assertEquals("Burnham's Celestial Handbook, Vol 3", neworder.getLineItemArray(2).getDescription()); + assertEquals(new BigDecimal("19.89"), neworder.getLineItemArray(2).getPrice()); + assertEquals(new BigInteger("1"), neworder.getLineItemArray(2).getQuantity()); + assertEquals(new BigDecimal("5"), neworder.getLineItemArray(2).getPerUnitOunces()); + + assertTrue(neworder.isSetShipper()); + assertEquals("UPS", neworder.getShipper().getName()); + assertEquals(new BigDecimal("0.74"), neworder.getShipper().getPerOunceRate()); + } + + @Test + public void testWsdlSerialization() throws IOException, XmlException { + // test for TextSaver + File wsdlFile = JarUtil.getResourceFromJarasFile("xbean/xmlobject/wsdl.xml"); + + List loaders = new ArrayList(); + loaders.add(SchemaDocument.type.getTypeSystem()); + SchemaTypeLoader[] loadersArr = (SchemaTypeLoader[]) loaders.toArray(new SchemaTypeLoader[1]); + SchemaTypeLoader loader = XmlBeans.typeLoaderUnion(loadersArr); + + XmlOptions options = new XmlOptions(); + options.setLoadLineNumbers(); + XmlObject wsdlObj = (XmlObject) loader.parse(wsdlFile, XmlObject.type, options); + + Reader reader = wsdlObj.newReader(); + InputSource source = new InputSource(reader); + source.setSystemId(""); + + + XmlObject.Factory.parse(reader); + } +} diff --git a/test/src/xmlobject/checkin/SetTest.java b/src/test/java/xmlobject/checkin/SetTest.java similarity index 84% rename from test/src/xmlobject/checkin/SetTest.java rename to src/test/java/xmlobject/checkin/SetTest.java index 20a2bfe..a3ba40b 100755 --- a/test/src/xmlobject/checkin/SetTest.java +++ b/src/test/java/xmlobject/checkin/SetTest.java @@ -14,46 +14,25 @@ */ package xmlobject.checkin; -import java.util.*; - -import junit.framework.*; - -import xmlcursor.common.*; - - -import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlCalendar; import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlString; import org.apache.xmlbeans.XmlDate; -import org.apache.xmlbeans.XmlCalendar; - +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlString; +import org.junit.Test; import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; import test.xbean.xmlcursor.purchaseOrder.USAddress; - import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; +import java.util.Calendar; -/** - * - * - */ -public class SetTest extends BasicCursorTestCase { - public SetTest(String sName) { - super(sName); - } +import static org.junit.Assert.*; - public static Test suite() { - return new TestSuite(SetTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } +public class SetTest extends BasicCursorTestCase { + @Test public void testSetFromSTART() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -63,6 +42,7 @@ public void testSetFromSTART() throws Exception { assertEquals("newtext", m_xc.getTextValue()); } + @Test public void testSetFromATTR() throws Exception { m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); m_xc = m_xo.newCursor(); @@ -72,6 +52,7 @@ public void testSetFromATTR() throws Exception { assertEquals(" new attr text ", m_xc.getTextValue()); } + @Test public void testSetFromSTARTstronglyTyped() throws Exception { PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); @@ -80,12 +61,13 @@ public void testSetFromSTARTstronglyTyped() throws Exception { assertEquals("new comment text", pod.getPurchaseOrder().getComment()); } + @Test public void testSetFromATTRstronglyTyped() throws Exception { PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); XmlDate xorderDate = pod.getPurchaseOrder().xgetOrderDate(); - assertFalse(xorderDate==null); + assertNotNull(xorderDate); Calendar d = new XmlCalendar(new java.util.Date()); xorderDate.setCalendarValue(d); @@ -100,33 +82,34 @@ public void testSetFromATTRstronglyTyped() throws Exception { Calendar.DAY_OF_MONTH)); } + @Test public void testSetFromFixedATTR() throws Exception { PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); USAddress usa = pod.getPurchaseOrder().getShipTo(); - assertFalse(usa==null); + assertNotNull(usa); XmlString xcountry = usa.xgetCountry(); xcountry.setStringValue("UK"); - - assertEquals(false, pod.validate()); + assertFalse(pod.validate()); } + @Test public void testSetFromComplexType() throws Exception { PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); USAddress usa = pod.getPurchaseOrder().getShipTo(); - assertFalse(usa==null); + assertNotNull(usa); usa.set( USAddress.Factory.parse( "FredpavedtownAK00000")); // assertTrue(true); - assertEquals(false, pod.validate()); + assertFalse(pod.validate()); } } diff --git a/src/test/java/xmlobject/checkin/SubstGroupTests.java b/src/test/java/xmlobject/checkin/SubstGroupTests.java new file mode 100755 index 0000000..856b289 --- /dev/null +++ b/src/test/java/xmlobject/checkin/SubstGroupTests.java @@ -0,0 +1,233 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Test; +import org.openuri.sgs.ADocument; +import org.openuri.sgs.BDocument; +import org.openuri.sgs.CDocument; +import org.openuri.sgs.RootDocument; + +import static org.junit.Assert.*; + +public class SubstGroupTests { + @Test + public void test1() throws Exception { + String xml1 = "" + + "\ta\ta\t" + + "\tb\tb\t" + + "\tc\tc\t" + + ""; + + + RootDocument doc1 = RootDocument.Factory.parse(xml1); + RootDocument.Root root = doc1.getRoot(); + assertTrue(doc1.validate()); + + XmlString a = root.xgetAArray(0); + assertEquals(a.schemaType(), XmlString.type); + assertEquals("\ta\ta\t", a.getStringValue()); + + XmlString b = root.xgetAArray(1); + assertEquals(b.schemaType(), XmlNormalizedString.type); + assertEquals(" b b ", b.getStringValue()); + + XmlString c = root.xgetAArray(2); + assertEquals(c.schemaType(), XmlToken.type); + assertEquals("c c", c.getStringValue()); + + root.insertA(2, "d d"); + assertEquals("d d", root.getAArray(2)); + assertEquals(4, root.sizeOfAArray()); + root.removeA(2); + + root.removeA(1); + assertEquals("c c", root.getAArray(1)); + assertEquals(2, root.sizeOfAArray()); + + root.addA("f f"); + assertEquals(3, root.sizeOfAArray()); + assertEquals("f f", root.getAArray(2)); + + // Test array setters + + // test m < n case + String[] smaller = new String[]{"x", "y"}; + root.setAArray(smaller); + assertEquals(2, root.sizeOfAArray()); + assertEquals("y", root.getAArray(1)); + + // test m > n case + String[] larger = new String[]{"p", "q", "r", "s"}; + root.setAArray(larger); + assertEquals(4, root.sizeOfAArray()); + assertEquals("r", root.getAArray(2)); + } + + @Test + public void test2() throws Exception { + String xml1 = "\ta\ta\t"; + String xml2 = "\tb\tb\t"; + String xml3 = "\tc\tc\t"; + + ADocument d1 = ADocument.Factory.parse(xml1); + XmlString a = d1.xgetA(); + assertEquals(a.schemaType(), XmlString.type); + assertEquals("\ta\ta\t", a.getStringValue()); + + ADocument d2 = ADocument.Factory.parse(xml2); + XmlString b = d2.xgetA(); + assertEquals(d2.schemaType(), BDocument.type); + assertEquals(b.schemaType(), XmlNormalizedString.type); + assertEquals(" b b ", b.getStringValue()); + + ADocument d3 = ADocument.Factory.parse(xml3); + XmlString c = d3.xgetA(); + assertEquals(d3.schemaType(), CDocument.type); + assertEquals(c.schemaType(), XmlToken.type); + assertEquals("c c", c.getStringValue()); + } + + private static final String[] invalidSchemas = { + " " + + " " + + " " + + "", + " " + + " " + + " " + + " " + + " " + + " " + + "", + " " + + " " + + " " + + "", + " " + + " " + + " " + + "", + " " + + " " + + " " + + " " + + " " + + " " + + "", + " " + + " " + + "", + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "", + }; + + public static final String[] validSchemas = { + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "", + }; + + @Test + public void test3() throws Exception { + SchemaDocument[] schemas = new SchemaDocument[invalidSchemas.length]; + + // Parse the invalid schema files + for (int i = 0; i < invalidSchemas.length; i++) + schemas[i] = SchemaDocument.Factory.parse(invalidSchemas[i]); + + // Now compile the invalid schemas, test that they fail + for (int i = 0; i < schemas.length; i++) { + try { + XmlBeans.loadXsd(new XmlObject[]{schemas[i]}); + fail("Schema should have failed to compile:\n" + invalidSchemas[i]); + } catch (XmlException success) { /* System.out.println(success); */ } + } + + + // Parse the valid schema files + schemas = new SchemaDocument[validSchemas.length]; + for (int i = 0; i < validSchemas.length; i++) + schemas[i] = SchemaDocument.Factory.parse(validSchemas[i]); + + // Now compile the valid schemas, test that they succeed + for (int i = 0; i < schemas.length; i++) { + try { + XmlBeans.loadXsd(new XmlObject[]{schemas[i]}); + } catch (XmlException fail) { + fail("Failed to compile schema: " + schemas[i] + " with error: " + fail); + } + } + } + + private static String[] invalidDocs = + { + "" + + " content " + + " ", + }; + + private static String[] validDocs = + { + "" + + " content " + + " ", + }; + + @Test + public void test4() throws Exception { + + for (int i = 0; i < invalidDocs.length; i++) { + XmlObject xo = XmlObject.Factory.parse(invalidDocs[i]); + assertTrue("Doc was valid. Should be invalid: " + invalidDocs[i], + !xo.validate()); + } + + for (int i = 0; i < validDocs.length; i++) { + XmlObject xo = XmlObject.Factory.parse(validDocs[i]); + assertTrue("Doc was invalid. Should be valid: " + validDocs[i], + xo.validate()); + } + } + +} diff --git a/src/test/java/xmlobject/checkin/ValidateTest.java b/src/test/java/xmlobject/checkin/ValidateTest.java new file mode 100755 index 0000000..04106f0 --- /dev/null +++ b/src/test/java/xmlobject/checkin/ValidateTest.java @@ -0,0 +1,72 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.*; + +public class ValidateTest extends BasicCursorTestCase { + @Test + public void testValidateTrue() throws Exception { + //m_xo = XmlObject.Factory.parse(Common.XML_PURCHASEORDER); + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + assertTrue(m_xo.validate()); + } + + @Test + public void testValidateTrueWithOptionDiscardDocElement() throws Exception { + XmlOptions map = new XmlOptions(); + map.setLoadReplaceDocumentElement(null); + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO) + , map); + + assertFalse(m_xo.validate(map)); + } + + @Test + public void testValidateFalseFixedAttr() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + String ns = "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\";"; + String exp_ns = "xmlns:po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; + + m_xc = m_xo.newCursor(); + m_xc.selectPath(ns + " $this//po:shipTo"); + QName name = new QName("country"); + m_xc.setAttributeText(name, "UK"); + XmlObject xo = m_xc.getObject(); + assertEquals("UK", m_xc.getAttributeText(name)); + PurchaseOrderDocument pod = (PurchaseOrderDocument) m_xo; + + assertFalse(xo.validate()); + assertFalse(pod.validate()); + assertFalse(m_xo.validate()); + + assertTrue(true); + } +} + diff --git a/src/test/java/xmlobject/checkin/XPathTest.java b/src/test/java/xmlobject/checkin/XPathTest.java new file mode 100644 index 0000000..f2de712 --- /dev/null +++ b/src/test/java/xmlobject/checkin/XPathTest.java @@ -0,0 +1,125 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.checkin; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class XPathTest { + @Test + public void testPath() throws XmlException { + final XmlObject obj = XmlObject.Factory.parse( + "" + + "" + + "val1" + + "val2" + + "" + + "val3" + + ""); + final XmlCursor c = obj.newCursor(); + + c.selectPath(".//b/c"); + + int selCount = c.getSelectionCount(); + assertEquals("SelectionCount", 1, selCount); + + while (c.hasNextSelection()) { + c.toNextSelection(); + + assertTrue("OnStartElement", c.isStart()); + assertEquals("TextValue", "val1", c.getTextValue()); + System.out.println(" -> " + c.getObject()); + } + c.dispose(); + } + + @Test + public void testPath2() throws XmlException { + final XmlObject obj = XmlObject.Factory.parse( + "" + + "" + + "val1" + + "" + + "val2" + + "val3" + + "" + + "" + + "val4" + + ""); + final XmlCursor c = obj.newCursor(); + + c.selectPath(".//b/c"); + + int selCount = c.getSelectionCount(); + assertEquals("SelectionCount", 2, selCount); + + assertTrue("hasNextSelection", c.hasNextSelection()); + c.toNextSelection(); + + System.out.println(" -> " + c.getObject()); + assertTrue("OnStartElement", c.isStart()); + assertEquals("TextValue", "val1", c.getTextValue()); + + + assertTrue("hasNextSelection2", c.hasNextSelection()); + c.toNextSelection(); + + System.out.println(" -> " + c.getObject()); + assertTrue("OnStartElement2", c.isStart()); + assertEquals("TextValue2", "val3", c.getTextValue()); + + c.dispose(); + } + + @Test + public void testPath3() throws XmlException { + final XmlObject obj = XmlObject.Factory.parse( + "" + + "" + + "val1" + + "" + + "val2" + + "" + + "val3" + + "val5" + + "" + + "" + + "" + + "" + + "val4" + + ""); + final XmlCursor c = obj.newCursor(); + + c.selectPath(".//b/c//c"); + + int selCount = c.getSelectionCount(); + assertEquals("SelectionCount", 1, selCount); + + while (c.hasNextSelection()) { + c.toNextSelection(); + + System.out.println(" -> " + c.getObject()); + assertTrue("OnStartElement", c.isStart()); + assertEquals("TextValue", "val5", c.getTextValue()); + } + c.dispose(); + } +} diff --git a/src/test/java/xmlobject/common/SelectChildrenAttribCommon.java b/src/test/java/xmlobject/common/SelectChildrenAttribCommon.java new file mode 100755 index 0000000..cd451be --- /dev/null +++ b/src/test/java/xmlobject/common/SelectChildrenAttribCommon.java @@ -0,0 +1,118 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.common; + +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Before; +import tools.util.JarUtil; +import tools.xml.XmlComparator; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.*; + + +public class SelectChildrenAttribCommon { + // Common + public XmlOptions opts; + + + @Before + public void setUp() { + opts = new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2); + } + + + ////////////////////////////////////////////////////////////////// + // Helper methods + protected void validateTest(String testName, String[] exps, XmlObject[] act) + throws Exception { + assertEquals(testName + ": Return array has more/less elements than expected: " + + act.length, act.length, exps.length); + boolean passed = true; + + for (int i = 0; i < act.length; i++) { + boolean res; + res = XComp(convertFragToDoc(act[i].xmlText()), exps[i], true); + if (!res) { + System.out.println("Expected value differs from actual: Index=" + i); + System.out.println("Expected: " + exps[i]); + System.out.println("Actual: " + act[i].xmlText()); + passed = false; + } + } + assertTrue(testName + ": Failed!", passed); + } + + + protected void validateTest(String testName, String exp, XmlObject xml) throws Exception { + assertNotNull(testName + ": XmlObject Recevied is null", xml); + + boolean res = XComp(convertFragToDoc(xml.xmlText()), exp, true); + assertTrue("Expected value differs from actual\n" + + "Expected: " + exp + "\n" + + "Actual: " + xml.xmlText(), + res); + } + + + protected static String getXml(String file) + throws java.io.IOException { + return JarUtil.getResourceFromJar(file); + } + + + /** + * Just a thin wrapper around XmlComparator + */ + private static boolean XComp(String actual, String expected, boolean verbose) + throws org.apache.xmlbeans.XmlException { + boolean same; + XmlComparator.Diagnostic diag = new XmlComparator.Diagnostic(); + same = XmlComparator.lenientlyCompareTwoXmlStrings(actual, expected, diag); + if (!same && verbose) + System.out.println(diag.toString()); + + return same; + } + + /** + * This is a workaround for using XmlComparator to compare XML that are just + * a single value like '7' wrapped in tags. Inside + * XmlComparator creates XmlObjects and tags are ignored. So + * this method will replace that with something like so that they look + * like Xml Docs... + */ + protected static String convertFragToDoc(String xmlFragment) { + String startFragStr = " 0); + + GeographicLocation gl = aEventStatus[0].getGeographicLocation(); + CityName cname0 = gl.getCityName(); + ETA eta = aEventStatus[0].getETA(); + CityName cname1 = eta.getGeographicLocation().getCityName(); + assertTrue(cname0.valueEquals(cname1)); + assertEquals(XmlObject.EQUAL, cname0.compareTo(cname1)); + } + + @Test(expected = ClassCastException.class) + public void testCompareToNull() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + assertEquals(XmlObject.NOT_EQUAL, m_xo.compareTo(null)); + } + + @Test + public void testCompareToLessThan() throws Exception { + PurchaseOrderDocument poDoc = (PurchaseOrderDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + + BigDecimal bdUSPrice0 = poDoc.getPurchaseOrder().getItems() + .getItemArray(0) + .getUSPrice(); + BigDecimal bdUSPrice1 = poDoc.getPurchaseOrder().getItems() + .getItemArray(1) + .getUSPrice(); + assertEquals(XmlObject.LESS_THAN, bdUSPrice1.compareTo(bdUSPrice0)); + } + + @Test + public void testCompareToGreaterThan() throws Exception { + PurchaseOrderDocument poDoc = (PurchaseOrderDocument) + XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + BigDecimal bdUSPrice0 = poDoc.getPurchaseOrder().getItems() + .getItemArray(0) + .getUSPrice(); + BigDecimal bdUSPrice1 = poDoc.getPurchaseOrder().getItems() + .getItemArray(1) + .getUSPrice(); + assertEquals(XmlObject.GREATER_THAN, bdUSPrice0.compareTo(bdUSPrice1)); + } + + @Test(expected = ClassCastException.class) + public void testCompareToString() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + assertEquals(0, m_xo.compareTo("")); + } + + @Test + public void testCompareValue() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + XmlCursor m_xc = m_xo.newCursor(); + m_xc.toFirstChild(); + XmlObject xo = m_xc.getObject(); + assertEquals(XmlObject.NOT_EQUAL, m_xo.compareValue(xo)); + } + + private XmlObject m_xo; +} + diff --git a/src/test/java/xmlobject/detailed/CopyTest.java b/src/test/java/xmlobject/detailed/CopyTest.java new file mode 100644 index 0000000..7367b7d --- /dev/null +++ b/src/test/java/xmlobject/detailed/CopyTest.java @@ -0,0 +1,52 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CopyTest { + // Test for a Document object being copied as DocFrag if the type of the + // source of the copy is not a document type (as is the case with NO_TYPE). + @Test + public void testXobjTypeOnDomNodeCopy() throws Exception { + XmlObject o = XmlObject.Factory.parse(""); + String xobjOrgClassName = "org.apache.xmlbeans.impl.store.DocumentXobj"; + assertEquals("Invalid Type!", o.getDomNode().getClass().getName(), xobjOrgClassName); + + XmlObject o2 = o.copy(); + String xobjCopyClassName = o2.getDomNode().getClass().getName(); + System.out.println("DocXobj:" + xobjCopyClassName); + + // check for the expected type + assertEquals("Invalid Type!", "org.apache.xmlbeans.impl.store.DocumentXobj", xobjOrgClassName); + assertEquals("Invalid Type!", "org.apache.xmlbeans.impl.store.DocumentXobj", xobjCopyClassName); + } + + // Test the same for a simple untyped XmlObject copy + @Test + public void testXobjTypeOnCopy() throws Exception { + String untypedXobjClass = "org.apache.xmlbeans.impl.values.XmlAnyTypeImpl"; + + XmlObject o = XmlObject.Factory.parse(""); + assertEquals("Invalid Type!", untypedXobjClass, o.getClass().getName()); + + XmlObject o2 = o.copy(); + // type should be unchanged after the copy + assertEquals("Invalid Type!", untypedXobjClass, o2.getClass().getName()); + } +} diff --git a/src/test/java/xmlobject/detailed/IsImmutableTest.java b/src/test/java/xmlobject/detailed/IsImmutableTest.java new file mode 100755 index 0000000..da98328 --- /dev/null +++ b/src/test/java/xmlobject/detailed/IsImmutableTest.java @@ -0,0 +1,53 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.detailed; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.*; + + +public class IsImmutableTest extends BasicCursorTestCase { + @Test + public void testIsImmutableFalse() throws Exception { + CarLocationMessageDocument clmDoc = + (CarLocationMessageDocument) XmlObject.Factory + .parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + assertFalse(clmDoc.isImmutable()); + } + + @Test + public void testIsImmutableTrue() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//Initial"); + m_xc.toNextSelection(); + SchemaType st = m_xc.getObject().schemaType(); + XmlObject xoNew = st.newValue("ZZZZ"); + assertTrue(xoNew.isImmutable()); + // verify it's not in main store + assertEquals("GATX", m_xc.getTextValue()); + } +} diff --git a/test/src/xmlobject/detailed/NilTest.java b/src/test/java/xmlobject/detailed/NilTest.java similarity index 80% rename from test/src/xmlobject/detailed/NilTest.java rename to src/test/java/xmlobject/detailed/NilTest.java index e1efb0b..f65b787 100755 --- a/test/src/xmlobject/detailed/NilTest.java +++ b/src/test/java/xmlobject/detailed/NilTest.java @@ -16,73 +16,53 @@ package xmlobject.detailed; -import junit.framework.*; - +import knextest.bug38361.TestDocument; import org.apache.xmlbeans.XmlObject; - -import xmlcursor.common.*; - +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.values.XmlValueNotNillableException; +import org.junit.Test; import org.tranxml.tranXML.version40.CarLocationMessageDocument; import org.tranxml.tranXML.version40.CarLocationMessageDocument.CarLocationMessage; import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; -import knextest.bug38361.TestDocument; - - -import org.apache.xmlbeans.impl.values.XmlValueNotNillableException; import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -/** - * - * - */ -public class NilTest extends BasicCursorTestCase { - public NilTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(NilTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } +public class NilTest extends BasicCursorTestCase { + @Test public void testIsNilFalse() throws Exception { CarLocationMessageDocument clmDoc = (CarLocationMessageDocument) XmlObject.Factory.parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); CarLocationMessage clm = clmDoc.getCarLocationMessage(); - assertEquals(false, clm.isNil()); + assertFalse(clm.isNil()); } + @Test public void testSetNilNillable() throws Exception { PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); m_xo = pod.getPurchaseOrder().getShipTo().xgetName(); m_xo.setNil(); - assertEquals(true, m_xo.isNil()); + assertTrue(m_xo.isNil()); } + @Test(expected = XmlValueNotNillableException.class) public void testSetNilNotNillable() throws Exception { + XmlOptions xo = new XmlOptions(); + xo.setValidateOnSet(); CarLocationMessageDocument clmDoc = (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - try { - clmDoc.setNil(); - fail("Expected XmlValueNotNillableException"); - } - catch (XmlValueNotNillableException xvnne) { - } - assertTrue(true); + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM), xo); + clmDoc.setNil(); } /** * Test case for Radar bug: #38361 */ + @Test public void nillableTest() throws Exception { //Generates a xml document programatically TestDocument generated = TestDocument.Factory.newInstance(); diff --git a/src/test/java/xmlobject/detailed/SelectAttributeTests.java b/src/test/java/xmlobject/detailed/SelectAttributeTests.java new file mode 100755 index 0000000..9d84257 --- /dev/null +++ b/src/test/java/xmlobject/detailed/SelectAttributeTests.java @@ -0,0 +1,116 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.openuri.test.selectAttribute.DocDocument; +import xmlobject.common.SelectChildrenAttribCommon; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.Collection; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class SelectAttributeTests extends SelectChildrenAttribCommon { + + private static String saUri = "http://openuri.org/test/selectAttribute"; + private static String saStartFrag = ""; + + private static String abcUri = "http://abc"; + private static String defUri = "http://def"; + + static String anyStartFrag = ""; + + private static String endFrag = ""; + // To speed up tests when running multiple test methods in the same run + private DocDocument.Doc doc = null; + + /////////////////////////////////////////////////////////////////// + // Tests for non-wildcard attributes + @Test + public void testSelectWithQName() + throws Exception { + if (doc == null) + doc = (DocDocument.Doc) getTestObject(); + QName qn = new QName("", "att1"); + XmlObject x = doc.getNormal().selectAttribute(qn); + String exp = saStartFrag + "Attribute 1" + endFrag; + + validateTest("testSelectWithQName", exp, x); + // Check Select with QName that is not present.. should get null back. + x = doc.getWithOther().selectAttribute(qn); + assertNull(x); + } + + + @Test + public void testSelectWithURI() + throws Exception { + if (doc == null) + doc = (DocDocument.Doc) getTestObject(); + + XmlObject x = doc.getNormal().selectAttribute("", "att2"); + String exp = saStartFrag + "Attribute 2" + endFrag; + + validateTest("testSelectWithURI", exp, x); + // Check Select with QName that is not present.. should get null back. + x = doc.getWithAny().selectAttribute("", "att2"); + assertNull(x); + + } + + //////////////////////////////////////////////////////////////////// + // Test for wild-card attributes + @Test + public void testSelectWithQNameForAny() + throws Exception { + if (doc == null) + doc = (DocDocument.Doc) getTestObject(); + + QName qn = new QName(abcUri, "att3"); + String exp = saStartFrag + "Attribute 3" + endFrag; + XmlObject x = doc.getWithOther().selectAttribute(qn); + + validateTest("testSelectWithQNameForAny", exp, x); + + + x = doc.getWithAny(); + System.out.println(x.xmlText()); + + } + + //////////////////////////////////////////////////////////////////// + // Helper + private XmlObject getTestObject() + throws Exception { + String xml = getXml("xbean/xmlobject/SelectAttribute-Doc.xml"); + DocDocument xmlObj = DocDocument.Factory.parse(xml); + DocDocument.Doc doc = xmlObj.getDoc(); + + Collection errors = new ArrayList(); + opts.setErrorListener(errors); + boolean valid = doc.validate(opts); + tools.xml.Utils.printXMLErrors(errors); + + assertTrue("Test Xml is not valid!!", valid); + return doc; + } +} diff --git a/src/test/java/xmlobject/detailed/SelectChildrenTests.java b/src/test/java/xmlobject/detailed/SelectChildrenTests.java new file mode 100755 index 0000000..a4c0057 --- /dev/null +++ b/src/test/java/xmlobject/detailed/SelectChildrenTests.java @@ -0,0 +1,207 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + + +import org.apache.xmlbeans.QNameSet; +import org.apache.xmlbeans.QNameSetBuilder; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.openuri.test.selectChildren.ElemWithAnyDocument; +import org.openuri.test.selectChildren.NormalDocument; +import org.openuri.test.selectChildren.NormalType; +import org.openuri.test.selectChildren.WithAnyType; +import xmlobject.common.SelectChildrenAttribCommon; + +import javax.xml.namespace.QName; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertTrue; + +public class SelectChildrenTests extends SelectChildrenAttribCommon { + private static String scUri = "http://openuri.org/test/selectChildren"; + private static String scStartFrag = ""; + + private static String abcUri = "http://abc"; + private static String defUri = "http://def"; + private static String xyzUri = "http://xyz"; + + private static String anyStartFrag = ""; + + private static String endFrag = ""; + + ////////////////////////////////////////////////////////////////// + // Tests + @Test + public void testSelectWithQName() + throws Exception { + String xml = getXml("xbean/xmlobject/SelectChildren-NormalDoc.xml"); + + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + + NormalDocument doc = NormalDocument.Factory.parse(xml); + assertTrue(doc.validate()); + NormalType norm = doc.getNormal(); + + exps = new String[]{scStartFrag + "first element" + endFrag}; + xos = norm.selectChildren(new QName(scUri, "first")); + + this.validateTest("testSelectWithQName", exps, xos); + } + + @Test + public void testSelectWithURI() + throws Exception { + String xml = getXml("xbean/xmlobject/SelectChildren-NormalDoc.xml"); + + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + + NormalDocument doc = NormalDocument.Factory.parse(xml); + assertTrue(doc.validate()); + NormalType norm = doc.getNormal(); + + exps = new String[]{scStartFrag + "second element" + endFrag}; + xos = norm.selectChildren(scUri, "second"); + + this.validateTest("testSelectWithURI", exps, xos); + } + + @Test + public void testSelectWithQNameSet() + throws Exception { + String xml = getXml("xbean/xmlobject/SelectChildren-NormalDoc.xml"); + + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + + NormalDocument doc = NormalDocument.Factory.parse(xml); + assertTrue(doc.validate()); + NormalType norm = doc.getNormal(); + + QName[] qArr = new QName[]{new QName(scUri, "first"), + new QName(scUri, "numbers"), + new QName(scUri, "second")}; + + QNameSet qSet = QNameSet.forArray(qArr); + + exps = new String[]{scStartFrag + "first element" + endFrag, + scStartFrag + "second element" + endFrag, + scStartFrag + "10" + endFrag, + scStartFrag + "11" + endFrag, + scStartFrag + "12" + endFrag}; + + xos = norm.selectChildren(qSet); + + this.validateTest("testSelectWithQNameSet", exps, xos); + } + + ////////////////////////////////////////////////////////////////////// + // Tests with 'any' Element + @Test + public void testSelectWithQNameForAny() + throws Exception { + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + + String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); + ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); + assertTrue(doc.validate()); + + WithAnyType any = doc.getElemWithAny(); + // Select children from a known namespace + xos = any.selectChildren(new QName(defUri, "someElem2")); + exps = new String[]{anyStartFrag + "DEF Namespace" + endFrag}; + + validateTest("testSelectWithQNameForAny", exps, xos); + } + + @Test + public void testSelectWithURIForAny() + throws Exception { + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + + String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); + ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); + assertTrue(doc.validate()); + + WithAnyType any = doc.getElemWithAny(); + // Select children from a known namespace + xos = any.selectChildren(scUri, "simple"); + exps = new String[]{anyStartFrag + "Simple String" + endFrag}; + + validateTest("testSelectWithURIForAny", exps, xos); + } + + @Test + public void testSelectWithWildcard() + throws Exception { + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); + ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); + assertTrue(doc.validate()); + + WithAnyType any = doc.getElemWithAny(); + + xos = any.selectChildren(QNameSet.forWildcardNamespaceString("##other", + scUri)); + exps = new String[]{anyStartFrag + "ABC Namespace" + endFrag, + anyStartFrag + "DEF Namespace" + endFrag, + anyStartFrag + "XYX Namespace" + endFrag, + anyStartFrag + "ABC-SameElem" + endFrag, + anyStartFrag + "DEF-SameElem" + endFrag, + anyStartFrag + "XYZ-SameElem" + endFrag}; + + validateTest("testSelectWithWildcard", exps, xos); + } + + @Test + public void testSelectWithQNameBuilder() + throws Exception { + XmlObject[] xos; // For the return from selectChildren + String[] exps; // For the expected xml strings + String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); + ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); + assertTrue(doc.validate()); + + WithAnyType any = doc.getElemWithAny(); + + Set excFromIncSet = new HashSet(); + excFromIncSet.add(new QName(scUri, "simple")); + + Set excSet = new HashSet(); + excSet.add(xyzUri); + + Set incFromExcSet = new HashSet(); + incFromExcSet.add(new QName(xyzUri, "sameElem")); + + QNameSet qset = new QNameSetBuilder(excSet, + null, + excFromIncSet, + incFromExcSet).toQNameSet(); + xos = any.selectChildren(qset); + + for (int i = 0; i < xos.length; i++) + System.out.println(xos[i].xmlText()); + } +} diff --git a/src/test/java/xmlobject/detailed/SerializationDetailedTests.java b/src/test/java/xmlobject/detailed/SerializationDetailedTests.java new file mode 100644 index 0000000..5123202 --- /dev/null +++ b/src/test/java/xmlobject/detailed/SerializationDetailedTests.java @@ -0,0 +1,55 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlInteger; +import org.junit.Test; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Node; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.math.BigInteger; + +import static org.junit.Assert.assertTrue; + +public class SerializationDetailedTests { + + @Test + public void testDocFragmentSerialization() throws Exception { + XmlInteger xmlInt = XmlInteger.Factory.newInstance(); + xmlInt.setBigIntegerValue(new BigInteger("10")); + + Node node = xmlInt.getDomNode(); + assertTrue("DOM node from XmlObject not instance of DocumentFragment (it is a " + node + ")", node instanceof DocumentFragment); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(out); + oos.writeObject(xmlInt); + + + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(in); + XmlInteger deserialized = (XmlInteger) ois.readObject(); + + node = deserialized.getDomNode(); + assertTrue("DOM node from deserialized XmlObject not instance of DocumentFragment (it is a " + node + ")", node instanceof DocumentFragment); + } + +} diff --git a/src/test/java/xmlobject/detailed/SetIdentityTest.java b/src/test/java/xmlobject/detailed/SetIdentityTest.java new file mode 100755 index 0000000..a15e480 --- /dev/null +++ b/src/test/java/xmlobject/detailed/SetIdentityTest.java @@ -0,0 +1,56 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import org.tranxml.tranXML.version40.CodeList309; +import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; +import org.tranxml.tranXML.version40.LocationIdentifierDocument.LocationIdentifier; +import tools.util.JarUtil; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + + +public class SetIdentityTest { + @Test + public void testSetIdentity() throws Exception { + CarLocationMessageDocument clm = + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + XmlCursor xc = clm.newCursor(); + + xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + "$this//GeographicLocation"); + xc.toNextSelection(); + GeographicLocation gl = (GeographicLocation) xc.getObject(); + xc.dispose(); + LocationIdentifier li = gl.addNewLocationIdentifier(); + li.setQualifier(CodeList309.FR); + CodeList309 cl309 = li.xgetQualifier(); + // setQualifier to itself, i.e. x == x + li.xsetQualifier(cl309); + gl.setLocationIdentifier(li); + assertEquals(CodeList309.FR, gl.getLocationIdentifier().getQualifier()); + + } + +} + diff --git a/src/test/java/xmlobject/detailed/SoapFaultTest.java b/src/test/java/xmlobject/detailed/SoapFaultTest.java new file mode 100755 index 0000000..41fa11f --- /dev/null +++ b/src/test/java/xmlobject/detailed/SoapFaultTest.java @@ -0,0 +1,113 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Ignore; +import org.junit.Test; +import org.xmlsoap.schemas.soap.envelope.Detail; +import org.xmlsoap.schemas.soap.envelope.Fault; +import xmlobjecttest.soapfaults.FirstFaultType; + +import javax.xml.namespace.QName; +import java.util.ArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SoapFaultTest { + private static final String soapenv = "http://schemas.xmlsoap.org/soap/envelope/"; + + /** + * Regression test for Radar bug #25114 + */ + @Test + @Ignore + public void testSetDetail() throws Exception { + Fault fault = Fault.Factory.newInstance(); + fault.setDetail(Detail.Factory.parse(XmlObject.Factory.parse("").newXMLStreamReader())); + + assertEquals("", fault.xmlText()); + assertEquals("", fault.getDetail().xmlText()); + } + + /** + * Regression test for Radar bug #25119 + */ + @Test + public void testAddNewDetail() throws Exception { + Fault fault = Fault.Factory.newInstance(); + + fault.setFaultcode(new QName(soapenv, "foo")); + fault.setFaultstring("Undefined"); + fault.addNewDetail().set( + XmlObject.Factory.parse("").changeType(Detail.type)); + + String expect = "" + + "soapenv:foo" + + "Undefined" + + "" + + ""; + assertEquals(expect, fault.xmlText()); + assertEquals(new QName(soapenv, "foo"), fault.getFaultcode()); + assertEquals("Undefined", fault.getFaultstring()); + assertEquals("", fault.getDetail().xmlText()); + } + + /** + * Regression test for Radar bug #25409 + */ + @Test + @Ignore + public void testSetFaultDetail() throws Exception { + String soapFault = + "" + + "soapenv:Server" + + "Undefined" + + "" + + " " + + " The First Fault" + + " " + + " " + + " 1" + + " " + + " " + + " 2003-03-28" + + " " + + "" + + ""; + + Fault faultDoc = Fault.Factory.parse(soapFault); + XmlOptions opt = new XmlOptions(); + ArrayList errors = new ArrayList<>(); + opt.setErrorListener(errors); + assertTrue(faultDoc.validate(opt)); + assertEquals(new QName(soapenv, "Server"), faultDoc.getFaultcode()); + assertEquals("Undefined", faultDoc.getFaultstring()); + + + FirstFaultType firstFault = FirstFaultType.Factory.newInstance(); + System.out.println("firstFault = " + firstFault.xmlText()); + firstFault.set(faultDoc.getDetail()); + + assertEquals("The First Fault", firstFault.getAString().trim()); + assertEquals(1, firstFault.getAInt()); + assertEquals(new org.apache.xmlbeans.XmlCalendar("2003-03-28"), + firstFault.getADate()); + } +} diff --git a/src/test/java/xmlobject/detailed/SubstGroupTests.java b/src/test/java/xmlobject/detailed/SubstGroupTests.java new file mode 100644 index 0000000..c2d9104 --- /dev/null +++ b/src/test/java/xmlobject/detailed/SubstGroupTests.java @@ -0,0 +1,292 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlError; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.values.XmlValueDisconnectedException; +import org.junit.Assert; +import org.junit.Test; +import tools.xml.XmlComparator; +import xmlobject.substgroup.*; + +import javax.xml.namespace.QName; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class SubstGroupTests { + /** + * TODO: Determine what the proper Return value is + */ + @Test + public void test_invalidSubstitute() { + OrderItem order = OrderItem.Factory.newInstance(); + ItemType item = order.addNewItem(); + item.setName("ItemType"); + item.setSku(new BigInteger("42")); + + //FootstoolDocument fsd; + try { + + //on invalid substitute orignal value is returned. + FootstoolDocument fsd = (FootstoolDocument) item.substitute( + FootstoolDocument.type.getDocumentElementName(), + FootstoolDocument.type); + fail("Class Cast Exception was thrown on invalid substitute "); + } catch (ClassCastException ccEx) { + } + + XmlObject xm = item.substitute( + FootstoolDocument.type.getDocumentElementName(), + FootstoolDocument.type); + + System.out.println("XM: " + xm.xmlText()); + ArrayList err = new ArrayList(); + XmlOptions xOpts = new XmlOptions().setErrorListener(err); + //no way this should happen + if (xm.validate(xOpts)) { + System.err.println("Invalid substitute validated"); + + for (Iterator iterator = err.iterator(); iterator.hasNext(); ) { + System.err.println("Error: " + iterator.next()); + } + } + + //invalid substitute should leave good state + System.out.println("Item: " + item.xmlText()); + + String exp = "42ItemType"; + + assertEquals("text values should be the same", 0, exp.compareTo(xm.xmlText())); + } + + @Test(expected = XmlValueDisconnectedException.class) + public void test_validSubstitute() { + String URI = "http://xmlobject/substgroup"; + QName name = new QName(URI, "beanBag"); + // get an item + xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); + ItemType item = order.addNewItem(); + item.setName("ItemForTest"); + item.setSku(new BigInteger("12")); + + // types and content before substitution + System.out.println("Before Substitution :\nQNAme Item doc :" + ItemDocument.type.getName()); + System.out.println("QNAme beanBag elem:" + name); + System.out.println("item type:" + item.getClass().getName()); + System.out.println("item XMLText : " + item.xmlText()); + + try { + XmlObject xObj = item.substitute(name, BeanBagType.type); + System.out.println("After Substitution :\nSubstituted XObj text: " + xObj.xmlText()); + System.out.println("Substituted XObj type: " + xObj.getClass().getName()); + Assert.assertNotSame("Invalid Substitution. Xobj Types after substitution are the same.", xObj.getClass().getName(), item.getClass().getName()); + + } catch (NullPointerException npe) { + System.out.println("NPE Thrown: " + npe.getMessage()); + npe.printStackTrace(); + } + + // invoke some operation on the original XmlObject, it should thrown an XmlValueDisconnectedException + item.xmlText(); + } + + /** + * Tests substition upcase, from item to Document, then ensure validation + */ + @Test + public void test_valid_sub() throws Exception { + String expectedXML = "" + + " 12" + + " BeanBagType" + + " Blue" + + ""; + XmlObject xm = XmlObject.Factory.parse(expectedXML); + String itemName = "item"; + BigInteger bInt = new BigInteger("12"); + + xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); + ItemType item = order.addNewItem(); + item.setName(itemName); + item.setSku(bInt); + + System.out.println("Order: " + + order.xmlText(new XmlOptions().setSavePrettyPrint())); + System.out.println("valid: " + order.validate()); + + BeanBagType b2Type = (BeanBagType) item.substitute( + BeanBagDocument.type.getDocumentElementName(), + BeanBagType.type); + + assertEquals("Name Value was not as expected\nactual: " + + b2Type.getName() + + " exp: " + + itemName, 0, b2Type.getName().compareTo(itemName)); + assertEquals("Integer Value was not as Excepted", 0, b2Type.getSku().compareTo(bInt)); + + BeanBagSizeType bbSize = b2Type.addNewSize(); + bbSize.setColor("Blue"); + bbSize.setStringValue("Blue"); + b2Type.setSize(bbSize); + b2Type.setName("BeanBagType"); + + System.out.println("b2Type: " + + b2Type.xmlText(new XmlOptions().setSavePrettyPrint())); + System.out.println("b2Type: " + b2Type.validate()); + + System.out.println("Order: " + + order.xmlText(new XmlOptions().setSavePrettyPrint())); + System.out.println("ovalid: " + order.validate()); + + tools.xml.XmlComparator.Diagnostic diag = new tools.xml.XmlComparator.Diagnostic(); + + if (!XmlComparator.lenientlyCompareTwoXmlStrings(order.xmlText(), + xm.xmlText(), diag)) + throw new Exception("Compare Values Fails\n" + diag.toString()); + } + + @Test(expected = XmlValueDisconnectedException.class) + public void test_item_disconnect() { + String itemName = "item"; + BigInteger bInt = new BigInteger("12"); + boolean exThrown = false; + + xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); + ItemType item = order.addNewItem(); + item.setName(itemName); + item.setSku(bInt); + + System.out.println("Order: " + + order.xmlText(new XmlOptions().setSavePrettyPrint())); + System.out.println("valid: " + order.validate()); + + BeanBagType b2Type = (BeanBagType) item.substitute( + BeanBagDocument.type.getDocumentElementName(), + BeanBagType.type); + + item.xmlText(); + } + + @Test + public void test_item_downcasts_valid() throws Exception { + BigInteger bInt = new BigInteger("12"); + ArrayList err = new ArrayList(); + XmlOptions opts = new XmlOptions( + new XmlOptions().setErrorListener(err)); + + xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); + ItemType item = order.addNewItem(); + + BeanBagType b2Type = (BeanBagType) item.substitute( + BeanBagDocument.type.getDocumentElementName(), + BeanBagType.type); + + BeanBagSizeType bbSize = b2Type.addNewSize(); + bbSize.setColor("Blue"); + bbSize.setStringValue("Blue"); + b2Type.setSku(bInt); + b2Type.setSize(bbSize); + b2Type.setName("BeanBagType"); + + ItemType nItem = order.getItem(); + + //nItem.validate(opts); + if (!nItem.validate(opts)) + System.out.println( + "nItem - Downcasting Failed Validation:\n" + err); + err.clear(); + + item = (ItemType) nItem.substitute( + ItemDocument.type.getDocumentElementName(), + ItemType.type); + + //System.out.println("Item1: " + item.xmlText()); + + if (!item.validate(opts)) + System.out.println("Item - Downcasting Failed Validation:\n" + err); + + XmlError[] xErr = getXmlErrors(err); + assertEquals("Length of xm_errors was greater than expected", 1, xErr.length); + assertEquals("Error Code was not as Expected", 0, xErr[0].getErrorCode().compareTo("cvc-complex-type.2.4b")); + err.clear(); + + String nName = "ItemType"; + item.setName(nName); + System.out.println("Item2: " + item.xmlText()); + + if (!order.validate(opts)) + System.out.println( + "Order - Downcasting Failed Validation:\n" + err); + + //Check value was set + if (!(nName.compareTo(order.getItem().getName()) == 0)) + throw new Exception("Name Value was not changed"); + + //Check Error message + String expText = "Element not allowed: size in element item@http://xmlobject/substgroup"; + XmlError[] xErr2 = getXmlErrors(err); + assertEquals("Length of xm_errors was greater than expected", 1, xErr2.length); + assertEquals("Error Code was not as Expected", 0, xErr2[0].getErrorCode().compareTo("cvc-complex-type.2.4b")); + assertEquals("Error Message was not as expected", 0, xErr2[0].getMessage().compareTo(expText)); + + err.clear(); + } + + private XmlError[] getXmlErrors(ArrayList c) { + XmlError[] errs = new XmlError[c.size()]; + for (int i = 0; i < errs.length; i++) { + errs[i] = (XmlError) c.get(i); + } + return errs; + } + + @Test(expected = IllegalArgumentException.class) + public void test_null_newName() { + xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); + order.substitute(null, OrderItem.type); + } + + @Test(expected = IllegalArgumentException.class) + public void test_null_newType() { + OrderItem order = OrderItem.Factory.newInstance(); + order.substitute(OrderItem.type.getDocumentElementName(), null); + } + + @Test + public void test_unknownQName() { + QName exp = new QName("http://www.w3.org/2001/XMLSchema", "anyType"); + OrderItem order = OrderItem.Factory.newInstance(); + XmlObject xm = order.substitute(new QName("http://baz", "baz"), + OrderItem.type); + + //Verify that the invalid substitution results in an anyType + assertEquals("Namespace URIs were not the same", 0, exp.getNamespaceURI().compareTo( + xm.type.getName().getNamespaceURI())); + assertEquals("Local Part was not as Expected", 0, xm.type.getName().getLocalPart().compareTo( + exp.getLocalPart())); + } + + @Test(expected = IllegalArgumentException.class) + public void test_null_Params() { + XmlObject xml = XmlObject.Factory.newInstance(); + xml.substitute(null, null); + } +} diff --git a/src/test/java/xmlobject/detailed/TestXmlReader.java b/src/test/java/xmlobject/detailed/TestXmlReader.java new file mode 100755 index 0000000..f1f6bac --- /dev/null +++ b/src/test/java/xmlobject/detailed/TestXmlReader.java @@ -0,0 +1,57 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + +import org.junit.Test; +import tools.util.JarUtil; +import xmlobject.common.StringXmlReader; + +import static org.junit.Assert.assertTrue; + + +public class TestXmlReader { + + /** + * Tests read-only concurrency support in XML Beans + * See Radar Bug: 33254 + */ + @Test + public void testConcurrency() throws Exception { + // Get the file contents + String xmlFile = JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml"); + + StringXmlReader rdr1 = new StringXmlReader(xmlFile); + StringXmlReader rdr2 = new StringXmlReader(xmlFile); + StringXmlReader rdr3 = new StringXmlReader(xmlFile); + + Thread t1 = new Thread(rdr1, "Reader1"); + Thread t2 = new Thread(rdr2, "Reader2"); + Thread t3 = new Thread(rdr3, "Reader3"); + t1.start(); + t2.start(); + t3.start(); + + // Wait for threads to finish + t1.join(); + t2.join(); + t3.join(); + + // Check the status of the XmlReaders + boolean status = rdr1.getStatus() & rdr2.getStatus() & rdr3.getStatus(); + + assertTrue("Concurrency Test Failed.", status); + } +} \ No newline at end of file diff --git a/src/test/java/xmlobject/detailed/TestsFromBugs.java b/src/test/java/xmlobject/detailed/TestsFromBugs.java new file mode 100755 index 0000000..1249905 --- /dev/null +++ b/src/test/java/xmlobject/detailed/TestsFromBugs.java @@ -0,0 +1,175 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + +import com.mytest.Bar; +import com.mytest.Foo; +import com.mytest.Info; +import com.mytest.TestDocument; +import org.apache.xmlbeans.*; +import org.junit.Test; +import test.xmlobject.test36510.Test36510AppDocument; + +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Test file that implements test cases that come from closing bugs. + */ +public class TestsFromBugs { + File instance; + + /** + * Radar Bug: 36156 + * Problem with Namespace leaking into siblings + */ + @Test + public void test36156() + throws Exception { + String str = ""; + XmlObject x = XmlObject.Factory.parse(str); + + assertEquals("Test 36156 failed: ", x.xmlText(), str); + } + + /* + * Radar Bug: 36510 + */ + @Test + public void test36510() + throws Exception { + String str = + "" + + "" + + "" + + "These portlets don't" + + " require any guarantee" + + "BEST" + + "" + + ""; + + Test36510AppDocument doc = Test36510AppDocument.Factory.parse(str); + str = doc.getTest36510App().getTestConstraintArray()[0]. + getCustomConstraint().getOptions().toString(); + assertEquals("Test 36510 failed: ", "BEST", str); + } + + + /* + * Radar Bug: 40907 + */ + @Test + public void test40907() + throws Exception { + String str = + "" + + "" + + "this is foo member" + + "" + + ""; + TestDocument doc = TestDocument.Factory.parse(str); + + assertTrue("XML Instance did not validate.", doc.validate()); + + Bar bar = Bar.Factory.newInstance(); + bar.setFooMember("new foo member"); + bar.setBarMember("new bar member"); + + Info info = doc.getTest(); + + Foo foo = info.addNewFoo(); + foo.set(bar); + + assertTrue("Modified XML instance did not validate.", doc.validate()); + str = "" + + "" + + "this is foo member" + + "" + + "" + + "new foo member" + + "new bar member" + + "" + + ""; + assertEquals("XML instance is not as expected", doc.xmlText(), str); + + } + + /** + * Simple Compilation Tests - If the methods are not present, + * - this class won't compile + * Ensures method getSourceName is on SchemaComponent and + * can be called from SchemaGlobalElement and SchemaGlobalAttribute + */ + @Test + public void test199585() throws Exception { + String str = + "\n" + + "\n" + + " " + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " " + + ""; + + XmlObject[] schemas = new XmlObject[]{ + XmlObject.Factory.parse(str)}; + XmlOptions xOpt = new XmlOptions().setValidateTreatLaxAsSkip(); + + SchemaTypeSystem sts = XmlBeans.compileXmlBeans(null, null, schemas, + null, XmlBeans.getBuiltinTypeSystem(), null, xOpt); + + //ensure SchemaGlobalElement has getSourceName Method + SchemaGlobalElement[] sge = sts.globalElements(); + for (int i = 0; i < sge.length; i++) { + System.out.println("SGE SourceName: " + sge[i].getSourceName()); + + } + //ensure SchemaGlobalAttribute has getSourceName Method + SchemaGlobalAttribute[] sga = sts.globalAttributes(); + for (int i = 0; i < sga.length; i++) { + System.out.println("SGE SourceName: " + sga[i].getSourceName()); + } + + //ensure SchemaGlobalElement is a subType of SchemaComponent + SchemaComponent[] sce = sts.globalElements(); + for (int i = 0; i < sce.length; i++) { + System.out.println("SCE SourceName: " + sce[i].getSourceName()); + + } + + //ensure SchemaGlobalAttribute is a subType of SchemaComponent + SchemaComponent[] sca = sts.globalElements(); + for (int i = 0; i < sca.length; i++) { + System.out.println("SCA SourceName: " + sca[i].getSourceName()); + } + } +} diff --git a/src/test/java/xmlobject/detailed/TypedObjectCursor.java b/src/test/java/xmlobject/detailed/TypedObjectCursor.java new file mode 100644 index 0000000..6ac2efa --- /dev/null +++ b/src/test/java/xmlobject/detailed/TypedObjectCursor.java @@ -0,0 +1,48 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.detailed; + +import com.easypo.XmlCustomerBean; +import com.easypo.XmlPurchaseOrderDocumentBean; +import org.apache.xmlbeans.XmlCursor; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class TypedObjectCursor { + + @Test + public void testObjectCursor() { + XmlPurchaseOrderDocumentBean.PurchaseOrder po = XmlPurchaseOrderDocumentBean.PurchaseOrder.Factory.newInstance(); + XmlCursor cur = po.newCursor(); + XmlCustomerBean cust = po.addNewCustomer(); + cust.setAddress("123 Fake Street"); + cust.setAge(23); + cust.setName("Lisa Simpson"); + cur.toFirstContentToken(); + assertEquals(XmlCursor.TokenType.START, cur.currentTokenType()); + assertEquals(XmlCursor.TokenType.ATTR, cur.toNextToken()); + assertEquals("", cur.xmlText()); + assertEquals(XmlCursor.TokenType.START, cur.toNextToken()); + assertEquals(XmlCursor.TokenType.TEXT, cur.toNextToken()); + assertEquals("Lisa Simpson", cur.xmlText()); + assertEquals(XmlCursor.TokenType.END, cur.toNextToken()); + assertEquals(XmlCursor.TokenType.START, cur.toNextToken()); + assertEquals(XmlCursor.TokenType.TEXT, cur.toNextToken()); + assertEquals("123 Fake Street", cur.xmlText()); + cur.toPrevToken(); + cur.setTextValue("456".toCharArray(), 0, 3); + } +} diff --git a/src/test/java/xmlobject/detailed/TypedSettersTests.java b/src/test/java/xmlobject/detailed/TypedSettersTests.java new file mode 100755 index 0000000..5b5d017 --- /dev/null +++ b/src/test/java/xmlobject/detailed/TypedSettersTests.java @@ -0,0 +1,130 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.detailed; + +import org.junit.Assert; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlInt; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + + +public class TypedSettersTests { + private static final String schemaNs = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; + private static final String instanceNs = "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""; + + private static String fmt(String s) { + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + + if (ch != '$') { + sb.append(ch); + continue; + } + + ch = s.charAt(++i); + + String id = ""; + + while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { + id = id + ch; + ch = s.charAt(++i); + } + + String arg = ""; + + if (ch == '(') { + ch = s.charAt(++i); + + while (ch != ')') { + arg += ch; + ch = s.charAt(++i); + } + } else + i--; + + if (id.equals("schema")) + sb.append(schemaNs); + else if (id.equals("xsi")) + sb.append(instanceNs); + else if (id.equals("type")) { + Assert.assertTrue(arg.length() > 0); + sb.append("xsi:type=\"" + arg + "\""); + } else + Assert.fail(); + } + + return sb.toString(); + } + + private static final String nses = schemaNs + " " + instanceNs; + + @Test + public void testJavaNoTypeSingletonElement() + throws Exception { + XmlObject x = XmlObject.Factory.parse(""); + XmlObject x2 = XmlObject.Factory.parse("moo"); + XmlCursor c = x.newCursor(); + XmlCursor c2 = x2.newCursor(); + + c.toNextToken(); + c2.toNextToken(); + + c.getObject().set(c2.getObject()); + + assertEquals("moo", x.xmlText()); + } + + @Test + public void testJavaNoTypeSingletonAttribute() + throws Exception { + XmlObject x = XmlObject.Factory.parse(""); + XmlObject x2 = XmlObject.Factory.parse(""); + XmlCursor c = x.newCursor(); + XmlCursor c2 = x2.newCursor(); + + c.toNextToken(); + c.toNextToken(); + c2.toNextToken(); + c2.toNextToken(); + + c.getObject().set(c2.getObject()); + + assertEquals("", x.xmlText()); + } + + @Test + public void testJavaNoTypeSingletonElementWithXsiType() + throws Exception { + XmlObject x = XmlObject.Factory.parse("", new XmlOptions() + .setDocumentType(XmlObject.type)); + String input = fmt("" + + "69"); + //String input= + XmlObject x2 = XmlObject.Factory.parse(input); + + + assertSame(x2.schemaType(), XmlInt.type); + + } + +} diff --git a/src/test/java/xmlobject/detailed/TypesTest.java b/src/test/java/xmlobject/detailed/TypesTest.java new file mode 100755 index 0000000..62c63ba --- /dev/null +++ b/src/test/java/xmlobject/detailed/TypesTest.java @@ -0,0 +1,113 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.detailed; + +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.*; + + +public class TypesTest extends BasicCursorTestCase { + @Test + public void testSchemaTypeFromStronglyTypedBuiltIn() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//EventStatus/Date"); + m_xc.toNextSelection(); + XmlObject xo = m_xc.getObject(); + SchemaType st = xo.schemaType(); + assertEquals(true, st.isBuiltinType()); + QName q = st.getName(); + assertEquals("{" + Common.XML_SCHEMA_TYPE_SUFFIX + "}date", + q.toString()); + } + + @Test + public void testSchemaTypeFromStronglyTyped() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//EventStatus"); + m_xc.toNextSelection(); + XmlObject xo = m_xc.getObject(); + SchemaType st = xo.schemaType(); + assertEquals(false, st.isBuiltinType()); + assertEquals( + "E=EventStatus|D=EventStatus@" + + Common.TRANXML_SCHEMA_TYPE_SUFFIX, + st.toString()); + + } + + @Test + public void testSchemaTypeFromNonTyped() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); + m_xc = m_xo.newCursor(); + m_xc.selectPath("$this//bar"); + m_xc.toNextSelection(); + XmlObject xo = m_xc.getObject(); + SchemaType st = xo.schemaType(); + assertEquals(true, st.isNoType()); + //assertEquals("TanyType@" + Common.XML_SCHEMA_TYPE_SUFFIX, st.toString()); + } + + @Test + public void testInstanceTypeNotNillable() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + + "$this//EventStatus"); + XmlObject xo = m_xc.getObject(); + assertEquals(xo.schemaType(), ((SimpleValue) xo).instanceType()); + } + + @Test + public void testInstanceTypeNil() throws Exception { + PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); + m_xo = pod.getPurchaseOrder().getShipTo().xgetName(); + m_xo.setNil(); + assertEquals(true, m_xo.isNil()); + if (m_xo.schemaType() == ((SimpleValue) m_xo).instanceType()) { + fail("Nil object's instanceType should not be equal to schemaType"); + } + assertTrue(true); + } + + /* + public void testInstanceTypeUnion() throws Exception + { + // tbd + } + */ + + +} + diff --git a/src/test/java/xmlobject/detailed/ValueEqualsTest.java b/src/test/java/xmlobject/detailed/ValueEqualsTest.java new file mode 100755 index 0000000..11361b6 --- /dev/null +++ b/src/test/java/xmlobject/detailed/ValueEqualsTest.java @@ -0,0 +1,41 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.detailed; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ValueEqualsTest extends BasicCursorTestCase { + @Test + public void testValueEqualsTrue() throws Exception { + CarLocationMessageDocument clmDoc = (CarLocationMessageDocument) + XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + assertEquals(true, clmDoc.valueEquals(m_xo)); + } + +} + diff --git a/src/test/java/xmlobject/detailed/XmlObjectAbstractClassTest.java b/src/test/java/xmlobject/detailed/XmlObjectAbstractClassTest.java new file mode 100755 index 0000000..35a55e5 --- /dev/null +++ b/src/test/java/xmlobject/detailed/XmlObjectAbstractClassTest.java @@ -0,0 +1,123 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.detailed; + +import org.apache.xmlbeans.impl.tool.CodeGenUtil; +import org.junit.Test; +import tools.util.JarUtil; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +/** + * JUnit Test file to test XmlObject Abstract base class + */ + +public class XmlObjectAbstractClassTest { + + /** + * The test entry point. + */ + @Test + public void testAbstractBaseClass() throws Exception { + // create the source file + //String src = JarUtil.getResourceFromJarasStream(Common.XMLCASES_JAR, "xbean/xmlobject/SimpleXmlObject.java.txt"); + File to = new File("build/SimpleXmlObject.java"); + InputStreamReader r = new InputStreamReader( + JarUtil.getResourceFromJarasStream( + "xbean/xmlobject/SimpleXmlObject.java.txt")); + assertTrue("Could not create source file", copyTo(r, to)); + assertTrue("Could not compile SimpleXmlObject.java", compileFile(to)); + to.deleteOnExit(); + } + + + /** + * Compiles the source file. + * The destination for the compiled file is the current directory + */ + private boolean compileFile(File source) { + // the location for the compiled file + File dir = new File("build"); + File[] classpath = CodeGenUtil.systemClasspath(); + List srcFiles = new ArrayList(); + srcFiles.add(source); + + return CodeGenUtil.externalCompile(srcFiles, dir, classpath, false, + CodeGenUtil.DEFAULT_COMPILER, null, CodeGenUtil.DEFAULT_MEM_START, + CodeGenUtil.DEFAULT_MEM_MAX, false, false); + } + + /** + * Copies a file. If destination file exists it will be overwritten + */ + private boolean copyTo(InputStreamReader src, File to) { + try { + // inputstream to read in the file + BufferedReader in = new BufferedReader(src); + + // delete the existing file + to.delete(); + to.createNewFile(); + // outputstream to write out the java file + FileOutputStream fos = new FileOutputStream(to); + int b; + + while ((b = in.read()) != -1) { + fos.write(b); + } + + in.close(); + fos.close(); + } catch (Exception ioe) { + System.out.println("Could not create source file: " + ioe); + ioe.printStackTrace(); + return false; + } + + return true; + } + + /** + * Copies a file. If destination file exists it will be overwritten + */ + private boolean copyTo(File src, File to) { + try { + // inputstream to read in the file + FileInputStream fis = new FileInputStream(src); + + // delete the existing file + to.delete(); + to.createNewFile(); + // outputstream to write out the java file + FileOutputStream fos = new FileOutputStream(to); + int b; + + while ((b = fis.read()) != -1) { + fos.write(b); + } + fis.close(); + fos.close(); + } catch (Exception ioe) { + System.out.println("Could not create source file: " + ioe); + return false; + } + + return true; + } +} diff --git a/test/src/xmlobject/extensions/interfaceFeature/averageCase/checkin/AverageTest.java b/src/test/java/xmlobject/extensions/interfaceFeature/averageCase/checkin/AverageTest.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/averageCase/checkin/AverageTest.java rename to src/test/java/xmlobject/extensions/interfaceFeature/averageCase/checkin/AverageTest.java diff --git a/test/src/xmlobject/extensions/interfaceFeature/averageCase/existing/FooHandler.java b/src/test/java/xmlobject/extensions/interfaceFeature/averageCase/existing/FooHandler.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/averageCase/existing/FooHandler.java rename to src/test/java/xmlobject/extensions/interfaceFeature/averageCase/existing/FooHandler.java diff --git a/test/src/xmlobject/extensions/interfaceFeature/averageCase/existing/IFoo.java b/src/test/java/xmlobject/extensions/interfaceFeature/averageCase/existing/IFoo.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/averageCase/existing/IFoo.java rename to src/test/java/xmlobject/extensions/interfaceFeature/averageCase/existing/IFoo.java diff --git a/src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/checkin/NameCollisionTest.java b/src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/checkin/NameCollisionTest.java new file mode 100755 index 0000000..dda71c4 --- /dev/null +++ b/src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/checkin/NameCollisionTest.java @@ -0,0 +1,78 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.extensions.interfaceFeature.methodNameCollision.checkin; + +import junit.framework.TestCase; +import interfaceFeature.xbean.methodNameCollision.company.CompanyDocument; +import interfaceFeature.xbean.methodNameCollision.company.CompanyType; +import interfaceFeature.xbean.methodNameCollision.company.DepartmentType; +import interfaceFeature.xbean.methodNameCollision.company.ConsultantType; +import xmlobject.extensions.interfaceFeature.methodNameCollision.existing.IFoo; + +import org.apache.xmlbeans.XmlString; + +public class NameCollisionTest extends TestCase { + + public NameCollisionTest(String s) { + super(s); + } + + public void test() { + CompanyDocument poDoc; + + poDoc = CompanyDocument.Factory.newInstance(); + CompanyType po = poDoc.addNewCompany(); + + + int LEN = 20; + + StringBuilder sExpected = new StringBuilder(); + sExpected.append("" + + ""); + DepartmentType dept = po.addNewDepartments(); + ConsultantType[] it = new ConsultantType[LEN]; + for (int i = 0; i < LEN; i++) { + it[i] = dept.addNewConsultant(); + XmlString s = XmlString.Factory.newInstance(); + it[i].setAge(50); + it[i].setName4("BEAN Name" + i); + sExpected.append(""); + } + + sExpected.append(""); + + int[][] ints = new int[2][3]; + for (int i = 0; i < ints.length; i++) + for (int j = 0; j < ints[i].length; j++) + ints[i][j] = (i + 1) * (j + 1); + + IFoo.Inner inner = new IFoo.Inner() { + public String getValue() { + return "inner value"; + } + }; + + assertEquals(sExpected.toString(), poDoc.xmlText()); + assertTrue(poDoc.validate()); + assertEquals("Name0", it[0].getName()); + assertEquals("Name2: [1, 2, 3, ], [2, 4, 6, ], ", it[0].getName2(ints)); + assertEquals("Name3: inner value", it[0].getName3(inner)); + assertEquals("BEAN Name0", it[0].getName4()); + + + } + +} diff --git a/test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/FooHandler.java b/src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/FooHandler.java similarity index 96% rename from test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/FooHandler.java rename to src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/FooHandler.java index a6e239a..7a99230 100755 --- a/test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/FooHandler.java +++ b/src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/FooHandler.java @@ -24,7 +24,7 @@ public static String getName(XmlObject xo){ } public static String getName2(XmlObject xo, int[][] ints){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("Name2: "); for (int i = 0; i < ints.length; i++) { diff --git a/test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/IFoo.java b/src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/IFoo.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/IFoo.java rename to src/test/java/xmlobject/extensions/interfaceFeature/methodNameCollision/existing/IFoo.java diff --git a/test/src/xmlobject/extensions/interfaceFeature/multInterfaces/checkin/MultInterfacesTest.java b/src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/checkin/MultInterfacesTest.java similarity index 95% rename from test/src/xmlobject/extensions/interfaceFeature/multInterfaces/checkin/MultInterfacesTest.java rename to src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/checkin/MultInterfacesTest.java index 34f47ff..48a1641 100755 --- a/test/src/xmlobject/extensions/interfaceFeature/multInterfaces/checkin/MultInterfacesTest.java +++ b/src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/checkin/MultInterfacesTest.java @@ -50,13 +50,13 @@ public void test() { items.setItemArray(it); po.setItems(items); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append( ""); sb.append(""); - StringBuffer sbContent = new StringBuffer(); + StringBuilder sbContent = new StringBuilder(); for (int i = 0; i < LEN; i++) sbContent.append(""+i+""); @@ -74,7 +74,7 @@ public void test() { poDoc.setMinPrice((double)price); - sbContent = new StringBuffer(); + sbContent = new StringBuilder(); for (int i = 0; i < LEN; i++) if( i< price ) sbContent.append(""+price+""); diff --git a/test/src/xmlobject/extensions/interfaceFeature/multInterfaces/existing/IReport.java b/src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/existing/IReport.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/multInterfaces/existing/IReport.java rename to src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/existing/IReport.java diff --git a/test/src/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ISum.java b/src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ISum.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ISum.java rename to src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ISum.java diff --git a/test/src/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ReportHandler.java b/src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ReportHandler.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ReportHandler.java rename to src/test/java/xmlobject/extensions/interfaceFeature/multInterfaces/existing/ReportHandler.java diff --git a/src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/checkin/ReadOnlyTest.java b/src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/checkin/ReadOnlyTest.java new file mode 100755 index 0000000..c9399e4 --- /dev/null +++ b/src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/checkin/ReadOnlyTest.java @@ -0,0 +1,82 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.extensions.interfaceFeature.readOnlyBean.checkin; + + +import interfaceFeature.xbean.readOnlyBean.purchaseOrder.PurchaseOrderDocument; +import interfaceFeature.xbean.readOnlyBean.purchaseOrder.PurchaseOrderType; +import interfaceFeature.xbean.readOnlyBean.purchaseOrder.Items; + + +import java.math.BigDecimal; + +import junit.framework.*; + +public class ReadOnlyTest extends TestCase { + + + public ReadOnlyTest(String s) { + super(s); + } + + public void test() { + + PurchaseOrderDocument poDoc; + + poDoc = PurchaseOrderDocument.Factory.newInstance(); + PurchaseOrderType po = poDoc.addNewPurchaseOrder(); + int LEN = 20; + + Items.Item[] it = new Items.Item[LEN]; + for (int i = 0; i < LEN; i++) { + it[i] = Items.Item.Factory.newInstance(); + it[i].setUSPrice(new BigDecimal("" + 4)); + } + Items items = Items.Factory.newInstance(); + items.setItemArray(it); + po.setItems(items); + + StringBuilder sb = new StringBuilder(); + sb.append( + ""); + + sb.append(""); + + StringBuilder sbContent = new StringBuilder(); + for (int i = 0; i < LEN; i++) + sbContent.append("4"); + + int pos = sb.length(); + sb.append(""); + + String sExpected = sb.subSequence(0, pos) + + sbContent.toString() + + sb.subSequence(pos, sb.length()); + + assertEquals(sExpected, poDoc.xmlText()); + + try { + poDoc.setPrice(10); + + } catch (Exception t) { + t.printStackTrace(System.err); + System.exit(-1); + } + + + assertTrue(!poDoc.validate()); + } + +} diff --git a/test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/FooHandler.java b/src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/FooHandler.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/FooHandler.java rename to src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/FooHandler.java diff --git a/test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/IFoo.java b/src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/IFoo.java similarity index 100% rename from test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/IFoo.java rename to src/test/java/xmlobject/extensions/interfaceFeature/readOnlyBean/existing/IFoo.java diff --git a/src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/checkin/ValueRestrictionTest.java b/src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/checkin/ValueRestrictionTest.java new file mode 100755 index 0000000..e84b714 --- /dev/null +++ b/src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/checkin/ValueRestrictionTest.java @@ -0,0 +1,73 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.extensions.prePostFeature.ValueRestriction.checkin; + +import junit.framework.TestCase; +import prePostFeature.xbean.valueRestriction.company.*; +import org.apache.xmlbeans.XmlString; + + +public class ValueRestrictionTest extends TestCase { + + public ValueRestrictionTest(String s) { + super(s); + } + + public void test() throws Exception { + + CompanyDocument poDoc; + + poDoc = CompanyDocument.Factory.newInstance(); + CompanyType po = poDoc.addNewCompany(); + + + int LEN = 20; + + StringBuilder sExpected = new StringBuilder(); + sExpected.append(""); + DepartmentType dept = po.addNewDepartments(); + ConsultantType[] it = new ConsultantType[LEN]; + for (int i = 0; i < LEN; i++) { + it[i] = dept.addNewConsultant(); + XmlString s = XmlString.Factory.newInstance(); + it[i].setAge(50); + sExpected.append(""); + } + + sExpected.append(""); + + assertEquals(sExpected.toString(), poDoc.xmlText()); + assertTrue(poDoc.validate()); + + + xmlobject.extensions.prePostFeature.ValueRestriction.existing.SetterHandler.bReady = true; + + + for (int i = 0; i < LEN; i++) { + it[i].setAge(150); + } + + assertEquals(sExpected.toString(), poDoc.xmlText()); + assertTrue(poDoc.validate()); + + for (int i = 0; i < LEN; i++) { + it[i].setEmployeeAge(150); + } + assertTrue(sExpected.toString().equals(poDoc.xmlText())); + assertTrue(poDoc.validate()); + } + +} + diff --git a/test/src/xmlobject/extensions/prePostFeature/ValueRestriction/existing/ISetter.java b/src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/existing/ISetter.java similarity index 100% rename from test/src/xmlobject/extensions/prePostFeature/ValueRestriction/existing/ISetter.java rename to src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/existing/ISetter.java diff --git a/test/src/xmlobject/extensions/prePostFeature/ValueRestriction/existing/SetterHandler.java b/src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/existing/SetterHandler.java similarity index 100% rename from test/src/xmlobject/extensions/prePostFeature/ValueRestriction/existing/SetterHandler.java rename to src/test/java/xmlobject/extensions/prePostFeature/ValueRestriction/existing/SetterHandler.java diff --git a/test/src/xmlobject/extensions/prePostFeature/readOnlyBean/checkin/ReadOnlyTest.java b/src/test/java/xmlobject/extensions/prePostFeature/readOnlyBean/checkin/ReadOnlyTest.java similarity index 100% rename from test/src/xmlobject/extensions/prePostFeature/readOnlyBean/checkin/ReadOnlyTest.java rename to src/test/java/xmlobject/extensions/prePostFeature/readOnlyBean/checkin/ReadOnlyTest.java diff --git a/test/src/xmlobject/extensions/prePostFeature/readOnlyBean/existing/FooHandler.java b/src/test/java/xmlobject/extensions/prePostFeature/readOnlyBean/existing/FooHandler.java similarity index 100% rename from test/src/xmlobject/extensions/prePostFeature/readOnlyBean/existing/FooHandler.java rename to src/test/java/xmlobject/extensions/prePostFeature/readOnlyBean/existing/FooHandler.java diff --git a/test/src/xmlobject/extensions/prePostFeature/readOnlyBean/existing/IFoo.java b/src/test/java/xmlobject/extensions/prePostFeature/readOnlyBean/existing/IFoo.java similarity index 100% rename from test/src/xmlobject/extensions/prePostFeature/readOnlyBean/existing/IFoo.java rename to src/test/java/xmlobject/extensions/prePostFeature/readOnlyBean/existing/IFoo.java diff --git a/src/test/java/xmlobject/schematypes/checkin/EnumTests.java b/src/test/java/xmlobject/schematypes/checkin/EnumTests.java new file mode 100755 index 0000000..2804491 --- /dev/null +++ b/src/test/java/xmlobject/schematypes/checkin/EnumTests.java @@ -0,0 +1,156 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.schematypes.checkin; + +import com.enumtest.Data; +import com.enumtest.Quantity; +import com.enumtest.SalesreportDocument; +import com.enumtest.SalesreportDocument.Salesreport.Unit; +import com.enumtest.StatusreportDocument; +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.util.JarUtil; + +import static org.junit.Assert.assertEquals; + + +public class EnumTests { + @Test + public void testReport1() throws Exception { + StatusreportDocument doc = (StatusreportDocument) + XmlObject.Factory.parse( + JarUtil.getResourceFromJarasFile( + "xbean/xmlobject/enumtest.xml")); + + Quantity.Enum[] contents = { + Quantity.ALL, + Quantity.ALL, + Quantity.FEW, + Quantity.ALL, + Quantity.MOST, + Quantity.NONE, + Quantity.NONE, + Quantity.NONE, + }; + Data[] data = doc.getStatusreport().getStatusArray(); + int t = 0; + for (Data datum : data) { + assertEquals(contents[t++], datum.getEnumValue()); + // System.out.println("Target: " + data[i].getTarget() + ", value: " + data[i].enumValue()); + assertEquals(contents[t++], datum.getTarget()); + } + } + + @Test + public void testReport2() { + StatusreportDocument doc = StatusreportDocument.Factory.newInstance(); + StatusreportDocument.Statusreport report = doc.addNewStatusreport(); + + Data d = report.addNewStatus(); + d.setEnumValue(Quantity.ALL); + d.setTarget(Quantity.ALL); + + d = report.addNewStatus(); + d.setEnumValue(Quantity.FEW); + d.setTarget(Quantity.ALL); + + d = report.addNewStatus(); + d.setEnumValue(Quantity.MOST); + d.setTarget(Quantity.NONE); + + d = report.addNewStatus(); + d.setEnumValue(Quantity.NONE); + d.setTarget(Quantity.NONE); + + Quantity.Enum[] contents = { + Quantity.ALL, + Quantity.ALL, + Quantity.FEW, + Quantity.ALL, + Quantity.MOST, + Quantity.NONE, + Quantity.NONE, + Quantity.NONE, + }; + Data[] data = doc.getStatusreport().getStatusArray(); + int t = 0; + for (Data datum : data) { + assertEquals(contents[t++], datum.getEnumValue()); + // System.out.println("Target: " + data[i].getTarget() + ", value: " + data[i].enumValue()); + assertEquals(contents[t++], datum.getTarget()); + } + } + + @Test + public void testReport3() { + SalesreportDocument doc = SalesreportDocument.Factory.newInstance(); + SalesreportDocument.Salesreport report = doc.addNewSalesreport(); + + report.addUnit(Unit.ONE); + report.addUnit(Unit.TWO); + report.addUnit(Unit.NINETY_NINE); + report.addUnit(Unit.ONE_HUNDRED); + + Unit.Enum[] contents = { + Unit.ONE, + Unit.TWO, + Unit.NINETY_NINE, + Unit.ONE_HUNDRED, + }; + + Unit[] xunits = report.xgetUnitArray(); + for (int i = 0; i < xunits.length; i++) { + assertEquals(contents[i], xunits[i].getEnumValue()); + } + + Unit.Enum[] units = report.getUnitArray(); + for (int i = 0; i < units.length; i++) { + assertEquals(contents[i], units[i]); + } + } + + @Test(expected = XmlException.class) + public void testEnumRestriction() throws Exception { + String schema = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + // 'xyz' is an invalid enumeration value + " \n" + + " \n" + + " \n" + + "\n" + + "\n"; + + XmlObject xobj = XmlObject.Factory.parse(schema); + + XmlBeans.loadXsd(new XmlObject[]{xobj}); + } + +} diff --git a/src/test/java/xmlobject/schematypes/checkin/GDateTests.java b/src/test/java/xmlobject/schematypes/checkin/GDateTests.java new file mode 100755 index 0000000..f8f1404 --- /dev/null +++ b/src/test/java/xmlobject/schematypes/checkin/GDateTests.java @@ -0,0 +1,699 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.schematypes.checkin; + +import org.apache.xmlbeans.*; +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigDecimal; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import static org.junit.Assert.*; + +public class GDateTests { + + private static String[] validDurations = { + "PT0S", + "P1Y", + "P1M", + "P1D", + "P2Y", + "P2M", + "P2D", + "PT1H", + "PT1M", + "PT1S", + "PT3600S", + "P1Y1M1DT1H1M1S", + "P1Y1M1DT1H1M1.1S", + "P1Y365D", + "P1Y366D", + "PT0.1S", + "P1M29D", + + "PT0.1415926S", + "PT5233132S", + "PT142332M", + "PT98023H", + + "-PT0S", + "-P1Y", + "-P1M", + "-P1D", + "-PT1H", + "-PT1M", + "-PT1S", + "-P1Y1M1DT1H1M1S", + "-P1Y1M1DT1H1M1.1S", + "-P27D", + "-P28D", + "-P29D", + "-P30D", + "-P31D", + "-P364D", + "-P365D", + "-P366D", + "-PT0.1S", + "-PT0.1415926S", + "-PT5233132S", + "-PT142332M", + "-PT98023H", + + }; + + private static String[] invalidDurations = { + "P1Y-364D", + "P1Y-365D", + "P1Y-366D", + "P1Y-367D", + "P1Y-12M", + "P1M-27D", + "P1M-28D", + "P1M-29D", + "P1M-31D", + "P1M-32D", + "P1MT-660H", + "P1MT-670H", + "P1MT-680H", + "P1MT-690H", + "P1MT-700H", + "P1MT-710H", + "P1MT-720H", + "P1MT-730H", + "P1MT-740H", + + "-PT-0S", + "-P-1Y", + "-P-1M", + "-P-1D", + "-PT-1H", + "-PT-1M", + "-PT-1S", + "-P1Y1M-1DT1H1M1S", + "-P1Y1M1DT1H-1M1.1S", + "-PT-0.1S", + "-PT-0.1415926S", + }; + + private static String[] invalidDates = { + "+14:01", // tz + "-14:01", // tz + "+15:00", // tz + "-15:00", // tz + "X", + ",", + "T", + "+", + "-", + ":", + "0", + "March 2", + "T00:00:00Z", // T not allowed + "-00:00:00Z", // - not allowed + "96-02-28T00:00:00Z", // year width + "100-02-28T00:00:00Z", // year width + "1900-2-28T00:00:00Z", // month width + "1900-02-8T00:00:00Z", // day width + "1900-02-08T0:00:00Z", // hour width + "1900-02-08T00:0:00Z", // hour width + "1900-02-08T00:00:0Z", // hour width + "1900-02-08T00:00Z", // time incomplete + "1900-02-08 T00:00:00Z", // space + "1900-02-08T 00:00:00Z", // space + "1900-02-08T00:00:00 Z", // space + "1900-02-29T00Z", // time incomplete + "00:00", // time incomplete + "00", // incomplete + "2100-02-29", // not leap + "-999999999-02-28T00:00:00Z", // too long ago + "999999999-02-28T00:00:00Z", // too long from now + "9999999999999999999999999999999-02-28T00:00:00Z", // overflow? + "0000-01-01", // year zero + "0000-12-31T04:35:22.456", // year zero + "1996-00-28T00:00:00Z", // month + "1996-13-28T00:00:00Z", // month + "1996-02-00T00:00:00Z", // day + "2000-02-30T00:00:00Z", // day + "1996-02-29T25:00:00Z", // hr + "1996-02-29T24:00:01Z", // hr + "1996-02-29T00:60:00Z", // min + "1996-02-29T00:00:60Z", // sec + "1996-02-29T00:00:00+14:01", // tz + "1996-02-29T00:00:00-14:01", // tz + "1996-02-29T00:00:00+15:00", // tz + "1996-02-29T00:00:00-15:00", // tz + "1996-00-29", // month + "1996-13-29", // month + "1996-02-00", // day + "2000-02-30", // day + "--00", // month + "--13", // month + "--00-01", // month + "--13-01", // month + "--02-00", // day + "--02-30", // day + "--01-32", // day + "--11-31", // day + "---00", // day + "---32", // day + "25:00:00Z", // hr + "24:01:00Z", // hr + "00:60:00Z", // min + "00:00:60Z", // sec + "00:00:00+14:01", // tz + "00:00:00-14:01", // tz + "00:00:00+15:00", // tz + "00:00:00-15:00", // tz + }; + + private static String[] validDates = { + "", + "Z", // timezone only + "-14:00", // timezone only + "999999-12-31T23:59:59.999Z", + "1970-12-31T23:59:59.990+14:00", + "1996-02-29T00:00:00Z", // leap + "2000-02-29T00:00:00Z", // leap + "2004-02-29T00:00:00Z", // leap + "2008-02-29T00:00:00Z", // leap + "2012-02-29T00:00:00Z", // leap + "1900-02-28T00:00:00Z", // not leap + "2100-02-28T00:00:00Z", // not leap + "1900-03-28T00:00:00Z", // not leap + "-4712-01-01T00:00:00Z", + "1999-01-01T00:00:00+01:00", + "2001-12-31T23:59:59.010", + "2001-12-31T23:59:59.999901000", + "1999-12-31T23:59:59.1234567890-14:00", + "1992-12-31T23:59:59.01-14:00", + "1965-12-31T23:59:59.000Z", + //"0000-12-31T04:35:22.456", + "1696-09-01T00:00:00Z", + "1697-02-01T00:00:00Z", + "1903-03-01T00:00:00Z", + "1903-07-01T00:00:00Z", + "1696-09-01T00:00:00+00:00", + "1697-02-01T00:00:00-00:00", + "2002", + "-0001", + "--12", + "-0001-11", + "2002-01", + "---31", + "1554--31", + "-0004--31", + "--02-29", + "--12-31", + "2002-04-18", + "-0423-12-31", + "23:59:59", + "00:00:00", + "2010T23:59:59", + "-0001T00:00:00", + "--12T23:59:59", + "-0001-11T00:00:00", + "2011-01T23:59:59", + "---31T00:00:00", + "2002--31T23:59:59", + "-0004--31T00:00:00", + "2002-02-18T23:59:59", + "-0423-12-31T00:00:00", + "2002Z", + "-0001+01:30", + "--12-14:00", + "-0001-11Z", + "1970-12-01:00", + "---31+01:30", + "2002--31Z", + "--03-31-03:00", + "--04-30+05:00", + "-0004--31-01:00", + "2002-04-18-14:00", + "-0423-12-31Z", + "23:59:59-01:00", + "00:00:00Z", + "00:00:00+01:30", + "1776T23:59:59-14:00", + "-0001T00:00:00Z", + "--12T23:59:59+01:30", + "-0001-11T00:00:00-01:00", + "2002-02T23:59:59Z", + "---31T00:00:00-14:00", + "2002--31T23:59:59-01:00", + "-0004--31T00:00:00+01:30", + "2002-04-18T23:59:59Z", + "-0423-12-31T00:00:00-05:00", + "1996-02-29T24:00:00Z", // 24:00:00 is valid + "24:00:00Z", // 24:00:00 is valid + + }; + + private boolean hasTime(GDuration gd) { + return gd.getHour() != 0 || gd.getMinute() != 0 || gd.getSecond() != 0 || gd.getFraction().signum() != 0; + } + + @Test + public void testGregorianCalendar() { + // this is a check of DST offsets + Date date = new GDate("2002-04-18T23:59:59Z").getDate(); + GregorianCalendar gcal = new XmlCalendar(date); + assertEquals(date, gcal.getTime()); + + // now check out some things + GDate gd = new GDate("2001-12-31T07:00:59.010"); + GregorianCalendar gc = gd.getCalendar(); + Date gdd = gd.getDate(); + Date gcd = gc.getTime(); + assertEquals(gdd, gcd); + + // set up 2/29, and read out Feb 29 in the year 1 BC. + Calendar gregcal = new GDate("--02-29").getCalendar(); + assertEquals(29, gregcal.get(Calendar.DAY_OF_MONTH)); + assertEquals(2 - 1, gregcal.get(Calendar.MONTH)); + assertEquals(1, gregcal.get(Calendar.YEAR)); + assertEquals(0, gregcal.get(Calendar.ERA)); + // repeat some tests to make sure it's stable. + assertEquals(29, gregcal.get(Calendar.DAY_OF_MONTH)); + assertEquals(2 - 1, gregcal.get(Calendar.MONTH)); + + // now try some setters + gregcal = new GDate("--02-29").getCalendar(); + gregcal.set(Calendar.MONTH, 10); + assertEquals("--11-29", gregcal.toString()); + // repeat to ensure it's stable. + assertEquals("--11-29", gregcal.toString()); + } + + private void _testEmptyDuration(GDuration gd) { + assertTrue(gd.isValid()); + assertEquals("PT0S", gd.toString()); + assertEquals(0, gd.getYear()); + assertEquals(0, gd.getMonth()); + assertEquals(0, gd.getDay()); + assertEquals(0, gd.getHour()); + assertEquals(0, gd.getMinute()); + assertEquals(0, gd.getSecond()); + assertEquals(new java.math.BigDecimal(0.0), gd.getFraction()); + } + + @Test + public void testEmptyDuration() { + GDuration gd = new GDuration(); + _testEmptyDuration(gd); + GDuration gdCopy = new GDuration(gd); + _testEmptyDuration(gdCopy); + } + + @Test + public void testValidDuration() { + for (int i = 0; i < validDurations.length; i++) { + GDuration gd = null; + String str = validDurations[i]; + try { + gd = new GDuration(str); + } catch (IllegalArgumentException e) { + Assert.fail("Problem with " + str + ": " + e.getMessage()); + } + + assertEquals(str, gd.toString()); + + for (int j = 0; j < validDurations.length; j++) { + GDuration gd2 = null; + String str2 = validDurations[j]; + try { + gd2 = new GDuration(str2); + } catch (IllegalArgumentException e) { + Assert.fail("Problem with " + str2 + ": " + e.getMessage()); + } + + // subtracting two ways works + GDuration diff = gd.subtract(gd2); + GDurationBuilder gdb = new GDurationBuilder(gd2); + gdb.setSign(-gdb.getSign()); + gdb.addGDuration(gd); + GDuration sum2 = gdb.toGDuration(); + assertEquals(0, diff.compareToGDuration(sum2)); + gdb.normalize(); + GDurationBuilder gdb1 = new GDurationBuilder(diff); + gdb1.normalize(); + assertEquals("Problem: " + gd + " and " + gd2, gdb.toString(), gdb1.toString()); + + // comparing is reversible + int comp1 = gd.compareToGDuration(gd2); + int comp2 = gd2.compareToGDuration(gd); + if (comp1 == 2) + assertEquals(2, comp2); + else + assertEquals(-comp1, comp2); + + // comparing translates to addition to dates + boolean[] seen = new boolean[3]; + + for (int k = 0; k < validDates.length; k++) { + GDate date = new GDate(validDates[k]); + if (!date.hasDate() || date.getYear() > 99999 || date.getYear() < -4000) + continue; + if ((hasTime(gd) || hasTime(gd2)) && !date.hasTime()) + continue; + // System.out.println("Adding " + gd + " and " + gd2 + " to " + date + ", expecting " + comp1); + GDate date1 = date.add(gd); + GDate date2 = date.add(gd2); + + comp2 = date1.compareToGDate(date2); + if (comp1 != 2) { + assertEquals("Adding " + date + " + " + gd + " -> " + date1 + ", " + gd2 + " -> " + date2 + ", expecting " + comp1, comp1, comp2); + } else { + assertTrue(comp2 != 2); + seen[comp2 + 1] = true; + } + + // subtraction should yield the same result + if (comp1 != 2) { + GDate date3 = date.add(diff); + assertEquals(comp1, date3.compareToGDate(date)); + } + } + + if (comp1 == 2) { + int seencount = 0; + for (int k = 0; k < seen.length; k++) + if (seen[k]) + seencount += 1; + assertTrue("Not ambiguous as advertised" /* + gd + ", " + gd2 + " d: " + diff */, seencount > 1); + } + } + } + } + + private void _testAddAndSubtract(String date1, String date2, + String duration) { + GDate gd1 = new GDate(date1); + GDate gd2 = new GDate(date2); + GDuration gdur = new GDuration(duration); + GDate gd = gd1.add(gdur); + System.out.println(date1 + " + " + duration + " = " + gd.toString()); + assertEquals(gd2, gd); + gd = gd2.subtract(gdur); + System.out.println(date2 + " - " + duration + " = " + gd.toString()); + assertEquals(gd1, gd); + } + + private void _testAdd(String date1, String date2, String duration) { + GDate gd1 = new GDate(date1); + GDate gd2 = new GDate(date2); + GDuration gdur = new GDuration(duration); + GDate gd = gd1.add(gdur); + System.out.println(date1 + " + " + duration + " = " + gd.toString()); + assertEquals(gd2, gd); + } + + private void _testSubtract(String date1, String date2, String duration) { + GDate gd1 = new GDate(date1); + GDate gd2 = new GDate(date2); + GDuration gdur = new GDuration(duration); + GDate gd = gd2.subtract(gdur); + System.out.println(date2 + " - " + duration + " = " + gd.toString()); + assertEquals(gd1, gd); + } + + @Test + public void testAddAndSubtractDuration() { + _testAddAndSubtract("1970-01-01", "1973-01-01", "P3Y"); + _testAddAndSubtract("0001-01-01", "0004-01-01", "P3Y"); + // there is no year 0, so 1 BCE + 3Y = 3 CE + _testAddAndSubtract("-0001-01-01", "0003-01-01", "P3Y"); + _testAddAndSubtract("-0002-01-01", "0003-01-01", "P4Y"); + _testAddAndSubtract("-0001-01-01", "0001-01-01", "P1Y"); + _testSubtract("-0001-02-29", "0004-02-29", "P4Y"); + _testSubtract("-0001-12-31", "0001-01-01", "P1D"); + _testSubtract("-0002-12-31", "0001-12-31", "P731D"); + _testAddAndSubtract("1970-01-01T00:00:00", "1973-02-01T01:30:45", "P3Y31DT1H30M45S"); + _testAddAndSubtract("-0001-01-01T00:00:00", "0003-02-01T01:30:45", "P3Y31DT1H30M45S"); + // addition and subtraction of duration is not necessarily symmetric + // if duration is not constant, i.e., contains a component that varies + // in length, such as month (or year) + _testAdd("2000-02-29", "2001-02-28", "P1Y"); + _testSubtract("2000-02-28", "2001-02-28", "P1Y"); + _testAddAndSubtract("1970-01-01T23:00:00", "1970-01-02T00:00:00", "PT1H"); + _testAddAndSubtract("1970-01-01T00:00:00", "1969-12-31T23:00:00", "-PT1H"); + _testAddAndSubtract("1970-01-01T00:00:00", "1969-12-31T22:59:59", "-PT1H1S"); + _testAddAndSubtract("1971-02-02T01:01:01.1", "1970-01-01T00:00:00", "-P1Y1M1DT1H1M1.1S"); + _testAdd("1970-01-01T00:00:00", "1968-11-29T22:58:58.9", "-P1Y1M1DT1H1M1.1S"); + _testSubtract("1969-12-31T00:00:00", "1968-11-29T22:58:58.9", "-P1Y1M1DT1H1M1.1S"); + _testAdd("0001-01-01T00:00:00", "-0002-11-29T22:58:58.9", "-P1Y1M1DT1H1M1.1S"); + _testSubtract("0001-01-01T00:00:00", "-0002-11-29T22:58:58.9", "-P1Y1M2DT1H1M1.1S"); + } + + @Test + public void testOrder() { + assertEquals(-1, new GDate("1998-08-26").compareToGDate(new GDate("2001-08-06"))); + assertEquals(-1, new GDate("1970-12-20T04:14:22Z").compareToGDate(new GDate("1971-04-18T12:51:41Z"))); + assertEquals(2, new GDate("2001-08-06").compareToGDate(new GDate("2001-08-06Z"))); + assertEquals(2, new GDate("2001-08-06").compareToGDate(new GDate("2001-08-07+10:00"))); + assertEquals(2, new GDate("2001-08-06").compareToGDate(new GDate("2001-08-05-10:00"))); + assertEquals(2, new GDate("2001-02-28").compareToGDate(new GDate("2001-03-01+10:00"))); + assertEquals(2, new GDate("2001-03-01").compareToGDate(new GDate("2001-02-28-10:00"))); + assertEquals(-1, new GDate("2000-02-28").compareToGDate(new GDate("2000-03-01+10:00"))); + assertEquals(1, new GDate("2000-03-01").compareToGDate(new GDate("2000-02-28-10:00"))); + assertEquals(-1, new GDate("2001-08-06Z").compareToGDate(new GDate("2001-08-06-00:01"))); + assertEquals(0, new GDate("00:00:00Z").compareToGDate(new GDate("00:01:00+00:01"))); + assertEquals(0, new GDate("12:00:00-05:00").compareToGDate(new GDate("09:00:00-08:00"))); + assertEquals(-1, new GDate("09:00:00-05:00").compareToGDate(new GDate("09:00:00-08:00"))); // the east coast rises before the west + assertEquals(-1, new GDate("2003-05-05T09:00:00-05:00").compareToGDate(new GDate("2003-05-05T09:00:00-08:00"))); // the east coast rises before the west + assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---31"))); + assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---31+14:00"))); + assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---31-14:00"))); + assertEquals(1, new GDate("---31").compareToGDate(new GDate("---01"))); + assertEquals(1, new GDate("---31").compareToGDate(new GDate("---01+14:00"))); + assertEquals(1, new GDate("---31").compareToGDate(new GDate("---01-14:00"))); + assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---02"))); + assertEquals(1, new GDate("---02").compareToGDate(new GDate("---01"))); + assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---02Z"))); + assertEquals(1, new GDate("---02").compareToGDate(new GDate("---01Z"))); + assertEquals(2, new GDate("---02").compareToGDate(new GDate("---01-10:00"))); + assertEquals(2, new GDate("---01").compareToGDate(new GDate("---02+10:00"))); + assertEquals(1, new GDate("---02").compareToGDate(new GDate("---01-09:00"))); + assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---02+09:00"))); + assertEquals(0, new GDate("---01").compareToGDate(new GDate("---01"))); + assertEquals(-1, new GDate("2003").compareToGDate(new GDate("2004"))); + assertEquals(-1, new GDate("--11").compareToGDate(new GDate("--12"))); + assertEquals(-1, new GDate("2003-12").compareToGDate(new GDate("2004-01"))); + assertEquals(-1, new GDate("--11-30").compareToGDate(new GDate("--12-01"))); + assertEquals(-1, new GDate("--02-28").compareToGDate(new GDate("--02-29"))); + assertEquals(-1, new GDate("--02-29").compareToGDate(new GDate("--03-01"))); + assertEquals(2, new GDate("--02-29").compareToGDate(new GDate("--03-01+10:00"))); + assertEquals(2, new GDate("--02-28").compareToGDate(new GDate("--03-01+10:00"))); + assertEquals(2, new GDate("--03-01").compareToGDate(new GDate("--02-28-10:00"))); + assertEquals(2, new GDate("--03-01").compareToGDate(new GDate("--02-29-10:00"))); + assertEquals(-1, new GDate("--02-29").compareToGDate(new GDate("--03-01+09:00"))); + assertEquals(-1, new GDate("--02-28").compareToGDate(new GDate("--03-01+09:00"))); + assertEquals(1, new GDate("--03-01").compareToGDate(new GDate("--02-28-09:00"))); + assertEquals(1, new GDate("--03-01").compareToGDate(new GDate("--02-29-09:00"))); + assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:59"))); + assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:59+09:59"))); + assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:01+09:59"))); + assertEquals(2, new GDate("00:00:00").compareToGDate(new GDate("23:59:00+09:59"))); + assertEquals(2, new GDate("00:00:00").compareToGDate(new GDate("23:59:59+10:00"))); + assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:59-14:00"))); + assertEquals(1, new GDate("23:59:59").compareToGDate(new GDate("00:00:00-09:59"))); + assertEquals(1, new GDate("23:59:59").compareToGDate(new GDate("00:00:58-09:59"))); + assertEquals(2, new GDate("23:59:59").compareToGDate(new GDate("00:00:59-09:59"))); + assertEquals(2, new GDate("23:59:59").compareToGDate(new GDate("00:00:00-10:00"))); + assertEquals(1, new GDate("23:59:59").compareToGDate(new GDate("00:00:00+14:00"))); + } + + @Test + public void testAPI() throws Exception { + GDateBuilder builder = new GDateBuilder("1970-12-20T04:14:22Z"); + builder.normalizeToTimeZone(1, 0, 0); + assertEquals("1970-12-20T04:14:22+00:00", builder.toString()); + builder.setTimeZone(615); + assertEquals("1970-12-20T04:14:22+10:15", builder.toString()); + builder.setTimeZone(-345); + assertEquals("1970-12-20T04:14:22-05:45", builder.toString()); + builder.normalizeToTimeZone(-300); + assertEquals("1970-12-20T04:59:22-05:00", builder.toString()); + } + + @Test + public void testFailure() throws Exception { + for (int i = 0; i < invalidDurations.length; i++) { + String str = invalidDurations[i]; + try { + new GDuration(str); + } catch (IllegalArgumentException e) { + continue; + } + Assert.fail("Missing exception for GDuration: " + str); + } + + for (int i = 0; i < invalidDates.length; i++) { + String str = invalidDates[i]; + try { + new GDate(str); + } catch (IllegalArgumentException e) { + continue; + } + Assert.fail("Missing exception for GDate " + str); + } + } + + @Test + public void testSuccess() throws Exception { + for (int i = 0; i < validDates.length; i++) { + String str = validDates[i]; + GDate gdate = null; + try { + gdate = new GDate(str); + } catch (IllegalArgumentException e) { + Assert.fail("Problem with " + str + ": " + e.getMessage()); + } + + // for 24h if hasDay must be normalized, else has the same representation + if (str.contains("24:00:00") && gdate.hasDay()) { + assertTrue(str + " " + gdate.toString(), gdate.hasDay() && gdate.toString().contains("00:00:00")); + } else + // must round-trip to string + assertEquals(str, gdate.toString()); + + // must round-trip to GregorianCalendar if fractions-of-seconds <=3 digits + if (gdate.getFraction() == null || gdate.getFraction().scale() <= 3) + if (!gdate.toString().equals("--02-29")) // bug in gcal -> 03-01 + { + GregorianCalendar gcal = gdate.getCalendar(); + GDate gdate2 = new GDate(gcal); + assertEquals(gdate, gdate2); + + // and if fractions-of-seconds is 3 digits, stringrep must round-trip + if (gdate.getFraction() == null || gdate.getFraction().scale() == 3 || gdate.getFraction().scale() == 0) + assertEquals(gdate.toString(), gdate2.toString()); + } + + // must round-trip to Date if absolute time+timezone + fractions-of-seconds <= 3 + if (gdate.hasTimeZone() && gdate.getYear() > -4000 && gdate.getYear() < 99999 && gdate.getBuiltinTypeCode() == SchemaType.BTC_DATE_TIME && gdate.getFraction().scale() <= 3) { + Date date = gdate.getDate(); + GDate gdate2 = new GDate(date); + assertEquals(gdate, gdate2); + + // normalize to UTC fractions-of-seconds is 0 or 3 digits [not 000], stringrep must round-trip + if (gdate.getTimeZoneSign() == 0 && ((gdate.getFraction().scale() == 3 && gdate.getFraction().signum() != 0) || gdate.getFraction().scale() == 0)) { + GDateBuilder gdb = new GDateBuilder(gdate2); + gdb.normalizeToTimeZone(0, 0, 0); + assertEquals(gdate.toString(), gdb.toString()); + } + + // verify that going through gcal gives us the same thing + GregorianCalendar gcal = gdate.getCalendar(); + assertEquals(date, gcal.getTime()); + + // double-check XmlCalendar constructor + gcal = new XmlCalendar(date); + assertEquals("Doing " + gdate, date, gcal.getTime()); + } else if (gdate.hasDate() && (gdate.getFraction() == null || gdate.getFraction().scale() <= 3)) { + // must be able to get a date if time+timezone is unset (midnight, ltz are assumed) + Date date = gdate.getDate(); + GDateBuilder gdate1 = new GDateBuilder(gdate); + if (!gdate1.hasTime()) + gdate1.setTime(0, 0, 0, null); + assertEquals(gdate1.getDate(), date); + + // verify that going through gcal gives us the same thing + GregorianCalendar gcal = gdate.getCalendar(); + assertEquals("Comparing " + gdate + " and " + gcal, date, gcal.getTime()); + } + } + } + + @Test + public void test24hDates() { + GDate d1 = new GDate("2004-03-31T24:00:00"); + assertEquals("2004-04-01T00:00:00", d1.toString()); + + + GDateBuilder b = new GDateBuilder(); + b.setTime(24, 0, 0, new BigDecimal("0.00")); + System.out.println("hour 24: " + b.getCalendar()); + assertEquals("24:00:00.000", b.getCalendar().toString()); + + b.setDay(10); + b.setMonth(1); + System.out.println("hour 24: " + b.getCalendar()); + assertEquals("--01-10T24:00:00.000", b.getCalendar().toString()); + + b.setYear(2010); + System.out.println("hour 24: " + b.getCalendar()); + assertEquals("2010-01-10T24:00:00.000", b.getCalendar().toString()); + + b.setDay(31); + b.setMonth(03); + b.setYear(2004); + + System.out.println("hour 24: canonical str: " + b.canonicalString()); + assertEquals("2004-04-01T00:00:00", b.canonicalString()); + System.out.println("hour 24: toString: " + b.toString()); + assertEquals("2004-03-31T24:00:00.00", b.toString()); + System.out.println("hour 24: toGDate: " + b.toGDate()); + assertEquals("2004-03-31T24:00:00.00", b.toGDate().toString()); + System.out.println("hour 24: toGDate().canonicalStr: " + b.toGDate().canonicalString()); + assertEquals("2004-04-01T00:00:00", b.toGDate().canonicalString()); + System.out.println("hour 24: toGDate().getCal: " + b.toGDate().getCalendar()); + assertEquals("2004-03-31T24:00:00.000", b.toGDate().getCalendar().toString()); + + + GDateBuilder gdb = new GDateBuilder("24:00:00+01:00"); + System.out.println("gdb: " + gdb); + assertEquals("24:00:00+01:00", gdb.toString()); + + gdb.normalize(); + System.out.println("gdb.normalize(): " + gdb); + assertEquals("23:00:00Z", gdb.toString()); + } + + @Test + public void testYearStartingWith0() { + GDate gdate = new GDate("0004-08-01"); // 00004-08-01 must fail + System.out.println("year starting with 0: " + gdate.getCalendar()); + assertEquals("0004-08-01", gdate.toString()); + + String txt = "-9999-06"; + GDate d = new GDate(txt); + System.out.println(" gdate(" + txt + ") = " + d); + assertEquals("-9999-06", d.toString()); + + txt = "-12345-06"; + d = new GDate(txt); + System.out.println(" gdate(" + txt + ") = " + d); + assertEquals(txt, d.toString()); + + + try { + txt = "00004-08-01"; + d = new GDate(txt); // 00004-08-01 must fail + fail("Year starting with 0 of five digits: " + txt); + } catch (IllegalArgumentException e) { + } + + try { + txt = "-012340-08-01"; + d = new GDate(txt); + fail("Year starting with 0 of six digits: " + txt); + } catch (IllegalArgumentException e) { + } + } +} diff --git a/src/test/java/xmlobject/schematypes/checkin/IntTests.java b/src/test/java/xmlobject/schematypes/checkin/IntTests.java new file mode 100755 index 0000000..49f545f --- /dev/null +++ b/src/test/java/xmlobject/schematypes/checkin/IntTests.java @@ -0,0 +1,38 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.schematypes.checkin; + +import org.apache.xmlbeans.XmlException; +import org.junit.Test; +import xint.test.PositionDocument; + +import static org.junit.Assert.assertEquals; + +public class IntTests { + @Test + public void testLatLong() throws XmlException { + PositionDocument doc = PositionDocument.Factory.parse( + "43020"); + assertEquals(43, doc.getPosition().getLat()); + assertEquals(20, doc.getPosition().getLon()); + doc.getPosition().xgetLat().setStringValue("07"); + doc.getPosition().xgetLon().setStringValue("040"); + assertEquals(7, doc.getPosition().getLat()); + assertEquals(40, doc.getPosition().getLon()); + doc.getPosition().setLat((short) 22); + } +} diff --git a/src/test/java/xmlobject/schematypes/checkin/NumeralsTests.java b/src/test/java/xmlobject/schematypes/checkin/NumeralsTests.java new file mode 100755 index 0000000..9f22271 --- /dev/null +++ b/src/test/java/xmlobject/schematypes/checkin/NumeralsTests.java @@ -0,0 +1,247 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.schematypes.checkin; + + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openuri.testNumerals.DocDocument; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import static org.junit.Assert.*; + +public class NumeralsTests { + private static DocDocument.Doc doc; + + @BeforeClass + public static void initDoc() throws XmlException { + String inst = + "\n" + + " this is a long string \n" + + " ... \n" + + " \n" + + " +5\n" + + " \n" + + " \n" + + " -6\n" + + " \n" + + " \n" + + " +00000000015\n" + + " \n" + + " 77\n" + + " \n" + + " true\n" + + " \n" + + " \n" + + " false\n" + + " \n" + + " \n" + + " 0\n" + + " \n" + + " \n" + + " 1\n" + + " \n" + + " \n" + + " true is not\n" + + " \n" + + " \n" + + " +03\n" + + " \n" + + " \n" + + " +001\n" + + " \n" + + " -0500000\n" + + " \n" + + " 001\n" + + " \n" + + " \n" + + " +002\n" + + " \n" + + " \n" + + " +001\n" + + " \n" + + " \n" + + " -002.007000\n" + + " \n" + + " \n" + + " INF\n" + + " \n" + + " \n" + + " -INF\n" + + " \n" + + " \n" + + " NaN\n" + + " \n" + + " \n" + + " +12.325\n" + + " \n" + + " \n" + + " NaN\n" + + " \n" + + " \n" + + " INF\n" + + " \n" + + " \n" + + " -INF\n" + + " \n" + + " \n" + + " +001.001\n" + + " \n" + + " \n" + + " +001000000000\n" + + " \n" + + ""; + + doc = DocDocument.Factory.parse(inst).getDoc(); + } + + @Test + public void test1() { + String s = " this is a long string \n" + " ... "; + assertEquals("String expected:\n'" + s + "' actual:\n'" + + doc.getStringArray()[0] + "'", s, doc.getStringArray()[0]); + } + + @Test + public void test2() { + assertEquals("int expected:" + 5 + " actual:" + doc.getIntArray()[0], 5, doc.getIntArray()[0]); + } + + @Test + public void test3() { + assertEquals("int expected:" + (-6) + " actual:" + doc.getIntArray()[1], doc.getIntArray()[1], -6); + } + + @Test + public void test4() { + assertEquals("int expected:" + 15 + " actual:" + doc.getIntArray()[2], 15, doc.getIntArray()[2]); + } + + @Test + public void test5() { + assertEquals("int expected:" + 77 + " actual:" + doc.getIntArray()[3], 77, doc.getIntArray()[3]); + } + + @Test + public void test6() { + assertTrue(doc.getBooleanArray(0)); + } + + @Test + public void test7() { + assertFalse(doc.getBooleanArray(1)); + } + + @Test + public void test8() { + assertFalse(doc.getBooleanArray(2)); + } + + @Test + public void test9() { + assertTrue(doc.getBooleanArray(3)); + } + + @Test(expected = XmlValueOutOfRangeException.class) + public void test10() { + boolean b = doc.getBooleanArray()[4]; + } + + @Test + public void test11() { + assertEquals(3, doc.getShortArray()[0]); + } + + @Test + public void test12() { + assertEquals(1, doc.getByteArray()[0]); + } + + @Test + public void test13() { + assertEquals("long expected:" + (-50000) + " actual:" + doc.getLongArray()[0], doc.getLongArray()[0], -500000); + } + + @Test + public void test14() { + assertEquals("long expected:" + 1 + " actual:" + doc.getLongArray()[1], 1, doc.getLongArray()[1]); + } + + @Test + public void test15() { + assertEquals("long expected:" + 2 + " actual:" + doc.getLongArray()[2], 2, doc.getLongArray()[2]); + } + + @Test + public void test16() { + assertEquals(1, doc.getDoubleArray()[0], 0.0); + } + + @Test + public void test17() { + assertEquals("double expected:" + -2.007d + " actual:" + doc.getDoubleArray()[1], doc.getDoubleArray()[1], -2.007d, 0.0); + } + + @Test + public void test18() { + assertEquals(Double.POSITIVE_INFINITY, doc.getDoubleArray()[2], 0); + } + + @Test + public void test19() { + assertEquals(Double.NEGATIVE_INFINITY, doc.getDoubleArray()[3], 0); + } + + @Test + public void test20() { + assertEquals(Double.NaN, doc.getDoubleArray()[4], 0); + } + + @Test + public void test21() { + assertEquals("fload expected:" + 12.325f + " actual:" + doc.getFloatArray()[0], 12.325f, doc.getFloatArray()[0], 0.0); + } + + @Test + public void test22() { + assertEquals(Float.NaN, doc.getFloatArray()[1], 0); + } + + @Test + public void test23() { + assertEquals("fload expected:" + Float.POSITIVE_INFINITY + " actual:" + doc.getFloatArray()[2], Float.POSITIVE_INFINITY, doc.getFloatArray()[2], 0); + } + + @Test + public void test24() { + assertEquals(Float.NEGATIVE_INFINITY, doc.getFloatArray()[3], 0); + } + + @Test + public void test25() { + assertEquals(new BigDecimal("1.001"), doc.getDecimalArray()[0]); + } + + @Test + public void test26() { + assertEquals(new BigInteger("1000000000"), doc.getIntegerArray(0)); + } +} diff --git a/src/test/java/xmlobject/schematypes/checkin/QNameTests.java b/src/test/java/xmlobject/schematypes/checkin/QNameTests.java new file mode 100755 index 0000000..f7f51cf --- /dev/null +++ b/src/test/java/xmlobject/schematypes/checkin/QNameTests.java @@ -0,0 +1,102 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.schematypes.checkin; + +import org.apache.xmlbeans.*; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class QNameTests { + static String[] _args; + static String _test; + + @Test + public void testQName() throws Exception { + String schema = + "\n" + + "" + + " \n" + + " \n" + + "" + + "\n" + + ""; + + SchemaTypeLoader stl = + XmlBeans.loadXsd(new XmlObject[]{ + XmlObject.Factory.parse(schema)}); + + // + // Test the set_XMLName function on XmlQNameImpl + // + + String ns = + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " + + "xmlns:xs='http://www.w3.org/2001/XMLSchema'"; + + XmlObject sourceDocument = + stl.parse( + "" + + "xxx:abc", null, null); + + XmlCursor sourceCursor = sourceDocument.newCursor(); + + sourceCursor.toFirstChild(); + + XmlQName sourceQName = (XmlQName) sourceCursor.getObject(); + + XmlObject targetDocument = + stl.parse( + "" + + "", null, null); + + XmlCursor targetCursor = targetDocument.newCursor(); + + targetCursor.toFirstChild(); + + XmlQName targetQName = (XmlQName) targetCursor.getObject(); + + targetQName.set(sourceQName); + + assertEquals("xxx.com", targetQName.getQNameValue().getNamespaceURI()); + + // + // Test the set_text function on XmlQNameImpl + // + + targetDocument = + stl.parse( + "" + + "", null, null); + + targetCursor = targetDocument.newCursor(); + + targetCursor.toFirstChild(); + + targetQName = (XmlQName) targetCursor.getObject(); + + try { + targetQName.setStringValue("zzz:abc"); + fail("Must fail"); + } catch (Throwable t) { + } + + targetQName.setStringValue("xxx:abc"); + + assertEquals("xxx.com", targetQName.getQNameValue().getNamespaceURI()); + } +} diff --git a/src/test/java/xmlobject/schematypes/checkin/SchemaTypesTests.java b/src/test/java/xmlobject/schematypes/checkin/SchemaTypesTests.java new file mode 100755 index 0000000..bce2628 --- /dev/null +++ b/src/test/java/xmlobject/schematypes/checkin/SchemaTypesTests.java @@ -0,0 +1,199 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmlobject.schematypes.checkin; + +import org.apache.xmlbeans.*; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.junit.Test; +import org.openuri.def.DefaultsDocument; +import org.openuri.xstypes.test.CustomerDocument; +import org.openuri.xstypes.test.Person; +import tools.util.JarUtil; + +import javax.xml.namespace.QName; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SchemaTypesTests { + + private CustomerDocument doc; + + private void ensureDoc() + throws Exception { + if (doc == null) { + doc = (CustomerDocument) + XmlObject.Factory.parse( + JarUtil.getResourceFromJarasFile("xbean/xmlobject/person.xml")); + } + } + + @Test + public void testDefaults() { + DefaultsDocument doc = DefaultsDocument.Factory.newInstance(); + DefaultsDocument.Defaults defs = doc.addNewDefaults(); + assertEquals(783, defs.getCool()); // this is the default value + } + + @Test + public void testSourceName() throws IOException, XmlException { + String name = DefaultsDocument.type.getSourceName(); + assertEquals("defaults.xsd", name); + InputStream str = XmlBeans.getContextTypeLoader().getSourceAsStream("defaults.xsd"); + SchemaDocument doc = SchemaDocument.Factory.parse(str); + assertTrue(doc.validate()); + } + + @Test + public void testRead() throws Exception { + ensureDoc(); + + // Move from the root to the root customer element + Person person = doc.getCustomer(); + assertEquals("Howdy", person.getFirstname()); + assertEquals(4, person.sizeOfNumberArray()); + assertEquals(436, person.getNumberArray(0)); + assertEquals(123, person.getNumberArray(1)); + assertEquals(44, person.getNumberArray(2)); + assertEquals(933, person.getNumberArray(3)); + assertEquals(2, person.sizeOfBirthdayArray()); + assertEquals(new XmlCalendar("1998-08-26Z"), + person.getBirthdayArray(0)); + assertEquals(new XmlCalendar("2000-08-06-08:00"), + person.getBirthdayArray(1)); + + Person.Gender.Enum g = person.getGender(); + assertEquals(Person.Gender.MALE, g); + + assertEquals("EGIQTWYZJ", new String(person.getHex())); + assertEquals("This string is base64Binary encoded!", + new String(person.getBase64())); + + assertEquals("GGIQTWYGG", new String(person.getHexAtt())); + assertEquals("This string is base64Binary encoded!", + new String(person.getBase64Att())); + + assertEquals("{some_uri}localname", person.getQnameAtt().toString()); + assertEquals("{http://openuri.org/xstypes/test}openuri_org_localname", person.getQname().toString()); + + //assertEquals("http://dmoz.org/World/Fran\u00e7ais/", person.getAnyuriAtt().toString()); + assertEquals("http://3space.org/space%20space/", person.getAnyuri().toString()); + + //RuntimeException: src/xmlstore/org/apache/xmlbeans/impl/store/Splay.java(1537): ns != null && ns.length() > 0 failed + //assertEquals("JPEG", person.getNotationAtt().toString()); + //assertEquals("GIF", person.getNotation().toString()); + } + + @Test + public void testWriteRead() throws Exception { + ensureDoc(); + // Move from the root to the root customer element + Person person = doc.getCustomer(); + + person.setFirstname("George"); + assertEquals("George", person.getFirstname()); + + person.setHex("hex encoding".getBytes()); + assertEquals("hex encoding", new String(person.getHex())); + + person.setBase64("base64 encoded".getBytes()); + assertEquals("base64 encoded", + new String(person.getBase64())); + + person.setHexAtt("hex encoding in attributes".getBytes()); + assertEquals("hex encoding in attributes", + new String(person.getHexAtt())); + + person.setBase64Att("This string is base64Binary encoded!".getBytes()); + assertEquals("This string is base64Binary encoded!", + new String(person.getBase64Att())); + + person.setAnyuri("a.c:7001"); + assertEquals("a.c:7001", person.getAnyuri()); + + person.setAnyuriAtt("b.d:7002"); + assertEquals("b.d:7002", person.getAnyuriAtt()); + + person.setQnameAtt(new QName("aaa","bbb")); + assertEquals("{aaa}bbb", person.getQnameAtt().toString()); + + person.setQname(new QName("ddd","eee")); + assertEquals("{ddd}eee", person.getQname().toString()); + + //Exception: src/xmlstore/org/apache/xmlbeans/impl/store/Type.java(189): user == _user failed +// person.setAnyuriAtt(URI.create("b.d:7002")); +// assertEquals("b.d:7002", person.getAnyuriAtt().toString()); + + //XmlNOTATION notation = (XmlNOTATION)Person.Notation.type.createNode(); + //notation.setValue("JPEG"); + //person.setNotation( notation ); + //assertEquals("JPEG", person.getNotation().toString()); + + //XmlNOTATION notationAtt = (XmlNOTATION)Person.NotationAtt.type.createNode(); + //notationAtt.setValue("GIF"); + //person.setNotationAtt( notationAtt ); + //person.setNotationAtt(notation); + //assertEquals("GIF", person.getNotationAtt().toString()); + } + + @Test + public void testStoreWrite() throws Exception { + ensureDoc(); + // Move from the root to the root customer element + Person person = doc.getCustomer(); + + XmlObject xmlobj; + XmlCursor xmlcurs; + + person.setFirstname("George"); + xmlobj = person.xgetFirstname(); + xmlcurs = xmlobj.newCursor(); + assertEquals("George", xmlcurs.getTextValue() ); + + person.setQnameAtt( new QName("http://ggg.com","hhh") ); + xmlobj = person.xgetQnameAtt(); + xmlcurs = xmlobj.newCursor(); + assertEquals("ggg:hhh", xmlcurs.getTextValue() ); + + person.setQname( new QName("http://ggg.com/gggAgain","kkk") ); + xmlobj = person.xgetQname(); + xmlcurs = xmlobj.newCursor(); + assertEquals("ggg1:kkk", xmlcurs.getTextValue() ); + + person.setAnyuri( "crossgain.com" ); + xmlobj = person.xgetAnyuri(); + xmlcurs = xmlobj.newCursor(); + assertEquals("crossgain.com", xmlcurs.getTextValue() ); + + person.setAnyuriAtt( "www.crossgain.com" ); + xmlobj = person.xgetAnyuriAtt(); + xmlcurs = xmlobj.newCursor(); + assertEquals("www.crossgain.com", xmlcurs.getTextValue() ); + + //person.setNotation("GIF"); + //xmlobj = person.getNotation(); + //xmlcurs = xmlobj.newXmlCursor(); + //assertEquals("GIF", xmlcurs.getText() ); + + //person.setNotationAtt("JPEGu"); + //xmlobj = person.xgetNotationAtt(); + //xmlcurs = xmlobj.newXmlCursor(); + //assertEquals("JPEG", xmlcurs.getText() ); + } +} diff --git a/src/test/java/xmlobject/schematypes/detailed/ListAndUnionTests.java b/src/test/java/xmlobject/schematypes/detailed/ListAndUnionTests.java new file mode 100755 index 0000000..087a964 --- /dev/null +++ b/src/test/java/xmlobject/schematypes/detailed/ListAndUnionTests.java @@ -0,0 +1,172 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.schematypes.detailed; + +import org.junit.Assert; +import org.apache.xmlbeans.*; +import org.junit.Test; +import org.openuri.lut.DateOrDateTime; +import org.openuri.lut.IncidentReportsDocument; +import org.openuri.lut.ListsDocument; +import org.openuri.lut.UnionsDocument; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Calendar; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class ListAndUnionTests { + @Test + public void testListGetters() throws Exception { + ListsDocument lists = ListsDocument.Factory.parse( + "2 4 8 16 32unbounded 3 unbounded 6"); + List intList = lists.getLists().getIntList(); + assertEquals(2, intList.get(0)); + assertEquals(4, intList.get(1)); + assertEquals(8, intList.get(2)); + assertEquals(16, intList.get(3)); + assertEquals(32, intList.get(4)); + assertEquals(5, intList.size()); + + List nniList = lists.getLists().getNniList(); + assertEquals("unbounded", nniList.get(0)); + assertEquals(BigInteger.valueOf(3), nniList.get(1)); + assertEquals("unbounded", nniList.get(2)); + assertEquals(BigInteger.valueOf(6), nniList.get(3)); + assertEquals(4, nniList.size()); + } + + @Test + public void testListSetters() throws Exception { + ListsDocument doc = ListsDocument.Factory.newInstance(); + ListsDocument.Lists lists = doc.addNewLists(); + lists.setIntList(Arrays.asList(4, 18)); + lists.setNniList(Arrays.asList(BigInteger.valueOf(1), BigInteger.valueOf(2), "unbounded")); + String xtext = doc.xmlText(); + + ListsDocument docrt = ListsDocument.Factory.parse(xtext); + List intList = docrt.getLists().getIntList(); + assertEquals(4, intList.get(0)); + assertEquals(18, intList.get(1)); + assertEquals(2, intList.size()); + + List nniList = docrt.getLists().getNniList(); + assertEquals(BigInteger.valueOf(1), nniList.get(0)); + assertEquals(BigInteger.valueOf(2), nniList.get(1)); + assertEquals("unbounded", nniList.get(2)); + assertEquals(3, nniList.size()); + } + + @Test + public void testUnionGetters() throws Exception { + UnionsDocument unions = UnionsDocument.Factory.parse( + "unbounded2 3 5 7 11"); + + assertEquals("unbounded", unions.getUnions().getNni()); + + Assert.assertTrue(unions.getUnions().getSizes() instanceof List); + List sizes = (List) unions.getUnions().getSizes(); + assertEquals(2, sizes.get(0)); + assertEquals(3, sizes.get(1)); + assertEquals(5, sizes.get(2)); + assertEquals(7, sizes.get(3)); + assertEquals(11, sizes.get(4)); + assertEquals(5, sizes.size()); + + UnionsDocument unions2 = UnionsDocument.Factory.parse( + "37all"); + + assertEquals(BigInteger.valueOf(37), unions2.getUnions().getNni()); + assertEquals("all", unions2.getUnions().getSizes()); + } + + @Test + public void testUnionSetters() throws Exception { + + // create a document + UnionsDocument doc = UnionsDocument.Factory.newInstance(); + UnionsDocument.Unions unions = doc.addNewUnions(); + unions.setNni("unbounded"); + unions.setSizes(Arrays.asList(5, 22)); + + // round trip to s text + String xtext = doc.xmlText(); + UnionsDocument docrt = UnionsDocument.Factory.parse(xtext); + + // verify contents + assertEquals("unbounded", docrt.getUnions().getNni()); + List sizes = (List) docrt.getUnions().getSizes(); + assertEquals(5, sizes.get(0)); + assertEquals(22, sizes.get(1)); + assertEquals(2, sizes.size()); + + // change the original document + unions.setNni(11); + unions.setSizes("unknown"); + + // round trip it again + xtext = doc.xmlText(); + docrt = UnionsDocument.Factory.parse(xtext); + + // verify contents again + assertEquals(BigInteger.valueOf(11), docrt.getUnions().getNni()); + assertEquals("unknown", docrt.getUnions().getSizes()); + } + + @Test + public void testUnionArray() throws Exception { + IncidentReportsDocument doc = IncidentReportsDocument.Factory.parse( + "" + + "2001-08-06T03:34:00" + + "2002-01-04" + + "2002-08-26T23:10:00" + + ""); + IncidentReportsDocument.IncidentReports reports = doc.getIncidentReports(); + DateOrDateTime[] dt = reports.xgetWhenArray(); + Calendar[] gd = reports.getWhenArray(); + assertEquals(3, dt.length); + assertEquals(3, gd.length); + for (int i = 0; i < 3; i++) { + assertEquals(((SimpleValue) dt[i]).getGDateValue(), new GDate(gd[i])); + assertEquals(gd[i], dt[i].getObjectValue()); + } + + assertEquals(new XmlCalendar("2001-08-06T03:34:00"), gd[0]); + assertEquals(new XmlCalendar("2002-01-04"), gd[1]); + assertEquals(new XmlCalendar("2002-08-26T23:10:00"), gd[2]); + + assertEquals(XmlDateTime.type, dt[0].instanceType()); + assertEquals(XmlDate.type, dt[1].instanceType()); + assertEquals(XmlDateTime.type, dt[2].instanceType()); + + reports.setWhenArray(0, new XmlCalendar("1980-04-18")); + reports.setWhenArray(1, new XmlCalendar("1970-12-20T04:33:00")); + + dt = reports.xgetWhenArray(); + gd = reports.getWhenArray(); + + assertEquals(new XmlCalendar("1980-04-18"), gd[0]); + assertEquals(new XmlCalendar("1970-12-20T04:33:00"), gd[1]); + assertEquals(new XmlCalendar("2002-08-26T23:10:00"), gd[2]); + + assertEquals(XmlDate.type, dt[0].instanceType()); + assertEquals(XmlDateTime.type, dt[1].instanceType()); + assertEquals(XmlDateTime.type, dt[2].instanceType()); + + } + +} diff --git a/src/test/java/xmlobject/schematypes/detailed/QNameSetTest.java b/src/test/java/xmlobject/schematypes/detailed/QNameSetTest.java new file mode 100755 index 0000000..d3fa2ef --- /dev/null +++ b/src/test/java/xmlobject/schematypes/detailed/QNameSetTest.java @@ -0,0 +1,247 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.schematypes.detailed; + +import org.apache.xmlbeans.QNameSetBuilder; +import org.junit.Test; + +import javax.xml.namespace.QName; +import java.util.Random; +import java.util.Stack; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class QNameSetTest { + + private static String format(int iter, String p, QNameSetBuilder set) { + return "case# " + iter + " " + p + " " + set.toString(); + } + + @Test + public void testQNameSets() { + int iterations = 10000; + int seed = 0; + + Random rnd = new Random(seed); + String[] localname = {"a", "b", "c", "d", "e"}; + String[] namespace = {"n1", "n2", "n3", "n4", "n5"}; + int width = localname.length; + + QName[] name = new QName[width * namespace.length]; + for (int i = 0; i < width; i++) { + for (int j = 0; j < namespace.length; j++) { + name[i + width * j] = new QName(namespace[j], localname[i]); + } + } + + Stack teststack = new Stack(); // stack of sets + Stack trackstack = new Stack(); // stack of boolean arrays + + QNameSetBuilder current = new QNameSetBuilder(); + boolean[] contents = new boolean[width * namespace.length]; + boolean[] temp; + int i = 0; + int j = 0; + + for (int l = 0; l < iterations; l++) { + // apply a random operation + + if (rnd.nextInt(3) != 0) { + i = rnd.nextInt(width - 1); // don't do the last one for isAll test + j = rnd.nextInt(namespace.length - 1); // don't do the last one for isAll test + } + + switch (teststack.size() < 1 ? 24 : rnd.nextInt(iterations - l > teststack.size() ? 24 : 5)) { + default: + // new + teststack.push(current); + trackstack.push(contents); + current = new QNameSetBuilder(); + contents = new boolean[width * namespace.length]; + break; + + case 19: + case 20: + case 22: + // random + teststack.push(current); + trackstack.push(contents); + current = new QNameSetBuilder(); + contents = new boolean[width * namespace.length]; + + if (rnd.nextInt(2) == 0) { + current.invert(); + for (int k = 0; k < width; k++) { + contents[k + width * (namespace.length - 1)] = true; + } + } + + for (int h = 0; h < namespace.length - 1; h++) { + if (rnd.nextInt(2) == 0) + current.removeNamespace(namespace[h]); + else { + current.addNamespace(namespace[h]); + contents[width - 1 + width * h] = true; + } + for (int k = 0; k < width - 1; k++) { + if (rnd.nextInt(2) == 0) + current.remove(name[k + width * h]); + else { + current.add(name[k + width * h]); + contents[k + width * h] = true; + } + } + } + break; + + case 0: + // add set + current.addAll(teststack.pop()); + temp = trackstack.pop(); + for (int k = 0; k < width * namespace.length; k++) + if (temp[k]) + contents[k] = true; + break; + + case 1: + // remove set + current.removeAll(teststack.pop()); + temp = trackstack.pop(); + for (int k = 0; k < width * namespace.length; k++) + if (temp[k]) + contents[k] = false; + break; + + case 2: + // restrict set + current.restrict(teststack.pop()); + temp = trackstack.pop(); + for (int k = 0; k < width * namespace.length; k++) + if (!temp[k]) + contents[k] = false; + break; + + case 3: + // union + current = new QNameSetBuilder(current.union(teststack.pop())); + temp = trackstack.pop(); + for (int k = 0; k < width * namespace.length; k++) + if (temp[k]) + contents[k] = true; + break; + + case 4: + // intersect + current = new QNameSetBuilder(current.intersect(teststack.pop())); + temp = trackstack.pop(); + for (int k = 0; k < width * namespace.length; k++) + if (!temp[k]) + contents[k] = false; + break; + + case 5: + // copy + current = new QNameSetBuilder(current); + break; + + case 6: + case 7: + case 8: + // add one + name[i + width * j]; + current.add(name[i + width * j]); + contents[i + width * j] = true; + break; + + case 9: + case 10: + case 11: + // remove one + name[i + width * j]; + current.remove(name[i + width * j]); + contents[i + width * j] = false; + break; + + case 12: + case 13: + // add namespace + namespace[j]; + current.addNamespace(namespace[j]); + for (int k = 0; k < width; k++) + contents[k + width * j] = true; + break; + + case 14: + case 15: + // remove namespace + namespace[j]; + current.removeNamespace(namespace[j]); + for (int k = 0; k < width; k++) + contents[k + width * j] = false; + break; + + case 16: + case 17: + // invert + current.invert(); + for (int k = 0; k < width * namespace.length; k++) + contents[k] = !contents[k]; + break; + + case 18: + // inverse + current = new QNameSetBuilder(current.inverse()); + for (int k = 0; k < width * namespace.length; k++) + contents[k] = !contents[k]; + break; + + } + + // System.out.println(format(teststack.size(), l, label, current)); + + // then, verify current matches contents + int count = 0; + for (int k = 0; k < width * namespace.length; k++) { + assertTrue(format(l, "Content mismatch " + name[k], current), (current.contains(name[k]) == contents[k])); + if (contents[k]) + count++; + } + + assertTrue(format(l, "ERROR: isEmpty is wrong", current), ((count == 0) == current.isEmpty())); + + assertEquals(format(l, "ERROR: isAll is wrong", current), (count == width * namespace.length), current.isAll()); + + // test isDisjoint and containsAll + if (teststack.size() >= 1) { + boolean disjoint = true; + temp = trackstack.peek(); + for (int k = 0; k < width * namespace.length; k++) { + if (temp[k] && contents[k]) { + disjoint = false; + break; + } + } + assertEquals(format(l, "ERROR: disjoint is wrong", current), disjoint, current.isDisjoint(teststack.peek())); + + boolean containsAll = true; + for (int k = 0; k < width * namespace.length; k++) { + if (temp[k] && !contents[k]) { + containsAll = false; + break; + } + } + assertEquals(format(l, "ERROR: containsAll is wrong", current), containsAll, current.containsAll(teststack.peek())); + } + } + } +} diff --git a/src/test/java/xmlobject/usertype/averageCase/checkin/AverageTest.java b/src/test/java/xmlobject/usertype/averageCase/checkin/AverageTest.java new file mode 100644 index 0000000..d8a05a8 --- /dev/null +++ b/src/test/java/xmlobject/usertype/averageCase/checkin/AverageTest.java @@ -0,0 +1,78 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.usertype.averageCase.checkin; + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.junit.Test; +import usertype.xbean.averageCase.purchaseOrder.Items; +import usertype.xbean.averageCase.purchaseOrder.PurchaseOrderDocument; +import usertype.xbean.averageCase.purchaseOrder.PurchaseOrderType; +import xmlobject.usertype.averageCase.existing.SKU; + +import java.math.BigDecimal; + +import static org.junit.Assert.assertEquals; + + +public class AverageTest { + + @Test + public void test(){ + PurchaseOrderDocument poDoc = PurchaseOrderDocument.Factory.newInstance(); + PurchaseOrderType po=poDoc.addNewPurchaseOrder(); + int LEN=20; + + Items.Item[] it= new Items.Item[LEN]; + for (int i=0; i< LEN; i++){ + it[i]=Items.Item.Factory.newInstance(); + it[i].setUSPrice(new BigDecimal(""+ 2 )); + it[i].setPartNum(new SKU(i, "AB")); + } + Items items= Items.Factory.newInstance(); + items.setItemArray(it); + po.setItems(items); + + for (int i=0; i< LEN; i++){ + assertEquals(i, it[i].getPartNum().getDigits()); + assertEquals("AB", it[i].getPartNum().getLetters()); + } + } + + @Test(expected = XmlValueOutOfRangeException.class) + public void testBadInput() throws XmlException{ + String sb = + "" + + "2" + + "2" + + ""; + PurchaseOrderDocument poDocument = PurchaseOrderDocument.Factory.parse(sb); + + PurchaseOrderType po = poDocument.getPurchaseOrder(); + + Items.Item[] it = po.getItems().getItemArray(); + assertEquals(2, it.length); + + + SKU sku = it[0].getPartNum(); + + assertEquals(0, sku.getDigits()); + assertEquals("AB", sku.getLetters()); + + it[1].getPartNum(); + // Invalid SKU format should fail + } +} diff --git a/src/test/java/xmlobject/usertype/averageCase/existing/SKU.java b/src/test/java/xmlobject/usertype/averageCase/existing/SKU.java new file mode 100644 index 0000000..244c3ba --- /dev/null +++ b/src/test/java/xmlobject/usertype/averageCase/existing/SKU.java @@ -0,0 +1,57 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.usertype.averageCase.existing; + +public class SKU +{ + private int digits; + private String letters; + + + public SKU() + { + } + + public SKU(int digits, String letters) + { + setDigits(digits); + setLetters(letters); + } + + public int getDigits() + { + return digits; + } + + public void setDigits(int digits) + { + if (digits > 999 || digits < 0) + throw new IllegalArgumentException("bad digits"); + this.digits = digits; + } + + public String getLetters() + { + return letters; + } + + public void setLetters(String letters) + { + if (letters == null || letters.length() != 2) + throw new IllegalArgumentException("bad letters"); + this.letters = letters; + } +} diff --git a/src/test/java/xmlobject/usertype/averageCase/existing/SKUHandler.java b/src/test/java/xmlobject/usertype/averageCase/existing/SKUHandler.java new file mode 100644 index 0000000..7032fb6 --- /dev/null +++ b/src/test/java/xmlobject/usertype/averageCase/existing/SKUHandler.java @@ -0,0 +1,55 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.usertype.averageCase.existing; + +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; + +public class SKUHandler +{ + + public static void encodeSKU(SKU obj, SimpleValue target) + { + String digits; + if (obj.getDigits() < 10) + digits = "00" + Integer.toString(obj.getDigits()); + else if (obj.getDigits() < 100) + digits = "0" + Integer.toString(obj.getDigits()); + else + digits = Integer.toString(obj.getDigits()); + target.setStringValue(digits + "-" + obj.getLetters()); + } + + public static SKU decodeSKU(SimpleValue obj) throws XmlValueOutOfRangeException + { + String encoded = obj.getStringValue(); + if (encoded.length() != 6) + throw new XmlValueOutOfRangeException("Invalid SKU format: " + encoded); + + SKU sku = new SKU(); + try + { + sku.setDigits(Integer.parseInt(encoded.substring(0,3))); + } catch (NumberFormatException e) { + throw new XmlValueOutOfRangeException("Invalid SKU format: " + encoded); + } catch (IllegalArgumentException e) { + throw new XmlValueOutOfRangeException("Invalid SKU format: " + encoded); + } + + sku.setLetters(encoded.substring(4,6)); + return sku; + } +} diff --git a/src/test/java/xmlobject/usertype/multipleItems/checkin/AverageTest.java b/src/test/java/xmlobject/usertype/multipleItems/checkin/AverageTest.java new file mode 100644 index 0000000..76ca345 --- /dev/null +++ b/src/test/java/xmlobject/usertype/multipleItems/checkin/AverageTest.java @@ -0,0 +1,182 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.usertype.multipleItems.checkin; + + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; +import org.junit.Test; +import usertype.xbean.multipleItems.company.CompanyDocument; +import usertype.xbean.multipleItems.company.CompanyType; +import usertype.xbean.multipleItems.company.ConsultantType; +import usertype.xbean.multipleItems.company.DepartmentType; +import xmlobject.usertype.multipleItems.existing.Room; + +import java.math.BigInteger; + +import static org.junit.Assert.assertEquals; + + +public class AverageTest { + + @Test + public void test() { + CompanyDocument doc = CompanyDocument.Factory.newInstance(); + CompanyType company = doc.addNewCompany(); + DepartmentType dept = company.addNewDepartments(); + + ConsultantType cons = dept.addNewConsultant(); + + cons.setName("Joe Smith"); + cons.setAge(BigInteger.valueOf(100)); + + int LEN=20; + + for (int i=0; i < LEN; i++) { + cons.addRoom(new Room(i, "AB")); + } + + System.out.println(doc.xmlText()); + + Room[] rooms = cons.getRoomArray(); + + for (int i=0; i < LEN; i++) { + assertEquals(i, rooms[i].getDigits()); + assertEquals("AB", rooms[i].getLetters()); + } + } + + + @Test + public void testArrayGetSet() { + + CompanyDocument doc = CompanyDocument.Factory.newInstance(); + CompanyType company = doc.addNewCompany(); + DepartmentType dept = company.addNewDepartments(); + + ConsultantType cons = dept.addNewConsultant(); + + cons.setName("Joe Smith"); + cons.setAge(BigInteger.valueOf(100)); + + int LEN=20; + + Room[] rooms = new Room[LEN]; + + for (int i=0; i < LEN; i++) { + rooms[i] = new Room(i, "AB"); + } + + cons.setRoomArray(rooms); + + rooms = cons.getRoomArray(); + for (int i=0; i < LEN; i++) { + assertEquals(i, rooms[i].getDigits()); + assertEquals("AB", rooms[i].getLetters()); + } + + + } + + @Test + public void testIthGetSet() { + + CompanyDocument doc = CompanyDocument.Factory.newInstance(); + CompanyType company = doc.addNewCompany(); + DepartmentType dept = company.addNewDepartments(); + + ConsultantType cons = dept.addNewConsultant(); + + cons.setName("Joe Smith"); + cons.setAge(BigInteger.valueOf(100)); + + + int LEN=20; + + for (int i=0; i < LEN; i++) { + cons.addNewRoom(); + } + + + for (int i=0; i < LEN; i++) { + cons.setRoomArray(i, new Room(i, "AB")); + } + + for (int i=0; i < LEN; i++) { + assertEquals(i, cons.getRoomArray(i).getDigits()); + assertEquals("AB", cons.getRoomArray(i).getLetters()); + } + + + } + + @Test(expected = XmlValueOutOfRangeException.class) + public void testBadInput() throws XmlException{ + + StringBuilder sb = new StringBuilder(); + sb.append(""); + sb.append(""); + sb.append("000-AB0001-AB002-AB"); + sb.append(""); + + CompanyDocument doc = CompanyDocument.Factory.parse(sb.toString()); + + CompanyType company = doc.getCompany(); + + ConsultantType cons = company.getDepartmentsArray(0).getConsultantArray(0); + assertEquals(3, cons.xgetRoomArray().length); + + cons.getRoomArray(); + } + + @Test(expected = XmlValueOutOfRangeException.class) + public void testBadInputGetIthBad() throws XmlException{ + + String sb = + "" + + "" + + "000-AB0001-AB002-AB" + + ""; + CompanyDocument doc = CompanyDocument.Factory.parse(sb); + + CompanyType company = doc.getCompany(); + + ConsultantType cons = company.getDepartmentsArray(0).getConsultantArray(0); + assertEquals(3, cons.xgetRoomArray().length); + + cons.getRoomArray(1); + } + + @Test + public void testBadInputGetIthGood() throws XmlException{ + String sb = + "" + + "" + + "000-AB0001-AB002-AB" + + ""; + CompanyDocument doc = CompanyDocument.Factory.parse(sb); + + CompanyType company = doc.getCompany(); + + ConsultantType cons = company.getDepartmentsArray(0).getConsultantArray(0); + assertEquals(3, cons.xgetRoomArray().length); + + assertEquals(0, cons.getRoomArray(0).getDigits()); + assertEquals("AB", cons.getRoomArray(0).getLetters()); + assertEquals(2, cons.getRoomArray(2).getDigits()); + assertEquals("AB", cons.getRoomArray(2).getLetters()); + } +} diff --git a/src/test/java/xmlobject/usertype/multipleItems/existing/Room.java b/src/test/java/xmlobject/usertype/multipleItems/existing/Room.java new file mode 100644 index 0000000..e44d290 --- /dev/null +++ b/src/test/java/xmlobject/usertype/multipleItems/existing/Room.java @@ -0,0 +1,57 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.usertype.multipleItems.existing; + +public class Room +{ + private int digits; + private String letters; + + + public Room() + { + } + + public Room(int digits, String letters) + { + setDigits(digits); + setLetters(letters); + } + + public int getDigits() + { + return digits; + } + + public void setDigits(int digits) + { + if (digits > 999 || digits < 0) + throw new IllegalArgumentException("bad digits"); + this.digits = digits; + } + + public String getLetters() + { + return letters; + } + + public void setLetters(String letters) + { + if (letters == null || letters.length() != 2) + throw new IllegalArgumentException("bad letters"); + this.letters = letters; + } +} diff --git a/src/test/java/xmlobject/usertype/multipleItems/existing/RoomHandler.java b/src/test/java/xmlobject/usertype/multipleItems/existing/RoomHandler.java new file mode 100644 index 0000000..22a05cb --- /dev/null +++ b/src/test/java/xmlobject/usertype/multipleItems/existing/RoomHandler.java @@ -0,0 +1,56 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.usertype.multipleItems.existing; + +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; + +public class RoomHandler +{ + + public static void encodeRoom(Room obj, SimpleValue target) + { + String digits; + if (obj.getDigits() < 10) + digits = "00" + Integer.toString(obj.getDigits()); + else if (obj.getDigits() < 100) + digits = "0" + Integer.toString(obj.getDigits()); + else + digits = Integer.toString(obj.getDigits()); + target.setStringValue(digits + "-" + obj.getLetters()); + } + + + public static Room decodeRoom(SimpleValue obj) throws XmlValueOutOfRangeException + { + String encoded = obj.getStringValue(); + if (encoded.length() != 6) + throw new XmlValueOutOfRangeException("Invalid Room format: " + encoded); + + Room sku = new Room(); + try + { + sku.setDigits(Integer.parseInt(encoded.substring(0,3))); + } catch (NumberFormatException e) { + throw new XmlValueOutOfRangeException("Invalid Room format: " + encoded); + } catch (IllegalArgumentException e) { + throw new XmlValueOutOfRangeException("Invalid Room format: " + encoded); + } + + sku.setLetters(encoded.substring(4,6)); + return sku; + } +} diff --git a/src/test/java/xmlobject/xmlloader/detailed/JapaneseTextTest.java b/src/test/java/xmlobject/xmlloader/detailed/JapaneseTextTest.java new file mode 100644 index 0000000..3c7801d --- /dev/null +++ b/src/test/java/xmlobject/xmlloader/detailed/JapaneseTextTest.java @@ -0,0 +1,93 @@ +/* Copyright 2004 The Apache Software Foundation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package xmlobject.xmlloader.detailed; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import tools.util.JarUtil; + +public class JapaneseTextTest { + + @Test + public void testEucJp() throws Exception { + loadFile("pr-xml-euc-jp.xml"); + } + + @Test + public void testIso2022Jp() throws Exception { + loadFile("pr-xml-iso-2022-jp.xml"); + } + + @Test + public void testLittleEndian() throws Exception { + loadFile("pr-xml-little-endian.xml"); + } + + @Test + public void testShift_jis() throws Exception { + loadFile("pr-xml-shift_jis.xml"); + } + + @Test + public void testUtf8() throws Exception { + loadFile("pr-xml-utf-8.xml"); + } + + @Test + public void testUtf16() throws Exception { + loadFile("pr-xml-utf-16.xml"); + } + + @Test + public void testWeeklyEucJp() throws Exception { + loadFile("weekly-euc-jp.xml"); + } + + @Test + public void testWeeklyIso2022Jp() throws Exception { + loadFile("weekly-iso-2022-jp.xml"); + } + + @Test + public void testWeeklyLittleEndian() throws Exception { + loadFile("weekly-little-endian.xml"); + } + + @Test + public void testWeeklyShift_jis() throws Exception { + loadFile("weekly-shift_jis.xml"); + } + + @Test + public void testWeeklyUtf8() throws Exception { + loadFile("weekly-utf-8.xml"); + } + + @Test + public void testWeeklyUtf16() throws Exception { + loadFile("weekly-utf-16.xml"); + } + + @Test + public void testPrefixLocalName() throws Exception { + loadFile("prefix_test.xml"); + } + + + private void loadFile(String file) throws Exception { + XmlObject.Factory.parse(JarUtil. + getResourceFromJarasStream("xbean/xmlobject/japanese/" + file)); + } +} diff --git a/src/test/java/xmlobject/xmlloader/detailed/ParseTest.java b/src/test/java/xmlobject/xmlloader/detailed/ParseTest.java new file mode 100755 index 0000000..5f33094 --- /dev/null +++ b/src/test/java/xmlobject/xmlloader/detailed/ParseTest.java @@ -0,0 +1,79 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.xmlloader.detailed; + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import xmlcursor.common.BasicCursorTestCase; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.StringReader; +import java.util.Vector; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class ParseTest extends BasicCursorTestCase { + private final XmlOptions m_map = new XmlOptions(); + + @Test + public void testLoadStripWhitespace() throws Exception { + m_map.setLoadStripWhitespace(); + m_xo = XmlObject.Factory.parse("01234 text chars \r\n ", + m_map); + m_xc = m_xo.newCursor(); + assertEquals("01234textchars", m_xc.xmlText()); + } + + + @Test + public void testLoadDiscardDocumentElement() throws Exception { + m_map.setLoadReplaceDocumentElement(new QName("")); + XmlObject.Factory.parse("01234 text chars ", m_map); + } + + @Test(expected = XmlException.class) + public void testPrefixNotDefined() throws Exception { + String sXml = "steve"; + XmlObject.Factory.parse(sXml); + } + + @Test(expected = XmlException.class) + public void testErrorListener() throws Exception { + Vector vErrors = new Vector(); + m_map.setErrorListener(vErrors); + XmlObject.Factory.parse("text", m_map); // improper end tag + } + + @Test + public void testParsingDOMWithDTD() throws Exception { + final String svgDocumentString = "\n" + + ""; + assertNotNull(XmlObject.Factory.parse(svgDocumentString)); + final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + final Document parse = documentBuilder.parse(new InputSource(new StringReader(svgDocumentString))); + assertNotNull(XmlObject.Factory.parse(parse)); + } +} + diff --git a/test/src/xmlobject/xmlloader/detailed/PiccoloParseTests.java b/src/test/java/xmlobject/xmlloader/detailed/PiccoloParseTests.java similarity index 76% rename from test/src/xmlobject/xmlloader/detailed/PiccoloParseTests.java rename to src/test/java/xmlobject/xmlloader/detailed/PiccoloParseTests.java index 8cf3b42..9478adf 100644 --- a/test/src/xmlobject/xmlloader/detailed/PiccoloParseTests.java +++ b/src/test/java/xmlobject/xmlloader/detailed/PiccoloParseTests.java @@ -14,33 +14,38 @@ */ package xmlobject.xmlloader.detailed; -import junit.framework.TestCase; +import org.apache.xmlbeans.XmlObject; +import org.junit.Ignore; +import org.junit.Test; import tools.util.JarUtil; import java.io.InputStream; -import org.apache.xmlbeans.XmlObject; +import static org.junit.Assert.assertTrue; -public class PiccoloParseTests extends TestCase{ +@Ignore("Piccolo is not anymore used") +public class PiccoloParseTests { String filename="xbean/xmlobject/japanese/core_generated_wsdl_src.xml"; String temp="xbean/xmlobject/japanese/UCS2Encoding.xml"; + @Test public void testParseInputStream() throws Exception{ InputStream is=JarUtil.getResourceFromJarasStream(filename); assertTrue (is != null ); XmlObject obj=XmlObject.Factory.parse(is); } + @Test public void testParseString() throws Exception{ String str=JarUtil.getResourceFromJar(filename); assertTrue (str != null ); XmlObject obj=XmlObject.Factory.parse(str); } - public void testParseInputStreamUCS2() throws Exception{ - InputStream is=JarUtil.getResourceFromJarasStream(temp); - assertTrue (is != null ); - XmlObject obj=XmlObject.Factory.parse(is); - } - + @Test + public void testParseInputStreamUCS2() throws Exception { + InputStream is = JarUtil.getResourceFromJarasStream(temp); + assertTrue(is != null); + XmlObject obj = XmlObject.Factory.parse(is); + } } diff --git a/src/test/java/xmlobject/xmlloader/detailed/XmlLoaderBvtTest.java b/src/test/java/xmlobject/xmlloader/detailed/XmlLoaderBvtTest.java new file mode 100755 index 0000000..2db3b4b --- /dev/null +++ b/src/test/java/xmlobject/xmlloader/detailed/XmlLoaderBvtTest.java @@ -0,0 +1,39 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package xmlobject.xmlloader.detailed; + +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import org.tranxml.tranXML.version40.CarLocationMessageDocument; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class XmlLoaderBvtTest extends BasicCursorTestCase { + @Test + public void testCastDocument() throws Exception { + + CarLocationMessageDocument clm = + (CarLocationMessageDocument) XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + + assertNotNull(clm); + } +} diff --git a/test/src/xmlobject/xmlloader/detailed/XmlLoaderMiscTest.java b/src/test/java/xmlobject/xmlloader/detailed/XmlLoaderMiscTest.java similarity index 87% rename from test/src/xmlobject/xmlloader/detailed/XmlLoaderMiscTest.java rename to src/test/java/xmlobject/xmlloader/detailed/XmlLoaderMiscTest.java index 44cbc3c..0ce7015 100755 --- a/test/src/xmlobject/xmlloader/detailed/XmlLoaderMiscTest.java +++ b/src/test/java/xmlobject/xmlloader/detailed/XmlLoaderMiscTest.java @@ -16,10 +16,9 @@ package xmlobject.xmlloader.detailed; -import junit.framework.Test; -import junit.framework.TestSuite; import org.apache.xmlbeans.*; import org.apache.xmlbeans.XmlCursor.TokenType; +import org.junit.Test; import org.tranxml.tranXML.version40.CarLocationMessageDocument; import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; import tools.util.JarUtil; @@ -28,26 +27,15 @@ import javax.xml.namespace.QName; import java.util.Collections; -import java.util.Set; import java.util.HashSet; +import java.util.Set; import java.util.Vector; +import static org.junit.Assert.*; -public class XmlLoaderMiscTest extends BasicCursorTestCase { - public XmlLoaderMiscTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(XmlLoaderMiscTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } +public class XmlLoaderMiscTest extends BasicCursorTestCase { + @Test public void testNewInstance() throws Exception { m_xo = XmlObject.Factory.newInstance(); m_xc = m_xo.newCursor(); @@ -56,6 +44,7 @@ public void testNewInstance() throws Exception { assertEquals(TokenType.ENDDOC, m_xc.currentTokenType()); } + @Test public void testTypeForClass() throws Exception { m_xc = XmlObject.Factory.parse(JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)).newCursor(); m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + "$this//GeographicLocation"); @@ -65,7 +54,8 @@ public void testTypeForClass() throws Exception { assertEquals(gl.schemaType(), XmlBeans.typeForClass(GeographicLocation.class)); } - public void testGetBuiltInTypeSystem() throws Exception { + @Test + public void testGetBuiltInTypeSystem() { SchemaTypeSystem sts = XmlBeans.getBuiltinTypeSystem(); if (sts == null) { fail("XmlBeans.getBuiltinTypeSystem() returned null"); @@ -76,11 +66,13 @@ public void testGetBuiltInTypeSystem() throws Exception { assertEquals(14, stDateTime.getBuiltinTypeCode()); } - public void testTypeLoaderUnion() throws Exception { + @Test + public void testTypeLoaderUnion() { System.out.println("testTypeLoaderUnion not implemented"); // TODO } + @Test public void testTypeLoaderForClassLoader() throws Exception { SchemaTypeLoader stl = XmlBeans.typeLoaderForClassLoader(CarLocationMessageDocument.class.getClassLoader()); @@ -93,6 +85,7 @@ public void testTypeLoaderForClassLoader() throws Exception { assertEquals("FLEETNAME", m_xc.getTextValue()); } + @Test public void testGetContextTypeLoader() throws Exception { SchemaTypeLoader stl = XmlBeans.getContextTypeLoader(); if (stl == null) diff --git a/src/test/java/xmlobject/xmlloader/detailed/XmlStreamBeanReader.java b/src/test/java/xmlobject/xmlloader/detailed/XmlStreamBeanReader.java new file mode 100644 index 0000000..869ebb9 --- /dev/null +++ b/src/test/java/xmlobject/xmlloader/detailed/XmlStreamBeanReader.java @@ -0,0 +1,80 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package xmlobject.xmlloader.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.openuri.bea.samples.workshop.CreditCardDataDocument; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.ByteArrayInputStream; + +import static org.junit.Assert.assertEquals; + +public class XmlStreamBeanReader { + + + @Test + public void testXMLStreamReaderLoader() throws XMLStreamException, XmlException { + String creditCardXmlwPrefix = " \n" + + " \n" + + " \n" + + " 0\n" + + " 0\n" + + " \n" + + " \n" + + " 0\n" + + " 0\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 0\n" + + " 0\n" + + " \n" + + " \n" + + " 0\n" + + " 0\n" + + " \n" + + " \n" + + " "; + + XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(creditCardXmlwPrefix.getBytes())); + CreditCardDataDocument ccdoc = (CreditCardDataDocument) XmlObject.Factory.parse(reader, new XmlOptions().setDocumentType(CreditCardDataDocument.type)); + assertEquals(1, ccdoc.getCreditCardData().getCustomerArray(0).getId()); + } + + // test for IllegalStateException thrown on using XmlStreamReader + @Test + public void testXmlStreamReaderException() throws XMLStreamException { + XmlObject xo = XmlObject.Factory.newInstance(); + XmlCursor xc = xo.newCursor(); + xc.toNextToken(); + + xc.insertElementWithText("int", "http://openuri.org/testNumerals", "5"); + xc.insertElementWithText("float", "http://openuri.org/testNumerals", "7.654321"); + + XMLStreamReader xsr = xo.newXMLStreamReader(); + + while (xsr.hasNext()) { + xsr.next(); + } + } +} diff --git a/test/src/xmltokensource/detailed/NewDomNodeTest.java b/src/test/java/xmltokensource/detailed/NewDomNodeTest.java similarity index 90% rename from test/src/xmltokensource/detailed/NewDomNodeTest.java rename to src/test/java/xmltokensource/detailed/NewDomNodeTest.java index f29ebf9..5607aa8 100755 --- a/test/src/xmltokensource/detailed/NewDomNodeTest.java +++ b/src/test/java/xmltokensource/detailed/NewDomNodeTest.java @@ -19,26 +19,23 @@ import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; -import xmlcursor.common.BasicCursorTestCase; -import junit.framework.Test; -import junit.framework.TestSuite; +import org.junit.Test; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import xmlcursor.common.BasicCursorTestCase; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class NewDomNodeTest extends BasicCursorTestCase { public static final String DOC_FRAGMENT = "#document-fragment"; - public static final String DOC = "#document"; + private static final String DOC = "#document"; private XmlOptions m_map = new XmlOptions(); - public NewDomNodeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(NewDomNodeTest.class); - } - + @Test public void testNewDomNode() throws Exception { m_xo = XmlObject.Factory.parse("01234 text chars "); Node doc = m_xo.newDomNode(); @@ -67,6 +64,7 @@ public void testNewDomNode() throws Exception { assertEquals("text", node.getNodeValue()); } + @Test public void testNewDomNodeWithNamespace() throws Exception { m_xo = XmlObject.Factory.parse("01234 text chars "); Node doc = m_xo.newDomNode(); @@ -74,12 +72,13 @@ public void testNewDomNodeWithNamespace() throws Exception { assertEquals(DOC, doc.getNodeName()); } + @Test public void testNewDomNodeWithOptions() throws Exception { m_xo = XmlObject.Factory.parse("01234 text chars "); XmlOptions map = new XmlOptions(); - map.put(XmlOptions.LOAD_STRIP_WHITESPACE, ""); - map.put(XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT, ""); - map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); + map.setLoadStripComments(); + map.setLoadReplaceDocumentElement(new QName("")); + map.setSaveNamespacesFirst(); Node doc = m_xo.newDomNode(map); assertEquals(DOC, doc.getNodeName()); NodeList nl = doc.getChildNodes(); @@ -106,6 +105,7 @@ public void testNewDomNodeWithOptions() throws Exception { assertEquals("text", node.getNodeValue()); } + @Test public void testNewDomNodeRoundTrip() throws Exception { m_xo = XmlObject.Factory.parse("01234 text chars "); Node doc = m_xo.newDomNode(); diff --git a/test/src/xmltokensource/detailed/PrettyPrintNamespaceTest.java b/src/test/java/xmltokensource/detailed/PrettyPrintNamespaceTest.java similarity index 83% rename from test/src/xmltokensource/detailed/PrettyPrintNamespaceTest.java rename to src/test/java/xmltokensource/detailed/PrettyPrintNamespaceTest.java index 2ed12a7..a294800 100755 --- a/test/src/xmltokensource/detailed/PrettyPrintNamespaceTest.java +++ b/src/test/java/xmltokensource/detailed/PrettyPrintNamespaceTest.java @@ -15,19 +15,18 @@ package xmltokensource.detailed; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; import com.mtest.SubInfo; import com.mtest.TestDocument; -import junit.framework.TestCase; +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.junit.Test; +import static org.junit.Assert.assertEquals; -public class PrettyPrintNamespaceTest extends TestCase { - public PrettyPrintNamespaceTest(String name) { - super(name); - } +public class PrettyPrintNamespaceTest { + @Test public void testWithNewInstance() throws Exception { XmlObject x = XmlObject.Factory.newInstance(); @@ -41,10 +40,11 @@ public void testWithNewInstance() String str = ""; - assertTrue("XmlText() Failed.", x.xmlText().equals(str)); - assertTrue("toString() Failed.", x.toString().trim().equals(str)); + assertEquals("XmlText() Failed.", x.xmlText(), str); + assertEquals("toString() Failed.", x.toString().trim(), str); } + @Test public void testWithInstanceFromSchema() throws Exception { String xml = " "; @@ -64,7 +64,7 @@ public void testWithInstanceFromSchema() "there" + ""; - assertTrue("XmlText() Failed.", doc.xmlText().equals(str2)); - assertTrue("toString() Failed.", doc.toString().trim().equals(str1)); + assertEquals("XmlText() Failed.", doc.xmlText(), str2); + assertEquals("toString() Failed.", doc.toString().trim(), str1); } } diff --git a/src/test/java/xmltokensource/detailed/RoundTripLoaderTest.java b/src/test/java/xmltokensource/detailed/RoundTripLoaderTest.java new file mode 100755 index 0000000..4c95ec1 --- /dev/null +++ b/src/test/java/xmltokensource/detailed/RoundTripLoaderTest.java @@ -0,0 +1,131 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmltokensource.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Node; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import java.io.InputStream; +import java.io.Reader; + +import static org.junit.Assert.assertNotNull; + + +public class RoundTripLoaderTest extends BasicCursorTestCase { + public static final String DOC_FRAGMENT = "#document-fragment"; + private XmlOptions m_map = new XmlOptions(); + + @Before + public void setUp() { + m_map.setCharacterEncoding("Big5"); + m_map.setSaveNamespacesFirst(); + } + + private void _newDomNodeRoundTrip(XmlOptions map) throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); + Node doc = m_xo.newDomNode(map); + assertNotNull(doc); + XmlObject xo = XmlObject.Factory.parse(doc, map); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = xo.newCursor(); + try { + compareDocTokens(m_xc, xc1); + } finally { + xc1.dispose(); + } + } + + @Test + public void testNewDomNodeRoundTrip() throws Exception { + _newDomNodeRoundTrip(null); + } + + @Test + public void testNewDomNodeWithOptionsRoundTrip() throws Exception { + _newDomNodeRoundTrip(m_map); + } + + private void _newInputStreamRoundTrip(XmlOptions map) throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); + InputStream is = m_xo.newInputStream(map); + assertNotNull(is); + XmlOptions options = new XmlOptions(map); + XmlObject xo = XmlObject.Factory.parse(is, options); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = xo.newCursor(); + try { + compareDocTokens(m_xc, xc1); + } finally { + xc1.dispose(); + } + } + + @Test + public void testNewInputStreamRoundTrip() throws Exception { + _newInputStreamRoundTrip(null); + } + + @Test + public void testNewInputStreamWithOptionsRoundTrip() throws Exception { + _newInputStreamRoundTrip(m_map); + } + + private void _newReaderRoundTrip(XmlOptions map) throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); + Reader reader = m_xo.newReader(map); + assertNotNull(reader); + XmlOptions options = new XmlOptions(map); + XmlObject xo = XmlObject.Factory.parse(reader, options); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = xo.newCursor(); + try { + compareDocTokens(m_xc, xc1); + } finally { + xc1.dispose(); + } + } + + private void _xmlTextRoundTrip(XmlOptions map) throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); + String sXml = m_xo.xmlText(map); + assertNotNull(sXml); + XmlOptions options = new XmlOptions(map); + XmlObject xo = XmlObject.Factory.parse(sXml, options); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = xo.newCursor(); + try { + compareDocTokens(m_xc, xc1); + } finally { + xc1.dispose(); + } + } + + @Test + public void testXmlTextRoundTrip() throws Exception { + _xmlTextRoundTrip(null); + } + + public void testXmlTextWithOptionsRoundTrip() throws Exception { + _xmlTextRoundTrip(m_map); + } +} diff --git a/src/test/java/xmltokensource/detailed/XmlTextTest.java b/src/test/java/xmltokensource/detailed/XmlTextTest.java new file mode 100755 index 0000000..73ed04f --- /dev/null +++ b/src/test/java/xmltokensource/detailed/XmlTextTest.java @@ -0,0 +1,133 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package xmltokensource.detailed; + +import org.apache.xmlbeans.XmlCursor; +import org.apache.xmlbeans.XmlCursor.TokenType; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import tools.util.JarUtil; +import xmlcursor.common.BasicCursorTestCase; +import xmlcursor.common.Common; + +import javax.xml.namespace.QName; + +import static org.junit.Assert.assertEquals; + + +public class XmlTextTest extends BasicCursorTestCase { + private XmlOptions m_map = new XmlOptions(); + + @Test + public void testSAVENAMESPACESFIRST() throws Exception { + m_xo = XmlObject.Factory.parse("01234"); + m_xc = m_xo.newCursor(); + m_map.setSaveNamespacesFirst(); + assertEquals("01234", + m_xc.xmlText(m_map)); + } + + @Test + public void testSAVENAMESPACESlast() throws Exception { + m_xo = XmlObject.Factory.parse("01234"); + m_xc = m_xo.newCursor(); + assertEquals("01234", + m_xc.xmlText(m_map)); + } + + @Test + public void testSaveSyntheticDocumentElement() throws Exception { + m_xo = XmlObject.Factory.parse("text"); + m_xc = m_xo.newCursor(); + m_map.setSaveSyntheticDocumentElement(new QName("foo")); + assertEquals("text", m_xc.xmlText(m_map)); + } + + @Test + public void testSavePrettyPrint() throws Exception { + m_xo = XmlObject.Factory.parse(" text "); + m_xc = m_xo.newCursor(); + m_map.setSavePrettyPrint(); + String lnSep = System.getProperty("line.separator"); + assertEquals("" + lnSep + " " + lnSep + " text " + lnSep + " " + lnSep + "", m_xc.xmlText(m_map)); + } + + @Test + public void testSavePrettyPrintIndent3() throws Exception { + m_xo = XmlObject.Factory.parse(" text "); + m_xc = m_xo.newCursor(); + m_map.setSavePrettyPrint(); + m_map.setSavePrettyPrintIndent(3); + String lnSep = System.getProperty("line.separator"); + assertEquals("" + lnSep + " " + lnSep + " text " + lnSep + " " + lnSep + "", m_xc.xmlText(m_map)); + } + + @Test + public void testSavePrettyPrintIndentNeg1() throws Exception { + m_xc = XmlObject.Factory.parse(" \n \n text \n \n ").newCursor(); + m_map.setSavePrettyPrint(); + m_map.setSavePrettyPrintIndent(-1); + assertEquals(" text ", m_xc.xmlText(m_map)); + } + + @Test + public void testDefaultNamespace() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + "$this//FleetID"); + m_xc.toNextSelection(); + m_map.setSaveNamespacesFirst(); + assertEquals("FLEETNAME", + m_xc.xmlText(m_map)); + } + + @Test + public void testSTARTDOCvsFirstChild() throws Exception { + m_xo = XmlObject.Factory.parse( + JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); + m_xc = m_xo.newCursor(); + XmlCursor xc1 = m_xo.newCursor(); + xc1.toFirstChild(); + try { + assertEquals(m_xc.xmlText().replaceFirst("(?s)", ""), xc1.xmlText()); + } finally { + xc1.dispose(); + } + } + + @Test + public void testXmlTextFromTEXT() throws Exception { + m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertEquals("text", m_xc.getChars()); + } + + @Test + public void testXmlTextFromTEXTafterEND() throws Exception { + m_xo = XmlObject.Factory.parse(" text ws \\r\\n "); + m_xc = m_xo.newCursor(); + toNextTokenOfType(m_xc, TokenType.TEXT); + toNextTokenOfType(m_xc, TokenType.TEXT); + assertEquals(" ws \\r\\n ", m_xc.getChars()); + } +} + diff --git a/src/test/resources/schema/appview/Add_AcctSiebel7.xml b/src/test/resources/schema/appview/Add_AcctSiebel7.xml new file mode 100644 index 0000000..983cc8d --- /dev/null +++ b/src/test/resources/schema/appview/Add_AcctSiebel7.xml @@ -0,0 +1,55 @@ + + + + + + + + + USD + + + + + + + Bea Demo + + Commercial + + + + Default Organization + + + + + + NY + NY + USA + 9876543211 + + 1234567890 + 07301 + + NY + 2 Madision Square + + + + + + diff --git a/src/test/resources/xbean/ValidatingStream/CarLocationMessage-inv.xml b/src/test/resources/xbean/ValidatingStream/CarLocationMessage-inv.xml new file mode 100755 index 0000000..6102fca --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/CarLocationMessage-inv.xml @@ -0,0 +1,53 @@ + + + + + FLEETNAME + CSXT + + + GATX + 123456 + L + + 2001-03-23 + + + P + + Q12345 + + DALLAS + TX + + CSXT + + + DALLAS + TX + + + + + DALLAS + TX + + 2001-03-23 + + P + + Y + + diff --git a/src/test/resources/xbean/ValidatingStream/CarLocationMessage.xml b/src/test/resources/xbean/ValidatingStream/CarLocationMessage.xml new file mode 100755 index 0000000..6102fca --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/CarLocationMessage.xml @@ -0,0 +1,53 @@ + + + + + FLEETNAME + CSXT + + + GATX + 123456 + L + + 2001-03-23 + + + P + + Q12345 + + DALLAS + TX + + CSXT + + + DALLAS + TX + + + + + DALLAS + TX + + 2001-03-23 + + P + + Y + + diff --git a/src/test/resources/xbean/ValidatingStream/Employees.xml b/src/test/resources/xbean/ValidatingStream/Employees.xml new file mode 100755 index 0000000..8ed5c35 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/Employees.xml @@ -0,0 +1,71 @@ + + + + + + Fred Jones + + 900 Aurora Ave. + Seattle + WA + 98115 + + + 2011 152nd Avenue NE + Redmond + WA + 98052 + + (425)555-5665 + (206)555-5555 + (206)555-4321 + + + Sally Smith + + 1430 Oak Place + Salem + OR + 97125 + + + 765 Main St. + Kaiser + OR + 97103 + + (503)555-3856 + (503)555-6951 + (503)555-5152 + + + Gladys Kravitz + + 1313 Mockingbird Lane + Seattle + WA + 98115 + + + 2011 152nd Avenue NE + Redmond + WA + 98052 + + (425)555-6897 + (206)555-6594 + (206)555-7894 + + diff --git a/src/test/resources/xbean/ValidatingStream/foo-inv.xml b/src/test/resources/xbean/ValidatingStream/foo-inv.xml new file mode 100644 index 0000000..8ffb46d --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/foo-inv.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/foo.xsd b/src/test/resources/xbean/ValidatingStream/foo.xsd new file mode 100644 index 0000000..1fa7a66 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/foo.xsd @@ -0,0 +1,30 @@ + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/ValidatingStream/global-attr.xml b/src/test/resources/xbean/ValidatingStream/global-attr.xml new file mode 100755 index 0000000..76c319d --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/global-attr.xml @@ -0,0 +1,18 @@ + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/location-inv.xml b/src/test/resources/xbean/ValidatingStream/location-inv.xml new file mode 100755 index 0000000..12406bc --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/location-inv.xml @@ -0,0 +1,25 @@ + + + + + Bellevue + WA + 98033 + USA + NA + 1234 + + diff --git a/src/test/resources/xbean/ValidatingStream/location.xml b/src/test/resources/xbean/ValidatingStream/location.xml new file mode 100755 index 0000000..a6b512f --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/location.xml @@ -0,0 +1,24 @@ + + + + + Bellevue + WA + 98033 + USA + NA + 1234 + diff --git a/src/test/resources/xbean/ValidatingStream/location.xsd b/src/test/resources/xbean/ValidatingStream/location.xsd new file mode 100755 index 0000000..6c72a04 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/location.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/ValidatingStream/mixed-content-inv.xml b/src/test/resources/xbean/ValidatingStream/mixed-content-inv.xml new file mode 100755 index 0000000..cc122f5 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/mixed-content-inv.xml @@ -0,0 +1,23 @@ + + + + + Your Order is being Shipped. + John Doe + 1000 + Your expected Ship-date is: 2004-12-12 + Thank you for your order + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/mixed-content.xml b/src/test/resources/xbean/ValidatingStream/mixed-content.xml new file mode 100755 index 0000000..cc122f5 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/mixed-content.xml @@ -0,0 +1,23 @@ + + + + + Your Order is being Shipped. + John Doe + 1000 + Your expected Ship-date is: 2004-12-12 + Thank you for your order + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/mixed-content.xsd b/src/test/resources/xbean/ValidatingStream/mixed-content.xsd new file mode 100755 index 0000000..84b48c6 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/mixed-content.xsd @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/nomixed-content-inv.xml b/src/test/resources/xbean/ValidatingStream/nomixed-content-inv.xml new file mode 100755 index 0000000..a37ee85 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/nomixed-content-inv.xml @@ -0,0 +1,23 @@ + + + + + Your Order is being Shipped. + John Doe + 1000 + Your expected Ship-date is: 2004-12-12 + Thank you for your order + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/numerals.xsd b/src/test/resources/xbean/ValidatingStream/numerals.xsd new file mode 100755 index 0000000..17156b7 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/numerals.xsd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person-frag.xml b/src/test/resources/xbean/ValidatingStream/person-frag.xml new file mode 100755 index 0000000..0c6c391 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-frag.xml @@ -0,0 +1,21 @@ + + + + + Person + Two + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person-frag2.xml b/src/test/resources/xbean/ValidatingStream/person-frag2.xml new file mode 100755 index 0000000..16c4750 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-frag2.xml @@ -0,0 +1,20 @@ + + + +Person + Two + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person-inv.xml b/src/test/resources/xbean/ValidatingStream/person-inv.xml new file mode 100755 index 0000000..a5ac8b9 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-inv.xml @@ -0,0 +1,35 @@ + + + + + + Person + One + + + + Person + Two + + + + Person + Three + + + + diff --git a/src/test/resources/xbean/ValidatingStream/person-justname-inv.xml b/src/test/resources/xbean/ValidatingStream/person-justname-inv.xml new file mode 100755 index 0000000..13af5cd --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-justname-inv.xml @@ -0,0 +1,21 @@ + + + + + Person + Two + M + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person-justname.xml b/src/test/resources/xbean/ValidatingStream/person-justname.xml new file mode 100755 index 0000000..57f41ea --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-justname.xml @@ -0,0 +1,22 @@ + + + + + Person + Two + M + diff --git a/src/test/resources/xbean/ValidatingStream/person-sibling-inv.xml b/src/test/resources/xbean/ValidatingStream/person-sibling-inv.xml new file mode 100755 index 0000000..f19d45e --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-sibling-inv.xml @@ -0,0 +1,32 @@ + + + + + + Person + Two + + + + Person + Three + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person-sibling.xml b/src/test/resources/xbean/ValidatingStream/person-sibling.xml new file mode 100755 index 0000000..44c55dd --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-sibling.xml @@ -0,0 +1,32 @@ + + + + + + Person + Two + + + + Person + Three + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person-xsi-inv.xml b/src/test/resources/xbean/ValidatingStream/person-xsi-inv.xml new file mode 100755 index 0000000..5c434d0 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person-xsi-inv.xml @@ -0,0 +1,22 @@ + + + + + Person + Two + M + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/person.xml b/src/test/resources/xbean/ValidatingStream/person.xml new file mode 100755 index 0000000..563d024 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person.xml @@ -0,0 +1,35 @@ + + + + + + Person + One + + + + Person + Two + + + + Person + Three + + + + diff --git a/src/test/resources/xbean/ValidatingStream/person.xsd b/src/test/resources/xbean/ValidatingStream/person.xsd new file mode 100755 index 0000000..dd8e504 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/person.xsd @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/ValidatingStream/po.xml b/src/test/resources/xbean/ValidatingStream/po.xml new file mode 100755 index 0000000..e426b54 --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/po.xml @@ -0,0 +1,47 @@ + + + + + + Alice Smith + 123 Maple Street + Mill Valley + CA + 90952 + + + Robert Smith + 8 Oak Avenue + Old Town + PA + 95819 + + Hurry, my lawn is going wild! + + + Lawnmower + 1 + 148.95 + Confirm this is electric + + + Baby Monitor + 1 + 39.98 + 1999-05-21 + + + \ No newline at end of file diff --git a/src/test/resources/xbean/ValidatingStream/simpleTypes.xsd b/src/test/resources/xbean/ValidatingStream/simpleTypes.xsd new file mode 100755 index 0000000..e76eb3e --- /dev/null +++ b/src/test/resources/xbean/ValidatingStream/simpleTypes.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/compile/scomp/detailed/laxDoc.xsd b/src/test/resources/xbean/compile/scomp/detailed/laxDoc.xsd new file mode 100644 index 0000000..818a68c --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/detailed/laxDoc.xsd @@ -0,0 +1,56 @@ + + + + + + + + + + Ensure that XML content is allowed and not validated when the novdoc option is set + provided content is XHTML compliant and no elements use the schema namespaces + + + foobaz + + + + + + + provided content is XHTML compliant and no elements use the schema namespaces + + + + + + + Ensure that XML content is allowed and not validated when the novdoc option is set + provided content is XHTML compliant and no elements use the schema namespaces + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/incr/incr1.xsd b/src/test/resources/xbean/compile/scomp/incr/incr1.xsd new file mode 100644 index 0000000..a47ad59 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/incr/incr1.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/incr/incr2-1.xsd b/src/test/resources/xbean/compile/scomp/incr/incr2-1.xsd new file mode 100644 index 0000000..02d611c --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/incr/incr2-1.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/incr/incr2.xsd b/src/test/resources/xbean/compile/scomp/incr/incr2.xsd new file mode 100644 index 0000000..41d0cbb --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/incr/incr2.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/incr/incr3.xsd b/src/test/resources/xbean/compile/scomp/incr/incr3.xsd new file mode 100644 index 0000000..ce29a8e --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/incr/incr3.xsd @@ -0,0 +1,18 @@ + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/incr/incr4.xsd b/src/test/resources/xbean/compile/scomp/incr/incr4.xsd new file mode 100644 index 0000000..855892b --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/incr/incr4.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/test/cases/xbean/compile/scomp/j2ee/XML.xsd b/src/test/resources/xbean/compile/scomp/j2ee/XML.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/XML.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/XML.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/application-client_1_4.xsd b/src/test/resources/xbean/compile/scomp/j2ee/application-client_1_4.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/application-client_1_4.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/application-client_1_4.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/application_1_4.xsd b/src/test/resources/xbean/compile/scomp/j2ee/application_1_4.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/application_1_4.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/application_1_4.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/connector_1_5.xsd b/src/test/resources/xbean/compile/scomp/j2ee/connector_1_5.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/connector_1_5.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/connector_1_5.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/ejb-jar_2_1.xsd b/src/test/resources/xbean/compile/scomp/j2ee/ejb-jar_2_1.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/ejb-jar_2_1.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/ejb-jar_2_1.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/j2ee_1_4.xsd b/src/test/resources/xbean/compile/scomp/j2ee/j2ee_1_4.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/j2ee_1_4.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/j2ee_1_4.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/jsp_2_0.xsd b/src/test/resources/xbean/compile/scomp/j2ee/jsp_2_0.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/jsp_2_0.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/jsp_2_0.xsd diff --git a/test/cases/xbean/compile/scomp/j2ee/web-app_2_4.xsd b/src/test/resources/xbean/compile/scomp/j2ee/web-app_2_4.xsd similarity index 100% rename from test/cases/xbean/compile/scomp/j2ee/web-app_2_4.xsd rename to src/test/resources/xbean/compile/scomp/j2ee/web-app_2_4.xsd diff --git a/src/test/resources/xbean/compile/scomp/pricequote/PriceQuote.xsd b/src/test/resources/xbean/compile/scomp/pricequote/PriceQuote.xsd new file mode 100755 index 0000000..0ae2153 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/pricequote/PriceQuote.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/enum1.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum1.xsd_ new file mode 100644 index 0000000..f4a9473 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum1.xsd_ @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/enum1_redefine.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum1_redefine.xsd_ new file mode 100644 index 0000000..47d297d --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum1_redefine.xsd_ @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/enum2.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum2.xsd_ new file mode 100644 index 0000000..9bb540e --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum2.xsd_ @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/enum2_redefine.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum2_redefine.xsd_ new file mode 100644 index 0000000..64c3d30 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum2_redefine.xsd_ @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/enum3.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum3.xsd_ new file mode 100644 index 0000000..5514461 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum3.xsd_ @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/enum3_redefine.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum3_redefine.xsd_ new file mode 100644 index 0000000..4582e0f --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/enum3_redefine.xsd_ @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/ext/H1.java b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/H1.java new file mode 100644 index 0000000..81a22c1 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/H1.java @@ -0,0 +1,23 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ext; + +public class H1 +{ + public static void get(org.apache.xmlbeans.XmlObject xo) + { + } +} \ No newline at end of file diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/ext/H2.java b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/H2.java new file mode 100644 index 0000000..1d8860d --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/H2.java @@ -0,0 +1,24 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ext; + +public class H2 +{ + public static String get(org.apache.xmlbeans.XmlObject xo) + { + return null; + } +} \ No newline at end of file diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/ext/I1.java b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/I1.java new file mode 100644 index 0000000..8ef6e4f --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/I1.java @@ -0,0 +1,21 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ext; + +public interface I1 +{ + public void get(); +} \ No newline at end of file diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/ext/I2.java b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/I2.java new file mode 100644 index 0000000..93f635c --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/ext/I2.java @@ -0,0 +1,21 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ext; + +public interface I2 +{ + public String get(); +} \ No newline at end of file diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsd_ b/src/test/resources/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsd_ new file mode 100644 index 0000000..04c65a9 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsd_ @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsdconfig_ b/src/test/resources/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsdconfig_ new file mode 100644 index 0000000..0af7cf9 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsdconfig_ @@ -0,0 +1,32 @@ + + + + + + + + ext.H1 + + + + + + + ext.H2 + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/union_initial.xsd b/src/test/resources/xbean/compile/scomp/schemacompiler/union_initial.xsd new file mode 100644 index 0000000..8f95fe4 --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/union_initial.xsd @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/compile/scomp/schemacompiler/union_redefine.xsd b/src/test/resources/xbean/compile/scomp/schemacompiler/union_redefine.xsd new file mode 100644 index 0000000..8582a1c --- /dev/null +++ b/src/test/resources/xbean/compile/scomp/schemacompiler/union_redefine.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + diff --git a/test/cases/xbean/compile/som/constraints.xsd_ b/src/test/resources/xbean/compile/som/constraints.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/constraints.xsd_ rename to src/test/resources/xbean/compile/som/constraints.xsd_ diff --git a/test/cases/xbean/compile/som/constraints_added.xsd_ b/src/test/resources/xbean/compile/som/constraints_added.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/constraints_added.xsd_ rename to src/test/resources/xbean/compile/som/constraints_added.xsd_ diff --git a/test/cases/xbean/compile/som/datatypes.xsd_ b/src/test/resources/xbean/compile/som/datatypes.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/datatypes.xsd_ rename to src/test/resources/xbean/compile/som/datatypes.xsd_ diff --git a/test/cases/xbean/compile/som/datatypes_added.xsd_ b/src/test/resources/xbean/compile/som/datatypes_added.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/datatypes_added.xsd_ rename to src/test/resources/xbean/compile/som/datatypes_added.xsd_ diff --git a/test/cases/xbean/compile/som/datatypes_modified.xsd_ b/src/test/resources/xbean/compile/som/datatypes_modified.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/datatypes_modified.xsd_ rename to src/test/resources/xbean/compile/som/datatypes_modified.xsd_ diff --git a/test/cases/xbean/compile/som/derived_types.xsd_ b/src/test/resources/xbean/compile/som/derived_types.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/derived_types.xsd_ rename to src/test/resources/xbean/compile/som/derived_types.xsd_ diff --git a/test/cases/xbean/compile/som/derived_types_added.xsd_ b/src/test/resources/xbean/compile/som/derived_types_added.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/derived_types_added.xsd_ rename to src/test/resources/xbean/compile/som/derived_types_added.xsd_ diff --git a/test/cases/xbean/compile/som/derived_types_modifed.xsd_ b/src/test/resources/xbean/compile/som/derived_types_modifed.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/derived_types_modifed.xsd_ rename to src/test/resources/xbean/compile/som/derived_types_modifed.xsd_ diff --git a/test/cases/xbean/compile/som/elemattr.xsd_ b/src/test/resources/xbean/compile/som/elemattr.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/elemattr.xsd_ rename to src/test/resources/xbean/compile/som/elemattr.xsd_ diff --git a/test/cases/xbean/compile/som/elemattr_added.xsd_ b/src/test/resources/xbean/compile/som/elemattr_added.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/elemattr_added.xsd_ rename to src/test/resources/xbean/compile/som/elemattr_added.xsd_ diff --git a/test/cases/xbean/compile/som/elemattr_modified.xsd_ b/src/test/resources/xbean/compile/som/elemattr_modified.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/elemattr_modified.xsd_ rename to src/test/resources/xbean/compile/som/elemattr_modified.xsd_ diff --git a/test/cases/xbean/compile/som/groups.xsd_ b/src/test/resources/xbean/compile/som/groups.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/groups.xsd_ rename to src/test/resources/xbean/compile/som/groups.xsd_ diff --git a/test/cases/xbean/compile/som/groups_added.xsd_ b/src/test/resources/xbean/compile/som/groups_added.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/groups_added.xsd_ rename to src/test/resources/xbean/compile/som/groups_added.xsd_ diff --git a/test/cases/xbean/compile/som/groups_modified.xsd_ b/src/test/resources/xbean/compile/som/groups_modified.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/groups_modified.xsd_ rename to src/test/resources/xbean/compile/som/groups_modified.xsd_ diff --git a/test/cases/xbean/compile/som/instance_constraints_invalid.xml b/src/test/resources/xbean/compile/som/instance_constraints_invalid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_constraints_invalid.xml rename to src/test/resources/xbean/compile/som/instance_constraints_invalid.xml diff --git a/test/cases/xbean/compile/som/instance_constraints_valid.xml b/src/test/resources/xbean/compile/som/instance_constraints_valid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_constraints_valid.xml rename to src/test/resources/xbean/compile/som/instance_constraints_valid.xml diff --git a/test/cases/xbean/compile/som/instance_datatypes_valid.xml b/src/test/resources/xbean/compile/som/instance_datatypes_valid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_datatypes_valid.xml rename to src/test/resources/xbean/compile/som/instance_datatypes_valid.xml diff --git a/test/cases/xbean/compile/som/instance_derived_types_modify.xml b/src/test/resources/xbean/compile/som/instance_derived_types_modify.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_derived_types_modify.xml rename to src/test/resources/xbean/compile/som/instance_derived_types_modify.xml diff --git a/test/cases/xbean/compile/som/instance_derived_types_valid.xml b/src/test/resources/xbean/compile/som/instance_derived_types_valid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_derived_types_valid.xml rename to src/test/resources/xbean/compile/som/instance_derived_types_valid.xml diff --git a/test/cases/xbean/compile/som/instance_elemattr.xml b/src/test/resources/xbean/compile/som/instance_elemattr.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_elemattr.xml rename to src/test/resources/xbean/compile/som/instance_elemattr.xml diff --git a/test/cases/xbean/compile/som/instance_elemattr_added.xml b/src/test/resources/xbean/compile/som/instance_elemattr_added.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_elemattr_added.xml rename to src/test/resources/xbean/compile/som/instance_elemattr_added.xml diff --git a/test/cases/xbean/compile/som/instance_elemattr_valid.xml b/src/test/resources/xbean/compile/som/instance_elemattr_valid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_elemattr_valid.xml rename to src/test/resources/xbean/compile/som/instance_elemattr_valid.xml diff --git a/test/cases/xbean/compile/som/instance_simple_types_invalid.xml b/src/test/resources/xbean/compile/som/instance_simple_types_invalid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_simple_types_invalid.xml rename to src/test/resources/xbean/compile/som/instance_simple_types_invalid.xml diff --git a/src/test/resources/xbean/compile/som/instance_simple_types_valid.xml b/src/test/resources/xbean/compile/som/instance_simple_types_valid.xml new file mode 100644 index 0000000..6b203a7 --- /dev/null +++ b/src/test/resources/xbean/compile/som/instance_simple_types_valid.xml @@ -0,0 +1,70 @@ + + + + + MS Word + 3 + + MS Word + 4 + +
      This is a test Email Header
      + + + + user@unknown.domain.org + user@cduce.org + 2003-10-15T15:44:01Z + Xml Beans Testing +
      bill@microsoft.com
      +
      + bla +
      +
      + + + + + + + user@unknown.domain.org + user@cduce.org + 2003-10-15T15:44:01Z + Xml Beans Testing +
      bill@microsoft.com
      +
      + bla +
      + + +
      + + + + + English + Arial + + + + Hello + Mr X., Bea Systems + 425-123-1234 + + +
      diff --git a/test/cases/xbean/compile/som/instance_subst_grps_valid.xml b/src/test/resources/xbean/compile/som/instance_subst_grps_valid.xml similarity index 100% rename from test/cases/xbean/compile/som/instance_subst_grps_valid.xml rename to src/test/resources/xbean/compile/som/instance_subst_grps_valid.xml diff --git a/test/cases/xbean/compile/som/namespaces1.xsd_ b/src/test/resources/xbean/compile/som/namespaces1.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/namespaces1.xsd_ rename to src/test/resources/xbean/compile/som/namespaces1.xsd_ diff --git a/test/cases/xbean/compile/som/namespaces2.xsd_ b/src/test/resources/xbean/compile/som/namespaces2.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/namespaces2.xsd_ rename to src/test/resources/xbean/compile/som/namespaces2.xsd_ diff --git a/test/cases/xbean/compile/som/namespaces_import_fileonly.xsd_ b/src/test/resources/xbean/compile/som/namespaces_import_fileonly.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/namespaces_import_fileonly.xsd_ rename to src/test/resources/xbean/compile/som/namespaces_import_fileonly.xsd_ diff --git a/test/cases/xbean/compile/som/namespaces_import_filepath.xsd b/src/test/resources/xbean/compile/som/namespaces_import_filepath.xsd similarity index 91% rename from test/cases/xbean/compile/som/namespaces_import_filepath.xsd rename to src/test/resources/xbean/compile/som/namespaces_import_filepath.xsd index 7cae692..a9a91e1 100644 --- a/test/cases/xbean/compile/som/namespaces_import_filepath.xsd +++ b/src/test/resources/xbean/compile/som/namespaces_import_filepath.xsd @@ -25,7 +25,7 @@ + schemaLocation="namespaces1.xsd_" /> diff --git a/test/cases/xbean/compile/som/namespaces_include.xsd_ b/src/test/resources/xbean/compile/som/namespaces_include.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/namespaces_include.xsd_ rename to src/test/resources/xbean/compile/som/namespaces_include.xsd_ diff --git a/test/cases/xbean/compile/som/namespaces_noimports.xsd_ b/src/test/resources/xbean/compile/som/namespaces_noimports.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/namespaces_noimports.xsd_ rename to src/test/resources/xbean/compile/som/namespaces_noimports.xsd_ diff --git a/test/cases/xbean/compile/som/reusable_grps.xsd_ b/src/test/resources/xbean/compile/som/reusable_grps.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/reusable_grps.xsd_ rename to src/test/resources/xbean/compile/som/reusable_grps.xsd_ diff --git a/test/cases/xbean/compile/som/reusable_grps_added.xsd_ b/src/test/resources/xbean/compile/som/reusable_grps_added.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/reusable_grps_added.xsd_ rename to src/test/resources/xbean/compile/som/reusable_grps_added.xsd_ diff --git a/test/cases/xbean/compile/som/reusable_grps_modified.xsd_ b/src/test/resources/xbean/compile/som/reusable_grps_modified.xsd_ similarity index 100% rename from test/cases/xbean/compile/som/reusable_grps_modified.xsd_ rename to src/test/resources/xbean/compile/som/reusable_grps_modified.xsd_ diff --git a/test/cases/xbean/dom/ComplexTypeTest.xsd b/src/test/resources/xbean/dom/ComplexTypeTest.xsd similarity index 100% rename from test/cases/xbean/dom/ComplexTypeTest.xsd rename to src/test/resources/xbean/dom/ComplexTypeTest.xsd diff --git a/test/cases/xbean/dom/W3C/level2/core/files/README b/src/test/resources/xbean/dom/W3C/level2/core/files/README similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/README rename to src/test/resources/xbean/dom/W3C/level2/core/files/README diff --git a/test/cases/xbean/dom/W3C/level2/core/files/hc_staff.xml b/src/test/resources/xbean/dom/W3C/level2/core/files/hc_staff.xml similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/hc_staff.xml rename to src/test/resources/xbean/dom/W3C/level2/core/files/hc_staff.xml diff --git a/test/cases/xbean/dom/W3C/level2/core/files/nodtdstaff.xml b/src/test/resources/xbean/dom/W3C/level2/core/files/nodtdstaff.xml similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/nodtdstaff.xml rename to src/test/resources/xbean/dom/W3C/level2/core/files/nodtdstaff.xml diff --git a/test/cases/xbean/dom/W3C/level2/core/files/staff.dtd b/src/test/resources/xbean/dom/W3C/level2/core/files/staff.dtd similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/staff.dtd rename to src/test/resources/xbean/dom/W3C/level2/core/files/staff.dtd diff --git a/test/cases/xbean/dom/W3C/level2/core/files/staff.xml b/src/test/resources/xbean/dom/W3C/level2/core/files/staff.xml similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/staff.xml rename to src/test/resources/xbean/dom/W3C/level2/core/files/staff.xml diff --git a/test/cases/xbean/dom/W3C/level2/core/files/staff2.dtd b/src/test/resources/xbean/dom/W3C/level2/core/files/staff2.dtd similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/staff2.dtd rename to src/test/resources/xbean/dom/W3C/level2/core/files/staff2.dtd diff --git a/test/cases/xbean/dom/W3C/level2/core/files/staff2.xml b/src/test/resources/xbean/dom/W3C/level2/core/files/staff2.xml similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/staff2.xml rename to src/test/resources/xbean/dom/W3C/level2/core/files/staff2.xml diff --git a/test/cases/xbean/dom/W3C/level2/core/files/staffNS.dtd b/src/test/resources/xbean/dom/W3C/level2/core/files/staffNS.dtd similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/staffNS.dtd rename to src/test/resources/xbean/dom/W3C/level2/core/files/staffNS.dtd diff --git a/test/cases/xbean/dom/W3C/level2/core/files/staffNS.xml b/src/test/resources/xbean/dom/W3C/level2/core/files/staffNS.xml similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/staffNS.xml rename to src/test/resources/xbean/dom/W3C/level2/core/files/staffNS.xml diff --git a/test/cases/xbean/dom/W3C/level2/core/files/xhtml1-frameset.dtd b/src/test/resources/xbean/dom/W3C/level2/core/files/xhtml1-frameset.dtd similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/xhtml1-frameset.dtd rename to src/test/resources/xbean/dom/W3C/level2/core/files/xhtml1-frameset.dtd diff --git a/test/cases/xbean/dom/W3C/level2/core/files/xhtml1-strict.dtd b/src/test/resources/xbean/dom/W3C/level2/core/files/xhtml1-strict.dtd similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/xhtml1-strict.dtd rename to src/test/resources/xbean/dom/W3C/level2/core/files/xhtml1-strict.dtd diff --git a/test/cases/xbean/dom/W3C/level2/core/files/xhtml1-transitional.dtd b/src/test/resources/xbean/dom/W3C/level2/core/files/xhtml1-transitional.dtd similarity index 100% rename from test/cases/xbean/dom/W3C/level2/core/files/xhtml1-transitional.dtd rename to src/test/resources/xbean/dom/W3C/level2/core/files/xhtml1-transitional.dtd diff --git a/test/cases/xbean/dom/dumb.xsd b/src/test/resources/xbean/dom/dumb.xsd similarity index 100% rename from test/cases/xbean/dom/dumb.xsd rename to src/test/resources/xbean/dom/dumb.xsd diff --git a/test/cases/xbean/dom/id.xml b/src/test/resources/xbean/dom/id.xml similarity index 100% rename from test/cases/xbean/dom/id.xml rename to src/test/resources/xbean/dom/id.xml diff --git a/test/cases/xbean/dom/id.xsd b/src/test/resources/xbean/dom/id.xsd similarity index 91% rename from test/cases/xbean/dom/id.xsd rename to src/test/resources/xbean/dom/id.xsd index 79df05f..5ce8f0e 100644 --- a/test/cases/xbean/dom/id.xsd +++ b/src/test/resources/xbean/dom/id.xsd @@ -15,7 +15,7 @@ * limitations under the License. */ --> - - @@ -41,6 +40,7 @@ elementFormDefault="qualified" + diff --git a/src/test/resources/xbean/extensions/interfaceFeature/averageCase/po.xsd b/src/test/resources/xbean/extensions/interfaceFeature/averageCase/po.xsd new file mode 100755 index 0000000..4d7b48a --- /dev/null +++ b/src/test/resources/xbean/extensions/interfaceFeature/averageCase/po.xsd @@ -0,0 +1,76 @@ + + + + + + + Purchase order schema for Example.com. + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/extensions/interfaceFeature/averageCase/po.xsdconfig b/src/test/resources/xbean/extensions/interfaceFeature/averageCase/po.xsdconfig similarity index 100% rename from test/cases/xbean/extensions/interfaceFeature/averageCase/po.xsdconfig rename to src/test/resources/xbean/extensions/interfaceFeature/averageCase/po.xsdconfig diff --git a/src/test/resources/xbean/extensions/interfaceFeature/methodNameCollision/company.xsd b/src/test/resources/xbean/extensions/interfaceFeature/methodNameCollision/company.xsd new file mode 100755 index 0000000..13182c2 --- /dev/null +++ b/src/test/resources/xbean/extensions/interfaceFeature/methodNameCollision/company.xsd @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/extensions/interfaceFeature/methodNameCollision/company.xsdconfig b/src/test/resources/xbean/extensions/interfaceFeature/methodNameCollision/company.xsdconfig similarity index 100% rename from test/cases/xbean/extensions/interfaceFeature/methodNameCollision/company.xsdconfig rename to src/test/resources/xbean/extensions/interfaceFeature/methodNameCollision/company.xsdconfig diff --git a/src/test/resources/xbean/extensions/interfaceFeature/multInterfaces/po.xsd b/src/test/resources/xbean/extensions/interfaceFeature/multInterfaces/po.xsd new file mode 100755 index 0000000..e6fd926 --- /dev/null +++ b/src/test/resources/xbean/extensions/interfaceFeature/multInterfaces/po.xsd @@ -0,0 +1,76 @@ + + + + + + + Purchase order schema for Example.com. + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/extensions/interfaceFeature/multInterfaces/po.xsdconfig b/src/test/resources/xbean/extensions/interfaceFeature/multInterfaces/po.xsdconfig similarity index 100% rename from test/cases/xbean/extensions/interfaceFeature/multInterfaces/po.xsdconfig rename to src/test/resources/xbean/extensions/interfaceFeature/multInterfaces/po.xsdconfig diff --git a/src/test/resources/xbean/extensions/interfaceFeature/readOnlyBean/po.xsd b/src/test/resources/xbean/extensions/interfaceFeature/readOnlyBean/po.xsd new file mode 100755 index 0000000..99aaea3 --- /dev/null +++ b/src/test/resources/xbean/extensions/interfaceFeature/readOnlyBean/po.xsd @@ -0,0 +1,76 @@ + + + + + + + Purchase order schema for Example.com. + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/extensions/interfaceFeature/readOnlyBean/po.xsdconfig b/src/test/resources/xbean/extensions/interfaceFeature/readOnlyBean/po.xsdconfig similarity index 100% rename from test/cases/xbean/extensions/interfaceFeature/readOnlyBean/po.xsdconfig rename to src/test/resources/xbean/extensions/interfaceFeature/readOnlyBean/po.xsdconfig diff --git a/src/test/resources/xbean/extensions/prePostFeature/ValueRestriction/company.xsd b/src/test/resources/xbean/extensions/prePostFeature/ValueRestriction/company.xsd new file mode 100755 index 0000000..c285fb5 --- /dev/null +++ b/src/test/resources/xbean/extensions/prePostFeature/ValueRestriction/company.xsd @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/extensions/prePostFeature/ValueRestriction/company.xsdconfig b/src/test/resources/xbean/extensions/prePostFeature/ValueRestriction/company.xsdconfig similarity index 100% rename from test/cases/xbean/extensions/prePostFeature/ValueRestriction/company.xsdconfig rename to src/test/resources/xbean/extensions/prePostFeature/ValueRestriction/company.xsdconfig diff --git a/src/test/resources/xbean/extensions/prePostFeature/readOnlyBean/po.xsd b/src/test/resources/xbean/extensions/prePostFeature/readOnlyBean/po.xsd new file mode 100755 index 0000000..f6474fe --- /dev/null +++ b/src/test/resources/xbean/extensions/prePostFeature/readOnlyBean/po.xsd @@ -0,0 +1,76 @@ + + + + + + + Purchase order schema for Example.com. + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/extensions/prePostFeature/readOnlyBean/po.xsdconfig b/src/test/resources/xbean/extensions/prePostFeature/readOnlyBean/po.xsdconfig similarity index 100% rename from test/cases/xbean/extensions/prePostFeature/readOnlyBean/po.xsdconfig rename to src/test/resources/xbean/extensions/prePostFeature/readOnlyBean/po.xsdconfig diff --git a/test/cases/xbean/marshal/com/mytest/YourClass.java b/src/test/resources/xbean/marshal/com/mytest/YourClass.java similarity index 100% rename from test/cases/xbean/marshal/com/mytest/YourClass.java rename to src/test/resources/xbean/marshal/com/mytest/YourClass.java diff --git a/src/test/resources/xbean/misc/dyntest.xml b/src/test/resources/xbean/misc/dyntest.xml new file mode 100755 index 0000000..9b77808 --- /dev/null +++ b/src/test/resources/xbean/misc/dyntest.xml @@ -0,0 +1,23 @@ + + + + + + + + + 42 + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/dyntest.xsd b/src/test/resources/xbean/misc/dyntest.xsd new file mode 100755 index 0000000..d0a4af0 --- /dev/null +++ b/src/test/resources/xbean/misc/dyntest.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/dyntest2.xml b/src/test/resources/xbean/misc/dyntest2.xml new file mode 100755 index 0000000..3557d29 --- /dev/null +++ b/src/test/resources/xbean/misc/dyntest2.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/dyntest2.xsd b/src/test/resources/xbean/misc/dyntest2.xsd new file mode 100755 index 0000000..35dcdc7 --- /dev/null +++ b/src/test/resources/xbean/misc/dyntest2.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/easypo.xml b/src/test/resources/xbean/misc/jira/easypo.xml new file mode 100644 index 0000000..a1a6d76 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/easypo.xml @@ -0,0 +1,38 @@ + + + + + + Gladys Kravitz +
      Anytown, PA
      +
      + 2003-01-07T14:16:00-05:00 + + Burnham's Celestial Handbook, Vol 1 + 5 + 21.79 + 2 + + + Burnham's Celestial Handbook, Vol 2 + 5 + 19.89 + 2 + + + ZipShip + 0.74 + +
      \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_04.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_04.xsd_ new file mode 100644 index 0000000..4e99000 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_04.xsd_ @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_08.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_08.xsd_ new file mode 100644 index 0000000..736473e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_08.xsd_ @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_08a.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_08a.xsd_ new file mode 100644 index 0000000..e9bd3f0 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_08a.xsd_ @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_09.xml b/src/test/resources/xbean/misc/jira/xmlbeans_09.xml new file mode 100644 index 0000000..b62dd5e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_09.xml @@ -0,0 +1,23 @@ + + + + + + enum1 + + + one + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_09.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_09.xsd_ new file mode 100644 index 0000000..b3849ec --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_09.xsd_ @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/misc/jira/xmlbeans_102.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_102.xsd similarity index 90% rename from test/cases/xbean/misc/jira/xmlbeans_102.xsd rename to src/test/resources/xbean/misc/jira/xmlbeans_102.xsd index 5f682d2..e184fd9 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_102.xsd +++ b/src/test/resources/xbean/misc/jira/xmlbeans_102.xsd @@ -1,4 +1,18 @@ + + - + @@ -51,7 +65,7 @@ - + @@ -60,7 +74,7 @@ - + @@ -73,13 +87,13 @@ - + - - + + @@ -93,7 +107,7 @@ - + @@ -113,7 +127,7 @@ - + @@ -170,4 +184,4 @@ - + diff --git a/test/cases/xbean/misc/jira/xmlbeans_102_netui-config.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_102_netui-config.xsd_ similarity index 90% rename from test/cases/xbean/misc/jira/xmlbeans_102_netui-config.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_102_netui-config.xsd_ index 5f682d2..3296897 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_102_netui-config.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_102_netui-config.xsd_ @@ -1,4 +1,17 @@ + - + @@ -51,7 +64,7 @@ - + @@ -60,7 +73,7 @@ - + @@ -73,13 +86,13 @@ - + - - + + @@ -93,7 +106,7 @@ - + @@ -113,7 +126,7 @@ - + @@ -170,4 +183,4 @@ - + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_105.xml b/src/test/resources/xbean/misc/jira/xmlbeans_105.xml new file mode 100644 index 0000000..497af80 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_105.xml @@ -0,0 +1,18 @@ + + + + + 2004-05-14T10:21:18.6939682+08:00 + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_105.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_105.xsd new file mode 100644 index 0000000..646226a --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_105.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_105a.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_105a.xsd new file mode 100644 index 0000000..51f8eb6 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_105a.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_175.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_175.xsd new file mode 100644 index 0000000..6eae88e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_175.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_177.xml b/src/test/resources/xbean/misc/jira/xmlbeans_177.xml new file mode 100644 index 0000000..1d7779e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_177.xml @@ -0,0 +1,24 @@ + + + + + This is a greater than sign: > + This is a less than sign: < + This is a single quote: ' + This is a double quote: " + W.L.Gore & Associates + Character data may not contain the three-character sequence ]]> with the > unescaped. + In particular, with the > unescaped. + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_177.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_177.xsd new file mode 100644 index 0000000..d0db1d5 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_177.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_177a.xml b/src/test/resources/xbean/misc/jira/xmlbeans_177a.xml new file mode 100644 index 0000000..6f28246 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_177a.xml @@ -0,0 +1,22 @@ + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_177a.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_177a.xsd new file mode 100644 index 0000000..59653fc --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_177a.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_datentypen_V1.30.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_datentypen_V1.30.xsd_ similarity index 87% rename from test/cases/xbean/misc/jira/xmlbeans_184_datentypen_V1.30.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_184_datentypen_V1.30.xsd_ index 17350d5..fd7ceba 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_184_datentypen_V1.30.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_datentypen_V1.30.xsd_ @@ -1,22 +1,20 @@ - - + + + @@ -25,16 +23,16 @@ Dokument/Instanz Identifikation ID-Elemente identifizieren eindeutig Objekte. Werte zur Identifizierung werden in Attribute EX, RT und RTV eingetragen: - RT-Attribut (Root) enth�lt eine eindeutige OID des Objekts (Person/Organisation oder - Schl�sseltabelle ...) - EX-Attribut (Extension) enth�lt die Erweiterung zu OID z.B. fortlaufende Nummer, - oder GUID bei XML-Dokumenten oder kodierten Wert aus der Schl�sseltabelle. - RTV-Attribut wird bei Referenzierung auf Schl�sseltabellen verwendet. Hier wird - Schl�sseltabellenversion eingegeben. + RT-Attribut (Root) enthält eine eindeutige OID des Objekts (Person/Organisation oder + Schlüsseltabelle ...) + EX-Attribut (Extension) enthält die Erweiterung zu OID z.B. fortlaufende Nummer, + oder GUID bei XML-Dokumenten oder kodierten Wert aus der Schlüsseltabelle. + RTV-Attribut wird bei Referenzierung auf Schlüsseltabellen verwendet. Hier wird + Schlüsseltabellenversion eingegeben. ============================================================--> - enth�lt eindeutige Instanz-ID + enthält eindeutige Instanz-ID @@ -52,17 +50,17 @@ - enth�lt eindeutige Instanz-ID, die �ber alle Versionen und zusammgengeh�rende Dokumente konstant bleibt + enthält eindeutige Instanz-ID, die über alle Versionen und zusammgengehörende Dokumente konstant bleibt @@ -128,14 +126,14 @@ - G�ltigkeitszeitraum (date..date) + Gültigkeitszeitraum (date..date) @@ -156,8 +154,8 @@ - Empf�nger / Zielgruppe der Daten + Empfänger / Zielgruppe der Daten @@ -259,7 +257,7 @@
      - zugeh�rende Gruppe, Auspr�gung (z.B. Augenarzt) + zugehörende Gruppe, Ausprägung (z.B. Augenarzt) @@ -391,12 +389,12 @@ - Element f�r weitere, datenartspezifische, Metainformationen + Element für weitere, datenartspezifische, Metainformationen @@ -409,11 +407,11 @@ @@ -423,7 +421,7 @@ - interne/alternative Kodes und Schl�sseltabellen + interne/alternative Kodes und Schlüsseltabellen @@ -459,8 +457,8 @@ - enth�lt Informationen �ber die Schnittstelle selbst + enthält Informationen über die Schnittstelle selbst @@ -516,7 +514,7 @@ @@ -556,7 +554,7 @@ @@ -576,7 +574,7 @@ - Auspr�gungen f�r NULL-Attribut + Ausprägungen für NULL-Attribut @@ -592,7 +590,7 @@ - Typ f�r einen Global Unique Identifier + Typ für einen Global Unique Identifier diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_184_ehd_header_V1.30.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_ehd_header_V1.30.xsd_ new file mode 100644 index 0000000..8aa6962 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_ehd_header_V1.30.xsd_ @@ -0,0 +1,58 @@ + + + + + + + + + + + ehd-header + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_184_ehd_root_V1.30.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_ehd_root_V1.30.xsd_ new file mode 100644 index 0000000..55f973e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_ehd_root_V1.30.xsd_ @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + alle Metainformationen zu den Daten + + + + + die eigentlichen Daten + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_184_keytabs_V1.30.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_keytabs_V1.30.xsd_ new file mode 100644 index 0000000..42697b7 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_keytabs_V1.30.xsd_ @@ -0,0 +1,75 @@ + + + + + + + + Schlüsseltabellen zu den Daten + + + + + + + + + + + + + + + + Sclüsseltabelle mit S=OID, SN=Name der Schlüsseltabelle, SV=Version + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Schlüssel mit V=Wert, DN=WertBezeichnung, S=OID zur welchen Sclüsseltabelle der Wert gehört, SV=Version der Schlüsseltabelle + + + + + + + + + diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_vdx_data_V1.04.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_data_V1.04.xsd_ similarity index 89% rename from test/cases/xbean/misc/jira/xmlbeans_184_vdx_data_V1.04.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_data_V1.04.xsd_ index 7f9d6de..c0afb32 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_184_vdx_data_V1.04.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_data_V1.04.xsd_ @@ -1,36 +1,34 @@ - - + + + - - klammerndes Element von jeweils einem LE und seinen F�llen oder einer Kasse und zahlungspflichtigen KV mit den zugeh�rigen Vorg�ngen. Das Element vdx_data nimmt die zahlungsfordernde KV auf. + klammerndes Element von jeweils einem LE und seinen Fällen oder einer Kasse und zahlungspflichtigen KV mit den zugehörigen Vorgängen. Das Element vdx_data nimmt die zahlungsfordernde KV auf. - abrechnende, leistungserbringende Organisation oder Person. In der an die KBV zu �bermittelnden DA D06 ist "provider" Pflichtelement + abrechnende, leistungserbringende Organisation oder Person. In der an die KBV zu übermittelnden DA D06 ist "provider" Pflichtelement @@ -54,7 +52,7 @@ - EX-Attribut enth�lt eine eindeutige ID des Objekts + EX-Attribut enthält eine eindeutige ID des Objekts @@ -68,7 +66,7 @@ - RT-Attribut enth�lt eine eindeutige Stamm-ID + RT-Attribut enthält eine eindeutige Stamm-ID @@ -98,7 +96,7 @@ - RT-Attribut enth�lt Praxisabrechnungsnummer + RT-Attribut enthält Praxisabrechnungsnummer @@ -175,7 +173,7 @@ - + @@ -205,7 +203,7 @@ - KVspez. Honorartopf, aus dem die f�r Fachgruppent�pfe relevanten Leistungen honoriert werden + KVspez. Honorartopf, aus dem die für Fachgruppentöpfe relevanten Leistungen honoriert werden @@ -254,7 +252,7 @@ - Gesamthonorar der Praxis nach allen 4 Kostentr�gerarten + Gesamthonorar der Praxis nach allen 4 Kostenträgerarten @@ -262,9 +260,9 @@ - + - + @@ -276,7 +274,7 @@ - + @@ -285,7 +283,7 @@ - + @@ -305,7 +303,7 @@ - Gesamt- oder GKV-Leistungsbedarf der Praxis nach Kostentr�gerarten + Gesamt- oder GKV-Leistungsbedarf der Praxis nach Kostenträgerarten @@ -322,9 +320,9 @@ - + - + @@ -344,7 +342,7 @@ - + @@ -355,7 +353,7 @@ - Basistyp f�r listen_ids zur Verarbeitungssteuerung + Basistyp für listen_ids zur Verarbeitungssteuerung @@ -403,7 +401,7 @@ - enth�lt Scheinuntergruppe + enthält Scheinuntergruppe gem. FK 4239 @@ -504,7 +502,7 @@ gem. FK 4239 - + @@ -520,13 +518,13 @@ gem. FK 4239 - + - bei GNRn gem�� Anerkennungsvereinbarung Anlage 15 und 17 sowie FKZ-Richtlinie Kap.1.3.7, immer in EUR + bei GNRn gemäß Anerkennungsvereinbarung Anlage 15 und 17 sowie FKZ-Richtlinie Kap.1.3.7, immer in EUR @@ -537,7 +535,7 @@ gem. FK 4239 - erl�uternder Text der GNR + erläuternder Text der GNR @@ -560,7 +558,7 @@ gem. FK 4239 - Schl�ssel gem. OPS-301 + Schlüssel gem. OPS-301 @@ -658,7 +656,7 @@ gem. FK 4239 - Diagnoseerl�uterung FK:6006 + Diagnoseerläuterung FK:6006 @@ -679,7 +677,7 @@ gem. FK 4239 - @@ -782,7 +780,7 @@ nummer, FK 0105 - + @@ -802,7 +800,7 @@ nummer, FK 0105 - Punktwert oder Quote, nur bei GNRn gem�� Anerkennungsvereinbarung Anlage 15 und 17 sowie FKZ-Richtlinie Kap. 1.3.7. + Punktwert oder Quote, nur bei GNRn gemäß Anerkennungsvereinbarung Anlage 15 und 17 sowie FKZ-Richtlinie Kap. 1.3.7. @@ -820,7 +818,7 @@ nummer, FK 0105 - + @@ -856,13 +854,13 @@ nummer, FK 0105 - + - f�r Rechnungslegung gegen�ber KT zust�ndige KV-Stelle | ST 12 + für Rechnungslegung gegenüber KT zuständige KV-Stelle | ST 12 @@ -905,7 +903,7 @@ nummer, FK 0105 - nimmt steuernde Attribute f�r ggf. abweichende Bewertung bereichsfremder Leistungen auf | ST 07 + nimmt steuernde Attribute für ggf. abweichende Bewertung bereichsfremder Leistungen auf | ST 07 @@ -1083,7 +1081,7 @@ nummer, FK 0105 - Praxisabrechnungsnummer bei LE-bezogenen Vorg�ngen + Praxisabrechnungsnummer bei LE-bezogenen Vorgängen @@ -1094,7 +1092,7 @@ nummer, FK 0105 - + @@ -1125,7 +1123,7 @@ nummer, FK 0105 - + @@ -1149,11 +1147,11 @@ nummer, FK 0105 - + - Kostentr�gerarten- + Kostenträgerarten- Kennung | ST 06 @@ -1166,14 +1164,14 @@ Kennung | ST 06 - - Mengensteuerungskennung f�r Honorar und Leistungsbedarf | ST 05 + Mengensteuerungskennung für Honorar und Leistungsbedarf | ST 05 @@ -1185,7 +1183,7 @@ Kennung ST 06"/> - + @@ -1203,7 +1201,7 @@ Kennung ST 06"/> - + @@ -1250,7 +1248,7 @@ Kennung ST 06"/> - + diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_vdx_header_V1.04.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_header_V1.04.xsd_ similarity index 84% rename from test/cases/xbean/misc/jira/xmlbeans_184_vdx_header_V1.04.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_header_V1.04.xsd_ index ee4e711..1194dd2 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_184_vdx_header_V1.04.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_header_V1.04.xsd_ @@ -1,20 +1,18 @@ - - + + + @@ -59,7 +57,7 @@ - + diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_vdx_root_V1.04.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_root_V1.04.xsd_ similarity index 76% rename from test/cases/xbean/misc/jira/xmlbeans_184_vdx_root_V1.04.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_root_V1.04.xsd_ index 07e9709..bf2ab75 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_184_vdx_root_V1.04.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_184_vdx_root_V1.04.xsd_ @@ -1,41 +1,39 @@ - - + + + - - - root element ehd "eHealthData" - @@ -57,7 +55,7 @@ - diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_208.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_208.xsd new file mode 100644 index 0000000..55b0443 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_208.xsd @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_228.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_228.xsd new file mode 100644 index 0000000..6c53954 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_228.xsd @@ -0,0 +1,47 @@ + + + + + + + Wrong element order after substitution. + 14.11.05 11:11 + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_236.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_236.xsd_ new file mode 100644 index 0000000..ac49863 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_236.xsd_ @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_239a.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_239a.xsd_ new file mode 100644 index 0000000..1457608 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_239a.xsd_ @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_239b.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_239b.xsd_ new file mode 100644 index 0000000..876fc17 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_239b.xsd_ @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_239c.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_239c.xsd_ new file mode 100644 index 0000000..028458c --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_239c.xsd_ @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_251.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_251.xsd_ new file mode 100644 index 0000000..f364890 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_251.xsd_ @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/misc/jira/xmlbeans_307_maxallowedenum.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_307_maxallowedenum.xsd similarity index 99% rename from test/cases/xbean/misc/jira/xmlbeans_307_maxallowedenum.xsd rename to src/test/resources/xbean/misc/jira/xmlbeans_307_maxallowedenum.xsd index f6c2d60..8a9675a 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_307_maxallowedenum.xsd +++ b/src/test/resources/xbean/misc/jira/xmlbeans_307_maxallowedenum.xsd @@ -1,10 +1,24 @@ + + - + @@ -3670,11 +3684,13 @@ + diff --git a/test/cases/xbean/misc/jira/xmlbeans_307_morethanallowedenum.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_307_morethanallowedenum.xsd similarity index 99% rename from test/cases/xbean/misc/jira/xmlbeans_307_morethanallowedenum.xsd rename to src/test/resources/xbean/misc/jira/xmlbeans_307_morethanallowedenum.xsd index d02ccb0..ca8fa16 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_307_morethanallowedenum.xsd +++ b/src/test/resources/xbean/misc/jira/xmlbeans_307_morethanallowedenum.xsd @@ -1,11 +1,25 @@ + + - + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_33a.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_33a.xsd new file mode 100644 index 0000000..35570ea --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_33a.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_33b.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_33b.xsd new file mode 100644 index 0000000..b6d8c3c --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_33b.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_34a.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_34a.xsd_ new file mode 100644 index 0000000..ca8bb31 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_34a.xsd_ @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_34b.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_34b.xsd_ new file mode 100644 index 0000000..ed17c3d --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_34b.xsd_ @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/misc/jira/xmlbeans_35.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_35.xsd_ similarity index 88% rename from test/cases/xbean/misc/jira/xmlbeans_35.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_35.xsd_ index 6b319a2..92dabae 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_35.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_35.xsd_ @@ -1,4 +1,17 @@ + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_45a.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_45a.xsd new file mode 100644 index 0000000..afface4 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_45a.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_45b.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_45b.xsd new file mode 100644 index 0000000..cdfcf03 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_45b.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_46.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_46.xsd new file mode 100644 index 0000000..c58199e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_46.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_48.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_48.xsd new file mode 100644 index 0000000..baa1b0d --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_48.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_49.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_49.xsd_ similarity index 95% rename from test/cases/xbean/misc/jira/xmlbeans_49.xsd_ rename to src/test/resources/xbean/misc/jira/xmlbeans_49.xsd_ index cc1ce73..2affb0b 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_49.xsd_ +++ b/src/test/resources/xbean/misc/jira/xmlbeans_49.xsd_ @@ -1,4 +1,18 @@ - + + + @@ -719,7 +733,7 @@ which language is used in the description according to RFC 1766 (http://www.ietf.org/rfc/rfc1766.txt). The default - value of this attribute is English(“en�?). + value of this attribute is English("en"). diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_54.xsd_ b/src/test/resources/xbean/misc/jira/xmlbeans_54.xsd_ new file mode 100644 index 0000000..bad98ae --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_54.xsd_ @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_57.xml b/src/test/resources/xbean/misc/jira/xmlbeans_57.xml new file mode 100644 index 0000000..f1abc85 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_57.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_62.xml b/src/test/resources/xbean/misc/jira/xmlbeans_62.xml new file mode 100644 index 0000000..a4b1a90 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_62.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/misc/jira/xmlbeans_64.xml b/src/test/resources/xbean/misc/jira/xmlbeans_64.xml similarity index 97% rename from test/cases/xbean/misc/jira/xmlbeans_64.xml rename to src/test/resources/xbean/misc/jira/xmlbeans_64.xml index d5dbbfe..18be86a 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_64.xml +++ b/src/test/resources/xbean/misc/jira/xmlbeans_64.xml @@ -1,4 +1,18 @@ + + XhtmlCheckBox ekoneil @@ -78,7 +92,7 @@ .title {color: #000099;font-family:Verdana; font-size:12pt;margin:2,0,5,0;} .resultDiv {border: thin solid;margin:5,5,5,5;} </style> - </head> + </head> <body> <h1 class="normalHead">CheckBox and CheckBox Group tests</h1> <a href="/coreWeb/xhtml/begin.do" class="normal" rel="contents" rev="chapter">Home</a> @@ -92,32 +106,32 @@ <input type="hidden" name="wlw-checkbox_group_key:{actionForm.cbg}OldValue" value="true" /> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.cbg}" value="CheckBox Option 1" disabled="disabled" lang="en" title="Title Text" alt="Alt Text" dir="ltr" /><span class="normal">Text CB Option One</span> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.cbg}" value="CheckBox Option 2" checked="checked" /><span class="normal">Text CB Option Two</span> - + </td> </tr> <tr valign="top" > <td class="normalBold" align="right">Repeating CheckBox Group</td> <td> <table> - + <tr><td align="right" class="normal2"> <span>CBG Option 1</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 1" /><input type="hidden" name="wlw-checkbox_group_key:{actionForm.optCbg}OldValue" value="true" /> </td></tr> - + <tr><td align="right" class="normal2"> <span>CBG Option 2</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 2" checked="checked" /> </td></tr> - + <tr><td align="right" class="normal2"> <span>CBG Option 3</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 3" /> </td></tr> - + </table> </td> </tr> @@ -137,22 +151,22 @@ <td colspan="2" align="center"> <table cellspacing="0" border="1"> <tr><th class="normalBold" valign="top" align="center">Complex Repeater</th><td> - + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-1" checked="checked" /><input type="hidden" name="wlw-checkbox_group_key:{actionForm.optCbgMap}OldValue" value="true" /> <span class="normal">Option One</span><br/> - - + + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-2" /> <span class="normal2">Option Two</span><br/> - - + + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-3" /> <span class="normal3">Option Three</span><br/> - - + + </td></tr></table> </td> - </tr> + </tr> </table> <br /> <input type="submit" class="normal" value="Post To Results One" title="Post to Results One" lang="en" alt="Post to Results One" dir="ltr" /> @@ -314,14 +328,14 @@ .title {color: #000099;font-family:Verdana; font-size:12pt;margin:2,0,5,0;} .resultDiv {border: thin solid;height: 400px;} - +

      Checkbox Results

      Input Tests

      - Action: postFormOne + Action: postFormOne

      @@ -446,7 +460,7 @@ .title {color: #000099;font-family:Verdana; font-size:12pt;margin:2,0,5,0;} .resultDiv {border: thin solid;margin:5,5,5,5;} </style> - </head> + </head> <body> <h1 class="normalHead">CheckBox and CheckBox Group tests</h1> <a href="/coreWeb/xhtml/begin.do" class="normal" rel="contents" rev="chapter">Home</a> @@ -460,32 +474,32 @@ <input type="hidden" name="wlw-checkbox_group_key:{actionForm.cbg}OldValue" value="true" /> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.cbg}" value="CheckBox Option 1" disabled="disabled" lang="en" title="Title Text" alt="Alt Text" dir="ltr" /><span class="normal">Text CB Option One</span> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.cbg}" value="CheckBox Option 2" checked="checked" /><span class="normal">Text CB Option Two</span> - + </td> </tr> <tr valign="top" > <td class="normalBold" align="right">Repeating CheckBox Group</td> <td> <table> - + <tr><td align="right" class="normal2"> <span>CBG Option 1</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 1" /><input type="hidden" name="wlw-checkbox_group_key:{actionForm.optCbg}OldValue" value="true" /> </td></tr> - + <tr><td align="right" class="normal2"> <span>CBG Option 2</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 2" checked="checked" /> </td></tr> - + <tr><td align="right" class="normal2"> <span>CBG Option 3</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 3" /> </td></tr> - + </table> </td> </tr> @@ -505,22 +519,22 @@ <td colspan="2" align="center"> <table cellspacing="0" border="1"> <tr><th class="normalBold" valign="top" align="center">Complex Repeater</th><td> - + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-1" checked="checked" /><input type="hidden" name="wlw-checkbox_group_key:{actionForm.optCbgMap}OldValue" value="true" /> <span class="normal">Option One</span><br/> - - + + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-2" /> <span class="normal2">Option Two</span><br/> - - + + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-3" /> <span class="normal3">Option Three</span><br/> - - + + </td></tr></table> </td> - </tr> + </tr> </table> <br /> <input type="submit" class="normal" value="Post To Results One" title="Post to Results One" lang="en" alt="Post to Results One" dir="ltr" /> @@ -686,14 +700,14 @@ .title {color: #000099;font-family:Verdana; font-size:12pt;margin:2,0,5,0;} .resultDiv {border: thin solid;height: 400px;} - +

      Checkbox Results

      Input Tests

      - Action: postFormTwo + Action: postFormTwo

      @@ -818,7 +832,7 @@ .title {color: #000099;font-family:Verdana; font-size:12pt;margin:2,0,5,0;} .resultDiv {border: thin solid;margin:5,5,5,5;} </style> - </head> + </head> <body> <h1 class="normalHead">CheckBox and CheckBox Group tests</h1> <a href="/coreWeb/xhtml/begin.do" class="normal" rel="contents" rev="chapter">Home</a> @@ -832,32 +846,32 @@ <input type="hidden" name="wlw-checkbox_group_key:{actionForm.cbg}OldValue" value="true" /> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.cbg}" value="CheckBox Option 1" disabled="disabled" lang="en" title="Title Text" alt="Alt Text" dir="ltr" /><span class="normal">Text CB Option One</span> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.cbg}" value="CheckBox Option 2" checked="checked" /><span class="normal">Text CB Option Two</span> - + </td> </tr> <tr valign="top" > <td class="normalBold" align="right">Repeating CheckBox Group</td> <td> <table> - + <tr><td align="right" class="normal2"> <span>CBG Option 1</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 1" /><input type="hidden" name="wlw-checkbox_group_key:{actionForm.optCbg}OldValue" value="true" /> </td></tr> - + <tr><td align="right" class="normal2"> <span>CBG Option 2</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 2" checked="checked" /> </td></tr> - + <tr><td align="right" class="normal2"> <span>CBG Option 3</span> </td><td> <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbg}" value="CBG Option 3" /> </td></tr> - + </table> </td> </tr> @@ -877,22 +891,22 @@ <td colspan="2" align="center"> <table cellspacing="0" border="1"> <tr><th class="normalBold" valign="top" align="center">Complex Repeater</th><td> - + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-1" checked="checked" /><input type="hidden" name="wlw-checkbox_group_key:{actionForm.optCbgMap}OldValue" value="true" /> <span class="normal">Option One</span><br/> - - + + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-2" /> <span class="normal2">Option Two</span><br/> - - + + <input type="checkbox" name="wlw-checkbox_group_key:{actionForm.optCbgMap}" value="opt-3" /> <span class="normal3">Option Three</span><br/> - - + + </td></tr></table> </td> - </tr> + </tr> </table> <br /> <input type="submit" class="normal" value="Post To Results One" title="Post to Results One" lang="en" alt="Post to Results One" dir="ltr" /> diff --git a/test/cases/xbean/misc/jira/xmlbeans_64.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_64.xsd similarity index 88% rename from test/cases/xbean/misc/jira/xmlbeans_64.xsd rename to src/test/resources/xbean/misc/jira/xmlbeans_64.xsd index 5577572..7de6ed7 100644 --- a/test/cases/xbean/misc/jira/xmlbeans_64.xsd +++ b/src/test/resources/xbean/misc/jira/xmlbeans_64.xsd @@ -1,4 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_71.xml b/src/test/resources/xbean/misc/jira/xmlbeans_71.xml new file mode 100644 index 0000000..575eb7e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_71.xml @@ -0,0 +1,21 @@ + + + + +SUCCESS + +0 +0 + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_71.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_71.xsd new file mode 100644 index 0000000..55bfa0e --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_71.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_78.xml b/src/test/resources/xbean/misc/jira/xmlbeans_78.xml new file mode 100644 index 0000000..ecd7fc8 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_78.xml @@ -0,0 +1,54 @@ + + + + + + + + +
      + + 123456 + + + + 1234 + + + + True + + xyz + 123 + + + + 123 + http://xmlbeans.apache.org + + Apache + xmlbeans + Book + XmlBeans Apache Org + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_97.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_97.xsd new file mode 100644 index 0000000..fc503d9 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_97.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_97.xsdconfig b/src/test/resources/xbean/misc/jira/xmlbeans_97.xsdconfig new file mode 100644 index 0000000..64d502b --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_97.xsdconfig @@ -0,0 +1,36 @@ + + + + + + + org.apache.jira.xmlbeans98 + + + + + + Xml + Bean + + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_98.xml b/src/test/resources/xbean/misc/jira/xmlbeans_98.xml new file mode 100644 index 0000000..f17e3d7 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_98.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_98.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_98.xsd new file mode 100644 index 0000000..df00ecf --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_98.xsd @@ -0,0 +1,30 @@ + + + + + + + + + + Comment describing your root element + + + + + + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_98_exp.xml b/src/test/resources/xbean/misc/jira/xmlbeans_98_exp.xml new file mode 100644 index 0000000..7629ae3 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_98_exp.xml @@ -0,0 +1,15 @@ + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_99.xml b/src/test/resources/xbean/misc/jira/xmlbeans_99.xml new file mode 100644 index 0000000..a0f3f56 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_99.xml @@ -0,0 +1,25 @@ + + + + + + + + toto + + + diff --git a/src/test/resources/xbean/misc/jira/xmlbeans_99.xsd b/src/test/resources/xbean/misc/jira/xmlbeans_99.xsd new file mode 100644 index 0000000..aa7f465 --- /dev/null +++ b/src/test/resources/xbean/misc/jira/xmlbeans_99.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/misc/primitiveTypes.xml b/src/test/resources/xbean/misc/primitiveTypes.xml similarity index 77% rename from test/cases/xbean/misc/primitiveTypes.xml rename to src/test/resources/xbean/misc/primitiveTypes.xml index 5136e50..9413e6c 100755 --- a/test/cases/xbean/misc/primitiveTypes.xml +++ b/src/test/resources/xbean/misc/primitiveTypes.xml @@ -1,3 +1,18 @@ + + + + + + +]> + + + + + + + + + + + + + + j6lwx3rvEPO0vKtMup4NbeVu8nk= + + + + + + + + UrXLDLBIta6skoV5/A8Q38GEw44= + + + MC0CFFrVLtRlkMc3Daon4BqqnkhCOlEaAhUAk8pH1iRNK+q1I+sisDTz2TFEALE= + + + +

      ...

      ......... +
      +
      +
      + + + + + this is a test of the mixed content model + + + +
      diff --git a/src/test/resources/xbean/misc/syscachetest1.xsd b/src/test/resources/xbean/misc/syscachetest1.xsd new file mode 100644 index 0000000..e19b14a --- /dev/null +++ b/src/test/resources/xbean/misc/syscachetest1.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/misc/syscachetest2.xsd b/src/test/resources/xbean/misc/syscachetest2.xsd new file mode 100644 index 0000000..5560ef2 --- /dev/null +++ b/src/test/resources/xbean/misc/syscachetest2.xsd @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/misc/xkms-1.0.wsdl b/src/test/resources/xbean/misc/xkms-1.0.wsdl similarity index 85% rename from test/cases/xbean/misc/xkms-1.0.wsdl rename to src/test/resources/xbean/misc/xkms-1.0.wsdl index 4ae1f4f..4fc0393 100755 --- a/test/cases/xbean/misc/xkms-1.0.wsdl +++ b/src/test/resources/xbean/misc/xkms-1.0.wsdl @@ -1,1364 +1,695 @@ - + + + - - - - - - + version="0.1" elementFormDefault="qualified"> - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - + - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - - - - + + + + - - - - - - - + + + - - - - - - - + - - - - - - - + - - - - + - - - + - - - - - - - + - - - - - - + + - - - - - - - - - - - - - - + - - - - - - - - - - - - + + + + - - - - + - - - - + - - - - - - - + - - - - - - - - - - + - - - - - - + + - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - + + + + - - - - - - - - - - - + + - - - - - - + + - - - - - - - - - - - + - - - - - - - - + - - - - - - - - + - - - - - - + - - - + - - - - + - - - - + - - - + - - - - + - - - - + - - - + - - - - + - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Verisign's XML Key Management Service (XKMS) - - - - - - - - - - - - Verisign's Pilot XML Key Management Service (XKMS) - - - - - - - - - - - diff --git a/test/cases/xbean/misc/xmldsig-core-schema.xsd b/src/test/resources/xbean/misc/xmldsig-core-schema.xsd similarity index 100% rename from test/cases/xbean/misc/xmldsig-core-schema.xsd rename to src/test/resources/xbean/misc/xmldsig-core-schema.xsd diff --git a/src/test/resources/xbean/schema/typesonly/typesonly.xsd b/src/test/resources/xbean/schema/typesonly/typesonly.xsd new file mode 100755 index 0000000..59db0d0 --- /dev/null +++ b/src/test/resources/xbean/schema/typesonly/typesonly.xsd @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/attribute/AttributeGroup.xsd b/src/test/resources/xbean/scomp/attribute/AttributeGroup.xsd new file mode 100644 index 0000000..805f559 --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/AttributeGroup.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/attribute/GlobalAttrDefault.xsd b/src/test/resources/xbean/scomp/attribute/GlobalAttrDefault.xsd new file mode 100644 index 0000000..05efc5e --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/GlobalAttrDefault.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/attribute/GlobalAttrFixed.xsd b/src/test/resources/xbean/scomp/attribute/GlobalAttrFixed.xsd new file mode 100644 index 0000000..e359242 --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/GlobalAttrFixed.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/attribute/GlobalAttrId.xsd b/src/test/resources/xbean/scomp/attribute/GlobalAttrId.xsd new file mode 100644 index 0000000..1d1a888 --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/GlobalAttrId.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/attribute/GlobalAttrType.xsd b/src/test/resources/xbean/scomp/attribute/GlobalAttrType.xsd new file mode 100644 index 0000000..a5c80aa --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/GlobalAttrType.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/attribute/LocalAttrFixedDefault.xsd b/src/test/resources/xbean/scomp/attribute/LocalAttrFixedDefault.xsd new file mode 100644 index 0000000..de30886 --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/LocalAttrFixedDefault.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/attribute/LocalAttrUse.xsd b/src/test/resources/xbean/scomp/attribute/LocalAttrUse.xsd new file mode 100644 index 0000000..b431f50 --- /dev/null +++ b/src/test/resources/xbean/scomp/attribute/LocalAttrUse.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/contentType/Anonymous.xsd b/src/test/resources/xbean/scomp/contentType/Anonymous.xsd new file mode 100644 index 0000000..055f7ad --- /dev/null +++ b/src/test/resources/xbean/scomp/contentType/Anonymous.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/contentType/ComplexTypeTest.xsd b/src/test/resources/xbean/scomp/contentType/ComplexTypeTest.xsd new file mode 100644 index 0000000..7254783 --- /dev/null +++ b/src/test/resources/xbean/scomp/contentType/ComplexTypeTest.xsd @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/Group.xsd b/src/test/resources/xbean/scomp/contentType/Group.xsd similarity index 79% rename from test/cases/xbean/scomp/contentType/Group.xsd rename to src/test/resources/xbean/scomp/contentType/Group.xsd index f00b84a..139e089 100644 --- a/test/cases/xbean/scomp/contentType/Group.xsd +++ b/src/test/resources/xbean/scomp/contentType/Group.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/contentType/Named.xsd b/src/test/resources/xbean/scomp/contentType/Named.xsd new file mode 100644 index 0000000..5f094d5 --- /dev/null +++ b/src/test/resources/xbean/scomp/contentType/Named.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/contentType/SimpleType.xsd b/src/test/resources/xbean/scomp/contentType/SimpleType.xsd new file mode 100644 index 0000000..61cc674 --- /dev/null +++ b/src/test/resources/xbean/scomp/contentType/SimpleType.xsd @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/UnionType.xsd b/src/test/resources/xbean/scomp/contentType/UnionType.xsd similarity index 77% rename from test/cases/xbean/scomp/contentType/UnionType.xsd rename to src/test/resources/xbean/scomp/contentType/UnionType.xsd index c3d0860..44d1be2 100644 --- a/test/cases/xbean/scomp/contentType/UnionType.xsd +++ b/src/test/resources/xbean/scomp/contentType/UnionType.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/contentType/builtInTypes/NumberBased.xsd b/src/test/resources/xbean/scomp/contentType/builtInTypes/NumberBased.xsd new file mode 100644 index 0000000..89cdd54 --- /dev/null +++ b/src/test/resources/xbean/scomp/contentType/builtInTypes/NumberBased.xsd @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/contentType/builtInTypes/StringBased.xsd b/src/test/resources/xbean/scomp/contentType/builtInTypes/StringBased.xsd new file mode 100644 index 0000000..8e93c63 --- /dev/null +++ b/src/test/resources/xbean/scomp/contentType/builtInTypes/StringBased.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/derivation/Abstract.xsd b/src/test/resources/xbean/scomp/derivation/Abstract.xsd new file mode 100644 index 0000000..a459953 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/Abstract.xsd @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/AttributeExtension.xsd b/src/test/resources/xbean/scomp/derivation/AttributeExtension.xsd new file mode 100644 index 0000000..d866020 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/AttributeExtension.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/AttributeRestriction.xsd b/src/test/resources/xbean/scomp/derivation/AttributeRestriction.xsd new file mode 100644 index 0000000..dfc4366 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/AttributeRestriction.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/AttributeUseProhibited.xsd b/src/test/resources/xbean/scomp/derivation/AttributeUseProhibited.xsd new file mode 100644 index 0000000..e325065 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/AttributeUseProhibited.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/AttributeWCExtension.xsd b/src/test/resources/xbean/scomp/derivation/AttributeWCExtension.xsd similarity index 89% rename from test/cases/xbean/scomp/derivation/AttributeWCExtension.xsd rename to src/test/resources/xbean/scomp/derivation/AttributeWCExtension.xsd index 3b46bb6..e54a36d 100644 --- a/test/cases/xbean/scomp/derivation/AttributeWCExtension.xsd +++ b/src/test/resources/xbean/scomp/derivation/AttributeWCExtension.xsd @@ -1,3 +1,18 @@ + + + + + - - + + diff --git a/src/test/resources/xbean/scomp/derivation/Block.xsd b/src/test/resources/xbean/scomp/derivation/Block.xsd new file mode 100644 index 0000000..fcdcdfc --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/Block.xsd @@ -0,0 +1,192 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/ComplexContentExtension.xsd b/src/test/resources/xbean/scomp/derivation/ComplexContentExtension.xsd new file mode 100644 index 0000000..ab039c6 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/ComplexContentExtension.xsd @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/ElementRestriction.xsd b/src/test/resources/xbean/scomp/derivation/ElementRestriction.xsd new file mode 100644 index 0000000..19ffab4 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/ElementRestriction.xsd @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/derivation/ElementWCRestriction.xsd b/src/test/resources/xbean/scomp/derivation/ElementWCRestriction.xsd new file mode 100644 index 0000000..79068c8 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/ElementWCRestriction.xsd @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/EmptyContent.xsd b/src/test/resources/xbean/scomp/derivation/EmptyContent.xsd new file mode 100644 index 0000000..29cbffd --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/EmptyContent.xsd @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/FinalBlockDefault.xsd b/src/test/resources/xbean/scomp/derivation/FinalBlockDefault.xsd similarity index 79% rename from test/cases/xbean/scomp/derivation/FinalBlockDefault.xsd rename to src/test/resources/xbean/scomp/derivation/FinalBlockDefault.xsd index 4090709..43f5ded 100644 --- a/test/cases/xbean/scomp/derivation/FinalBlockDefault.xsd +++ b/src/test/resources/xbean/scomp/derivation/FinalBlockDefault.xsd @@ -1,4 +1,19 @@ - + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/MixedContentRestriction.xsd b/src/test/resources/xbean/scomp/derivation/MixedContentRestriction.xsd similarity index 77% rename from test/cases/xbean/scomp/derivation/MixedContentRestriction.xsd rename to src/test/resources/xbean/scomp/derivation/MixedContentRestriction.xsd index 8afc401..0c269f2 100644 --- a/test/cases/xbean/scomp/derivation/MixedContentRestriction.xsd +++ b/src/test/resources/xbean/scomp/derivation/MixedContentRestriction.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/SimpleTypeRestriction.xsd b/src/test/resources/xbean/scomp/derivation/SimpleTypeRestriction.xsd new file mode 100644 index 0000000..17df368 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/SimpleTypeRestriction.xsd @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/derivation/facets/DateTimePattern.xsd b/src/test/resources/xbean/scomp/derivation/facets/DateTimePattern.xsd new file mode 100644 index 0000000..7eca0d1 --- /dev/null +++ b/src/test/resources/xbean/scomp/derivation/facets/DateTimePattern.xsd @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/scomp/derivation/facets/FacetRestriction.xsd b/src/test/resources/xbean/scomp/derivation/facets/FacetRestriction.xsd similarity index 83% rename from test/cases/xbean/scomp/derivation/facets/FacetRestriction.xsd rename to src/test/resources/xbean/scomp/derivation/facets/FacetRestriction.xsd index 1e0ca3f..f9e3ecd 100644 --- a/test/cases/xbean/scomp/derivation/facets/FacetRestriction.xsd +++ b/src/test/resources/xbean/scomp/derivation/facets/FacetRestriction.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/element/Any.xsd b/src/test/resources/xbean/scomp/element/Any.xsd new file mode 100644 index 0000000..bf1fc32 --- /dev/null +++ b/src/test/resources/xbean/scomp/element/Any.xsd @@ -0,0 +1,24 @@ + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/element/GlobalEltDefault.xsd b/src/test/resources/xbean/scomp/element/GlobalEltDefault.xsd new file mode 100644 index 0000000..15b5fb2 --- /dev/null +++ b/src/test/resources/xbean/scomp/element/GlobalEltDefault.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/element/GlobalEltFixed.xsd b/src/test/resources/xbean/scomp/element/GlobalEltFixed.xsd new file mode 100644 index 0000000..6d4069d --- /dev/null +++ b/src/test/resources/xbean/scomp/element/GlobalEltFixed.xsd @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/src/test/resources/xbean/scomp/element/GlobalEltNillable.xsd b/src/test/resources/xbean/scomp/element/GlobalEltNillable.xsd new file mode 100644 index 0000000..41fb271 --- /dev/null +++ b/src/test/resources/xbean/scomp/element/GlobalEltNillable.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/element/LocalEltMinMaxOccurs.xsd b/src/test/resources/xbean/scomp/element/LocalEltMinMaxOccurs.xsd new file mode 100644 index 0000000..0679aa2 --- /dev/null +++ b/src/test/resources/xbean/scomp/element/LocalEltMinMaxOccurs.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/element/NamedModelGroup.xsd b/src/test/resources/xbean/scomp/element/NamedModelGroup.xsd new file mode 100644 index 0000000..246f973 --- /dev/null +++ b/src/test/resources/xbean/scomp/element/NamedModelGroup.xsd @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/element/NillTest.xsd b/src/test/resources/xbean/scomp/element/NillTest.xsd new file mode 100644 index 0000000..8cb1330 --- /dev/null +++ b/src/test/resources/xbean/scomp/element/NillTest.xsd @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/scomp/idConstraints/Constraint.xsd b/src/test/resources/xbean/scomp/idConstraints/Constraint.xsd similarity index 82% rename from test/cases/xbean/scomp/idConstraints/Constraint.xsd rename to src/test/resources/xbean/scomp/idConstraints/Constraint.xsd index b1bf893..05da1c1 100644 --- a/test/cases/xbean/scomp/idConstraints/Constraint.xsd +++ b/src/test/resources/xbean/scomp/idConstraints/Constraint.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/namespace/AttributeWC.xsd b/src/test/resources/xbean/scomp/namespace/AttributeWC.xsd similarity index 83% rename from test/cases/xbean/scomp/namespace/AttributeWC.xsd rename to src/test/resources/xbean/scomp/namespace/AttributeWC.xsd index 80fbc9b..7c7e1a8 100644 --- a/test/cases/xbean/scomp/namespace/AttributeWC.xsd +++ b/src/test/resources/xbean/scomp/namespace/AttributeWC.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/namespace/ElementWC.xsd b/src/test/resources/xbean/scomp/namespace/ElementWC.xsd similarity index 85% rename from test/cases/xbean/scomp/namespace/ElementWC.xsd rename to src/test/resources/xbean/scomp/namespace/ElementWC.xsd index 0ecd327..630d482 100644 --- a/test/cases/xbean/scomp/namespace/ElementWC.xsd +++ b/src/test/resources/xbean/scomp/namespace/ElementWC.xsd @@ -1,8 +1,23 @@ + + + diff --git a/src/test/resources/xbean/scomp/namespace/NoNamespace.xsd b/src/test/resources/xbean/scomp/namespace/NoNamespace.xsd new file mode 100644 index 0000000..44edfbb --- /dev/null +++ b/src/test/resources/xbean/scomp/namespace/NoNamespace.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/AttrRedefineSub.xs b/src/test/resources/xbean/scomp/redefine/AttrRedefineSub.xs new file mode 100644 index 0000000..b0fdb05 --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/AttrRedefineSub.xs @@ -0,0 +1,27 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/AttrRedefineSuper.xsd b/src/test/resources/xbean/scomp/redefine/AttrRedefineSuper.xsd new file mode 100644 index 0000000..632aae0 --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/AttrRedefineSuper.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/BaseAttrGroup.xs b/src/test/resources/xbean/scomp/redefine/BaseAttrGroup.xs new file mode 100644 index 0000000..6b83db3 --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/BaseAttrGroup.xs @@ -0,0 +1,25 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/BaseModelGroup.xs b/src/test/resources/xbean/scomp/redefine/BaseModelGroup.xs new file mode 100644 index 0000000..861d4be --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/BaseModelGroup.xs @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/redefine/BaseSimple.xs b/src/test/resources/xbean/scomp/redefine/BaseSimple.xs new file mode 100644 index 0000000..02cdefe --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/BaseSimple.xs @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/scomp/redefine/ModelGroupSub.xs b/src/test/resources/xbean/scomp/redefine/ModelGroupSub.xs new file mode 100644 index 0000000..38e46de --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/ModelGroupSub.xs @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/ModelGroupSuper.xsd b/src/test/resources/xbean/scomp/redefine/ModelGroupSuper.xsd new file mode 100644 index 0000000..fae7328 --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/ModelGroupSuper.xsd @@ -0,0 +1,38 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/SimpleRedefined.xsd b/src/test/resources/xbean/scomp/redefine/SimpleRedefined.xsd new file mode 100644 index 0000000..f4254cf --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/SimpleRedefined.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/TypeBase.xs b/src/test/resources/xbean/scomp/redefine/TypeBase.xs new file mode 100644 index 0000000..3c50f57 --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/TypeBase.xs @@ -0,0 +1,20 @@ + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/redefine/TypeRedefine.xsd b/src/test/resources/xbean/scomp/redefine/TypeRedefine.xsd new file mode 100644 index 0000000..058bfca --- /dev/null +++ b/src/test/resources/xbean/scomp/redefine/TypeRedefine.xsd @@ -0,0 +1,20 @@ + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/substGroup/Abstract.xsd b/src/test/resources/xbean/scomp/substGroup/Abstract.xsd new file mode 100644 index 0000000..6c23fe3 --- /dev/null +++ b/src/test/resources/xbean/scomp/substGroup/Abstract.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/substGroup/Block.xsd b/src/test/resources/xbean/scomp/substGroup/Block.xsd new file mode 100644 index 0000000..3b9f935 --- /dev/null +++ b/src/test/resources/xbean/scomp/substGroup/Block.xsd @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/scomp/substGroup/Deep.xsd b/src/test/resources/xbean/scomp/substGroup/Deep.xsd similarity index 81% rename from test/cases/xbean/scomp/substGroup/Deep.xsd rename to src/test/resources/xbean/scomp/substGroup/Deep.xsd index 0cb073b..dc5cd21 100644 --- a/test/cases/xbean/scomp/substGroup/Deep.xsd +++ b/src/test/resources/xbean/scomp/substGroup/Deep.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/substGroup/UserAbstract.xsd b/src/test/resources/xbean/scomp/substGroup/UserAbstract.xsd new file mode 100644 index 0000000..997707f --- /dev/null +++ b/src/test/resources/xbean/scomp/substGroup/UserAbstract.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/scomp/substGroup/UserReported.xsd b/src/test/resources/xbean/scomp/substGroup/UserReported.xsd new file mode 100644 index 0000000..b5602cf --- /dev/null +++ b/src/test/resources/xbean/scomp/substGroup/UserReported.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/scomp/substGroup/Wide.xsd b/src/test/resources/xbean/scomp/substGroup/Wide.xsd similarity index 80% rename from test/cases/xbean/scomp/substGroup/Wide.xsd rename to src/test/resources/xbean/scomp/substGroup/Wide.xsd index 2af3720..04399ad 100644 --- a/test/cases/xbean/scomp/substGroup/Wide.xsd +++ b/src/test/resources/xbean/scomp/substGroup/Wide.xsd @@ -1,3 +1,18 @@ + + + + + + diff --git a/src/test/resources/xbean/simple/dumb/dumb.xsd b/src/test/resources/xbean/simple/dumb/dumb.xsd new file mode 100755 index 0000000..0245181 --- /dev/null +++ b/src/test/resources/xbean/simple/dumb/dumb.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/simple/dumb/sub/bar.xsd b/src/test/resources/xbean/simple/dumb/sub/bar.xsd new file mode 100755 index 0000000..5c354e6 --- /dev/null +++ b/src/test/resources/xbean/simple/dumb/sub/bar.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + diff --git a/src/test/resources/xbean/simple/dupSchemaElements/DupElementsInSameSchema.xsd b/src/test/resources/xbean/simple/dupSchemaElements/DupElementsInSameSchema.xsd new file mode 100755 index 0000000..5e188e0 --- /dev/null +++ b/src/test/resources/xbean/simple/dupSchemaElements/DupElementsInSameSchema.xsd @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/simple/dupSchemaElements/custOrdUdf.xsd b/src/test/resources/xbean/simple/dupSchemaElements/custOrdUdf.xsd new file mode 100755 index 0000000..66ccd91 --- /dev/null +++ b/src/test/resources/xbean/simple/dupSchemaElements/custOrdUdf.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/simple/dupSchemaElements/viewtarget.xsd b/src/test/resources/xbean/simple/dupSchemaElements/viewtarget.xsd new file mode 100755 index 0000000..91e7c07 --- /dev/null +++ b/src/test/resources/xbean/simple/dupSchemaElements/viewtarget.xsd @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/simple/person/person.xml b/src/test/resources/xbean/simple/person/person.xml new file mode 100755 index 0000000..e23306c --- /dev/null +++ b/src/test/resources/xbean/simple/person/person.xml @@ -0,0 +1,31 @@ + + + + + Howdy + 436 + 123 + 1998-08-26Z + 44 + 933 + 2000-08-06-08:00 + 454749515457595A4A + VGhpcyBzdHJpbmcgaXMgYmFzZTY0QmluYXJ5IGVuY29kZWQh + diff --git a/src/test/resources/xbean/simple/person/person.xsd b/src/test/resources/xbean/simple/person/person.xsd new file mode 100755 index 0000000..533551e --- /dev/null +++ b/src/test/resources/xbean/simple/person/person.xsd @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/simple/person/simplec.xsd b/src/test/resources/xbean/simple/person/simplec.xsd new file mode 100755 index 0000000..bda4d7c --- /dev/null +++ b/src/test/resources/xbean/simple/person/simplec.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base.xml b/src/test/resources/xbean/tools/inst2xsd/options/base.xml new file mode 100644 index 0000000..f2aba9c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base.xml @@ -0,0 +1,20 @@ + + + + + abc + 123 + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base0.xsd new file mode 100644 index 0000000..3a53b46 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base0.xsd @@ -0,0 +1,27 @@ + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_rd0.xsd new file mode 100644 index 0000000..44c449c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_rd0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_rd_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_rd_eN0.xsd new file mode 100644 index 0000000..44c449c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_rd_eN0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_rd_scs0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_rd_scs0.xsd new file mode 100644 index 0000000..0d3e68c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_rd_scs0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_rd_scs_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_rd_scs_eN0.xsd new file mode 100644 index 0000000..0d3e68c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_rd_scs_eN0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_ss0.xsd new file mode 100644 index 0000000..c477c63 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_ss0.xsd @@ -0,0 +1,44 @@ + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_ss_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_ss_eN0.xsd new file mode 100644 index 0000000..c477c63 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_ss_eN0.xsd @@ -0,0 +1,44 @@ + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_ss_scs0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_ss_scs0.xsd new file mode 100644 index 0000000..fb58bae --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_ss_scs0.xsd @@ -0,0 +1,44 @@ + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_ss_scs_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_ss_scs_eN0.xsd new file mode 100644 index 0000000..fb58bae --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_ss_scs_eN0.xsd @@ -0,0 +1,44 @@ + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_vb0.xsd new file mode 100644 index 0000000..135684a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_vb0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_vb_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_vb_eN0.xsd new file mode 100644 index 0000000..135684a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_vb_eN0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_vb_scs0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_vb_scs0.xsd new file mode 100644 index 0000000..38bf440 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_vb_scs0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/options/base_vb_scs_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/options/base_vb_scs_eN0.xsd new file mode 100644 index 0000000..38bf440 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/options/base_vb_scs_eN0.xsd @@ -0,0 +1,41 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/choice.xml b/src/test/resources/xbean/tools/inst2xsd/schema/choice.xml new file mode 100644 index 0000000..7f1521b --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/choice.xml @@ -0,0 +1,21 @@ + + + + + 123 + abc123 + abc123abc + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/choice_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/choice_ss0.xsd new file mode 100644 index 0000000..d56bc35 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/choice_ss0.xsd @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice.xml new file mode 100644 index 0000000..5de8f2f --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice.xml @@ -0,0 +1,22 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss0.xsd new file mode 100644 index 0000000..5b0df16 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss0.xsd @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss1.xsd new file mode 100644 index 0000000..577b4e3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss1.xsd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice.xml new file mode 100644 index 0000000..543055f --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss0.xsd new file mode 100644 index 0000000..0c344cf --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss0.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss1.xsd new file mode 100644 index 0000000..e204b5c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss1.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss2.xsd new file mode 100644 index 0000000..608c076 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss2.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss3.xsd new file mode 100644 index 0000000..c59befc --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss3.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/schema0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/schema0.xsd new file mode 100644 index 0000000..3a86c46 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/schema0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/schema1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/schema1.xsd new file mode 100644 index 0000000..7594d83 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/schema1.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice.xml new file mode 100644 index 0000000..9be0492 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice.xml @@ -0,0 +1,22 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_rd0.xsd new file mode 100644 index 0000000..7395100 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_rd0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_ss0.xsd new file mode 100644 index 0000000..644547a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_ss0.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_vb0.xsd new file mode 100644 index 0000000..2aac62d --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_vb0.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum.xml new file mode 100644 index 0000000..eeecce8 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum.xml @@ -0,0 +1,26 @@ + + + + + + baz:foo + + + foo:baz + + + foo:bar + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd0.xsd new file mode 100644 index 0000000..ebf77a4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd1.xsd new file mode 100644 index 0000000..7a9dd89 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd2.xsd new file mode 100644 index 0000000..877e130 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd2.xsd @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum0.xsd new file mode 100644 index 0000000..ebf77a4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum1.xsd new file mode 100644 index 0000000..7a9dd89 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum2.xsd new file mode 100644 index 0000000..877e130 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum2.xsd @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss0.xsd new file mode 100644 index 0000000..ebf77a4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss1.xsd new file mode 100644 index 0000000..7a9dd89 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss2.xsd new file mode 100644 index 0000000..e1fc651 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss2.xsd @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum0.xsd new file mode 100644 index 0000000..ebf77a4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum1.xsd new file mode 100644 index 0000000..9c1cda3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum1.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum2.xsd new file mode 100644 index 0000000..290ad34 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum2.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb0.xsd new file mode 100644 index 0000000..ebf77a4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb1.xsd new file mode 100644 index 0000000..7a9dd89 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb2.xsd new file mode 100644 index 0000000..0254de0 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb2.xsd @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum0.xsd new file mode 100644 index 0000000..ebf77a4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum1.xsd new file mode 100644 index 0000000..7a9dd89 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum2.xsd new file mode 100644 index 0000000..0254de0 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum2.xsd @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum.xml new file mode 100644 index 0000000..ced46a2 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum.xml @@ -0,0 +1,27 @@ + + + + + + foo:baz + + + baz:foo + + + baz:foo + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_rd0.xsd new file mode 100644 index 0000000..da17f80 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_rd0.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_ss0.xsd new file mode 100644 index 0000000..65d62af --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_ss0.xsd @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_vb0.xsd new file mode 100644 index 0000000..4d8ad54 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum2_vb0.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName.xml new file mode 100644 index 0000000..f7734ae --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName.xml @@ -0,0 +1,27 @@ + + + + + + foo:baz + + + baz:foo + + + baz:foo this should not be a qName + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_eN0.xsd new file mode 100644 index 0000000..ac6b8b5 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_eN0.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_enum0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_enum0.xsd new file mode 100644 index 0000000..9afce84 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_enum0.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_eN0.xsd new file mode 100644 index 0000000..4d8ad54 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_eN0.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_scs_enum0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_scs_enum0.xsd new file mode 100644 index 0000000..32dd641 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_scs_enum0.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd0.xsd new file mode 100644 index 0000000..3a86c46 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd1.xsd new file mode 100644 index 0000000..7594d83 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd1.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss0.xsd new file mode 100644 index 0000000..3a86c46 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss1.xsd new file mode 100644 index 0000000..73ca885 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss1.xsd @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb0.xsd new file mode 100644 index 0000000..3a86c46 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb1.xsd new file mode 100644 index 0000000..67d4b95 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb1.xsd @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattribute.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattribute.xml new file mode 100644 index 0000000..168f9b6 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/global/globalattribute.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd0.xsd new file mode 100644 index 0000000..8007e6d --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd1.xsd new file mode 100644 index 0000000..928724a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd1.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd2.xsd new file mode 100644 index 0000000..d45a72f --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd2.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd3.xsd new file mode 100644 index 0000000..80e3d44 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd3.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss0.xsd new file mode 100644 index 0000000..8007e6d --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss1.xsd new file mode 100644 index 0000000..928724a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss1.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss2.xsd new file mode 100644 index 0000000..a3ca8ec --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss2.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss3.xsd new file mode 100644 index 0000000..80e3d44 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss3.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb0.xsd new file mode 100644 index 0000000..5b17cdc --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb0.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb1.xsd new file mode 100644 index 0000000..b30588d --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb1.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb2.xsd new file mode 100644 index 0000000..5874178 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb2.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb3.xsd new file mode 100644 index 0000000..f66af06 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb3.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedNSArray.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedNSArray.xml new file mode 100644 index 0000000..c16d2d9 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedNSArray.xml @@ -0,0 +1,27 @@ + + + + + a + b + c + + b + c + + notB + notC + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice.xml b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice.xml new file mode 100644 index 0000000..d7f921c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice.xml @@ -0,0 +1,22 @@ + + + + + 123 + abc123 + abc123abc + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd0.xsd new file mode 100644 index 0000000..48f6072 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd1.xsd similarity index 81% rename from test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd1.xsd index cedc4d6..ac1e130 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN0.xsd new file mode 100644 index 0000000..48f6072 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN1.xsd similarity index 81% rename from test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN1.xsd index cedc4d6..ac1e130 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN0.xsd new file mode 100644 index 0000000..48f6072 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN1.xsd similarity index 81% rename from test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN1.xsd index cedc4d6..ac1e130 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/oops0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/oops0.xsd new file mode 100644 index 0000000..48f6072 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/oops0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/oops1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/oops1.xsd similarity index 81% rename from test/cases/xbean/tools/inst2xsd/schema/complex/sample/oops1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/oops1.xsd index cedc4d6..ac1e130 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/oops1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/complex/sample/oops1.xsd @@ -1,4 +1,18 @@ + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog.xml similarity index 87% rename from test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog.xml rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog.xml index 0ce758b..2d74ff8 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog.xml +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog.xml @@ -1,5 +1,18 @@ - - + + + Empire Burlesque diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_rd0.xsd new file mode 100644 index 0000000..4bb3073 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_rd0.xsd @@ -0,0 +1,59 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_ss0.xsd new file mode 100644 index 0000000..caabd27 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_ss0.xsd @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_vb0.xsd new file mode 100644 index 0000000..91018a3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cd_catalog_vb0.xsd @@ -0,0 +1,58 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog.xml new file mode 100644 index 0000000..073b909 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog.xml @@ -0,0 +1,41 @@ + + + + + + Empire Burlesque + Bob Dylan + USA + Columbia + 10.90 + 1985 + + + Empire Burlesque + Bob Dylan + USA + Columbia + 10.90 + 1985 + + + Empire Burlesque + Bob Dylan + USA + Columbia + 10.90 + 1985 + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_rd0.xsd new file mode 100644 index 0000000..520e085 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_rd0.xsd @@ -0,0 +1,50 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_ss0.xsd new file mode 100644 index 0000000..d559ed5 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_ss0.xsd @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_vb0.xsd new file mode 100644 index 0000000..4602f82 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/cdcatalog_vb0.xsd @@ -0,0 +1,49 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/component.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component.xml new file mode 100644 index 0000000..88ca4f5 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component.xml @@ -0,0 +1,32 @@ + + + + + + + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_rd0.xsd new file mode 100644 index 0000000..49a02f5 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_rd0.xsd @@ -0,0 +1,58 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_ss0.xsd new file mode 100644 index 0000000..2dfcb41 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_ss0.xsd @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_vb0.xsd new file mode 100644 index 0000000..eea88d9 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/component_vb0.xsd @@ -0,0 +1,56 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example.xml new file mode 100644 index 0000000..a0166f8 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example.xml @@ -0,0 +1,33 @@ + + + + + + + + +
      + + + + +
      + + + +
      + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_rd0.xsd new file mode 100644 index 0000000..b5b1d0e --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_rd0.xsd @@ -0,0 +1,83 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_ss0.xsd new file mode 100644 index 0000000..e9cb056 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_ss0.xsd @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_vb0.xsd new file mode 100644 index 0000000..3d0cbbf --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/html_example_vb0.xsd @@ -0,0 +1,77 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po.xml new file mode 100644 index 0000000..69341de --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po.xml @@ -0,0 +1,47 @@ + + + + + + Alice Smith + 123 Maple Street + Mill Valley + CA + 90952 + + + Robert Smith + 8 Oak Avenue + Old Town + PA + 95819 + + Hurry, my lawn is going wild! + + + Lawnmower + 1 + 148.95 + Confirm this is electric + + + Baby Monitor + 1 + 39.98 + 1999-05-21 + + + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_rd_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_rd_eN0.xsd similarity index 83% rename from test/cases/xbean/tools/inst2xsd/schema/examples/po/po_rd_eN0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_rd_eN0.xsd index bf35157..eb87152 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_rd_eN0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_rd_eN0.xsd @@ -1,4 +1,18 @@ + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_ss0.xsd similarity index 87% rename from test/cases/xbean/tools/inst2xsd/schema/examples/po/po_ss0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_ss0.xsd index 1705f76..c078e4b 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_ss0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_ss0.xsd @@ -1,4 +1,18 @@ + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_ss_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_ss_eN0.xsd similarity index 82% rename from test/cases/xbean/tools/inst2xsd/schema/examples/po/po_ss_eN0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_ss_eN0.xsd index ff79e59..ea64bc0 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_ss_eN0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_ss_eN0.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb0.xsd new file mode 100644 index 0000000..4985425 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb0.xsd @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_eN0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_eN0.xsd similarity index 82% rename from test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_eN0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_eN0.xsd index 2e6a121..bdeceba 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_eN0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_eN0.xsd @@ -1,4 +1,18 @@ + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs0.xsd similarity index 82% rename from test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs0.xsd index bd0c327..127254a 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs0.xsd @@ -1,4 +1,18 @@ + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs_enum0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs_enum0.xsd similarity index 84% rename from test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs_enum0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs_enum0.xsd index 2d4d7fc..834aa66 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs_enum0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/po/po_vb_scs_enum0.xsd @@ -1,4 +1,18 @@ + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample.xml similarity index 79% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample.xml rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample.xml index 7eedaf8..e4f54b6 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample.xml +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample.xml @@ -1,4 +1,18 @@ - + + + Liftoff News diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_4enum_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_4enum_vb0.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_4enum_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_4enum_vb0.xsd index 104c489..a1ff050 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_4enum_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_4enum_vb0.xsd @@ -1,6 +1,36 @@ + + - + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_neverenum_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_neverenum_vb0.xsd new file mode 100644 index 0000000..42ed529 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_neverenum_vb0.xsd @@ -0,0 +1,64 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_4enum_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_4enum_vb0.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_4enum_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_4enum_vb0.xsd index 5b8509a..368f918 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_4enum_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_4enum_vb0.xsd @@ -1,6 +1,36 @@ + + - + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_neverenum_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_neverenum_vb0.xsd new file mode 100644 index 0000000..1c36afd --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_neverenum_vb0.xsd @@ -0,0 +1,64 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_vb0.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_vb0.xsd index 5b8509a..368f918 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_vb0.xsd @@ -1,6 +1,36 @@ + + - + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_neverenum_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_neverenum_vb0.xsd new file mode 100644 index 0000000..42ed529 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_neverenum_vb0.xsd @@ -0,0 +1,64 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_rd0.xsd similarity index 80% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_rd0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_rd0.xsd index a1c1a55..ccff17d 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_rd0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_rd0.xsd @@ -1,6 +1,35 @@ + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_ss0.xsd similarity index 79% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_ss0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_ss0.xsd index 28cb36e..23e48c7 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_ss0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_ss0.xsd @@ -1,4 +1,18 @@ + + @@ -87,6 +101,21 @@ + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_vb0.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_vb0.xsd index 104c489..a1ff050 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/rss2sample_vb0.xsd @@ -1,6 +1,36 @@ + + - + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091.xml new file mode 100644 index 0000000..c6244bc --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091.xml @@ -0,0 +1,64 @@ + + + + + + WriteTheWeb + http://writetheweb.com + News for web users that write back + en-us + Copyright 2000, WriteTheWeb team. + editor@writetheweb.com + webmaster@writetheweb.com + + WriteTheWeb + http://writetheweb.com/images/mynetscape88.gif + http://writetheweb.com + 88 + 31 + News for web users that write back + + + Giving the world a pluggable Gnutella + http://writetheweb.com/read.php?item=24 + WorldOS is a framework on which to build programs that work like Freenet or Gnutella -allowing distributed applications using peer-to-peer routing. + + + Syndication discussions hot up + http://writetheweb.com/read.php?item=23 + After a period of dormancy, the Syndication mailing list has become active again, with contributions from leaders in traditional media and Web syndication. + + + Personal web server integrates file sharing and messaging + http://writetheweb.com/read.php?item=22 + The Magi Project is an innovative project to create a combined personal web server and messaging system that enables the sharing and synchronization of information across desktop, laptop and palmtop devices. + + + Syndication and Metadata + http://writetheweb.com/read.php?item=21 + RSS is probably the best known metadata format around. RDF is probably one of the least understood. In this essay, published on my O'Reilly Network weblog, I argue that the next generation of RSS should be based on RDF. + + + UK bloggers get organised + http://writetheweb.com/read.php?item=20 + Looks like the weblogs scene is gathering pace beyond the shores of the US. There's now a UK-specific page on weblogs.com, and a mailing list at egroups. + + + Yournamehere.com more important than anything + http://writetheweb.com/read.php?item=19 + Whatever you're publishing on the web, your site name is the most valuable asset you have, according to Carl Steadman. + + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_rd0.xsd similarity index 80% rename from test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_rd0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_rd0.xsd index acac092..3ece938 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_rd0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_rd0.xsd @@ -1,6 +1,35 @@ + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_ss0.xsd similarity index 78% rename from test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_ss0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_ss0.xsd index 2499976..1b3e0e0 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_ss0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_ss0.xsd @@ -1,4 +1,18 @@ + + @@ -83,6 +97,21 @@ + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_vb0.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_vb0.xsd index 0b01555..d046978 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss091_vb0.xsd @@ -1,6 +1,36 @@ + + - + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092.xml similarity index 94% rename from test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092.xml rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092.xml index 5d75c35..a5a2562 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092.xml +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092.xml @@ -1,4 +1,18 @@ - + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_rd0.xsd new file mode 100644 index 0000000..2aecc18 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_rd0.xsd @@ -0,0 +1,93 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_ss0.xsd new file mode 100644 index 0000000..aa0f59a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_ss0.xsd @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_vb0.xsd new file mode 100644 index 0000000..6a35e4c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/sampleRss092_vb0.xsd @@ -0,0 +1,88 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/schema0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/schema0.xsd new file mode 100644 index 0000000..8cf3641 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/schema0.xsd @@ -0,0 +1,75 @@ + + + + + + + RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdot.rdf.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdot.rdf.xml new file mode 100644 index 0000000..b3ccaf8 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdot.rdf.xml @@ -0,0 +1,89 @@ + + + + + + +Slashdot: +http://slashdot.org/ +News for nerds, stuff that matters + + + +Slashdot: +http://images.slashdot.org/topics/topicslashdot.gif +http://slashdot.org/ + + + +Gene Doping: Genetically Engineered Athletes +http://slashdot.org/article.pl?sid=04/08/13/1819223 + + + +Microsoft Windows: A Lower Total Cost of 0wnership +http://slashdot.org/article.pl?sid=04/08/13/1621253 + + + +Speculation About An Apple Tablet +http://slashdot.org/article.pl?sid=04/08/13/1614232 + + + +Student Killed Driving Solar Car +http://slashdot.org/article.pl?sid=04/08/13/1416254 + + + +Digital Radio With Removable Flash Storage +http://slashdot.org/article.pl?sid=04/08/13/1353247 + + + +Nvidia 6600 Series Examined +http://slashdot.org/article.pl?sid=04/08/13/1341237 + + + +Open Source in California Government +http://slashdot.org/article.pl?sid=04/08/13/1317236 + + + +Spam's U.S. Roots +http://slashdot.org/article.pl?sid=04/08/13/132224 + + + +Human-powered Helicopter Fails to Lift Off +http://slashdot.org/article.pl?sid=04/08/13/1225238 + + + +BBC Begins Open-Source Streaming Challenge +http://slashdot.org/article.pl?sid=04/08/13/128249 + + + +Search Slashdot +Search Slashdot stories +query +http://slashdot.org/search.pl + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdot.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdot.xml similarity index 82% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdot.xml rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdot.xml index c98c0e7..1f52be0 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdot.xml +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdot.xml @@ -1,5 +1,19 @@ - + + + + Gene Doping: Genetically Engineered Athletes diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd0.xsd new file mode 100644 index 0000000..e3d6d83 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd0.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd1.xsd similarity index 86% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd1.xsd index 4117c73..cb6a4a0 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss0.xsd new file mode 100644 index 0000000..e3d6d83 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss0.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss1.xsd similarity index 79% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss1.xsd index 6329922..7a67ccf 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb0.xsd new file mode 100644 index 0000000..26362ca --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb0.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb1.xsd similarity index 86% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb1.xsd index b4eea08..92f6487 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_neverenum_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_neverenum_ss0.xsd new file mode 100644 index 0000000..ba3c693 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_neverenum_ss0.xsd @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_rd0.xsd similarity index 82% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_rd0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_rd0.xsd index 026c7a6..22b5948 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_rd0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_rd0.xsd @@ -1,6 +1,35 @@ + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_ss0.xsd similarity index 80% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_ss0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_ss0.xsd index c1cd8e7..53d6a07 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_ss0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_ss0.xsd @@ -1,4 +1,18 @@ + + @@ -114,6 +128,21 @@ + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_vb0.xsd similarity index 80% rename from test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_vb0.xsd index cabbb0f..366b1c6 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/slashdotxml_vb0.xsd @@ -1,6 +1,36 @@ + + - + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews.xml new file mode 100644 index 0000000..6d81044 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews.xml @@ -0,0 +1,39 @@ + + + + + + + Colombia Earthquake + + + + + + + 143 Dead in Colombia Earthquake + + + By Jared Kotler, Associated Press Writer + + + Bogota, Colombia + Monday January 25 1999 7:28 ET + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_rd0.xsd new file mode 100644 index 0000000..3573cd7 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_rd0.xsd @@ -0,0 +1,79 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_ss0.xsd new file mode 100644 index 0000000..7dbb33a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_ss0.xsd @@ -0,0 +1,90 @@ + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_vb0.xsd new file mode 100644 index 0000000..a398fde --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xmlnews_vb0.xsd @@ -0,0 +1,73 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_example.xml b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_example.xml new file mode 100644 index 0000000..77e181b --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_example.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + +
      TitleArtist
      + + + +
      + + +
      +
      \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_rd0.xsd new file mode 100644 index 0000000..be09ba2 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_rd0.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_rd1.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/examples/xsl_rd1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_rd1.xsd index ebd54c5..e05d285 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_rd1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_rd1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_ss0.xsd new file mode 100644 index 0000000..907f1d3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_ss0.xsd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_ss1.xsd new file mode 100644 index 0000000..90cd6b5 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_ss1.xsd @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_vb0.xsd new file mode 100644 index 0000000..70ecdca --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_vb0.xsd @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_vb1.xsd new file mode 100644 index 0000000..0feaa63 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/examples/xsl_vb1.xsd @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS.xml b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS.xml new file mode 100644 index 0000000..6287c6b --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS.xml @@ -0,0 +1,32 @@ + + + + + abc + 123 + + abc + 123 + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_rd0.xsd new file mode 100644 index 0000000..ec63515 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_rd0.xsd @@ -0,0 +1,52 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_ss0.xsd new file mode 100644 index 0000000..2fdf66e --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_ss0.xsd @@ -0,0 +1,47 @@ + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_vb0.xsd new file mode 100644 index 0000000..e90fc50 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_vb0.xsd @@ -0,0 +1,43 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS.xml b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS.xml new file mode 100644 index 0000000..1202939 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS.xml @@ -0,0 +1,25 @@ + + + + + abc + 123 + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd0.xsd new file mode 100644 index 0000000..82b21f3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd1.xsd new file mode 100644 index 0000000..c253357 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd1.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd2.xsd new file mode 100644 index 0000000..86f7563 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd2.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd3.xsd new file mode 100644 index 0000000..d09c6ef --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd3.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss0.xsd new file mode 100644 index 0000000..82b21f3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss1.xsd new file mode 100644 index 0000000..c253357 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss1.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss2.xsd new file mode 100644 index 0000000..86f7563 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss2.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss3.xsd new file mode 100644 index 0000000..59910bb --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss3.xsd @@ -0,0 +1,43 @@ + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb0.xsd new file mode 100644 index 0000000..82b21f3 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb1.xsd new file mode 100644 index 0000000..c253357 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb1.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb2.xsd new file mode 100644 index 0000000..86f7563 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb2.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb3.xsd new file mode 100644 index 0000000..3d1c830 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb3.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS.xml b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS.xml new file mode 100644 index 0000000..93f0066 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS.xml @@ -0,0 +1,27 @@ + + + + + abc + 123 + + bcd + 123 + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd0.xsd new file mode 100644 index 0000000..425e42c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd1.xsd new file mode 100644 index 0000000..23fbc80 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd2.xsd new file mode 100644 index 0000000..86f7563 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd2.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd3.xsd new file mode 100644 index 0000000..f9061ed --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd3.xsd @@ -0,0 +1,45 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss0.xsd new file mode 100644 index 0000000..425e42c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss1.xsd new file mode 100644 index 0000000..23fbc80 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss2.xsd new file mode 100644 index 0000000..2c2d6c9 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss2.xsd @@ -0,0 +1,46 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss3.xsd new file mode 100644 index 0000000..86f7563 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss3.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb0.xsd new file mode 100644 index 0000000..425e42c --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb0.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb1.xsd new file mode 100644 index 0000000..23fbc80 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb2.xsd new file mode 100644 index 0000000..86f7563 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb2.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb3.xsd new file mode 100644 index 0000000..6073cdb --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb3.xsd @@ -0,0 +1,45 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must.xml b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must.xml new file mode 100644 index 0000000..9ba5553 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_rd0.xsd new file mode 100644 index 0000000..cd7e112 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_rd0.xsd @@ -0,0 +1,39 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_rd1.xsd new file mode 100644 index 0000000..88d6736 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_rd1.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_ss0.xsd new file mode 100644 index 0000000..cd7e112 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_ss0.xsd @@ -0,0 +1,39 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_ss1.xsd new file mode 100644 index 0000000..88d6736 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_ss1.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_vb0.xsd new file mode 100644 index 0000000..c57c7f2 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_vb0.xsd @@ -0,0 +1,44 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_vb1.xsd new file mode 100644 index 0000000..af4e7d9 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/must_vb1.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple.xml b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple.xml new file mode 100644 index 0000000..5b1ca02 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple.xml @@ -0,0 +1,21 @@ + + + + + abc + 123 + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_rd0.xsd new file mode 100644 index 0000000..2c600b1 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_rd0.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_ss0.xsd new file mode 100644 index 0000000..8c797eb --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_ss0.xsd @@ -0,0 +1,46 @@ + + + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_vb0.xsd new file mode 100644 index 0000000..ebcb404 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/namespaces/simple_vb0.xsd @@ -0,0 +1,42 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/simpleName.xml b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName.xml new file mode 100644 index 0000000..56053fd --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName.xml @@ -0,0 +1,19 @@ + + + + + Bill + Gates + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_rd0.xsd new file mode 100644 index 0000000..d603516 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_rd0.xsd @@ -0,0 +1,40 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_ss0.xsd new file mode 100644 index 0000000..dacd38a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_ss0.xsd @@ -0,0 +1,42 @@ + + + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_vb0.xsd new file mode 100644 index 0000000..7ac18b7 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/simpleName_vb0.xsd @@ -0,0 +1,40 @@ + + + + + + + Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/CData.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/CData.xml new file mode 100644 index 0000000..d196b47 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/CData.xml @@ -0,0 +1,30 @@ + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_rd0.xsd new file mode 100644 index 0000000..1b4771a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_rd0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_ss0.xsd new file mode 100644 index 0000000..1b4771a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_ss0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_vb0.xsd new file mode 100644 index 0000000..1b4771a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/cdata_vb0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/comments.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments.xml new file mode 100644 index 0000000..5362965 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments.xml @@ -0,0 +1,25 @@ + + + + + + 123456 + + asdsa + 12323 + + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_rd0.xsd new file mode 100644 index 0000000..a30ca37 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_rd0.xsd @@ -0,0 +1,51 @@ + + + + + + + final comment + + + + + + this is a comment 1 + + + + + this is a comment 2 + + + + + this is a comment 4 this is a comment 5 + + + + + this is a comment 6 + + + + + this is a comment 7 this is a comment 8 + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_ss0.xsd new file mode 100644 index 0000000..a158d56 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_ss0.xsd @@ -0,0 +1,56 @@ + + + + + + + + final comment + + + + + + this is a comment 1 + + + + + this is a comment 2 + + + + + this is a comment 4 this is a comment 5 + + + + + this is a comment 6 + + + + + this is a comment 7 this is a comment 8 + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_vb0.xsd new file mode 100644 index 0000000..7959691 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/comments_vb0.xsd @@ -0,0 +1,51 @@ + + + + + + + final comment + + + + + + + this is a comment 1 + + + + + this is a comment 2 + + + + + this is a comment 4 this is a comment 5 + + + + + this is a comment 6 + + + + + this is a comment 7 this is a comment 8 + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice.xml new file mode 100644 index 0000000..d897f21 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice.xml @@ -0,0 +1,25 @@ + + + + + + 123456 + + asdsa + 12323 + + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNrd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNrd0.xsd new file mode 100644 index 0000000..6b32909 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNrd0.xsd @@ -0,0 +1,41 @@ + + + + + + + final comment + + + + + + this is a comment 1 + + + + + this is a comment 4 this is a comment 5 + + + + + this is a comment 7 this is a comment 8 + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNss0.xsd new file mode 100644 index 0000000..ff5f62a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNss0.xsd @@ -0,0 +1,44 @@ + + + + + + + final comment + + + + + + this is a comment 1 + + + + + this is a comment 4 this is a comment 5 + + + + + this is a comment 7 this is a comment 8 + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNvb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNvb0.xsd new file mode 100644 index 0000000..9eab3ba --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_eNvb0.xsd @@ -0,0 +1,41 @@ + + + + + + + final comment + + + + + + + this is a comment 1 + + + + + this is a comment 4 this is a comment 5 + + + + + this is a comment 7 this is a comment 8 + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_vb0.xsd new file mode 100644 index 0000000..bdd0af0 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/commentschoice_vb0.xsd @@ -0,0 +1,47 @@ + + + + + + + final comment + + + + + + + this is a comment 1 + + + + + this is a comment 4 this is a comment 5 + + + + + + + + + + + this is a comment 7 this is a comment 8 + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/innercomment.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/innercomment.xml new file mode 100644 index 0000000..233feaa --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/innercomment.xml @@ -0,0 +1,19 @@ + + + + + 1232323 + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/innercomment_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/innercomment_vb0.xsd new file mode 100644 index 0000000..1b659d6 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/innercomment_vb0.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + this is a comment 6 + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/person.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/person.xml new file mode 100644 index 0000000..f315cc8 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/person.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/person_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/person_vb0.xsd similarity index 78% rename from test/cases/xbean/tools/inst2xsd/schema/types/person_vb0.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/types/person_vb0.xsd index 3a1561e..83d60ba 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/types/person_vb0.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/person_vb0.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/po.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/po.xml new file mode 100644 index 0000000..20d905a --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/po.xml @@ -0,0 +1,37 @@ + + + + + John Smith + + Ola Nordmann +
      Langgt 23
      + 4000 Stavanger + Norway +
      + + Empire Burlesque + Special Edition + 1 + 10.90 + + + Hide your heart + 1 + 9.90 + +
      \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/po_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/po_vb0.xsd new file mode 100644 index 0000000..d69313e --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/po_vb0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/po_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/po_vb1.xsd similarity index 77% rename from test/cases/xbean/tools/inst2xsd/schema/types/po_vb1.xsd rename to src/test/resources/xbean/tools/inst2xsd/schema/types/po_vb1.xsd index d1739b1..457de71 100644 --- a/test/cases/xbean/tools/inst2xsd/schema/types/po_vb1.xsd +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/po_vb1.xsd @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation.xml new file mode 100644 index 0000000..897ff49 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation.xml @@ -0,0 +1,36 @@ + + + + + John + 28 + 59 + + Red + 4 + 2 + + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb0.xsd new file mode 100644 index 0000000..9dc8616 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb0.xsd @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb1.xsd new file mode 100644 index 0000000..ca86d73 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb1.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb2.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb2.xsd new file mode 100644 index 0000000..eb83b80 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb2.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb3.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb3.xsd new file mode 100644 index 0000000..3ba33e4 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/schemaLocation_vb3.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode.xml new file mode 100644 index 0000000..a6bfcfa --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode.xml @@ -0,0 +1,20 @@ + + + + + Jani + Tove + Norwegian: ���. French: ��� + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_rd0.xsd new file mode 100644 index 0000000..4d82c37 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_rd0.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_ss0.xsd new file mode 100644 index 0000000..538fee7 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_ss0.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_vb0.xsd new file mode 100644 index 0000000..9da9845 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/unicode_vb0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil.xml new file mode 100644 index 0000000..124376d --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil.xml @@ -0,0 +1,19 @@ + + + + John + + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_rd0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_rd0.xsd new file mode 100644 index 0000000..894b1ac --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_rd0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_rd1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_rd1.xsd new file mode 100644 index 0000000..62df435 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_rd1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_ss0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_ss0.xsd new file mode 100644 index 0000000..894b1ac --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_ss0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_ss1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_ss1.xsd new file mode 100644 index 0000000..62df435 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_ss1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_vb0.xsd new file mode 100644 index 0000000..e6ef8b8 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_vb0.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_vb1.xsd new file mode 100644 index 0000000..62df435 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsinil_vb1.xsd @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype.xml b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype.xml new file mode 100644 index 0000000..eb0dc21 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype.xml @@ -0,0 +1,22 @@ + + + + John + 59 + manager + diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype_vb0.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype_vb0.xsd new file mode 100644 index 0000000..fd1a56f --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype_vb0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype_vb1.xsd b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype_vb1.xsd new file mode 100644 index 0000000..7b2f511 --- /dev/null +++ b/src/test/resources/xbean/tools/inst2xsd/schema/types/xsitype_vb1.xsd @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/tranxml.tar.bz2 b/src/test/resources/xbean/tranxml.tar.bz2 similarity index 100% rename from test/cases/xbean/tranxml.tar.bz2 rename to src/test/resources/xbean/tranxml.tar.bz2 diff --git a/src/test/resources/xbean/usertype/averageCase/po.xsd b/src/test/resources/xbean/usertype/averageCase/po.xsd new file mode 100644 index 0000000..295a4f9 --- /dev/null +++ b/src/test/resources/xbean/usertype/averageCase/po.xsd @@ -0,0 +1,76 @@ + + + + + + + Purchase order schema for Example.com. + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/usertype/averageCase/po.xsdconfig b/src/test/resources/xbean/usertype/averageCase/po.xsdconfig similarity index 99% rename from test/cases/xbean/usertype/averageCase/po.xsdconfig rename to src/test/resources/xbean/usertype/averageCase/po.xsdconfig index 1f0a355..8c61e16 100644 --- a/test/cases/xbean/usertype/averageCase/po.xsdconfig +++ b/src/test/resources/xbean/usertype/averageCase/po.xsdconfig @@ -11,6 +11,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> + diff --git a/src/test/resources/xbean/usertype/multipleItems/company.xsd b/src/test/resources/xbean/usertype/multipleItems/company.xsd new file mode 100644 index 0000000..dd51e26 --- /dev/null +++ b/src/test/resources/xbean/usertype/multipleItems/company.xsd @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/usertype/multipleItems/company.xsdconfig b/src/test/resources/xbean/usertype/multipleItems/company.xsdconfig similarity index 99% rename from test/cases/xbean/usertype/multipleItems/company.xsdconfig rename to src/test/resources/xbean/usertype/multipleItems/company.xsdconfig index 62d0b53..dacc953 100644 --- a/test/cases/xbean/usertype/multipleItems/company.xsdconfig +++ b/src/test/resources/xbean/usertype/multipleItems/company.xsdconfig @@ -11,6 +11,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> + diff --git a/src/test/resources/xbean/xmlcursor/CR196679.xsd b/src/test/resources/xbean/xmlcursor/CR196679.xsd new file mode 100644 index 0000000..1d7bd07 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/CR196679.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/CarLocationMessage.xml b/src/test/resources/xbean/xmlcursor/CarLocationMessage.xml new file mode 100755 index 0000000..6102fca --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/CarLocationMessage.xml @@ -0,0 +1,53 @@ + + + + + FLEETNAME + CSXT + + + GATX + 123456 + L + + 2001-03-23 + + + P + + Q12345 + + DALLAS + TX + + CSXT + + + DALLAS + TX + + + + + DALLAS + TX + + 2001-03-23 + + P + + Y + + diff --git a/src/test/resources/xbean/xmlcursor/Employees.xml b/src/test/resources/xbean/xmlcursor/Employees.xml new file mode 100755 index 0000000..8ed5c35 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/Employees.xml @@ -0,0 +1,71 @@ + + + + + + Fred Jones + + 900 Aurora Ave. + Seattle + WA + 98115 + + + 2011 152nd Avenue NE + Redmond + WA + 98052 + + (425)555-5665 + (206)555-5555 + (206)555-4321 + + + Sally Smith + + 1430 Oak Place + Salem + OR + 97125 + + + 765 Main St. + Kaiser + OR + 97103 + + (503)555-3856 + (503)555-6951 + (503)555-5152 + + + Gladys Kravitz + + 1313 Mockingbird Lane + Seattle + WA + 98115 + + + 2011 152nd Avenue NE + Redmond + WA + 98052 + + (425)555-6897 + (206)555-6594 + (206)555-7894 + + diff --git a/test/cases/xbean/xmlcursor/TranXML_License.txt b/src/test/resources/xbean/xmlcursor/TranXML_License.txt similarity index 100% rename from test/cases/xbean/xmlcursor/TranXML_License.txt rename to src/test/resources/xbean/xmlcursor/TranXML_License.txt diff --git a/test/cases/xbean/xmlcursor/W3C_Software_Licence.txt b/src/test/resources/xbean/xmlcursor/W3C_Software_Licence.txt similarity index 100% rename from test/cases/xbean/xmlcursor/W3C_Software_Licence.txt rename to src/test/resources/xbean/xmlcursor/W3C_Software_Licence.txt diff --git a/src/test/resources/xbean/xmlcursor/XQueryInput.xml b/src/test/resources/xbean/xmlcursor/XQueryInput.xml new file mode 100644 index 0000000..0b91d56 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/XQueryInput.xml @@ -0,0 +1,29 @@ + + + + + Bob + 1000 + + + Beth + 1001 + + + NotBob + 1000 + + + diff --git a/src/test/resources/xbean/xmlcursor/XQueryInput.xsd b/src/test/resources/xbean/xmlcursor/XQueryInput.xsd new file mode 100644 index 0000000..d83b849 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/XQueryInput.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlcursor/doc.xml b/src/test/resources/xbean/xmlcursor/doc.xml new file mode 100755 index 0000000..c79e0aa --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/doc.xml @@ -0,0 +1,23 @@ + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/location.xsd b/src/test/resources/xbean/xmlcursor/location.xsd new file mode 100755 index 0000000..a11f963 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/location.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlcursor/person.xsd b/src/test/resources/xbean/xmlcursor/person.xsd new file mode 100755 index 0000000..7c1e1f4 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/person.xsd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/po.xml b/src/test/resources/xbean/xmlcursor/po.xml new file mode 100755 index 0000000..f55d52d --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/po.xml @@ -0,0 +1,46 @@ + + + + + + Alice Smith + 123 Maple Street + Mill Valley + CA + 90952 + + + Robert Smith + 8 Oak Avenue + Old Town + PA + 95819 + + Hurry, my lawn is going wild! + + + Lawnmower + 1 + 148.95 + Confirm this is electric + + + Baby Monitor + 1 + 39.98 + 1999-05-21 + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlcursor/po.xsd b/src/test/resources/xbean/xmlcursor/po.xsd new file mode 100755 index 0000000..8bf75ee --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/po.xsd @@ -0,0 +1,76 @@ + + + + + + + Purchase order schema for Example.com. + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/xmlcursor/xpath/LICENSE.txt b/src/test/resources/xbean/xmlcursor/xpath/LICENSE.txt similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/LICENSE.txt rename to src/test/resources/xbean/xmlcursor/xpath/LICENSE.txt diff --git a/src/test/resources/xbean/xmlcursor/xpath/cdcatalog.xml b/src/test/resources/xbean/xmlcursor/xpath/cdcatalog.xml new file mode 100755 index 0000000..1c6d53c --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/cdcatalog.xml @@ -0,0 +1,225 @@ + + + + + + Empire Burlesque + Bob Dylan + USA + Columbia + 10.90 + 1985 + + + Hide your heart + Bonnie Tyler + UK + CBS Records + 9.90 + 1988 + + + Greatest Hits + Dolly Parton + USA + RCA + 9.90 + 1982 + + + Still got the blues + Gary Moore + UK + Virgin records + 10.20 + 1990 + + + Eros + Eros Ramazzotti + EU + BMG + 9.90 + 1997 + + + One night only + Bee Gees + UK + Polydor + 10.90 + 1998 + + + Sylvias Mother + Dr.Hook + UK + CBS + 8.10 + 1973 + + + Maggie May + Rod Stewart + UK + Pickwick + 8.50 + 1990 + + + Romanza + Andrea Bocelli + EU + Polydor + 10.80 + 1996 + + + When a man loves a woman + Percy Sledge + USA + Atlantic + 8.70 + 1987 + + + Black angel + Savage Rose + EU + Mega + 10.90 + 1995 + + + 1999 Grammy Nominees + Many + USA + Grammy + 10.20 + 1999 + + + For the good times + Kenny Rogers + UK + Mucik Master + 8.70 + 1995 + + + Big Willie style + Will Smith + USA + Columbia + 9.90 + 1997 + + + Tupelo Honey + Van Morrison + UK + Polydor + 8.20 + 1971 + + + Soulsville + Jorn Hoel + Norway + WEA + 7.90 + 1996 + + + The very best of + Cat Stevens + UK + Island + 8.90 + 1990 + + + Stop + Sam Brown + UK + A and M + 8.90 + 1988 + + + Bridge of Spies + T`Pau + UK + Siren + 7.90 + 1987 + + + Private Dancer + Tina Turner + UK + Capitol + 8.90 + 1983 + + + Midt om natten + Kim Larsen + EU + Medley + 7.80 + 1983 + + + Pavarotti Gala Concert + Luciano Pavarotti + UK + DECCA + 9.90 + 1991 + + + The dock of the bay + Otis Redding + USA + Atlantic + 7.90 + 1987 + + + Picture book + Simply Red + EU + Elektra + 7.20 + 1985 + + + Red + The Communards + UK + London + 7.80 + 1987 + + + Unchain my heart + Joe Cocker + USA + EMI + 8.20 + 1987 + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/axis.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/axis.xml new file mode 100755 index 0000000..dee4665 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/axis.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/basic.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/basic.xml new file mode 100755 index 0000000..883f2e2 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/basic.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/basicupdate.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/basicupdate.xml new file mode 100755 index 0000000..9da9567 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/basicupdate.xml @@ -0,0 +1,60 @@ + + + + + + + Goudse kaas + Rond + + + + + + + More cheese! + + + + + Even more cheese! + + + + + No sausages today + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/contents.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/contents.xml similarity index 76% rename from test/cases/xbean/xmlcursor/xpath/jaxen/contents.xml rename to src/test/resources/xbean/xmlcursor/xpath/jaxen/contents.xml index 35e3ac7..b8e5afd 100755 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/contents.xml +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/contents.xml @@ -1,16 +1,30 @@ - + + + - - + ora:category="Java" +> diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/defaultNamespace.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/defaultNamespace.xml new file mode 100755 index 0000000..c20400b --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/defaultNamespace.xml @@ -0,0 +1,20 @@ + + + + + + Hello + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/evaluate.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/evaluate.xml new file mode 100755 index 0000000..8a73057 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/evaluate.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + brown + + + moderate + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/fibo.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/fibo.xml new file mode 100755 index 0000000..f69057d --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/fibo.xml @@ -0,0 +1,43 @@ + + + + + 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + 144 + 233 + 377 + 610 + 987 + 1597 + 2584 + 4181 + 6765 + 10946 + 17711 + 28657 + 46368 + 75025 + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/id.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/id.xml new file mode 100755 index 0000000..8870494 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/id.xml @@ -0,0 +1,34 @@ + + + + + + + + + +]> + + + + baz + gouda + baz + cheddar + baz + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/lang.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/lang.xml new file mode 100755 index 0000000..8b932c1 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/lang.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/message.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/message.xml new file mode 100755 index 0000000..66cf4b6 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/message.xml @@ -0,0 +1,41 @@ + + + + +
      + lookupformservice + 9 + stammdaten + new +
      + + + + + iteminfo + ELE + + + parentinfo + Pruefgebiete + + + id + 1 + + + + +
      diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/moreover.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/moreover.xml similarity index 94% rename from test/cases/xbean/xmlcursor/xpath/jaxen/moreover.xml rename to src/test/resources/xbean/xmlcursor/xpath/jaxen/moreover.xml index 38d4c4f..eac971a 100755 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/moreover.xml +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/moreover.xml @@ -1,5 +1,19 @@ - - + + + +
      http://c.moreover.com/click/here.pl?x13563273 e-Commerce Operators Present Version 1.0 of the XML Standard diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/much_ado.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/much_ado.xml similarity index 99% rename from test/cases/xbean/xmlcursor/xpath/jaxen/much_ado.xml rename to src/test/resources/xbean/xmlcursor/xpath/jaxen/much_ado.xml index f008fad..d822ba6 100755 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/much_ado.xml +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/much_ado.xml @@ -1,4 +1,18 @@ - + + + Much Ado about Nothing diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/namespaces.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/namespaces.xml new file mode 100755 index 0000000..4b46b9e --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/namespaces.xml @@ -0,0 +1,32 @@ + + + + + + Hello + + + + Hey + + + + Hey2 + + + + Hey3 + + diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/nitf.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/nitf.xml similarity index 82% rename from test/cases/xbean/xmlcursor/xpath/jaxen/nitf.xml rename to src/test/resources/xbean/xmlcursor/xpath/jaxen/nitf.xml index 269d99e..74c2c8a 100755 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/nitf.xml +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/nitf.xml @@ -1,4 +1,18 @@ + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/numbers.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/numbers.xml new file mode 100755 index 0000000..a5bff4c --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/numbers.xml @@ -0,0 +1,31 @@ + + + + + + 3 + 24 + 55 + 11 + 2 + -3 + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/pi.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/pi.xml new file mode 100755 index 0000000..74cae57 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/pi.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/pi2.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/pi2.xml new file mode 100755 index 0000000..ae7f912 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/pi2.xml @@ -0,0 +1,20 @@ + + + + + foo + + bar + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/simple.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/simple.xml new file mode 100755 index 0000000..38fb89e --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/simple.xml @@ -0,0 +1,22 @@ + + + + + a + b + + d + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/testNamespaces.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/testNamespaces.xml new file mode 100755 index 0000000..701e8b4 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/testNamespaces.xml @@ -0,0 +1,36 @@ + + + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/text.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/text.xml new file mode 100755 index 0000000..17c23d6 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/text.xml @@ -0,0 +1,24 @@ + + + + + + baz + + baz + + baz + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/underscore.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/underscore.xml new file mode 100755 index 0000000..530ee1b --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/underscore.xml @@ -0,0 +1,20 @@ + + + + + 1 + <_b>2 + + diff --git a/src/test/resources/xbean/xmlcursor/xpath/jaxen/web.xml b/src/test/resources/xbean/xmlcursor/xpath/jaxen/web.xml new file mode 100755 index 0000000..23f3eb0 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xpath/jaxen/web.xml @@ -0,0 +1,56 @@ + + + + + + snoop + SnoopServlet + + + file + ViewFile + + initial + + 1000 + + + The initial value for the counter + + + + + + mv + + + *.wm + + + + + + + + manager + + + director + + + president + + + diff --git a/test/cases/xbean/xmlcursor/xpath/zvon1.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon1.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon1.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon1.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon10.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon10.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon10.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon10.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon11.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon11.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon11.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon11.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon12.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon12.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon12.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon12.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon13.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon13.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon13.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon13.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon14.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon14.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon14.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon14.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon15.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon15.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon15.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon15.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon16.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon16.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon16.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon16.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon17.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon17.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon17.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon17.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon18.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon18.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon18.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon18.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon19.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon19.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon19.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon19.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon2.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon2.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon2.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon2.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon20.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon20.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon20.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon20.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon21.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon21.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon21.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon21.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon22.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon22.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon22.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon22.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon3.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon3.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon3.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon3.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon4.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon4.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon4.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon4.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon5.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon5.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon5.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon5.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon6.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon6.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon6.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon6.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon7.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon7.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon7.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon7.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon8.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon8.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon8.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon8.xml diff --git a/test/cases/xbean/xmlcursor/xpath/zvon9.xml b/src/test/resources/xbean/xmlcursor/xpath/zvon9.xml similarity index 100% rename from test/cases/xbean/xmlcursor/xpath/zvon9.xml rename to src/test/resources/xbean/xmlcursor/xpath/zvon9.xml diff --git a/src/test/resources/xbean/xmlcursor/xquery/2DocJoin.xq b/src/test/resources/xbean/xmlcursor/xquery/2DocJoin.xq new file mode 100644 index 0000000..60dd66c --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xquery/2DocJoin.xq @@ -0,0 +1,13 @@ +(: Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. :) diff --git a/src/test/resources/xbean/xmlcursor/xquery/Constructor.xq b/src/test/resources/xbean/xmlcursor/xquery/Constructor.xq new file mode 100644 index 0000000..b885941 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xquery/Constructor.xq @@ -0,0 +1,19 @@ +(: Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. :) + +for $e in .//employee +return + + { $e/name } + diff --git a/src/test/resources/xbean/xmlcursor/xquery/Join.xq b/src/test/resources/xbean/xmlcursor/xquery/Join.xq new file mode 100644 index 0000000..d721971 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xquery/Join.xq @@ -0,0 +1,24 @@ +(: Copyright 2004 The Apache Software Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. :) + +for $a in .//employee +return + { $a/ssn }, + { $a/name }, + { + for $b in .//employee + where $b/ssn=$a/ssn and $a/name !=$b/name + return $b/name + } + diff --git a/test/cases/xbean/xmlcursor/xquery/NIST/XQcatalog.xsd b/src/test/resources/xbean/xmlcursor/xquery/NIST/XQcatalog.xsd similarity index 85% rename from test/cases/xbean/xmlcursor/xquery/NIST/XQcatalog.xsd rename to src/test/resources/xbean/xmlcursor/xquery/NIST/XQcatalog.xsd index 1b02bcd..2e2882c 100644 --- a/test/cases/xbean/xmlcursor/xquery/NIST/XQcatalog.xsd +++ b/src/test/resources/xbean/xmlcursor/xquery/NIST/XQcatalog.xsd @@ -1,8 +1,22 @@ + + - @@ -19,9 +33,9 @@ - + - + @@ -34,7 +48,7 @@ - + @@ -42,7 +56,7 @@ - + @@ -52,7 +66,7 @@ - + @@ -76,13 +90,13 @@ - + - - + + @@ -94,7 +108,7 @@ - + @@ -141,9 +155,9 @@ - + - + @@ -170,7 +184,7 @@ - + @@ -185,7 +199,7 @@ - + @@ -201,7 +215,7 @@ - + @@ -217,7 +231,7 @@ - + @@ -235,8 +249,8 @@ - - + + @@ -247,7 +261,7 @@ - + diff --git a/src/test/resources/xbean/xmlcursor/xquery/bookstore.xml b/src/test/resources/xbean/xmlcursor/xquery/bookstore.xml new file mode 100644 index 0000000..5c5ddb5 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xquery/bookstore.xml @@ -0,0 +1,50 @@ + + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + + XQuery Kick Start + James McGovern + Per Bothner + Kurt Cagle + James Linn + Vaidyanathan Nagarajan + 2003 + 49.99 + + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + diff --git a/src/test/resources/xbean/xmlcursor/xquery/employees.xml b/src/test/resources/xbean/xmlcursor/xquery/employees.xml new file mode 100644 index 0000000..439e015 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xquery/employees.xml @@ -0,0 +1,71 @@ + + + + + + Fred Jones +
      + 900 Aurora Ave. + Seattle + WA + 98115 +
      +
      + 2011 152nd Avenue NE + Redmond + WA + 98052 +
      + (425)555-5665 + (206)555-5555 + (206)555-4321 +
      + + Sally Smith +
      + 1430 Oak Place + Salem + OR + 97125 +
      +
      + 765 Main St. + Keizer + OR + 97303 +
      + (503)555-3856 + (503)555-6951 + (503)555-5152 +
      + + Gladys Kravitz +
      + 1313 Mockingbird Lane + Seattle + WA + 98115 +
      +
      + 2011 152nd Avenue NE + Redmond + WA + 98052 +
      + (425)555-6897 + (206)555-6594 + (206)555-7894 +
      +
      diff --git a/test/cases/xbean/xmlcursor/xquery/xmlQuery.zip b/src/test/resources/xbean/xmlcursor/xquery/xmlQuery.zip similarity index 100% rename from test/cases/xbean/xmlcursor/xquery/xmlQuery.zip rename to src/test/resources/xbean/xmlcursor/xquery/xmlQuery.zip diff --git a/src/test/resources/xbean/xmlcursor/xstypes/default.xsd b/src/test/resources/xbean/xmlcursor/xstypes/default.xsd new file mode 100755 index 0000000..a0bddd0 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xstypes/default.xsd @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xstypes/person.xsd b/src/test/resources/xbean/xmlcursor/xstypes/person.xsd new file mode 100755 index 0000000..9cf29f9 --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xstypes/person.xsd @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xstypes/setters.xsd b/src/test/resources/xbean/xmlcursor/xstypes/setters.xsd new file mode 100755 index 0000000..a53812a --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xstypes/setters.xsd @@ -0,0 +1,21 @@ + + + + + + diff --git a/src/test/resources/xbean/xmlcursor/xstypes/xstypes.xml b/src/test/resources/xbean/xmlcursor/xstypes/xstypes.xml new file mode 100755 index 0000000..af23c0b --- /dev/null +++ b/src/test/resources/xbean/xmlcursor/xstypes/xstypes.xml @@ -0,0 +1,38 @@ + + + + + Howdy + 436 + 123 + 1998-08-26Z + 44 + 933 + 2000-08-06-08:00 + 454749515457595A4A + VGhpcyBzdHJpbmcgaXMgYmFzZTY0QmluYXJ5IGVuY29kZWQh + http://3space.org/space%20space/ + openuri_org_localname + GIF + diff --git a/src/test/resources/xbean/xmlobject/CR192525.xsd b/src/test/resources/xbean/xmlobject/CR192525.xsd new file mode 100644 index 0000000..fa76956 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/CR192525.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/SelectAttribute-Doc.xml b/src/test/resources/xbean/xmlobject/SelectAttribute-Doc.xml new file mode 100755 index 0000000..f9817ab --- /dev/null +++ b/src/test/resources/xbean/xmlobject/SelectAttribute-Doc.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/SelectAttribute.xsd b/src/test/resources/xbean/xmlobject/SelectAttribute.xsd new file mode 100755 index 0000000..172f554 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/SelectAttribute.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/SelectChildren-AnyTypeDoc.xml b/src/test/resources/xbean/xmlobject/SelectChildren-AnyTypeDoc.xml new file mode 100755 index 0000000..fd492a9 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/SelectChildren-AnyTypeDoc.xml @@ -0,0 +1,29 @@ + + + + + Simple String + + ABC Namespace + DEF Namespace + XYX Namespace + + ABC-SameElem + DEF-SameElem + XYZ-SameElem + diff --git a/src/test/resources/xbean/xmlobject/SelectChildren-NormalDoc.xml b/src/test/resources/xbean/xmlobject/SelectChildren-NormalDoc.xml new file mode 100755 index 0000000..17005cf --- /dev/null +++ b/src/test/resources/xbean/xmlobject/SelectChildren-NormalDoc.xml @@ -0,0 +1,22 @@ + + + + + first element + second element + 10 + 11 + 12 + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/SelectChildren.xsd b/src/test/resources/xbean/xmlobject/SelectChildren.xsd new file mode 100755 index 0000000..b935c7a --- /dev/null +++ b/src/test/resources/xbean/xmlobject/SelectChildren.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/SimpleXmlObject.java.txt b/src/test/resources/xbean/xmlobject/SimpleXmlObject.java.txt new file mode 100755 index 0000000..0dcce79 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/SimpleXmlObject.java.txt @@ -0,0 +1,82 @@ +/* Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import javax.xml.namespace.QName; +import org.apache.xmlbeans.*; + +import dumbNS.RootDocument; + + +/** + * Test Class that extends the abstract base class FilterXmlObject + * The only method that needs to be implemented is underlyingXmlObject(); + * + * @author: Raju Subramanian. + */ + +public class SimpleXmlObject + extends FilterXmlObject +{ + + /** + * The underlying XmlObject to which all calls will be delegated + */ + private transient XmlObject _under; + + /** + * Default constructor that creates a XmlObject from the instance + * xbean/simple/dumb/dumb.xml + */ + public SimpleXmlObject() + throws Exception + { + try { + String xml = ""+ + ""; + RootDocument rootDoc = (RootDocument)XmlObject.Factory.parse(xml); + // Set the underlying XmlObject + _under = (XmlObject) rootDoc; + + } catch (Exception e) + { + throw new Exception("Error creating XmlObject: " + e); + } + } + + /** + * The underlyingXmlObject() implementation + */ + public XmlObject underlyingXmlObject() + { + return _under; + } + + public XmlObject substitute(javax.xml.namespace.QName qName,org.apache.xmlbeans.SchemaType schemaType){ + return underlyingXmlObject().substitute(qName, schemaType); + } + + public void dump(){ + System.out.println( _under.xmlText()); + } + + /** + * + */ + public static void main (String args[]) throws Exception + { + SimpleXmlObject test = new SimpleXmlObject(); + System.out.println(test.xmlText()); + } +} \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/Test.xsd b/src/test/resources/xbean/xmlobject/Test.xsd new file mode 100755 index 0000000..cb51e74 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/Test.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/Test36510.xsd b/src/test/resources/xbean/xmlobject/Test36510.xsd new file mode 100755 index 0000000..c2a5fb6 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/Test36510.xsd @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/Test40907.xsd b/src/test/resources/xbean/xmlobject/Test40907.xsd new file mode 100755 index 0000000..132d415 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/Test40907.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/defaults.xsd b/src/test/resources/xbean/xmlobject/defaults.xsd new file mode 100755 index 0000000..943b534 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/defaults.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/easypo.xsd b/src/test/resources/xbean/xmlobject/easypo.xsd new file mode 100755 index 0000000..d4fcb11 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/easypo.xsd @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/xmlobject/easypo.xsdconfig b/src/test/resources/xbean/xmlobject/easypo.xsdconfig similarity index 99% rename from test/cases/xbean/xmlobject/easypo.xsdconfig rename to src/test/resources/xbean/xmlobject/easypo.xsdconfig index b6ffadd..bde00d3 100755 --- a/test/cases/xbean/xmlobject/easypo.xsdconfig +++ b/src/test/resources/xbean/xmlobject/easypo.xsdconfig @@ -11,6 +11,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> + diff --git a/src/test/resources/xbean/xmlobject/easypo1.xml b/src/test/resources/xbean/xmlobject/easypo1.xml new file mode 100755 index 0000000..de2b587 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/easypo1.xml @@ -0,0 +1,44 @@ + + + + + + David Bau + Gladwyne, PA + + 2002-09-30T14:16:00-05:00 + + Burnham's Celestial Handbook, Vol 1 + 5 + 21.79 + 2 + + + Burnham's Celestial Handbook, Vol 2 + 5 + 19.89 + 2 + + + Burnham's Celestial Handbook, Vol 3 + 5 + 19.89 + 1 + + + UPS + 0.74 + + diff --git a/src/test/resources/xbean/xmlobject/enumtest.xml b/src/test/resources/xbean/xmlobject/enumtest.xml new file mode 100755 index 0000000..1ff1c00 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/enumtest.xml @@ -0,0 +1,21 @@ + + + + + all + few + most + none + diff --git a/test/cases/xbean/xmlobject/enumtest.xsd b/src/test/resources/xbean/xmlobject/enumtest.xsd similarity index 75% rename from test/cases/xbean/xmlobject/enumtest.xsd rename to src/test/resources/xbean/xmlobject/enumtest.xsd index b75ae57..dcb856f 100755 --- a/test/cases/xbean/xmlobject/enumtest.xsd +++ b/src/test/resources/xbean/xmlobject/enumtest.xsd @@ -1,3 +1,18 @@ + + + + + + + + + com.enumtest + + + diff --git a/src/test/resources/xbean/xmlobject/inttest.xsd b/src/test/resources/xbean/xmlobject/inttest.xsd new file mode 100755 index 0000000..db0abd9 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/inttest.xsd @@ -0,0 +1,62 @@ + + + + + + + + + Degrees of Latitude + See USMTF field latitude.degrees.17.1 + TBD + + + + + + + + + + + + + Degrees of Longitude + See USMTF field longitude.degrees.18.1 + TBD + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/japanese/LICENSE.txt b/src/test/resources/xbean/xmlobject/japanese/LICENSE.txt similarity index 100% rename from test/cases/xbean/xmlobject/japanese/LICENSE.txt rename to src/test/resources/xbean/xmlobject/japanese/LICENSE.txt diff --git a/test/cases/xbean/xmlobject/japanese/japanese.xml b/src/test/resources/xbean/xmlobject/japanese/japanese.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/japanese.xml rename to src/test/resources/xbean/xmlobject/japanese/japanese.xml diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-euc-jp.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-euc-jp.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/pr-xml-euc-jp.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-euc-jp.xml diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-euc-jp1.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-euc-jp1.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/pr-xml-euc-jp1.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-euc-jp1.xml diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-iso-2022-jp.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-iso-2022-jp.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/pr-xml-iso-2022-jp.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-iso-2022-jp.xml diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-little-endian.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-little-endian.xml similarity index 99% rename from test/cases/xbean/xmlobject/japanese/pr-xml-little-endian.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-little-endian.xml index 5cbf147..fbc0982 100644 Binary files a/test/cases/xbean/xmlobject/japanese/pr-xml-little-endian.xml and b/src/test/resources/xbean/xmlobject/japanese/pr-xml-little-endian.xml differ diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-shift_jis.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-shift_jis.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/pr-xml-shift_jis.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-shift_jis.xml diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-utf-16.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-utf-16.xml similarity index 99% rename from test/cases/xbean/xmlobject/japanese/pr-xml-utf-16.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-utf-16.xml index 0c985a2..1fec57b 100644 Binary files a/test/cases/xbean/xmlobject/japanese/pr-xml-utf-16.xml and b/src/test/resources/xbean/xmlobject/japanese/pr-xml-utf-16.xml differ diff --git a/test/cases/xbean/xmlobject/japanese/pr-xml-utf-8.xml b/src/test/resources/xbean/xmlobject/japanese/pr-xml-utf-8.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/pr-xml-utf-8.xml rename to src/test/resources/xbean/xmlobject/japanese/pr-xml-utf-8.xml diff --git a/test/cases/xbean/xmlobject/japanese/prefix_test.xml b/src/test/resources/xbean/xmlobject/japanese/prefix_test.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/prefix_test.xml rename to src/test/resources/xbean/xmlobject/japanese/prefix_test.xml diff --git a/test/cases/xbean/xmlobject/japanese/readme.html b/src/test/resources/xbean/xmlobject/japanese/readme.html similarity index 100% rename from test/cases/xbean/xmlobject/japanese/readme.html rename to src/test/resources/xbean/xmlobject/japanese/readme.html diff --git a/test/cases/xbean/xmlobject/japanese/spec.dtd b/src/test/resources/xbean/xmlobject/japanese/spec.dtd similarity index 100% rename from test/cases/xbean/xmlobject/japanese/spec.dtd rename to src/test/resources/xbean/xmlobject/japanese/spec.dtd diff --git a/test/cases/xbean/xmlobject/japanese/weekly-euc-jp.dtd b/src/test/resources/xbean/xmlobject/japanese/weekly-euc-jp.dtd similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-euc-jp.dtd rename to src/test/resources/xbean/xmlobject/japanese/weekly-euc-jp.dtd diff --git a/test/cases/xbean/xmlobject/japanese/weekly-euc-jp.xml b/src/test/resources/xbean/xmlobject/japanese/weekly-euc-jp.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-euc-jp.xml rename to src/test/resources/xbean/xmlobject/japanese/weekly-euc-jp.xml diff --git a/test/cases/xbean/xmlobject/japanese/weekly-iso-2022-jp.dtd b/src/test/resources/xbean/xmlobject/japanese/weekly-iso-2022-jp.dtd similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-iso-2022-jp.dtd rename to src/test/resources/xbean/xmlobject/japanese/weekly-iso-2022-jp.dtd diff --git a/test/cases/xbean/xmlobject/japanese/weekly-iso-2022-jp.xml b/src/test/resources/xbean/xmlobject/japanese/weekly-iso-2022-jp.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-iso-2022-jp.xml rename to src/test/resources/xbean/xmlobject/japanese/weekly-iso-2022-jp.xml diff --git a/test/cases/xbean/xmlobject/japanese/weekly-little-endian.xml b/src/test/resources/xbean/xmlobject/japanese/weekly-little-endian.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-little-endian.xml rename to src/test/resources/xbean/xmlobject/japanese/weekly-little-endian.xml diff --git a/test/cases/xbean/xmlobject/japanese/weekly-shift_jis.dtd b/src/test/resources/xbean/xmlobject/japanese/weekly-shift_jis.dtd similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-shift_jis.dtd rename to src/test/resources/xbean/xmlobject/japanese/weekly-shift_jis.dtd diff --git a/test/cases/xbean/xmlobject/japanese/weekly-shift_jis.xml b/src/test/resources/xbean/xmlobject/japanese/weekly-shift_jis.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-shift_jis.xml rename to src/test/resources/xbean/xmlobject/japanese/weekly-shift_jis.xml diff --git a/test/cases/xbean/xmlobject/japanese/weekly-utf-16.dtd b/src/test/resources/xbean/xmlobject/japanese/weekly-utf-16.dtd similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-utf-16.dtd rename to src/test/resources/xbean/xmlobject/japanese/weekly-utf-16.dtd diff --git a/test/cases/xbean/xmlobject/japanese/weekly-utf-16.xml b/src/test/resources/xbean/xmlobject/japanese/weekly-utf-16.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-utf-16.xml rename to src/test/resources/xbean/xmlobject/japanese/weekly-utf-16.xml diff --git a/test/cases/xbean/xmlobject/japanese/weekly-utf-8.dtd b/src/test/resources/xbean/xmlobject/japanese/weekly-utf-8.dtd similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-utf-8.dtd rename to src/test/resources/xbean/xmlobject/japanese/weekly-utf-8.dtd diff --git a/test/cases/xbean/xmlobject/japanese/weekly-utf-8.xml b/src/test/resources/xbean/xmlobject/japanese/weekly-utf-8.xml similarity index 100% rename from test/cases/xbean/xmlobject/japanese/weekly-utf-8.xml rename to src/test/resources/xbean/xmlobject/japanese/weekly-utf-8.xml diff --git a/src/test/resources/xbean/xmlobject/listandunion.xsd b/src/test/resources/xbean/xmlobject/listandunion.xsd new file mode 100755 index 0000000..76417ba --- /dev/null +++ b/src/test/resources/xbean/xmlobject/listandunion.xsd @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/nameworld.xml b/src/test/resources/xbean/xmlobject/nameworld.xml new file mode 100755 index 0000000..c8007bd --- /dev/null +++ b/src/test/resources/xbean/xmlobject/nameworld.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/nameworld.xsd b/src/test/resources/xbean/xmlobject/nameworld.xsd new file mode 100755 index 0000000..e5379e2 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/nameworld.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/numerals.xsd b/src/test/resources/xbean/xmlobject/numerals.xsd new file mode 100755 index 0000000..47c8427 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/numerals.xsd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/person.xml b/src/test/resources/xbean/xmlobject/person.xml new file mode 100755 index 0000000..5f724f0 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/person.xml @@ -0,0 +1,38 @@ + + + + + Howdy + 436 + 123 + 1998-08-26Z + 44 + 933 + 2000-08-06-08:00 + 454749515457595A4A + VGhpcyBzdHJpbmcgaXMgYmFzZTY0QmluYXJ5IGVuY29kZWQh + http://3space.org/space%20space/ + openuri_org_localname + GIF + diff --git a/src/test/resources/xbean/xmlobject/person.xsd b/src/test/resources/xbean/xmlobject/person.xsd new file mode 100755 index 0000000..9cf29f9 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/person.xsd @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/redefine1.xsd b/src/test/resources/xbean/xmlobject/redefine1.xsd new file mode 100755 index 0000000..6303358 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/redefine1.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/xbean/xmlobject/redefine2.xsd b/src/test/resources/xbean/xmlobject/redefine2.xsd new file mode 100755 index 0000000..629e722 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/redefine2.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/selectChldAttTest.xsd b/src/test/resources/xbean/xmlobject/selectChldAttTest.xsd similarity index 76% rename from test/cases/xbean/xmlobject/selectChldAttTest.xsd rename to src/test/resources/xbean/xmlobject/selectChldAttTest.xsd index dd2401c..5a282ac 100755 --- a/test/cases/xbean/xmlobject/selectChldAttTest.xsd +++ b/src/test/resources/xbean/xmlobject/selectChldAttTest.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + Comment describing your root element + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/store/ConsolidateTest.xml b/src/test/resources/xbean/xmlobject/store/ConsolidateTest.xml new file mode 100755 index 0000000..0e0a3e4 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/store/ConsolidateTest.xml @@ -0,0 +1,53 @@ + + + + + + Fred Jones +
      + 900 Aurora Ave. + Seattle + WA + 98109 +
      +
      + 2011 152nd Avenue NE + Redmond + WA + 98052 +
      + (425)641-9385 + (206)441-1695 + (206)714-2515 +
      + + Sally Smith +
      + 1430 Oak Place + Salem + OR + 97125 +
      +
      + 765 Main St. + Kaiser + OR + 97103 +
      + (503)264-3856 + (503)416-6951 + (503)214-5152 +
      +
      diff --git a/test/cases/xbean/xmlobject/store/XML.xsd b/src/test/resources/xbean/xmlobject/store/XML.xsd similarity index 100% rename from test/cases/xbean/xmlobject/store/XML.xsd rename to src/test/resources/xbean/xmlobject/store/XML.xsd diff --git a/test/cases/xbean/xmlobject/store/XMLSchema.xsd b/src/test/resources/xbean/xmlobject/store/XMLSchema.xsd similarity index 100% rename from test/cases/xbean/xmlobject/store/XMLSchema.xsd rename to src/test/resources/xbean/xmlobject/store/XMLSchema.xsd diff --git a/src/test/resources/xbean/xmlobject/store/easypo1.xml b/src/test/resources/xbean/xmlobject/store/easypo1.xml new file mode 100755 index 0000000..de2b587 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/store/easypo1.xml @@ -0,0 +1,44 @@ + + + + + + David Bau + Gladwyne, PA + + 2002-09-30T14:16:00-05:00 + + Burnham's Celestial Handbook, Vol 1 + 5 + 21.79 + 2 + + + Burnham's Celestial Handbook, Vol 2 + 5 + 19.89 + 2 + + + Burnham's Celestial Handbook, Vol 3 + 5 + 19.89 + 1 + + + UPS + 0.74 + + diff --git a/src/test/resources/xbean/xmlobject/store/erictest.xml b/src/test/resources/xbean/xmlobject/store/erictest.xml new file mode 100755 index 0000000..9d78715 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/store/erictest.xml @@ -0,0 +1,16 @@ + + + +12 \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/store/people.xml b/src/test/resources/xbean/xmlobject/store/people.xml similarity index 78% rename from test/cases/xbean/xmlobject/store/people.xml rename to src/test/resources/xbean/xmlobject/store/people.xml index 64d1044..caf89cf 100755 --- a/test/cases/xbean/xmlobject/store/people.xml +++ b/src/test/resources/xbean/xmlobject/store/people.xml @@ -1,3 +1,18 @@ + + + diff --git a/src/test/resources/xbean/xmlobject/store/small.xml b/src/test/resources/xbean/xmlobject/store/small.xml new file mode 100755 index 0000000..5c8a601 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/store/small.xml @@ -0,0 +1,26 @@ + + + + + + diff --git a/src/test/resources/xbean/xmlobject/store/test.xml b/src/test/resources/xbean/xmlobject/store/test.xml new file mode 100755 index 0000000..a1653a5 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/store/test.xml @@ -0,0 +1,16 @@ + + + +ab \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/substgroup.xsd b/src/test/resources/xbean/xmlobject/substgroup.xsd similarity index 80% rename from test/cases/xbean/xmlobject/substgroup.xsd rename to src/test/resources/xbean/xmlobject/substgroup.xsd index bf3a884..61f0a25 100755 --- a/test/cases/xbean/xmlobject/substgroup.xsd +++ b/src/test/resources/xbean/xmlobject/substgroup.xsd @@ -1,4 +1,18 @@ - + + + diff --git a/test/cases/xbean/xmlobject/substgroup2.xsd b/src/test/resources/xbean/xmlobject/substgroup2.xsd similarity index 77% rename from test/cases/xbean/xmlobject/substgroup2.xsd rename to src/test/resources/xbean/xmlobject/substgroup2.xsd index ed9c5e5..6118434 100644 --- a/test/cases/xbean/xmlobject/substgroup2.xsd +++ b/src/test/resources/xbean/xmlobject/substgroup2.xsd @@ -1,3 +1,18 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/version2.xsddonotcompile b/src/test/resources/xbean/xmlobject/version2.xsddonotcompile new file mode 100644 index 0000000..f805154 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/version2.xsddonotcompile @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/xbean/xmlobject/version3.xsd b/src/test/resources/xbean/xmlobject/version3.xsd new file mode 100644 index 0000000..784f4f9 --- /dev/null +++ b/src/test/resources/xbean/xmlobject/version3.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/test/cases/xbean/xmlobject/wsdl.xml b/src/test/resources/xbean/xmlobject/wsdl.xml similarity index 96% rename from test/cases/xbean/xmlobject/wsdl.xml rename to src/test/resources/xbean/xmlobject/wsdl.xml index f498f54..90f509f 100644 --- a/test/cases/xbean/xmlobject/wsdl.xml +++ b/src/test/resources/xbean/xmlobject/wsdl.xml @@ -1,4 +1,18 @@ + + @@ -697,7 +711,7 @@ @@ -742,7 +756,7 @@ - + diff --git a/src/test/resources/xbean/xmltokensource/PrettyPrintNamespaceTest.xsd b/src/test/resources/xbean/xmltokensource/PrettyPrintNamespaceTest.xsd new file mode 100755 index 0000000..f6882ae --- /dev/null +++ b/src/test/resources/xbean/xmltokensource/PrettyPrintNamespaceTest.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java b/src/tools/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java deleted file mode 100644 index 48c7422..0000000 --- a/src/tools/org/apache/xmlbeans/impl/inst2xsd/RussianDollStrategy.java +++ /dev/null @@ -1,831 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.inst2xsd; - -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.common.PrefixResolver; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.XmlWhitespace; -import org.apache.xmlbeans.impl.inst2xsd.util.Attribute; -import org.apache.xmlbeans.impl.inst2xsd.util.Element; -import org.apache.xmlbeans.impl.inst2xsd.util.TypeSystemHolder; -import org.apache.xmlbeans.impl.inst2xsd.util.Type; -import org.apache.xmlbeans.impl.util.XsTypeConverter; -import org.apache.xmlbeans.impl.values.*; - -import javax.xml.namespace.QName; -import java.util.*; - -/** - * @author Cezar Andrei ( cezar.andrei at bea.com ) - * Date: Jul 26, 2004 - */ -public class RussianDollStrategy - implements XsdGenStrategy -{ - static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance"; - - static final QName _xsiNil = new QName( _xsi, "nil", "xsi" ); - static final QName _xsiType = new QName( _xsi, "type", "xsi" ); - - public void processDoc(XmlObject[] instances, Inst2XsdOptions options, TypeSystemHolder typeSystemHolder) - { - for (int i = 0; i < instances.length; i++) - { - XmlObject instance = instances[i]; - XmlCursor xc = instance.newCursor(); - // xc on start doc - - StringBuffer comment = new StringBuffer(); - - while( !xc.isStart() ) - { - xc.toNextToken(); - if( xc.isComment() ) - comment.append(xc.getTextValue()); - else if (xc.isEnddoc()) - return; - } - // xc now on the root element - - Element withElem = processElement(xc, comment.toString(), options, typeSystemHolder); - withElem.setGlobal(true); - - addGlobalElement(withElem, typeSystemHolder, options); - } - } - - protected Element addGlobalElement(Element withElem, TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) - { - assert withElem.isGlobal(); - Element intoElem = typeSystemHolder.getGlobalElement(withElem.getName()); - - if (intoElem==null) - { - typeSystemHolder.addGlobalElement(withElem); - return withElem; - } - else - { - combineTypes(intoElem.getType(), withElem.getType(), options); - combineElementComments(intoElem, withElem); - return intoElem; - } - } - - protected Element processElement(XmlCursor xc, String comment, - Inst2XsdOptions options, TypeSystemHolder typeSystemHolder) - { - assert xc.isStart(); - Element element = new Element(); - element.setName(xc.getName()); - element.setGlobal(false); - - Type elemType = Type.createUnnamedType(Type.SIMPLE_TYPE_SIMPLE_CONTENT); //assume simple, set later - element.setType(elemType); - - StringBuffer textBuff = new StringBuffer(); - StringBuffer commentBuff = new StringBuffer(); - List children = new ArrayList(); - List attributes = new ArrayList(); - - loop: do - { - XmlCursor.TokenType tt = xc.toNextToken(); - switch (tt.intValue()) - { - case XmlCursor.TokenType.INT_ATTR: - // todo check for xsi:type - // ignore xsi:... attributes other than xsi:nil - QName attName = xc.getName(); - if (!_xsiNil.getNamespaceURI().equals(attName.getNamespaceURI())) - attributes.add(processAttribute(xc, options, element.getName().getNamespaceURI(), typeSystemHolder)); - else if (_xsiNil.equals(attName)) - element.setNillable(true); - - break; - - case XmlCursor.TokenType.INT_START: - children.add(processElement(xc, commentBuff.toString(), options, typeSystemHolder)); - commentBuff.delete(0, commentBuff.length()); - break; - - case XmlCursor.TokenType.INT_TEXT: - textBuff.append(xc.getChars()); - break; - - case XmlCursor.TokenType.INT_COMMENT: - commentBuff.append(xc.getTextValue()); - break; - - case XmlCursor.TokenType.INT_NAMESPACE: - // ignore, - // each element and attribute will take care to define itself in the right targetNamespace - break; - - case XmlCursor.TokenType.INT_END: - break loop; - - case XmlCursor.TokenType.INT_PROCINST: - // ignore - break; - - case XmlCursor.TokenType.INT_ENDDOC: - break loop; - - case XmlCursor.TokenType.INT_NONE: - break loop; - - case XmlCursor.TokenType.INT_STARTDOC: - throw new IllegalStateException(); - - default: - throw new IllegalStateException("Unknown TokenType."); - } - } - while( true ); - - String collapsedText = XmlWhitespace.collapse(textBuff.toString(), XmlWhitespace.WS_COLLAPSE); - - String commnetStr = (comment == null ? - ( commentBuff.length() == 0 ? null : commentBuff.toString() ) : - ( commentBuff.length() == 0 ? comment : commentBuff.insert(0, comment).toString()) ); - element.setComment(commnetStr); - - if (children.size()>0) - { - // complex content - if (collapsedText.length()>0) - { - elemType.setContentType(Type.COMPLEX_TYPE_MIXED_CONTENT); - } - else - { - elemType.setContentType(Type.COMPLEX_TYPE_COMPLEX_CONTENT); - } - processElementsInComplexType(elemType, children, element.getName().getNamespaceURI(), typeSystemHolder, options); - processAttributesInComplexType(elemType, attributes); - } - else - { - // simple content - // hack workaround for being able to call xc.getNamespaceForPrefix() - XmlCursor xcForNamespaces = xc.newCursor(); - xcForNamespaces.toParent(); - - if (attributes.size()>0) - { - elemType.setContentType(Type.COMPLEX_TYPE_SIMPLE_CONTENT); - - Type extendedType = Type.createNamedType( - processSimpleContentType(textBuff.toString(), options, xcForNamespaces), Type.SIMPLE_TYPE_SIMPLE_CONTENT); - elemType.setExtensionType(extendedType); - - processAttributesInComplexType(elemType, attributes); - } - else - { - elemType.setContentType(Type.SIMPLE_TYPE_SIMPLE_CONTENT); - elemType.setName(processSimpleContentType(textBuff.toString(), options, xcForNamespaces)); - - // add enumeration value - String enumValue = XmlString.type.getName().equals(elemType.getName()) ? textBuff.toString() : collapsedText; - elemType.addEnumerationValue(enumValue, xcForNamespaces); - } - - xcForNamespaces.dispose(); // end hack - } - - checkIfReferenceToGlobalTypeIsNeeded( element, typeSystemHolder, options); - - return element; - } - - protected void processElementsInComplexType(Type elemType, List children, String parentNamespace, - TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) - { - Map elemNamesToElements = new HashMap(); - Element currentElem = null; - - for (Iterator iterator = children.iterator(); iterator.hasNext();) - { - Element child = (Element) iterator.next(); - - if (currentElem==null) - { // first element in this type - checkIfElementReferenceIsNeeded(child, parentNamespace, typeSystemHolder, options); - elemType.addElement(child); - elemNamesToElements.put(child.getName(), child); - currentElem = child; - continue; - } - - if (currentElem.getName()==child.getName()) - { // same contiguos element - combineTypes(currentElem.getType(), child.getType(), options); // unify types - combineElementComments(currentElem, child); - // minOcc=0 maxOcc=unbounded - currentElem.setMinOccurs(0); - currentElem.setMaxOccurs(Element.UNBOUNDED); - } - else - { - Element sameElem = (Element)elemNamesToElements.get(child.getName()); - if (sameElem==null) - { // new element name - checkIfElementReferenceIsNeeded(child, parentNamespace, typeSystemHolder, options); - elemType.addElement(child); - elemNamesToElements.put(child.getName(), child); - } - else - { //same non contiguos - combineTypes(currentElem.getType(), child.getType(), options); - combineElementComments(currentElem, child); - elemType.setTopParticleForComplexOrMixedContent(Type.PARTICLE_CHOICE_UNBOUNDED); - } - currentElem = child; - } - } - } - - protected void checkIfElementReferenceIsNeeded(Element child, String parentNamespace, - TypeSystemHolder typeSystemHolder, Inst2XsdOptions options) - { - if (!child.getName().getNamespaceURI().equals(parentNamespace)) - { - Element referencedElem = new Element(); - referencedElem.setGlobal(true); - referencedElem.setName(child.getName()); - referencedElem.setType(child.getType()); - - if (child.isNillable()) - { - referencedElem.setNillable(true); - child.setNillable(false); - } - - referencedElem = addGlobalElement(referencedElem, typeSystemHolder, options); - - child.setRef(referencedElem); // clears child's type - } - } - - protected void checkIfReferenceToGlobalTypeIsNeeded(Element elem, TypeSystemHolder typeSystemHolder, - Inst2XsdOptions options) - { - // RussianDollDesign doesn't define global types - } - - protected void processAttributesInComplexType(Type elemType, List attributes) - { - assert elemType.isComplexType(); - for (Iterator iterator = attributes.iterator(); iterator.hasNext();) - { - Attribute att = (Attribute) iterator.next(); - elemType.addAttribute(att); - } - } - - protected Attribute processAttribute(XmlCursor xc, Inst2XsdOptions options, String parentNamespace, - TypeSystemHolder typeSystemHolder) - { - assert xc.isAttr() : "xc not on attribute"; - Attribute attribute = new Attribute(); - QName attName = xc.getName(); - - attribute.setName(attName); - - XmlCursor parent = xc.newCursor(); - parent.toParent(); - - Type simpleContentType = Type.createNamedType( - processSimpleContentType(xc.getTextValue(), options, parent), Type.SIMPLE_TYPE_SIMPLE_CONTENT); - - parent.dispose(); - - attribute.setType(simpleContentType); - - checkIfAttributeReferenceIsNeeded(attribute, parentNamespace, typeSystemHolder); - - return attribute; - } - - protected void checkIfAttributeReferenceIsNeeded(Attribute attribute, String parentNamespace, TypeSystemHolder typeSystemHolder) - { - if (!attribute.getName().getNamespaceURI().equals("") && - !attribute.getName().getNamespaceURI().equals(parentNamespace)) - { - // make attribute be a reference to a top level attribute in a different targetNamespace - Attribute referencedAtt = new Attribute(); - referencedAtt.setGlobal(true); - referencedAtt.setName(attribute.getName()); - referencedAtt.setType(attribute.getType()); - - typeSystemHolder.addGlobalAttribute(referencedAtt); - - attribute.setRef(referencedAtt); - } - } - - protected class SCTValidationContext - implements ValidationContext - { - protected boolean valid = true; - - public boolean isValid() - { - return valid; - } - - public void resetToValid() - { - valid = true; - } - - public void invalid(String message) - { - valid = false; - } - - public void invalid(String code, Object[] args) - { - valid = false; - } - } - - private SCTValidationContext _validationContext = new SCTValidationContext(); - - - // List of precedence for smart simple primitive type determination - // byte, short, int, long, integer, float, double, decimal, - // boolean - // date, dateTime, time, gDuration, - // QName ?, - // anyUri ? - triggered only for http:// or www. constructs, - // list types ? - // string - protected QName processSimpleContentType(String lexicalValue, Inst2XsdOptions options, final XmlCursor xc) - { - // check options and return xsd:string or if smart is enabled, look for a better type - if (options.getSimpleContentTypes()==Inst2XsdOptions.SIMPLE_CONTENT_TYPES_STRING) - return XmlString.type.getName(); - - if (options.getSimpleContentTypes()!=Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART) - throw new IllegalArgumentException("Unknown value for Inst2XsdOptions.getSimpleContentTypes() :" + options.getSimpleContentTypes()); - - // Inst2XsdOptions.SIMPLE_CONTENT_TYPES_SMART case - - - try - { - XsTypeConverter.lexByte(lexicalValue); - return XmlByte.type.getName(); - } - catch (Exception e) {} - - try - { - XsTypeConverter.lexShort(lexicalValue); - return XmlShort.type.getName(); - } - catch (Exception e) {} - - try - { - XsTypeConverter.lexInt(lexicalValue); - return XmlInt.type.getName(); - } - catch (Exception e) {} - - try - { - XsTypeConverter.lexLong(lexicalValue); - return XmlLong.type.getName(); - } - catch (Exception e) {} - - try - { - XsTypeConverter.lexInteger(lexicalValue); - return XmlInteger.type.getName(); - } - catch (Exception e) {} - - try - { - XsTypeConverter.lexFloat(lexicalValue); - return XmlFloat.type.getName(); - } - catch (Exception e) {} - -// // this not needed because it's lexical space is covered by float -// try -// { -// XsTypeConverter.lexDouble(lexicalValue); -// return XmlDouble.type.getName(); -// } -// catch (Exception e) {} -// -// try -// { -// XsTypeConverter.lexDecimal(lexicalValue); -// return XmlDecimal.type.getName(); -// } -// catch (Exception e) {} - - XmlDateImpl.validateLexical(lexicalValue, XmlDate.type, _validationContext); - if (_validationContext.isValid()) - return XmlDate.type.getName(); - _validationContext.resetToValid(); - - XmlDateTimeImpl.validateLexical(lexicalValue, XmlDateTime.type, _validationContext); - if (_validationContext.isValid()) - return XmlDateTime.type.getName(); - _validationContext.resetToValid(); - - XmlTimeImpl.validateLexical(lexicalValue, XmlTime.type, _validationContext); - if (_validationContext.isValid()) - return XmlTime.type.getName(); - _validationContext.resetToValid(); - - XmlDurationImpl.validateLexical(lexicalValue, XmlDuration.type, _validationContext); - if (_validationContext.isValid()) - return XmlDuration.type.getName(); - _validationContext.resetToValid(); - - // check for uri - if (lexicalValue.startsWith("http://") || lexicalValue.startsWith("www.")) - { - XmlAnyUriImpl.validateLexical(lexicalValue, _validationContext); - if (_validationContext.isValid()) - return XmlAnyURI.type.getName(); - _validationContext.resetToValid(); - } - - // check for QName - int idx = lexicalValue.indexOf(':'); - if (idx>=0 && idx==lexicalValue.lastIndexOf(':') && idx+1options.getUseEnumerations()) - { - into.closeEnumeration(); - } - } - } - - protected QName combineToMoreGeneralSimpleType(QName t1, QName t2) - { - if (t1.equals(t2)) - return t1; - - if (t2.equals(XmlShort.type.getName()) && t1.equals(XmlByte.type.getName())) - return t2; - if (t1.equals(XmlShort.type.getName()) && t2.equals(XmlByte.type.getName())) - return t1; - - if (t2.equals(XmlInt.type.getName()) && - (t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) ) - return t2; - if (t1.equals(XmlInt.type.getName()) && - (t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) ) - return t1; - - if (t2.equals(XmlLong.type.getName()) && - (t1.equals(XmlInt.type.getName()) || t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) ) - return t2; - if (t1.equals(XmlLong.type.getName()) && - (t2.equals(XmlInt.type.getName()) || t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) ) - return t1; - - if (t2.equals(XmlInteger.type.getName()) && - (t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) || - t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) ) - return t2; - if (t1.equals(XmlInteger.type.getName()) && - (t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) || - t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) ) - return t1; - - if (t2.equals(XmlFloat.type.getName()) && - (t1.equals(XmlInteger.type.getName()) || - t1.equals(XmlLong.type.getName()) || t1.equals(XmlInt.type.getName()) || - t1.equals(XmlShort.type.getName()) || t1.equals(XmlByte.type.getName())) ) - return t2; - if (t1.equals(XmlFloat.type.getName()) && - (t2.equals(XmlInteger.type.getName()) || - t2.equals(XmlLong.type.getName()) || t2.equals(XmlInt.type.getName()) || - t2.equals(XmlShort.type.getName()) || t2.equals(XmlByte.type.getName())) ) - return t1; - - //double, decimal will never get here since they don't get generated - - //the rest of the combinations are not compatible, so they will combine in xsd:string - return XmlString.type.getName(); - } - - protected void combineAttributesOfTypes(Type into, Type from) - { - // loop through attributes: add fromAtt if they don't exist, combine them if they exist - outterLoop: - for (int i = 0; i < from.getAttributes().size(); i++) - { - Attribute fromAtt = (Attribute)from.getAttributes().get(i); - for (int j = 0; j < into.getAttributes().size(); j++) - { - Attribute intoAtt = (Attribute)into.getAttributes().get(j); - if (intoAtt.getName().equals(fromAtt.getName())) - { - intoAtt.getType().setName( - combineToMoreGeneralSimpleType(intoAtt.getType().getName(), fromAtt.getType().getName())); - continue outterLoop; - } - } - // fromAtt doesn't exist in into type, will add it right now - into.addAttribute(fromAtt); - } - - //optional attributes: if there are atts in into that are not in from, make them optional - outterLoop: - for (int i = 0; i < into.getAttributes().size(); i++) - { - Attribute intoAtt = (Attribute)into.getAttributes().get(i); - for (int j = 0; j < from.getAttributes().size(); j++) - { - Attribute fromAtt = (Attribute)from.getAttributes().get(j); - if (fromAtt.getName().equals(intoAtt.getName())) - { - continue; - } - } - // intoAtt doesn't exist in into type, will add it right now - intoAtt.setOptional(true); - } - } - - protected void combineElementsOfTypes(Type into, Type from, boolean makeElementsOptional, Inst2XsdOptions options) - { - boolean needsUnboundedChoice = false; - - if (into.getTopParticleForComplexOrMixedContent()!=Type.PARTICLE_SEQUENCE || - from.getTopParticleForComplexOrMixedContent()!=Type.PARTICLE_SEQUENCE) - needsUnboundedChoice = true; - - List res = new ArrayList(); - - int fromStartingIndex = 0; - int fromMatchedIndex = -1; - int intoMatchedIndex = -1; - - // for each element in into - for (int i = 0; !needsUnboundedChoice && i < into.getElements().size(); i++) - { - // try to find one with same name in from - Element intoElement = (Element) into.getElements().get(i); - for (int j = fromStartingIndex; j < from.getElements().size(); j++) - { - Element fromElement = (Element) from.getElements().get(j); - if (intoElement.getName().equals(fromElement.getName())) - { - fromMatchedIndex = j; - break; - } - } - - // if not found, it's safe to add this one to result 'res' (as optional) and continue - if ( fromMatchedIndex < fromStartingIndex ) - { - res.add(intoElement); - intoElement.setMinOccurs(0); - continue; - } - - // else try out all from elemens between fromStartingIndex to fromMatchedIndex - // to see if they match one of the into elements - intoMatchingLoop: - for (int j2 = fromStartingIndex; j2 < fromMatchedIndex; j2++) - { - Element fromCandidate = (Element) from.getElements().get(j2); - - for (int i2 = i+1; i2 < into.getElements().size(); i2++) - { - Element intoCandidate = (Element) into.getElements().get(i2); - if (fromCandidate.getName().equals(intoCandidate.getName())) - { - intoMatchedIndex = i2; - break intoMatchingLoop; - } - } - } - - if (intoMatchedIndex0) - { - if (into.getComment()==null) - into.setComment(with.getComment()); - else - into.setComment(into.getComment() + with.getComment()); - } - } -} diff --git a/src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Type.java b/src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Type.java deleted file mode 100644 index b067624..0000000 --- a/src/tools/org/apache/xmlbeans/impl/inst2xsd/util/Type.java +++ /dev/null @@ -1,326 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.xmlbeans.impl.inst2xsd.util; - -import org.apache.xmlbeans.XmlQName; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.impl.common.PrefixResolver; -import org.apache.xmlbeans.impl.values.XmlQNameImpl; - -import javax.xml.namespace.QName; -import java.util.List; -import java.util.ArrayList; - -/** - * @author Cezar Andrei (cezar.andrei at bea.com) Date: Jul 16, 2004 - */ -public class Type -{ - private QName _name; - - private int _kind = SIMPLE_TYPE_SIMPLE_CONTENT; - // _kind value space - public static final int SIMPLE_TYPE_SIMPLE_CONTENT = 1; // ie no atts, no elems, just text - public static final int COMPLEX_TYPE_SIMPLE_CONTENT = 2; // ie atts*, no elems, text* - simple type extension - public static final int COMPLEX_TYPE_COMPLEX_CONTENT = 3; // ie atts*, elems, no text - public static final int COMPLEX_TYPE_MIXED_CONTENT = 4; // ie atts*, elems, text - public static final int COMPLEX_TYPE_EMPTY_CONTENT = 5; // no elems, no text, just atts - - private int _topParticleForComplexOrMixedContent = PARTICLE_SEQUENCE; - // _topParticleForComplexOrMixedContent - public static final int PARTICLE_SEQUENCE = 1; - public static final int PARTICLE_CHOICE_UNBOUNDED = 2; - - private List _elements; // size>0 COMPLEX - private List _attributes; // size>0 COMPLEX - - private Type _extensionType; - private boolean _isGlobal = false; - - private List _enumerationValues; - private boolean _acceptsEnumerationValue = true; - private List _enumerationQNames; // This is a special case where the lexical representation - // is not enough for a value, the QNames need to be remembered - // in case the _extensionType is QName - - protected Type() - {} - - public static Type createNamedType(QName name, int contentType) - { - assert name!=null; - Type type = new Type(); - type.setName(name); - type.setContentType(contentType); - return type; - } - - public static Type createUnnamedType(int contentType) - { - assert contentType==SIMPLE_TYPE_SIMPLE_CONTENT || - contentType==COMPLEX_TYPE_SIMPLE_CONTENT || - contentType==COMPLEX_TYPE_COMPLEX_CONTENT || - contentType==COMPLEX_TYPE_MIXED_CONTENT || - contentType==COMPLEX_TYPE_EMPTY_CONTENT: "Unknown contentType: " + contentType; - Type type = new Type(); - type.setContentType(contentType); - return type; - } - - - public QName getName() - { - return _name; - } - - public void setName(QName name) - { - this._name = name; - } - - /** - * @return - * SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text - * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension - * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text - * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text - * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts - */ - public int getContentType() - { - return _kind; - } - - /** - * @param kind 4 kinds: - * SIMPLE_TYPE_SIMPLE_CONTENT // ie no atts, no elems, just text - * COMPLEX_TYPE_SIMPLE_CONTENT // ie atts*, no elems, text* - simple type extension - * COMPLEX_TYPE_COMPLEX_CONTENT // ie atts*, elems, no text - * COMPLEX_TYPE_MIXED_CONTENT // ie atts*, elems, text - * COMPLEX_TYPE_EMPTY_CONTENT // no elems, no text, just atts - */ - public void setContentType(int kind) - { - this._kind = kind; - } - - public List getElements() - { - ensureElements(); - return _elements; - } - - public void addElement(Element element) - { - ensureElements(); - _elements.add(element); - } - - public void setElements(List elements) - { - ensureElements(); - _elements.clear(); - _elements.addAll(elements); - } - - private void ensureElements() - { - if (_elements==null) - _elements = new ArrayList(); - } - - public List getAttributes() - { - ensureAttributes(); - return _attributes; - } - - public void addAttribute(Attribute attribute) - { - ensureAttributes(); - _attributes.add(attribute); - } - - public Attribute getAttribute(QName name) - { - for (int i = 0; i < _attributes.size(); i++) - { - Attribute attribute = (Attribute) _attributes.get(i); - if (attribute.getName().equals(name)) - return attribute; - } - return null; - } - - private void ensureAttributes() - { - if (_attributes==null) - _attributes = new ArrayList(); - } - - public boolean isComplexType() - { - return (_kind==COMPLEX_TYPE_COMPLEX_CONTENT || - _kind==COMPLEX_TYPE_MIXED_CONTENT|| - _kind==COMPLEX_TYPE_SIMPLE_CONTENT); - } - - public boolean hasSimpleContent() - { - return (_kind==SIMPLE_TYPE_SIMPLE_CONTENT || - _kind==COMPLEX_TYPE_SIMPLE_CONTENT); - } - - /** - * @return PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED - */ - public int getTopParticleForComplexOrMixedContent() - { - return _topParticleForComplexOrMixedContent; - } - - /** - * @param topParticleForComplexOrMixedContent PARTICLE_SEQUENCE or PARTICLE_CHOICE_UNBOUNDED - */ - public void setTopParticleForComplexOrMixedContent(int topParticleForComplexOrMixedContent) - { - this._topParticleForComplexOrMixedContent = topParticleForComplexOrMixedContent; - } - - public boolean isGlobal() - { - return _isGlobal; - } - - public void setGlobal(boolean isGlobal) - { - assert isGlobal && getName()!=null; - _isGlobal = isGlobal; - } - - public Type getExtensionType() - { - return _extensionType; - } - - public void setExtensionType(Type extendedType) - { - assert _kind == COMPLEX_TYPE_SIMPLE_CONTENT : "Extension used only for type which are COMPLEX_TYPE_SIMPLE_CONTENT"; - assert extendedType!=null && extendedType.getName()!=null : "Extended type must be a named type."; - _extensionType = extendedType; - } - - public List getEnumerationValues() - { - ensureEnumerationValues(); - return _enumerationValues; - } - - public List getEnumerationQNames() - { - ensureEnumerationValues(); - return _enumerationQNames; - } - - public void addEnumerationValue(String enumerationValue, final XmlCursor xc) - { - assert _kind==SIMPLE_TYPE_SIMPLE_CONTENT || _kind==COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content"; - ensureEnumerationValues(); - if (_acceptsEnumerationValue && !_enumerationValues.contains(enumerationValue)) - { - _enumerationValues.add(enumerationValue); - if (_name.equals(XmlQName.type.getName())) - { - // check for QName - PrefixResolver prefixResolver = new PrefixResolver() - { - public String getNamespaceForPrefix(String prefix) - { return xc.namespaceForPrefix(prefix); } - }; - - QName qname = XmlQNameImpl.validateLexical(enumerationValue, null, prefixResolver); - - assert qname!=null : "The check for QName should allready have happened."; - _enumerationQNames.add(qname); - } - } - } - - private void ensureEnumerationValues() - { - if (_enumerationValues==null) - { - _enumerationValues = new ArrayList(); - _enumerationQNames = new ArrayList(); - } - } - - public boolean isEnumeration() - { - return _acceptsEnumerationValue && _enumerationValues!=null && _enumerationValues.size()>1; - } - - public boolean isQNameEnumeration() - { - return isEnumeration() && _name.equals(XmlQName.type.getName()) && _enumerationQNames!=null && _enumerationQNames.size()>1; - } - - public void closeEnumeration() - { - _acceptsEnumerationValue=false; - } - - public String toString() - { - return "Type{" + - "_name = " + _name + - ", _extensionType = " + _extensionType + - ", _kind = " + _kind + - ", _elements = " + _elements + - ", _attributes = " + _attributes + - "}"; - } - - public void addAllEnumerationsFrom(Type from) - { - assert _kind==SIMPLE_TYPE_SIMPLE_CONTENT || _kind==COMPLEX_TYPE_SIMPLE_CONTENT : "Enumerations possible only on simple content"; - ensureEnumerationValues(); - - if (_name.equals(XmlQName.type.getName()) && from._name.equals(XmlQName.type.getName())) - { - for (int i = 0; i < from.getEnumerationValues().size(); i++) - { - String enumValue = (String) from.getEnumerationValues().get(i); - QName enumQNameValue = (QName) from.getEnumerationQNames().get(i); - if (_acceptsEnumerationValue && !_enumerationQNames.contains(enumQNameValue)) - { - _enumerationValues.add(enumValue); - _enumerationQNames.add(enumQNameValue); - } - } - } - else - { - for (int i = 0; i < from.getEnumerationValues().size(); i++) - { - String enumValue = (String) from.getEnumerationValues().get(i); - if (_acceptsEnumerationValue && !_enumerationValues.contains(enumValue)) - { - _enumerationValues.add(enumValue); - } - } - } - } -} diff --git a/src/tools/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java b/src/tools/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java deleted file mode 100644 index 210646d..0000000 --- a/src/tools/org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.java +++ /dev/null @@ -1,1189 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.xsd2inst; - -/* - * TODO: -* Comment on enumerations? -* Comment on facets? -* Have a verbose option? -* Have a sample data option, would create valid instance with sample data? -* Add the pattern facet; this is tricky, considering the relationship with length -*/ - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaLocalElement; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.GDurationBuilder; -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDateBuilder; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlInteger; -import org.apache.xmlbeans.XmlDate; -import org.apache.xmlbeans.XmlDateTime; -import org.apache.xmlbeans.XmlTime; -import org.apache.xmlbeans.XmlGYear; -import org.apache.xmlbeans.XmlGYearMonth; -import org.apache.xmlbeans.XmlGMonth; -import org.apache.xmlbeans.XmlGMonthDay; -import org.apache.xmlbeans.XmlGDay; -import org.apache.xmlbeans.XmlDecimal; -import org.apache.xmlbeans.XmlDuration; -import org.apache.xmlbeans.soap.SchemaWSDLArrayType; -import org.apache.xmlbeans.soap.SOAPArrayType; -import org.apache.xmlbeans.impl.util.Base64; -import org.apache.xmlbeans.impl.util.HexBin; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.Random; -import java.util.Set; -import java.util.HashSet; -import java.util.Arrays; - -import javax.xml.namespace.QName; - -public class SampleXmlUtil -{ - private boolean _soapEnc; - private static final int MAX_ELEMENTS = 1000; - private int _nElements; - - private SampleXmlUtil(boolean soapEnc) - { - _soapEnc = soapEnc; - } - - public static String createSampleForType(SchemaType sType) - { - XmlObject object = XmlObject.Factory.newInstance(); - XmlCursor cursor = object.newCursor(); - // Skip the document node - cursor.toNextToken(); - // Using the type and the cursor, call the utility method to get a - // sample XML payload for that Schema element - new SampleXmlUtil(false).createSampleForType(sType, cursor); - // Cursor now contains the sample payload - // Pretty print the result. Note that the cursor is positioned at the - // end of the doc so we use the original xml object that the cursor was - // created upon to do the xmlText() against. - XmlOptions options = new XmlOptions(); - options.put(XmlOptions.SAVE_PRETTY_PRINT); - options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 2); - options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES); - String result = object.xmlText(options); - return result; - } - - Random _picker = new Random(1); - - /** - * Cursor position - * Before: - * ^ - * After: - * ^ - */ - private void createSampleForType(SchemaType stype, XmlCursor xmlc) - { - if (_typeStack.contains( stype )) - return; - - _typeStack.add( stype ); - - try - { - if (stype.isSimpleType() || stype.isURType()) - { - processSimpleType(stype, xmlc); - return; - } - - // complex Type - // ^ - processAttributes(stype, xmlc); - - // ^ - switch (stype.getContentType()) - { - case SchemaType.NOT_COMPLEX_TYPE : - case SchemaType.EMPTY_CONTENT : - // noop - break; - case SchemaType.SIMPLE_CONTENT : - { - processSimpleType(stype, xmlc); - } - break; - case SchemaType.MIXED_CONTENT : - xmlc.insertChars(pick(WORDS) + " "); - if (stype.getContentModel() != null) - { - processParticle(stype.getContentModel(), xmlc, true); - } - xmlc.insertChars(pick(WORDS)); - break; - case SchemaType.ELEMENT_CONTENT : - if (stype.getContentModel() != null) - { - processParticle(stype.getContentModel(), xmlc, false); - } - break; - } - } - finally - { - _typeStack.remove( _typeStack.size() - 1 ); - } - } - - private void processSimpleType(SchemaType stype, XmlCursor xmlc) - { - String sample = sampleDataForSimpleType(stype); - xmlc.insertChars(sample); - } - - private String sampleDataForSimpleType(SchemaType sType) - { - if (XmlObject.type.equals(sType)) - return "anyType"; - - if (XmlAnySimpleType.type.equals(sType)) - return "anySimpleType"; - - if (sType.getSimpleVariety() == SchemaType.LIST) - { - SchemaType itemType = sType.getListItemType(); - StringBuffer sb = new StringBuffer(); - int length = pickLength(sType); - if (length > 0) - sb.append(sampleDataForSimpleType(itemType)); - for (int i = 1; i < length; i += 1) - { - sb.append(' '); - sb.append(sampleDataForSimpleType(itemType)); - } - return sb.toString(); - } - - if (sType.getSimpleVariety() == SchemaType.UNION) - { - SchemaType[] possibleTypes = sType.getUnionConstituentTypes(); - if (possibleTypes.length == 0) - return ""; - return sampleDataForSimpleType(possibleTypes[pick(possibleTypes.length)]); - } - - XmlAnySimpleType[] enumValues = sType.getEnumerationValues(); - if (enumValues != null && enumValues.length > 0) - { - return enumValues[pick(enumValues.length)].getStringValue(); - } - - switch (sType.getPrimitiveType().getBuiltinTypeCode()) - { - default: - case SchemaType.BTC_NOT_BUILTIN: - return ""; - - case SchemaType.BTC_ANY_TYPE: - case SchemaType.BTC_ANY_SIMPLE: - return "anything"; - - case SchemaType.BTC_BOOLEAN: - return pick(2) == 0 ? "true" : "false"; - - case SchemaType.BTC_BASE_64_BINARY: - { - String result = null; - try - { result = new String(Base64.encode(formatToLength(pick(WORDS), sType).getBytes("utf-8"))); } - catch (java.io.UnsupportedEncodingException e) - { /* Can't possibly happen */ } - return result; - } - - case SchemaType.BTC_HEX_BINARY: - return HexBin.encode(formatToLength(pick(WORDS), sType)); - - case SchemaType.BTC_ANY_URI: - return formatToLength("http://www." + pick(DNS1) + "." + pick(DNS2) + "/" + pick(WORDS) + "/" + pick(WORDS), sType); - - case SchemaType.BTC_QNAME: - return formatToLength("qname", sType); - - case SchemaType.BTC_NOTATION: - return formatToLength("notation", sType); - - case SchemaType.BTC_FLOAT: - return "1.5E2"; - case SchemaType.BTC_DOUBLE: - return "1.051732E7"; - case SchemaType.BTC_DECIMAL: - switch (closestBuiltin(sType).getBuiltinTypeCode()) - { - case SchemaType.BTC_SHORT: - return formatDecimal("1", sType); - case SchemaType.BTC_UNSIGNED_SHORT: - return formatDecimal("5", sType); - case SchemaType.BTC_BYTE: - return formatDecimal("2", sType); - case SchemaType.BTC_UNSIGNED_BYTE: - return formatDecimal("6", sType); - case SchemaType.BTC_INT: - return formatDecimal("3", sType); - case SchemaType.BTC_UNSIGNED_INT: - return formatDecimal("7", sType); - case SchemaType.BTC_LONG: - return formatDecimal("10", sType); - case SchemaType.BTC_UNSIGNED_LONG: - return formatDecimal("11", sType); - case SchemaType.BTC_INTEGER: - return formatDecimal("100", sType); - case SchemaType.BTC_NON_POSITIVE_INTEGER: - return formatDecimal("-200", sType); - case SchemaType.BTC_NEGATIVE_INTEGER: - return formatDecimal("-201", sType); - case SchemaType.BTC_NON_NEGATIVE_INTEGER: - return formatDecimal("200", sType); - case SchemaType.BTC_POSITIVE_INTEGER: - return formatDecimal("201", sType); - default: - case SchemaType.BTC_DECIMAL: - return formatDecimal("1000.00", sType); - } - - case SchemaType.BTC_STRING: - { - String result; - switch (closestBuiltin(sType).getBuiltinTypeCode()) - { - case SchemaType.BTC_STRING: - case SchemaType.BTC_NORMALIZED_STRING: - result = "string"; - break; - - case SchemaType.BTC_TOKEN: - result = "token"; - break; - - default: - result = "string"; - break; - } - - return formatToLength(result, sType); - } - - case SchemaType.BTC_DURATION: - return formatDuration(sType); - - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - return formatDate(sType); - } - } - - // a bit from the Aenid - public static final String[] WORDS = new String[] - { - "ipsa", "iovis", "rapidum", "iaculata", "e", "nubibus", "ignem", - "disiecitque", "rates", "evertitque", "aequora", "ventis", - "illum", "exspirantem", "transfixo", "pectore", "flammas", - "turbine", "corripuit", "scopuloque", "infixit", "acuto", - "ast", "ego", "quae", "divum", "incedo", "regina", "iovisque", - "et", "soror", "et", "coniunx", "una", "cum", "gente", "tot", "annos", - "bella", "gero", "et", "quisquam", "numen", "iunonis", "adorat", - "praeterea", "aut", "supplex", "aris", "imponet", "honorem", - "talia", "flammato", "secum", "dea", "corde", "volutans", - "nimborum", "in", "patriam", "loca", "feta", "furentibus", "austris", - "aeoliam", "venit", "hic", "vasto", "rex", "aeolus", "antro", - "luctantis", "ventos", "tempestatesque", "sonoras", - "imperio", "premit", "ac", "vinclis", "et", "carcere", "frenat", - "illi", "indignantes", "magno", "cum", "murmure", "montis", - "circum", "claustra", "fremunt", "celsa", "sedet", "aeolus", "arce", - "sceptra", "tenens", "mollitque", "animos", "et", "temperat", "iras", - "ni", "faciat", "maria", "ac", "terras", "caelumque", "profundum", - "quippe", "ferant", "rapidi", "secum", "verrantque", "per", "auras", - "sed", "pater", "omnipotens", "speluncis", "abdidit", "atris", - "hoc", "metuens", "molemque", "et", "montis", "insuper", "altos", - "imposuit", "regemque", "dedit", "qui", "foedere", "certo", - "et", "premere", "et", "laxas", "sciret", "dare", "iussus", "habenas", - }; - - - - private static final String[] DNS1 = new String[] { "corp", "your", "my", "sample", "company", "test", "any" }; - private static final String[] DNS2 = new String[] { "com", "org", "com", "gov", "org", "com", "org", "com", "edu" }; - - private int pick(int n) - { - return _picker.nextInt(n); - } - - private String pick(String[] a) - { - return a[pick(a.length)]; - } - - private String pick(String[] a, int count) - { - if (count <= 0) - return ""; - - int i = pick(a.length); - StringBuffer sb = new StringBuffer(a[i]); - while (count-- > 0) - { - i += 1; - if (i >= a.length) - i = 0; - sb.append(' '); - sb.append(a[i]); - } - return sb.toString(); - } - - private String pickDigits(int digits) - { - StringBuffer sb = new StringBuffer(); - while (digits-- > 0) - sb.append(Integer.toString(pick(10))); - return sb.toString(); - } - - private int pickLength(SchemaType sType) - { - XmlInteger length = (XmlInteger) sType.getFacet(SchemaType.FACET_LENGTH); - if (length != null) - return length.getBigIntegerValue().intValue(); - XmlInteger min = (XmlInteger) sType.getFacet(SchemaType.FACET_MIN_LENGTH); - XmlInteger max = (XmlInteger) sType.getFacet(SchemaType.FACET_MAX_LENGTH); - int minInt, maxInt; - if (min == null) - minInt = 0; - else - minInt = min.getBigIntegerValue().intValue(); - if (max == null) - maxInt = Integer.MAX_VALUE; - else - maxInt = max.getBigIntegerValue().intValue(); - // We try to keep the length of the array within reasonable limits, - // at least 1 item and at most 3 if possible - if (minInt == 0 && maxInt >= 1) - minInt = 1; - if (maxInt > minInt + 2) - maxInt = minInt + 2; - if (maxInt < minInt) - maxInt = minInt; - return minInt + pick(maxInt-minInt); - } - - /** - * Formats a given string to the required length, using the following operations: - * - append the source string to itself as necessary to pass the minLength; - * - truncate the result of previous step, if necessary, to keep it within minLength. - */ - private String formatToLength(String s, SchemaType sType) - { - String result = s; - try - { - SimpleValue min = (SimpleValue)sType.getFacet(SchemaType.FACET_LENGTH); - if (min == null) - min = (SimpleValue)sType.getFacet(SchemaType.FACET_MIN_LENGTH); - if (min != null) - { - int len = min.getIntValue(); - while (result.length() < len) - result = result + result; - } - SimpleValue max = (SimpleValue)sType.getFacet(SchemaType.FACET_LENGTH); - if (max == null) - max = (SimpleValue)sType.getFacet(SchemaType.FACET_MAX_LENGTH); - if (max != null) - { - int len = max.getIntValue(); - if (result.length() > len) - result = result.substring(0, len); - } - } - catch (Exception e) // intValue can be out of range - { - } - return result; - } - - private String formatDecimal(String start, SchemaType sType) - { - BigDecimal result = new BigDecimal(start); - XmlDecimal xmlD; - xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null; - xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null; - boolean minInclusive = true, maxInclusive = true; - xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (xmlD != null) - { - BigDecimal minExcl = xmlD.getBigDecimalValue(); - if (min == null || min.compareTo(minExcl) < 0) - { - min = minExcl; - minInclusive = false; - } - } - xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (xmlD != null) - { - BigDecimal maxExcl = xmlD.getBigDecimalValue(); - if (max == null || max.compareTo(maxExcl) > 0) - { - max = maxExcl; - maxInclusive = false; - } - } - xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); - int totalDigits = -1; - if (xmlD != null) - { - totalDigits = xmlD.getBigDecimalValue().intValue(); - - StringBuffer sb = new StringBuffer(totalDigits); - for (int i = 0; i < totalDigits; i++) - sb.append('9'); - BigDecimal digitsLimit = new BigDecimal(sb.toString()); - if (max != null && max.compareTo(digitsLimit) > 0) - { - max = digitsLimit; - maxInclusive = true; - } - digitsLimit = digitsLimit.negate(); - if (min != null && min.compareTo(digitsLimit) < 0) - { - min = digitsLimit; - minInclusive = true; - } - } - - int sigMin = min == null ? 1 : result.compareTo(min); - int sigMax = max == null ? -1 : result.compareTo(max); - boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive; - boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive; - - // Compute the minimum increment - xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS); - int fractionDigits = -1; - BigDecimal increment; - if (xmlD == null) - increment = new BigDecimal(1); - else - { - fractionDigits = xmlD.getBigDecimalValue().intValue(); - if (fractionDigits > 0) - { - StringBuffer sb = new StringBuffer("0."); - for (int i = 1; i < fractionDigits; i++) - sb.append('0'); - sb.append('1'); - increment = new BigDecimal(sb.toString()); - } - else - increment = new BigDecimal(1.0); - } - - if (minOk && maxOk) - { - // OK - } - else if (minOk && !maxOk) - { - // TOO BIG - if (maxInclusive) - result = max; - else - result = max.subtract(increment); - } - else if (!minOk && maxOk) - { - // TOO SMALL - if (minInclusive) - result = min; - else - result = min.add(increment); - } - else - { - // MIN > MAX!! - } - - // We have the number - // Adjust the scale according to the totalDigits and fractionDigits - int digits = 0; - BigDecimal ONE = new BigDecimal(BigInteger.ONE); - for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++) - n = n.movePointLeft(1); - - if (fractionDigits > 0) - if (totalDigits >= 0) - result = result.setScale(Math.max(fractionDigits, totalDigits - digits)); - else - result = result.setScale(fractionDigits); - else if (fractionDigits == 0) - result = result.setScale(0); - - return result.toString(); - } - - private String formatDuration(SchemaType sType) - { - XmlDuration d = - (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - GDuration minInclusive = null; - if (d != null) - minInclusive = d.getGDurationValue(); - - d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - GDuration maxInclusive = null; - if (d != null) - maxInclusive = d.getGDurationValue(); - - d = (XmlDuration) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - GDuration minExclusive = null; - if (d != null) - minExclusive = d.getGDurationValue(); - - d = (XmlDuration) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - GDuration maxExclusive = null; - if (d != null) - maxExclusive = d.getGDurationValue(); - - GDurationBuilder gdurb = new GDurationBuilder(); - BigInteger min, max; - - gdurb.setSecond(pick(800000)); - gdurb.setMonth(pick(20)); - - // Years - // Months - // Days - // Hours - // Minutes - // Seconds - // Fractions - if (minInclusive != null) - { - if (gdurb.getYear() < minInclusive.getYear()) - gdurb.setYear(minInclusive.getYear()); - if (gdurb.getMonth() < minInclusive.getMonth()) - gdurb.setMonth(minInclusive.getMonth()); - if (gdurb.getDay() < minInclusive.getDay()) - gdurb.setDay(minInclusive.getDay()); - if (gdurb.getHour() < minInclusive.getHour()) - gdurb.setHour(minInclusive.getHour()); - if (gdurb.getMinute() < minInclusive.getMinute()) - gdurb.setMinute(minInclusive.getMinute()); - if (gdurb.getSecond() < minInclusive.getSecond()) - gdurb.setSecond(minInclusive.getSecond()); - if (gdurb.getFraction().compareTo(minInclusive.getFraction()) < 0) - gdurb.setFraction(minInclusive.getFraction()); - } - - if (maxInclusive != null) - { - if (gdurb.getYear() > maxInclusive.getYear()) - gdurb.setYear(maxInclusive.getYear()); - if (gdurb.getMonth() > maxInclusive.getMonth()) - gdurb.setMonth(maxInclusive.getMonth()); - if (gdurb.getDay() > maxInclusive.getDay()) - gdurb.setDay(maxInclusive.getDay()); - if (gdurb.getHour() > maxInclusive.getHour()) - gdurb.setHour(maxInclusive.getHour()); - if (gdurb.getMinute() > maxInclusive.getMinute()) - gdurb.setMinute(maxInclusive.getMinute()); - if (gdurb.getSecond() > maxInclusive.getSecond()) - gdurb.setSecond(maxInclusive.getSecond()); - if (gdurb.getFraction().compareTo(maxInclusive.getFraction()) > 0) - gdurb.setFraction(maxInclusive.getFraction()); - } - - if (minExclusive != null) - { - if (gdurb.getYear() <= minExclusive.getYear()) - gdurb.setYear(minExclusive.getYear()+1); - if (gdurb.getMonth() <= minExclusive.getMonth()) - gdurb.setMonth(minExclusive.getMonth()+1); - if (gdurb.getDay() <= minExclusive.getDay()) - gdurb.setDay(minExclusive.getDay()+1); - if (gdurb.getHour() <= minExclusive.getHour()) - gdurb.setHour(minExclusive.getHour()+1); - if (gdurb.getMinute() <= minExclusive.getMinute()) - gdurb.setMinute(minExclusive.getMinute()+1); - if (gdurb.getSecond() <= minExclusive.getSecond()) - gdurb.setSecond(minExclusive.getSecond()+1); - if (gdurb.getFraction().compareTo(minExclusive.getFraction()) <= 0) - gdurb.setFraction(minExclusive.getFraction().add(new BigDecimal(0.001))); - } - - if (maxExclusive != null) - { - if (gdurb.getYear() > maxExclusive.getYear()) - gdurb.setYear(maxExclusive.getYear()); - if (gdurb.getMonth() > maxExclusive.getMonth()) - gdurb.setMonth(maxExclusive.getMonth()); - if (gdurb.getDay() > maxExclusive.getDay()) - gdurb.setDay(maxExclusive.getDay()); - if (gdurb.getHour() > maxExclusive.getHour()) - gdurb.setHour(maxExclusive.getHour()); - if (gdurb.getMinute() > maxExclusive.getMinute()) - gdurb.setMinute(maxExclusive.getMinute()); - if (gdurb.getSecond() > maxExclusive.getSecond()) - gdurb.setSecond(maxExclusive.getSecond()); - if (gdurb.getFraction().compareTo(maxExclusive.getFraction()) > 0) - gdurb.setFraction(maxExclusive.getFraction()); - } - - gdurb.normalize(); - return gdurb.toString(); - } - - private String formatDate(SchemaType sType) - { - GDateBuilder gdateb = new GDateBuilder(new Date(1000L * pick(365 * 24 * 60 * 60) + (30L + pick(20)) * 365 * 24 * 60 * 60 * 1000)); - GDate min = null, max = null; - GDate temp; - - // Find the min and the max according to the type - switch (sType.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_DATE_TIME: - { - XmlDateTime x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlDateTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_TIME: - { - XmlTime x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlTime) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlTime) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_DATE: - { - XmlDate x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlDate) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlDate) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_G_YEAR_MONTH: - { - XmlGYearMonth x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlGYearMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_G_YEAR: - { - XmlGYear x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlGYear) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlGYear) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_G_MONTH_DAY: - { - XmlGMonthDay x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlGMonthDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_G_DAY: - { - XmlGDay x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlGDay) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlGDay) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - case SchemaType.BTC_G_MONTH: - { - XmlGMonth x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (x != null) - min = x.getGDateValue(); - x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (x != null) - if (min == null || min.compareToGDate(x.getGDateValue()) <= 0) - min = x.getGDateValue(); - - x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (x != null) - max = x.getGDateValue(); - x = (XmlGMonth) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (x != null) - if (max == null || max.compareToGDate(x.getGDateValue()) >= 0) - max = x.getGDateValue(); - break; - } - } - - if (min != null && max == null) - { - if (min.compareToGDate(gdateb) >= 0) - { - // Reset the date to min + (1-8) hours - Calendar c = gdateb.getCalendar(); - c.add(Calendar.HOUR_OF_DAY, pick(8)); - gdateb = new GDateBuilder(c); - } - } - else if (min == null && max != null) - { - if (max.compareToGDate(gdateb) <= 0) - { - // Reset the date to max - (1-8) hours - Calendar c = gdateb.getCalendar(); - c.add(Calendar.HOUR_OF_DAY, 0-pick(8)); - gdateb = new GDateBuilder(c); - } - } - else if (min != null && max != null) - { - if (min.compareToGDate(gdateb) >= 0 || max.compareToGDate(gdateb) <= 0) - { - // Find a date between the two - Calendar c = min.getCalendar(); - Calendar cmax = max.getCalendar(); - c.add(Calendar.HOUR_OF_DAY, 1); - if (c.after(cmax)) - { - c.add(Calendar.HOUR_OF_DAY, -1); - c.add(Calendar.MINUTE, 1); - if (c.after(cmax)) - { - c.add(Calendar.MINUTE, -1); - c.add(Calendar.SECOND, 1); - if (c.after(cmax)) - { - c.add(Calendar.SECOND, -1); - c.add(Calendar.MILLISECOND, 1); - if (c.after(cmax)) - c.add(Calendar.MILLISECOND, -1); - } - } - } - gdateb = new GDateBuilder(c); - } - } - - gdateb.setBuiltinTypeCode(sType.getPrimitiveType().getBuiltinTypeCode()); - if (pick(2) == 0) - gdateb.clearTimeZone(); - return gdateb.toString(); - } - - private SchemaType closestBuiltin(SchemaType sType) - { - while (!sType.isBuiltinType()) - sType = sType.getBaseType(); - return sType; - } - - /** - * Cracks a combined QName of the form URL:localname - */ - public static QName crackQName(String qName) - { - String ns; - String name; - - int index = qName.lastIndexOf( ':' ); - if (index >= 0) - { - ns = qName.substring( 0, index ); - name = qName.substring( index + 1); - } - else - { - ns = ""; - name = qName; - } - - return new QName(ns, name); - } - - - /** - * Cursor position: - * Before this call: - * ^ (cursor at the ^) - * After this call: - * <som text^ - */ - private void processParticle(SchemaParticle sp, XmlCursor xmlc, boolean mixed) - { - int loop = determineMinMaxForSample(sp, xmlc); - - while (loop-- > 0) - { - switch (sp.getParticleType()) - { - case (SchemaParticle.ELEMENT) : - processElement(sp, xmlc, mixed); - break; - case (SchemaParticle.SEQUENCE) : - processSequence(sp, xmlc, mixed); - break; - case (SchemaParticle.CHOICE) : - processChoice(sp, xmlc, mixed); - break; - case (SchemaParticle.ALL) : - processAll(sp, xmlc, mixed); - break; - case (SchemaParticle.WILDCARD) : - processWildCard(sp, xmlc, mixed); - break; - default : - // throw new Exception("No Match on Schema Particle Type: " + String.valueOf(sp.getParticleType())); - } - } - } - - private int determineMinMaxForSample(SchemaParticle sp, XmlCursor xmlc) - { - int minOccurs = sp.getIntMinOccurs(); - int maxOccurs = sp.getIntMaxOccurs(); - - if (minOccurs == maxOccurs) - return minOccurs; - - int result = minOccurs; - if (result == 0 && _nElements < MAX_ELEMENTS) - result = 1; - - if (sp.getParticleType() != SchemaParticle.ELEMENT) - return result; - - // it probably only makes sense to put comments in front of individual elements that repeat - - if (sp.getMaxOccurs() == null) - { - // xmlc.insertComment("The next " + getItemNameOrType(sp, xmlc) + " may be repeated " + minOccurs + " or more times"); - if (minOccurs == 0) - xmlc.insertComment("Zero or more repetitions:"); - else - xmlc.insertComment(minOccurs + " or more repetitions:"); - } - else if (sp.getIntMaxOccurs() > 1) - { - xmlc.insertComment(minOccurs + " to " + String.valueOf(sp.getMaxOccurs()) + " repetitions:"); - } - else - { - xmlc.insertComment("Optional:"); - } - return result; - } - - /* - Return a name for the element or the particle type to use in the comment for minoccurs, max occurs - */ - private String getItemNameOrType(SchemaParticle sp, XmlCursor xmlc) - { - String elementOrTypeName = null; - if (sp.getParticleType() == SchemaParticle.ELEMENT) - { - elementOrTypeName = "Element (" + sp.getName().getLocalPart() + ")"; - } - else - { - elementOrTypeName = printParticleType(sp.getParticleType()); - } - return elementOrTypeName; - } - - private void processElement(SchemaParticle sp, XmlCursor xmlc, boolean mixed) - { - // cast as schema local element - SchemaLocalElement element = (SchemaLocalElement) sp; - /// ^ -> ^ - if (_soapEnc) - xmlc.insertElement(element.getName().getLocalPart()); // soap encoded? drop namespaces. - else - xmlc.insertElement(element.getName().getLocalPart(), element.getName().getNamespaceURI()); - _nElements++; - /// -> ^ - xmlc.toPrevToken(); - // -> stuff^ - - createSampleForType(element.getType(), xmlc); - // -> stuff^ - xmlc.toNextToken(); - - } - - private void moveToken(int numToMove, XmlCursor xmlc) - { - for (int i = 0; i < Math.abs(numToMove); i++) - { - if (numToMove < 0) - { - xmlc.toPrevToken(); - } - else - { - xmlc.toNextToken(); - } - } - } - - private static final String formatQName(XmlCursor xmlc, QName qName) - { - XmlCursor parent = xmlc.newCursor(); - parent.toParent(); - String prefix = parent.prefixForNamespace(qName.getNamespaceURI()); - parent.dispose(); - String name; - if (prefix == null || prefix.length() == 0) - name = qName.getLocalPart(); - else - name = prefix + ":" + qName.getLocalPart(); - return name; - } - - private static final QName HREF = new QName("href"); - private static final QName ID = new QName("id"); - private static final QName XSI_TYPE = new QName("http://www.w3.org/2001/XMLSchema-instance", "type"); - private static final QName ENC_ARRAYTYPE = new QName("http://schemas.xmlsoap.org/soap/encoding/", "arrayType"); - private static final QName ENC_OFFSET = new QName("http://schemas.xmlsoap.org/soap/encoding/", "offset"); - - private static final Set SKIPPED_SOAP_ATTRS = new HashSet(Arrays.asList(new QName[] { HREF, ID, ENC_OFFSET})); - private void processAttributes(SchemaType stype, XmlCursor xmlc) - { - if (_soapEnc) - { - QName typeName = stype.getName(); - if (typeName != null) - { - xmlc.insertAttributeWithValue(XSI_TYPE, formatQName(xmlc, typeName)); - } - } - - SchemaProperty[] attrProps = stype.getAttributeProperties(); - for (int i = 0; i < attrProps.length; i++) - { - SchemaProperty attr = attrProps[i]; - if (_soapEnc) - { - if (SKIPPED_SOAP_ATTRS.contains(attr.getName())) - continue; - if (ENC_ARRAYTYPE.equals(attr.getName())) - { - SOAPArrayType arrayType = ((SchemaWSDLArrayType)stype.getAttributeModel().getAttribute(attr.getName())).getWSDLArrayType(); - if (arrayType != null) - xmlc.insertAttributeWithValue(attr.getName(), formatQName(xmlc, arrayType.getQName()) + arrayType.soap11DimensionString()); - continue; - } - } - String defaultValue = attr.getDefaultText(); - xmlc.insertAttributeWithValue(attr.getName(), defaultValue == null ? - sampleDataForSimpleType(attr.getType()) : defaultValue); - } - } - - private void processSequence(SchemaParticle sp, XmlCursor xmlc, boolean mixed) - { - SchemaParticle[] spc = sp.getParticleChildren(); - for (int i=0; i < spc.length; i++) - { - /// maybestuff^ - processParticle(spc[i], xmlc, mixed); - //maybestuff...morestuff^ - if (mixed && i < spc.length-1) - xmlc.insertChars(pick(WORDS)); - } - } - - private void processChoice(SchemaParticle sp, XmlCursor xmlc, boolean mixed) - { - SchemaParticle[] spc = sp.getParticleChildren(); - xmlc.insertComment("You have a CHOICE of the next " + String.valueOf(spc.length) + " items at this level"); - for (int i=0; i < spc.length; i++) - { - processParticle(spc[i], xmlc, mixed); - } - } - - private void processAll(SchemaParticle sp, XmlCursor xmlc, boolean mixed) - { - SchemaParticle[] spc = sp.getParticleChildren(); - // xmlc.insertComment("You may enter the following " + String.valueOf(spc.length) + " items in any order"); - for (int i=0; i < spc.length; i++) - { - processParticle(spc[i], xmlc, mixed); - if (mixed && i < spc.length-1) - xmlc.insertChars(pick(WORDS)); - } - } - - private void processWildCard(SchemaParticle sp, XmlCursor xmlc, boolean mixed) - { - xmlc.insertComment("You may enter ANY elements at this point"); - xmlc.insertElement("AnyElement"); - } - - /** - * This method will get the base type for the schema type - */ - - private static QName getClosestName(SchemaType sType) - { - while (sType.getName() == null) - sType = sType.getBaseType(); - - return sType.getName(); - } - - private String printParticleType(int particleType) - { - StringBuffer returnParticleType = new StringBuffer(); - returnParticleType.append("Schema Particle Type: "); - - switch (particleType) - { - case SchemaParticle.ALL : - returnParticleType.append("ALL\n"); - break; - case SchemaParticle.CHOICE : - returnParticleType.append("CHOICE\n"); - break; - case SchemaParticle.ELEMENT : - returnParticleType.append("ELEMENT\n"); - break; - case SchemaParticle.SEQUENCE : - returnParticleType.append("SEQUENCE\n"); - break; - case SchemaParticle.WILDCARD : - returnParticleType.append("WILDCARD\n"); - break; - default : - returnParticleType.append("Schema Particle Type Unknown"); - break; - } - - return returnParticleType.toString(); - } - - private ArrayList _typeStack = new ArrayList(); -} diff --git a/src/typeholder/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java b/src/typeholder/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java deleted file mode 100644 index 2b31e1b..0000000 --- a/src/typeholder/org/apache/xmlbeans/impl/schema/TypeSystemHolder.java +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.SchemaTypeSystem; - -/** - * This class is the hook which causes the SchemaTypeSystem to be loaded when - * a generated class is used. It isn't used by the runtime directly, instead - * this class is used by the schema compiler as a template class. By using a - * template class, the SchemaTypeSystemImpl can create all the binary files - * required without needing to rely on javac. The generated source still - * requires a java compiler. - * - * @see SchemaTypeSystemImpl.save() - */ -// -// !!! It's important that there never NEVER be any references to this class because -// !!! the static initializer will fail. This class must only be used as a class file. -// !!! If this scares you, turn back now !!! -// -// !!! If you modify this class, you will have to run bootstrap. -// !!! If this scares you, turn back now !!! -// -public class TypeSystemHolder -{ - private TypeSystemHolder() { } - - public static final SchemaTypeSystem typeSystem = loadTypeSystem(); - - // Commenting out this line has the effect of not loading all components in a - // typesystem upfront, but just as they are needed, which may improve - // performance significantly - //static { typeSystem.resolve(); } - - private static final SchemaTypeSystem loadTypeSystem() - { - try - { - // The fact that we are using TypeSystemHolder.class.getClassLoader() - // to load the SchemaTypeSystem class means that the TypeSystemHolder's - // classloader MUST be a descendant of the XmlBeans classloader, even - // though it can be different. - // In other words, each Schema type has only one copy per VM, not one - // copy per copy of XmlBeans in use, therefore this implies that - // there either must be one copy of XmlBeans in the VM or copies in - // different classloaders will each need a different copy of one - // Schema type, which seems a reasonable restriction, but needs to be - // understood nevertheless - return (SchemaTypeSystem) - Class.forName( - "org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl", - true, TypeSystemHolder.class.getClassLoader()) - .getConstructor(new Class[] { Class.class }) - .newInstance(new java.lang.Object[] { TypeSystemHolder.class }); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException("Cannot load org.apache.xmlbeans.impl.SchemaTypeSystemImpl: make sure xbean.jar is on the classpath.", e); - } - catch (Exception e) - { - throw new RuntimeException("Could not instantiate SchemaTypeSystemImpl (" + e.toString() + "): is the version of xbean.jar correct?", e); - } - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/regex/RangeToken.java b/src/typeimpl/org/apache/xmlbeans/impl/regex/RangeToken.java deleted file mode 100644 index 482ff08..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/regex/RangeToken.java +++ /dev/null @@ -1,614 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.regex; - -/** - * This class represents a character class such as [a-z] or a period. - */ -final class RangeToken extends Token implements java.io.Serializable { - - int[] ranges; - boolean sorted; - boolean compacted; - RangeToken icaseCache = null; - int[] map = null; - int nonMapIndex; - - RangeToken(int type) { - super(type); - this.setSorted(false); - } - - // for RANGE or NRANGE - protected void addRange(int start, int end) { - this.icaseCache = null; - //System.err.println("Token#addRange(): "+start+" "+end); - int r1, r2; - if (start <= end) { - r1 = start; - r2 = end; - } else { - r1 = end; - r2 = start; - } - - int pos = 0; - if (this.ranges == null) { - this.ranges = new int[2]; - this.ranges[0] = r1; - this.ranges[1] = r2; - this.setSorted(true); - } else { - pos = this.ranges.length; - if (this.ranges[pos-1]+1 == r1) { - this.ranges[pos-1] = r2; - return; - } - int[] temp = new int[pos+2]; - System.arraycopy(this.ranges, 0, temp, 0, pos); - this.ranges = temp; - if (this.ranges[pos-1] >= r1) - this.setSorted(false); - this.ranges[pos++] = r1; - this.ranges[pos] = r2; - if (!this.sorted) - this.sortRanges(); - } - } - - private final boolean isSorted() { - return this.sorted; - } - private final void setSorted(boolean sort) { - this.sorted = sort; - if (!sort) this.compacted = false; - } - private final boolean isCompacted() { - return this.compacted; - } - private final void setCompacted() { - this.compacted = true; - } - - protected void sortRanges() { - if (this.isSorted()) - return; - if (this.ranges == null) - return; - //System.err.println("Do sorting: "+this.ranges.length); - - // Bubble sort - // Why? -- In many cases, - // this.ranges has few elements. - for (int i = this.ranges.length-4; i >= 0; i -= 2) { - for (int j = 0; j <= i; j += 2) { - if (this.ranges[j] > this.ranges[j+2] - || this.ranges[j] == this.ranges[j+2] && this.ranges[j+1] > this.ranges[j+3]) { - int tmp; - tmp = this.ranges[j+2]; - this.ranges[j+2] = this.ranges[j]; - this.ranges[j] = tmp; - tmp = this.ranges[j+3]; - this.ranges[j+3] = this.ranges[j+1]; - this.ranges[j+1] = tmp; - } - } - } - this.setSorted(true); - } - - /** - * this.ranges is sorted. - */ - protected void compactRanges() { - boolean DEBUG = false; - if (this.ranges == null || this.ranges.length <= 2) - return; - if (this.isCompacted()) - return; - int base = 0; // Index of writing point - int target = 0; // Index of processing point - - while (target < this.ranges.length) { - if (base != target) { - this.ranges[base] = this.ranges[target++]; - this.ranges[base+1] = this.ranges[target++]; - } else - target += 2; - int baseend = this.ranges[base+1]; - while (target < this.ranges.length) { - if (baseend+1 < this.ranges[target]) - break; - if (baseend+1 == this.ranges[target]) { - if (DEBUG) - System.err.println("Token#compactRanges(): Compaction: ["+this.ranges[base] - +", "+this.ranges[base+1] - +"], ["+this.ranges[target] - +", "+this.ranges[target+1] - +"] -> ["+this.ranges[base] - +", "+this.ranges[target+1] - +"]"); - this.ranges[base+1] = this.ranges[target+1]; - baseend = this.ranges[base+1]; - target += 2; - } else if (baseend >= this.ranges[target+1]) { - if (DEBUG) - System.err.println("Token#compactRanges(): Compaction: ["+this.ranges[base] - +", "+this.ranges[base+1] - +"], ["+this.ranges[target] - +", "+this.ranges[target+1] - +"] -> ["+this.ranges[base] - +", "+this.ranges[base+1] - +"]"); - target += 2; - } else if (baseend < this.ranges[target+1]) { - if (DEBUG) - System.err.println("Token#compactRanges(): Compaction: ["+this.ranges[base] - +", "+this.ranges[base+1] - +"], ["+this.ranges[target] - +", "+this.ranges[target+1] - +"] -> ["+this.ranges[base] - +", "+this.ranges[target+1] - +"]"); - this.ranges[base+1] = this.ranges[target+1]; - baseend = this.ranges[base+1]; - target += 2; - } else { - throw new RuntimeException("Token#compactRanges(): Internel Error: [" - +this.ranges[base] - +","+this.ranges[base+1] - +"] ["+this.ranges[target] - +","+this.ranges[target+1]+"]"); - } - } // while - base += 2; - } - - if (base != this.ranges.length) { - int[] result = new int[base]; - System.arraycopy(this.ranges, 0, result, 0, base); - this.ranges = result; - } - this.setCompacted(); - } - - protected void mergeRanges(Token token) { - RangeToken tok = (RangeToken)token; - this.sortRanges(); - tok.sortRanges(); - if (tok.ranges == null) - return; - this.icaseCache = null; - this.setSorted(true); - if (this.ranges == null) { - this.ranges = new int[tok.ranges.length]; - System.arraycopy(tok.ranges, 0, this.ranges, 0, tok.ranges.length); - return; - } - int[] result = new int[this.ranges.length+tok.ranges.length]; - for (int i = 0, j = 0, k = 0; i < this.ranges.length || j < tok.ranges.length;) { - if (i >= this.ranges.length) { - result[k++] = tok.ranges[j++]; - result[k++] = tok.ranges[j++]; - } else if (j >= tok.ranges.length) { - result[k++] = this.ranges[i++]; - result[k++] = this.ranges[i++]; - } else if (tok.ranges[j] < this.ranges[i] - || tok.ranges[j] == this.ranges[i] && tok.ranges[j+1] < this.ranges[i+1]) { - result[k++] = tok.ranges[j++]; - result[k++] = tok.ranges[j++]; - } else { - result[k++] = this.ranges[i++]; - result[k++] = this.ranges[i++]; - } - } - this.ranges = result; - } - - protected void subtractRanges(Token token) { - if (token.type == NRANGE) { - this.intersectRanges(token); - return; - } - RangeToken tok = (RangeToken)token; - if (tok.ranges == null || this.ranges == null) - return; - this.icaseCache = null; - this.sortRanges(); - this.compactRanges(); - tok.sortRanges(); - tok.compactRanges(); - - //System.err.println("Token#substractRanges(): Entry: "+this.ranges.length+", "+tok.ranges.length); - - int[] result = new int[this.ranges.length+tok.ranges.length]; - int wp = 0, src = 0, sub = 0; - while (src < this.ranges.length && sub < tok.ranges.length) { - int srcbegin = this.ranges[src]; - int srcend = this.ranges[src+1]; - int subbegin = tok.ranges[sub]; - int subend = tok.ranges[sub+1]; - if (srcend < subbegin) { // Not overlapped - // src: o-----o - // sub: o-----o - // res: o-----o - // Reuse sub - result[wp++] = this.ranges[src++]; - result[wp++] = this.ranges[src++]; - } else if (srcend >= subbegin - && srcbegin <= subend) { // Overlapped - // src: o--------o - // sub: o----o - // sub: o----o - // sub: o----o - // sub: o------------o - if (subbegin <= srcbegin && srcend <= subend) { - // src: o--------o - // sub: o------------o - // res: empty - // Reuse sub - src += 2; - } else if (subbegin <= srcbegin) { - // src: o--------o - // sub: o----o - // res: o-----o - // Reuse src(=res) - this.ranges[src] = subend+1; - sub += 2; - } else if (srcend <= subend) { - // src: o--------o - // sub: o----o - // res: o-----o - // Reuse sub - result[wp++] = srcbegin; - result[wp++] = subbegin-1; - src += 2; - } else { - // src: o--------o - // sub: o----o - // res: o-o o-o - // Reuse src(=right res) - result[wp++] = srcbegin; - result[wp++] = subbegin-1; - this.ranges[src] = subend+1; - sub += 2; - } - } else if (subend < srcbegin) { - // Not overlapped - // src: o-----o - // sub: o----o - sub += 2; - } else { - throw new RuntimeException("Token#subtractRanges(): Internal Error: ["+this.ranges[src] - +","+this.ranges[src+1] - +"] - ["+tok.ranges[sub] - +","+tok.ranges[sub+1] - +"]"); - } - } - while (src < this.ranges.length) { - result[wp++] = this.ranges[src++]; - result[wp++] = this.ranges[src++]; - } - this.ranges = new int[wp]; - System.arraycopy(result, 0, this.ranges, 0, wp); - // this.ranges is sorted and compacted. - } - - /** - * @param tok Ignore whether it is NRANGE or not. - */ - protected void intersectRanges(Token token) { - RangeToken tok = (RangeToken)token; - if (tok.ranges == null || this.ranges == null) - return; - this.icaseCache = null; - this.sortRanges(); - this.compactRanges(); - tok.sortRanges(); - tok.compactRanges(); - - int[] result = new int[this.ranges.length+tok.ranges.length]; - int wp = 0, src1 = 0, src2 = 0; - while (src1 < this.ranges.length && src2 < tok.ranges.length) { - int src1begin = this.ranges[src1]; - int src1end = this.ranges[src1+1]; - int src2begin = tok.ranges[src2]; - int src2end = tok.ranges[src2+1]; - if (src1end < src2begin) { // Not overlapped - // src1: o-----o - // src2: o-----o - // res: empty - // Reuse src2 - src1 += 2; - } else if (src1end >= src2begin - && src1begin <= src2end) { // Overlapped - // src1: o--------o - // src2: o----o - // src2: o----o - // src2: o----o - // src2: o------------o - if (src2begin <= src2begin && src1end <= src2end) { - // src1: o--------o - // src2: o------------o - // res: o--------o - // Reuse src2 - result[wp++] = src1begin; - result[wp++] = src1end; - src1 += 2; - } else if (src2begin <= src1begin) { - // src1: o--------o - // src2: o----o - // res: o--o - // Reuse the rest of src1 - result[wp++] = src1begin; - result[wp++] = src2end; - this.ranges[src1] = src2end+1; - src2 += 2; - } else if (src1end <= src2end) { - // src1: o--------o - // src2: o----o - // res: o--o - // Reuse src2 - result[wp++] = src2begin; - result[wp++] = src1end; - src1 += 2; - } else { - // src1: o--------o - // src2: o----o - // res: o----o - // Reuse the rest of src1 - result[wp++] = src2begin; - result[wp++] = src2end; - this.ranges[src1] = src2end+1; - } - } else if (src2end < src1begin) { - // Not overlapped - // src1: o-----o - // src2: o----o - src2 += 2; - } else { - throw new RuntimeException("Token#intersectRanges(): Internal Error: [" - +this.ranges[src1] - +","+this.ranges[src1+1] - +"] & ["+tok.ranges[src2] - +","+tok.ranges[src2+1] - +"]"); - } - } - while (src1 < this.ranges.length) { - result[wp++] = this.ranges[src1++]; - result[wp++] = this.ranges[src1++]; - } - this.ranges = new int[wp]; - System.arraycopy(result, 0, this.ranges, 0, wp); - // this.ranges is sorted and compacted. - } - - /** - * for RANGE: Creates complement. - * for NRANGE: Creates the same meaning RANGE. - */ - static Token complementRanges(Token token) { - if (token.type != RANGE && token.type != NRANGE) - throw new IllegalArgumentException("Token#complementRanges(): must be RANGE: "+token.type); - RangeToken tok = (RangeToken)token; - tok.sortRanges(); - tok.compactRanges(); - int len = tok.ranges.length+2; - if (tok.ranges[0] == 0) - len -= 2; - int last = tok.ranges[tok.ranges.length-1]; - if (last == UTF16_MAX) - len -= 2; - RangeToken ret = Token.createRange(); - ret.ranges = new int[len]; - int wp = 0; - if (tok.ranges[0] > 0) { - ret.ranges[wp++] = 0; - ret.ranges[wp++] = tok.ranges[0]-1; - } - for (int i = 1; i < tok.ranges.length-2; i += 2) { - ret.ranges[wp++] = tok.ranges[i]+1; - ret.ranges[wp++] = tok.ranges[i+1]-1; - } - if (last != UTF16_MAX) { - ret.ranges[wp++] = last+1; - ret.ranges[wp] = UTF16_MAX; - } - ret.setCompacted(); - return ret; - } - - synchronized RangeToken getCaseInsensitiveToken() { - if (this.icaseCache != null) - return this.icaseCache; - - RangeToken uppers = this.type == Token.RANGE ? Token.createRange() : Token.createNRange(); - for (int i = 0; i < this.ranges.length; i += 2) { - for (int ch = this.ranges[i]; ch <= this.ranges[i+1]; ch ++) { - if (ch > 0xffff) - uppers.addRange(ch, ch); - else { - char uch = Character.toUpperCase((char)ch); - uppers.addRange(uch, uch); - } - } - } - RangeToken lowers = this.type == Token.RANGE ? Token.createRange() : Token.createNRange(); - for (int i = 0; i < uppers.ranges.length; i += 2) { - for (int ch = uppers.ranges[i]; ch <= uppers.ranges[i+1]; ch ++) { - if (ch > 0xffff) - lowers.addRange(ch, ch); - else { - char uch = Character.toUpperCase((char)ch); - lowers.addRange(uch, uch); - } - } - } - lowers.mergeRanges(uppers); - lowers.mergeRanges(this); - lowers.compactRanges(); - - this.icaseCache = lowers; - return lowers; - } - - void dumpRanges() { - System.err.print("RANGE: "); - if (this.ranges == null) - System.err.println(" NULL"); - for (int i = 0; i < this.ranges.length; i += 2) { - System.err.print("["+this.ranges[i]+","+this.ranges[i+1]+"] "); - } - System.err.println(""); - } - - boolean match(int ch) { - if (this.map == null) this.createMap(); - boolean ret; - if (this.type == RANGE) { - if (ch < MAPSIZE) - return (this.map[ch/32] & (1<<(ch&0x1f))) != 0; - ret = false; - for (int i = this.nonMapIndex; i < this.ranges.length; i += 2) { - if (this.ranges[i] <= ch && ch <= this.ranges[i+1]) - return true; - } - } else { - if (ch < MAPSIZE) - return (this.map[ch/32] & (1<<(ch&0x1f))) == 0; - ret = true; - for (int i = this.nonMapIndex; i < this.ranges.length; i += 2) { - if (this.ranges[i] <= ch && ch <= this.ranges[i+1]) - return false; - } - } - return ret; - } - - private static final int MAPSIZE = 256; - private void createMap() { - int asize = MAPSIZE/32; // 32 is the number of bits in `int'. - // CHANGE(radup) we need a new map, since this is not synchronized - // and if we init the instance map with 0's it's going to be trouble - // -this.map = new int[asize]; - // -this.nonMapIndex = this.ranges.length; - // -for (int i = 0; i < asize; i++) this.map[i] = 0; - int[] localmap = new int[asize]; // + - int localnonMapIndex = this.ranges.length; // + - for (int i = 0; i < asize; i ++) localmap[i] = 0; // + redundant - for (int i = 0; i < this.ranges.length; i += 2) { - int s = this.ranges[i]; - int e = this.ranges[i+1]; - if (s < MAPSIZE) { - for (int j = s; j <= e && j < MAPSIZE; j ++) - localmap[j/32] |= 1<<(j&0x1f); // s&0x1f : 0-31 - } else { - localnonMapIndex = i; - break; - } - if (e >= MAPSIZE) { - localnonMapIndex = i; - break; - } - } - this.nonMapIndex = localnonMapIndex; // + - this.map = localmap; // + - //for (int i = 0; i < asize; i ++) System.err.println("Map: "+Integer.toString(this.map[i], 16)); - } - - public String toString(int options) { - String ret; - if (this.type == RANGE) { - if (this == Token.token_dot) - ret = "."; - else if (this == Token.token_0to9) - ret = "\\d"; - else if (this == Token.token_wordchars) - ret = "\\w"; - else if (this == Token.token_spaces) - ret = "\\s"; - else { - StringBuffer sb = new StringBuffer(); - sb.append("["); - for (int i = 0; i < this.ranges.length; i += 2) { - if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0) sb.append(","); - if (this.ranges[i] == this.ranges[i+1]) { - sb.append(escapeCharInCharClass(this.ranges[i])); - } else { - sb.append(escapeCharInCharClass(this.ranges[i])); - sb.append((char)'-'); - sb.append(escapeCharInCharClass(this.ranges[i+1])); - } - } - sb.append("]"); - ret = sb.toString(); - } - } else { - if (this == Token.token_not_0to9) - ret = "\\D"; - else if (this == Token.token_not_wordchars) - ret = "\\W"; - else if (this == Token.token_not_spaces) - ret = "\\S"; - else { - StringBuffer sb = new StringBuffer(); - sb.append("[^"); - for (int i = 0; i < this.ranges.length; i += 2) { - if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0) sb.append(","); - if (this.ranges[i] == this.ranges[i+1]) { - sb.append(escapeCharInCharClass(this.ranges[i])); - } else { - sb.append(escapeCharInCharClass(this.ranges[i])); - sb.append('-'); - sb.append(escapeCharInCharClass(this.ranges[i+1])); - } - } - sb.append("]"); - ret = sb.toString(); - } - } - return ret; - } - - private static String escapeCharInCharClass(int ch) { - String ret; - switch (ch) { - case '[': case ']': case '-': case '^': - case ',': case '\\': - ret = "\\"+(char)ch; - break; - case '\f': ret = "\\f"; break; - case '\n': ret = "\\n"; break; - case '\r': ret = "\\r"; break; - case '\t': ret = "\\t"; break; - case 0x1b: ret = "\\e"; break; - //case 0x0b: ret = "\\v"; break; - default: - if (ch < 0x20) { - String pre = "0"+Integer.toHexString(ch); - ret = "\\x"+pre.substring(pre.length()-2, pre.length()); - } else if (ch >= 0x10000) { - String pre = "0"+Integer.toHexString(ch); - ret = "\\v"+pre.substring(pre.length()-6, pre.length()); - } else - ret = ""+(char)ch; - } - return ret; - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaContainer.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaContainer.java deleted file mode 100644 index e3fe3f5..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaContainer.java +++ /dev/null @@ -1,210 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeSystem; - -/*package*/ class SchemaContainer -{ - // The namespace that this is the container for - // TODO(radup) In the future, I think the right approach is one container - // per file instead of per namespace, but per namespace is easier for now - private String _namespace; - - SchemaContainer(String namespace) - { - _namespace = namespace; - } - - String getNamespace() - { - return _namespace; - } - - // The SchemaTypeSystem on behalf of which this acts - private SchemaTypeSystem _typeSystem; - - // This is the whole idea of the containers - // By synchronizing getter/setters on this field, we allow - // both SchemaTypeSystems and SchemaTypes to be immutable - // at the same time providing the mechanism through which - // we can "move" SchemaTypes from one SchemaTypeSystem to another - // via incremental compilation - synchronized SchemaTypeSystem getTypeSystem() - { - return _typeSystem; - } - - synchronized void setTypeSystem(SchemaTypeSystem typeSystem) - { - _typeSystem = typeSystem; - } - - // Immutability refers to the content of the container - // Once the container has been initialized, one cannot add/remove - // SchemaComponents from it. Instead, one has to blow it away - // and build a new one. - // Immutability does not mean that one cannot move this container - // between typesystems. - boolean _immutable; - - synchronized void setImmutable() - { - _immutable = true; - } - - synchronized void unsetImmutable() - { - _immutable = false; - } - - private void check_immutable() - { - if (_immutable) - throw new IllegalStateException("Cannot add components to immutable SchemaContainer"); - } - - // Data - // TODO(radup) unmodifiableList() is not really necessary, since this - // is package-level access and code in this package should do the "right thing" - // Global Elements - private List/**/ _globalElements = new ArrayList(); - - void addGlobalElement(SchemaGlobalElement.Ref e) - { check_immutable(); _globalElements.add(e); } - - List globalElements() - { return getComponentList(_globalElements); } - - // Global Attributes - private List/**/ _globalAttributes = new ArrayList(); - - void addGlobalAttribute(SchemaGlobalAttribute.Ref a) - { check_immutable(); _globalAttributes.add(a); } - - List globalAttributes() - { return getComponentList(_globalAttributes); } - - // Model Groups - private List/**/ _modelGroups = new ArrayList(); - - void addModelGroup(SchemaModelGroup.Ref g) - { check_immutable(); _modelGroups.add(g); } - - List modelGroups() - { return getComponentList(_modelGroups); } - - // Redefined Model Groups - private List/**/ _redefinedModelGroups = new ArrayList(); - - void addRedefinedModelGroup(SchemaModelGroup.Ref g) - { check_immutable(); _redefinedModelGroups.add(g); } - - List redefinedModelGroups() - { return getComponentList(_redefinedModelGroups); } - - // Attribute Groups - private List/**/ _attributeGroups = new ArrayList(); - - void addAttributeGroup(SchemaAttributeGroup.Ref g) - { check_immutable(); _attributeGroups.add(g); } - - List attributeGroups() - { return getComponentList(_attributeGroups); } - - // Redefined Attribute Groups - private List/**/ _redefinedAttributeGroups = new ArrayList(); - - void addRedefinedAttributeGroup(SchemaAttributeGroup.Ref g) - { check_immutable(); _redefinedAttributeGroups.add(g); } - - List redefinedAttributeGroups() - { return getComponentList(_redefinedAttributeGroups); } - - // Global Types - private List/**/ _globalTypes = new ArrayList(); - - void addGlobalType(SchemaType.Ref t) - { check_immutable(); _globalTypes.add(t); } - - List globalTypes() - { return getComponentList(_globalTypes); } - - // Redefined Global Types - private List/**/ _redefinedGlobalTypes = new ArrayList(); - - void addRedefinedType(SchemaType.Ref t) - { check_immutable(); _redefinedGlobalTypes.add(t); } - - List redefinedGlobalTypes() - { return getComponentList(_redefinedGlobalTypes); } - - // Document Types - private List/**/ _documentTypes = new ArrayList(); - - void addDocumentType(SchemaType.Ref t) - { check_immutable(); _documentTypes.add(t); } - - List documentTypes() - { return getComponentList(_documentTypes); } - - // Attribute Types - private List/**/ _attributeTypes = new ArrayList(); - - void addAttributeType(SchemaType.Ref t) - { check_immutable(); _attributeTypes.add(t); } - - List attributeTypes() - { return getComponentList(_attributeTypes); } - - // Identity Constraints - private List/**/ _identityConstraints = new ArrayList(); - - void addIdentityConstraint(SchemaIdentityConstraint.Ref c) - { check_immutable(); _identityConstraints.add(c); } - - List identityConstraints() - { return getComponentList(_identityConstraints); } - - // Annotations - private List/**/ _annotations = new ArrayList(); - - void addAnnotation(SchemaAnnotation a) - { check_immutable(); _annotations.add(a); } - - List annotations() - { return Collections.unmodifiableList(_annotations); } - - private List getComponentList(List referenceList) - { - List result = new ArrayList(); - for (int i = 0; i < referenceList.size(); i ++) - result.add(((SchemaComponent.Ref) referenceList.get(i)).getComponent()); - return Collections.unmodifiableList(result); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaDependencies.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaDependencies.java deleted file mode 100644 index 3f4b6c7..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaDependencies.java +++ /dev/null @@ -1,162 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class SchemaDependencies -{ - // This class is NOT synchronized - - void registerDependency(String source, String target) - { - Set depSet = (Set) _dependencies.get(target); - if (depSet == null) - { - depSet = new HashSet(); - _dependencies.put(target, depSet); - } - depSet.add(source); - } - - - - /** - * Records anti-dependencies. Keys are namespaces and values are - * the lists of namespaces that depend on each key - */ - private Map/*>*/ _dependencies; - - Set computeTransitiveClosure(List modifiedNamespaces) - { - List nsList = new ArrayList(modifiedNamespaces); - Set result = new HashSet(modifiedNamespaces); - for (int i = 0; i < nsList.size(); i++) - { - Set deps = (Set) _dependencies.get(nsList.get(i)); - if (deps == null) - continue; - for (Iterator it = deps.iterator(); it.hasNext(); ) - { - String ns = (String) it.next(); - if (!result.contains(ns)) - { - nsList.add(ns); - result.add(ns); - } - } - } - return result; - } - - SchemaDependencies() - { - _dependencies = new HashMap(); - _contributions = new HashMap(); - } - - SchemaDependencies(SchemaDependencies base, Set updatedNs) - { - _dependencies = new HashMap(); - _contributions = new HashMap(); - for (Iterator it = base._dependencies.keySet().iterator(); it.hasNext(); ) - { - String target = (String) it.next(); - if (updatedNs.contains(target)) - continue; - Set depSet = new HashSet(); - _dependencies.put(target, depSet); - Set baseDepSet = (Set) base._dependencies.get(target); - for (Iterator it2 = baseDepSet.iterator(); it2.hasNext(); ) - { - String source = (String) it2.next(); - if (updatedNs.contains(source)) - continue; - depSet.add(source); - } - } - for (Iterator it = base._contributions.keySet().iterator(); it.hasNext(); ) - { - String ns = (String) it.next(); - if (updatedNs.contains(ns)) - continue; - List fileList = new ArrayList(); - _contributions.put(ns, fileList); - List baseFileList = (List) base._contributions.get(ns); - for (Iterator it2 = baseFileList.iterator(); it2.hasNext(); ) - fileList.add(it2.next()); - } - } - - /** - * Records the list of files associated to each namespace. - * This is needed so that we can return a list of files that - * need to be compiled once we get a set of altered namespaces - */ - private Map/*>*/ _contributions; - - void registerContribution(String ns, String fileURL) - { - List fileList = (List) _contributions.get(ns); - if (fileList == null) - { - fileList = new ArrayList(); - _contributions.put(ns, fileList); - } - fileList.add(fileURL); - } - - boolean isFileRepresented(String fileURL) - { - for (Iterator it = _contributions.values().iterator(); it.hasNext(); ) - { - List fileList = (List) it.next(); - if (fileList.contains(fileURL)) - return true; - } - return false; - } - - List getFilesTouched(Set updatedNs) - { - List result = new ArrayList(); - for (Iterator it = updatedNs.iterator(); it.hasNext(); ) - { - result.addAll((List) _contributions.get(it.next())); - } - return result; - } - - List getNamespacesTouched(Set modifiedFiles) - { - List result = new ArrayList(); - for (Iterator it = _contributions.keySet().iterator(); it.hasNext(); ) - { - String ns = (String) it.next(); - List files = (List) _contributions.get(ns); - for (int i = 0; i < files.size(); i++) - if (modifiedFiles.contains(files.get(i))) - result.add(ns); - } - return result; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java deleted file mode 100644 index 196d24a..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java +++ /dev/null @@ -1,213 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.common.XPath; -import javax.xml.namespace.QName; -import java.util.Map; -import java.util.Collections; - -public class SchemaIdentityConstraintImpl implements SchemaIdentityConstraint -{ - private SchemaContainer _container; - private String _selector; - private String[] _fields; - private SchemaIdentityConstraint.Ref _key; - private QName _name; - private int _type; - private XmlObject _parse; - private Object _userData; - private SchemaAnnotation _annotation; - private Map _nsMap = Collections.EMPTY_MAP; - private String _parseTNS; - private boolean _chameleon; - private String _filename; - - // Lazily computed paths - private volatile XPath _selectorPath; - private volatile XPath[] _fieldPaths; - - public SchemaIdentityConstraintImpl(SchemaContainer c) { - _container = c; - } - - public void setFilename(String filename) - { _filename = filename; } - - public String getSourceName() - { return _filename; } - - - public String getSelector() { - return _selector; - } - - public Object getSelectorPath() { - XPath p = _selectorPath; - if (p == null) { - try { - buildPaths(); - p = _selectorPath; - } - catch (XPath.XPathCompileException e) { - assert false: "Failed to compile xpath. Should be caught by compiler " + e; - return null; - } - } - return p; - } - - public void setAnnotation(SchemaAnnotation ann) - { - _annotation = ann; - } - - public SchemaAnnotation getAnnotation() - { - return _annotation; - } - - public void setNSMap(Map nsMap) { - _nsMap = nsMap; - } - - public Map getNSMap() { - return Collections.unmodifiableMap(_nsMap); - } - - public void setSelector(String selector) { - assert selector != null; - _selector = selector; - } - - public void setFields(String[] fields) { - assert fields != null && fields.length > 0; - _fields = fields; - } - - public String[] getFields() { - String[] fields = new String[_fields.length]; - System.arraycopy(_fields, 0, fields, 0, fields.length); - return fields; - } - - public Object getFieldPath(int index) { - XPath[] p = _fieldPaths; - if (p == null) { - try { - buildPaths(); - p = _fieldPaths; - } - catch (XPath.XPathCompileException e) { - assert false: "Failed to compile xpath. Should be caught by compiler " + e; - return null; - } - } - return p[index]; - } - - public void buildPaths() throws XPath.XPathCompileException { - // TODO: Need the namespace map - requires store support - _selectorPath = XPath.compileXPath(_selector, _nsMap); - - _fieldPaths = new XPath[_fields.length]; - for (int i = 0 ; i < _fieldPaths.length ; i++) - _fieldPaths[i] = XPath.compileXPath(_fields[i], _nsMap); - } - - public void setReferencedKey(SchemaIdentityConstraint.Ref key) { - _key = key; - } - - public SchemaIdentityConstraint getReferencedKey() { - return _key.get(); - } - - public void setConstraintCategory(int type) { - assert type >= CC_KEY && type <= CC_UNIQUE; - _type = type; - } - - public int getConstraintCategory() { - return _type; - } - - public void setName(QName name) { - assert name != null; - _name = name; - } - - public QName getName() { - return _name; - } - - public int getComponentType() { - return IDENTITY_CONSTRAINT; - } - - public SchemaTypeSystem getTypeSystem() { - return _container.getTypeSystem(); - } - - SchemaContainer getContainer() { - return _container; - } - - public void setParseContext(XmlObject o, String targetNamespace, boolean chameleon) { - _parse = o; - _parseTNS = targetNamespace; - _chameleon = chameleon; - } - - public XmlObject getParseObject() { - return _parse; - } - - public String getTargetNamespace() { - return _parseTNS; - } - - public String getChameleonNamespace() { - return _chameleon ? _parseTNS : null; - } - - - /** - * Only applicable to keyrefs. Other types are implicitly resolved. - */ - public boolean isResolved() { - return getConstraintCategory() != CC_KEYREF || _key != null; - } - - private SchemaIdentityConstraint.Ref _selfref = new SchemaIdentityConstraint.Ref(this); - - public SchemaIdentityConstraint.Ref getRef() - { return _selfref; } - - public SchemaComponent.Ref getComponentRef() - { return getRef(); } - - public Object getUserData() - { return _userData; } - - public void setUserData(Object data) - { _userData = data; } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java deleted file mode 100644 index 047d95f..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaParticleImpl.java +++ /dev/null @@ -1,258 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlQName; -import org.apache.xmlbeans.impl.values.NamespaceContext; - -import java.math.BigInteger; - -import javax.xml.namespace.QName; - -public class SchemaParticleImpl implements SchemaParticle -{ - private int _particleType; - private BigInteger _minOccurs; - private BigInteger _maxOccurs; - private SchemaParticle[] _particleChildren; - private boolean _isImmutable; - private QNameSet _startSet; - private QNameSet _excludeNextSet; - private boolean _isSkippable; - private boolean _isDeterministic; - private int _intMinOccurs; - private int _intMaxOccurs; - private QNameSet _wildcardSet; - private int _wildcardProcess; - private String _defaultText; - private boolean _isDefault; - private boolean _isFixed; - private QName _qName; - private boolean _isNillable; - private SchemaType.Ref _typeref; - protected XmlObject _parseObject; - private Object _userData; - private XmlValueRef _defaultValue; - - protected void mutate() - { if (_isImmutable) throw new IllegalStateException(); } - - public void setImmutable() - { mutate(); _isImmutable = true; } - - public boolean hasTransitionRules() - { return (_startSet != null); } - - public boolean hasTransitionNotes() - { return (_excludeNextSet != null); } - - public void setTransitionRules(QNameSet start, - boolean isSkippable) - { - _startSet = start; - _isSkippable = isSkippable; - } - - public void setTransitionNotes(QNameSet excludeNext, boolean isDeterministic) - { - _excludeNextSet = excludeNext; - _isDeterministic = isDeterministic; - } - - public boolean canStartWithElement(QName name) - { return name != null && _startSet.contains(name); } - - public QNameSet acceptedStartNames() - { return _startSet; } - - public QNameSet getExcludeNextSet() - { return _excludeNextSet; } - - public boolean isSkippable() - { return _isSkippable; } - - public boolean isDeterministic() - { return _isDeterministic; } - - public int getParticleType() - { return _particleType; } - - public void setParticleType(int pType) - { mutate(); _particleType = pType; } - - public boolean isSingleton() - { return _maxOccurs != null && - _maxOccurs.compareTo(BigInteger.ONE) == 0 && - _minOccurs.compareTo(BigInteger.ONE) == 0; } - - public BigInteger getMinOccurs() - { return _minOccurs; } - - public void setMinOccurs(BigInteger min) - { mutate(); _minOccurs = min; _intMinOccurs = pegBigInteger(min); } - - public int getIntMinOccurs() - { return _intMinOccurs; } - - public BigInteger getMaxOccurs() - { return _maxOccurs; } - - public int getIntMaxOccurs() - { return _intMaxOccurs; } - - public void setMaxOccurs(BigInteger max) - { mutate(); _maxOccurs = max; _intMaxOccurs = pegBigInteger(max); } - - public SchemaParticle[] getParticleChildren() - { - if (_particleChildren == null) - { - assert _particleType != SchemaParticle.ALL && - _particleType != SchemaParticle.SEQUENCE && - _particleType != SchemaParticle.CHOICE; - return null; - } - SchemaParticle[] result = new SchemaParticle[_particleChildren.length]; - System.arraycopy(_particleChildren, 0, result, 0, _particleChildren.length); - return result; - } - - public void setParticleChildren(SchemaParticle[] children) - { mutate(); _particleChildren = children; } - - public SchemaParticle getParticleChild(int i) - { return _particleChildren[i]; } - - public int countOfParticleChild() - { return _particleChildren == null ? 0 : _particleChildren.length; } - - public void setWildcardSet(QNameSet set) - { mutate(); _wildcardSet = set; } - - public QNameSet getWildcardSet() - { return _wildcardSet; } - - public void setWildcardProcess(int process) - { mutate(); _wildcardProcess = process; } - - public int getWildcardProcess() - { return _wildcardProcess; } - - private static final BigInteger _maxint = BigInteger.valueOf(Integer.MAX_VALUE); - - private static final int pegBigInteger(BigInteger bi) - { - if (bi == null) - return Integer.MAX_VALUE; - if (bi.signum() <= 0) - return 0; - if (bi.compareTo(_maxint) >= 0) - return Integer.MAX_VALUE; - return bi.intValue(); - } - - public QName getName() - { return _qName; } - - public void setNameAndTypeRef(QName formname, SchemaType.Ref typeref) - { mutate(); _qName = formname; _typeref = typeref; } - - public boolean isTypeResolved() - { - return (_typeref != null); - } - - public void resolveTypeRef(SchemaType.Ref typeref) - { - if (_typeref != null) - throw new IllegalStateException(); - _typeref = typeref; - } - - public boolean isAttribute() - { return false; } - - public SchemaType getType() - { if (_typeref == null) return null; return _typeref.get(); } - - public String getDefaultText() - { return _defaultText; } - - public boolean isDefault() - { return _isDefault; } - - public boolean isFixed() - { return _isFixed; } - - public void setDefault(String deftext, boolean isFixed, XmlObject parseObject) - { - mutate(); - _defaultText = deftext; - _isDefault = (deftext != null); - _isFixed = isFixed; - _parseObject = parseObject; - } - - public boolean isNillable() - { return _isNillable; } - - public void setNillable(boolean nillable) - { mutate(); _isNillable = nillable; } - - public XmlAnySimpleType getDefaultValue() - { - if (_defaultValue != null) - return _defaultValue.get(); - if (_defaultText != null && XmlAnySimpleType.type.isAssignableFrom(getType())) - { - if (_parseObject != null && XmlQName.type.isAssignableFrom(getType())) - { - try - { - NamespaceContext.push(new NamespaceContext(_parseObject)); - return getType().newValue(_defaultText); - } - finally - { - NamespaceContext.pop(); - } - } - return getType().newValue(_defaultText); - } - return null; - } - - public void setDefaultValue(XmlValueRef defaultRef) - { - mutate(); - _defaultValue = defaultRef; - } - - public Object getUserData() - { - return _userData; - } - - public void setUserData(Object data) - { - _userData = data; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java deleted file mode 100644 index 0e6e20c..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java +++ /dev/null @@ -1,2859 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import java.io.Writer; -import java.io.IOException; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; - -import javax.xml.namespace.QName; -import org.apache.xmlbeans.impl.common.NameUtil; -import org.apache.xmlbeans.PrePostExtension; -import org.apache.xmlbeans.InterfaceExtension; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.SchemaStringEnumEntry; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SchemaCodePrinter; - -/** - * Prints the java code for a single schema type - */ -public final class SchemaTypeCodePrinter implements SchemaCodePrinter -{ - Writer _writer; - int _indent; - boolean _useJava15; - - - static final String LINE_SEPARATOR = - SystemProperties.getProperty("line.separator") == null - ? "\n" - : SystemProperties.getProperty("line.separator"); - - static final String MAX_SPACES = " "; - static final int INDENT_INCREMENT = 4; - - public static final String INDEX_CLASSNAME = "TypeSystemHolder"; - - public static void printTypeImpl ( Writer writer, SchemaType sType, - XmlOptions opt ) - throws IOException - { - getPrinter(opt).printTypeImpl( writer, sType ); - } - - public static void printType ( Writer writer, SchemaType sType, - XmlOptions opt ) - throws IOException - { - getPrinter(opt).printType( writer, sType ); - } - - /** @deprecated */ - public static void printLoader ( Writer writer, SchemaTypeSystem system, - XmlOptions opt ) - throws IOException - { - getPrinter(opt).printLoader( writer, system ); - } - - private static SchemaCodePrinter getPrinter(XmlOptions opt) - { - Object printer = XmlOptions.safeGet - (opt, XmlOptions.SCHEMA_CODE_PRINTER); - if (printer == null || !(printer instanceof SchemaCodePrinter)) - { - printer = new SchemaTypeCodePrinter(opt); - } - return (SchemaCodePrinter) printer; - } - - public SchemaTypeCodePrinter (XmlOptions opt) - { - _indent = 0; - - String genversion = null; - - if (opt != null && XmlOptions.hasOption(opt, XmlOptions.GENERATE_JAVA_VERSION)) - genversion = (String)opt.get(XmlOptions.GENERATE_JAVA_VERSION); - - if (genversion == null) - genversion = XmlOptions.GENERATE_JAVA_14; - - _useJava15 = XmlOptions.GENERATE_JAVA_15.equals(genversion); - } - - void indent() - { - _indent += INDENT_INCREMENT; - } - - void outdent() - { - _indent -= INDENT_INCREMENT; - } - - String encodeString ( String s ) - { - StringBuffer sb = new StringBuffer(); - - sb.append( '"' ); - - for ( int i = 0 ; i < s.length() ; i++ ) - { - char ch = s.charAt( i ); - - if (ch == '"') - { - sb.append( '\\' ); - sb.append( '\"' ); - } - else if (ch == '\\') - { - sb.append( '\\' ); - sb.append( '\\' ); - } - else if (ch == '\r') - { - sb.append( '\\' ); - sb.append( 'r' ); - } - else if (ch == '\n') - { - sb.append( '\\' ); - sb.append( 'n' ); - } - else if (ch == '\t') - { - sb.append( '\\' ); - sb.append( 't' ); - } - else - sb.append( ch ); - } - - sb.append( '"' ); - - return sb.toString(); - } - - void emit(String s) throws IOException - { - int indent = _indent; - - if (indent > MAX_SPACES.length() / 2) - indent = MAX_SPACES.length() / 4 + indent / 2; - - if (indent > MAX_SPACES.length()) - indent = MAX_SPACES.length(); - - _writer.write(MAX_SPACES.substring(0, indent)); - try - { - _writer.write(s); - } - catch (CharacterCodingException cce) - { - _writer.write(makeSafe(s)); - } - _writer.write(LINE_SEPARATOR); - - // System.out.print(MAX_SPACES.substring(0, indent)); - // System.out.println(s); - } - - private static String makeSafe(String s) - { - Charset charset = Charset.forName(System.getProperty("file.encoding")); - if (charset == null) - throw new IllegalStateException("Default character set is null!"); - CharsetEncoder cEncoder = charset.newEncoder(); - StringBuffer result = new StringBuffer(); - int i; - for (i = 0; i < s.length(); i++) - { - char c = s.charAt(i); - if (!cEncoder.canEncode(c)) - break; - } - for (; i < s.length(); i++) - { - char c = s.charAt(i); - if (cEncoder.canEncode(c)) - result.append(c); - else - { - String hexValue = Integer.toHexString((int) c); - switch (hexValue.length()) - { - case 1: - result.append("\\u000").append(hexValue); break; - case 2: - result.append("\\u00").append(hexValue); break; - case 3: - result.append("\\u0").append(hexValue); break; - case 4: - result.append("\\u").append(hexValue); break; - default: - throw new IllegalStateException(); - } - } - } - return result.toString(); - } - - public void printType(Writer writer, SchemaType sType) throws IOException - { - _writer = writer; - printTopComment(sType); - printPackage(sType, true); - emit(""); - printInnerType(sType, sType.getTypeSystem()); - _writer.flush(); - } - - public void printTypeImpl(Writer writer, SchemaType sType) - throws IOException - { - _writer = writer; - printTopComment(sType); - printPackage(sType, false); - printInnerTypeImpl(sType, sType.getTypeSystem(), false); - } - - /** - * Since not all schema types have java types, this skips - * over any that don't and gives you the nearest java base type. - */ - String findJavaType ( SchemaType sType ) - { - while ( sType.getFullJavaName() == null ) - sType = sType.getBaseType(); - - return sType.getFullJavaName(); - } - - static String prettyQName(QName qname) - { - String result = qname.getLocalPart(); - if (qname.getNamespaceURI() != null) - result += "(@" + qname.getNamespaceURI() + ")"; - return result; - } - - void printInnerTypeJavaDoc(SchemaType sType) throws IOException - { - QName name = sType.getName(); - if (name == null) - { - if (sType.isDocumentType()) - name = sType.getDocumentElementName(); - else if (sType.isAttributeType()) - name = sType.getAttributeTypeAttributeName(); - else if (sType.getContainerField() != null) - name = sType.getContainerField().getName(); - } - - emit("/**"); - if (sType.isDocumentType()) - emit(" * A document containing one " + prettyQName(name) + " element."); - else if (sType.isAttributeType()) - emit(" * A document containing one " + prettyQName(name) + " attribute."); - else if (name != null) - emit(" * An XML " + prettyQName(name) + "."); - else - emit(" * An anonymous inner XML type."); - emit(" *"); - switch (sType.getSimpleVariety()) - { - case SchemaType.NOT_SIMPLE: - emit(" * This is a complex type."); - break; - case SchemaType.ATOMIC: - emit(" * This is an atomic type that is a restriction of " + getFullJavaName(sType) + "."); - break; - case SchemaType.LIST: - emit(" * This is a list type whose items are " + sType.getListItemType().getFullJavaName() + "."); - break; - case SchemaType.UNION: - emit(" * This is a union type. Instances are of one of the following types:"); - SchemaType[] members = sType.getUnionConstituentTypes(); - for (int i = 0; i < members.length; i++) - emit(" * " + members[i].getFullJavaName()); - break; - } - emit(" */"); - } - - private String getFullJavaName(SchemaType sType) - { - - SchemaTypeImpl sTypeI = (SchemaTypeImpl) sType; - String ret = sTypeI.getFullJavaName(); - - while (sTypeI.isRedefinition()) - { - ret = sTypeI.getFullJavaName(); - sTypeI = (SchemaTypeImpl) sTypeI.getBaseType(); - } - return ret; - } - - private String getUserTypeStaticHandlerMethod(boolean encode, SchemaTypeImpl stype) - { - String unqualifiedName = stype.getName().getLocalPart(); - if (unqualifiedName.length() < 2) - unqualifiedName = unqualifiedName.toUpperCase(); - else - unqualifiedName = unqualifiedName.substring(0, 1).toUpperCase() + unqualifiedName.substring(1); - - if (encode) - return stype.getUserTypeHandlerName() + ".encode" + unqualifiedName; - else - return stype.getUserTypeHandlerName() + ".decode" + unqualifiedName; - } - - - public static String indexClassForSystem(SchemaTypeSystem system) - { - String name = system.getName(); - return name + "." + INDEX_CLASSNAME; - } - - static String shortIndexClassForSystem(SchemaTypeSystem system) - { - return INDEX_CLASSNAME; - } - - void printStaticTypeDeclaration(SchemaType sType, SchemaTypeSystem system) throws IOException - { - String interfaceShortName = sType.getShortJavaName(); - emit("public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)"); - indent(); - emit("org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(" + - interfaceShortName + ".class.getClassLoader(), \"" + system.getName() + "\")" + - ".resolveHandle(\"" + - ((SchemaTypeSystemImpl)system).handleForType(sType) + "\");"); - outdent(); - } - - /** @deprecated */ - public void printLoader(Writer writer, SchemaTypeSystem system) - throws IOException - { - // deprecated - } - - void printInnerType(SchemaType sType, SchemaTypeSystem system) throws IOException - { - emit(""); - - printInnerTypeJavaDoc(sType); - - startInterface(sType); - - printStaticTypeDeclaration(sType, system); - - if (sType.isSimpleType()) - { - if (sType.hasStringEnumValues()) - printStringEnumeration(sType); - } - else - { - if (sType.getContentType() == SchemaType.SIMPLE_CONTENT && sType.hasStringEnumValues()) - printStringEnumeration(sType); - - SchemaProperty[] props = getDerivedProperties(sType); - - for (int i = 0; i < props.length; i++) - { - SchemaProperty prop = props[i]; - - printPropertyGetters( - prop.getName(), - prop.isAttribute(), - prop.getJavaPropertyName(), - prop.getJavaTypeCode(), - javaTypeForProperty(prop), - xmlTypeForProperty(prop), - prop.hasNillable() != SchemaProperty.NEVER, - prop.extendsJavaOption(), - prop.extendsJavaArray(), - prop.extendsJavaSingleton() - ); - - if (!prop.isReadOnly()) - { - printPropertySetters( - prop.getName(), - prop.isAttribute(), - prop.getJavaPropertyName(), - prop.getJavaTypeCode(), - javaTypeForProperty(prop), - xmlTypeForProperty(prop), - prop.hasNillable() != SchemaProperty.NEVER, - prop.extendsJavaOption(), - prop.extendsJavaArray(), - prop.extendsJavaSingleton() - ); - } - } - - } - - printNestedInnerTypes(sType, system); - - printFactory(sType); - - endBlock(); - } - - void printFactory(SchemaType sType) throws IOException - { - // Only need full factories for top-level types - boolean fullFactory = true; - if (sType.isAnonymousType() && ! sType.isDocumentType() && !sType.isAttributeType()) - fullFactory = false; - - String fullName = sType.getFullJavaName().replace('$', '.'); - - emit(""); - emit("/**"); - emit(" * A factory class with static methods for creating instances"); - emit(" * of this type."); - emit(" */"); - emit(""); - // BUGBUG - Can I use the name loader here? could it be a - // nested type name? It is lower case! - emit("public static final class Factory"); - emit("{"); - indent(); - - if (sType.isSimpleType()) - { - emit("public static " + fullName + " newValue(java.lang.Object obj) {"); - emit(" return (" + fullName + ") type.newValue( obj ); }"); - emit(""); - } - - // Only need newInstance() for non-abstract types - if (sType.isAbstract()) { - emit("/** @deprecated No need to be able to create instances of abstract types */"); - if (_useJava15) - emit("@Deprecated"); - } - emit("public static " + fullName + " newInstance() {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }"); - emit(""); - - // Only need newInstance() for non-abstract types - if (sType.isAbstract()) { - emit("/** @deprecated No need to be able to create instances of abstract types */"); - if (_useJava15) - emit("@Deprecated"); - } - emit("public static " + fullName + " newInstance(org.apache.xmlbeans.XmlOptions options) {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }"); - emit(""); - - if (fullFactory) - { - emit("/** @param xmlAsString the string value to parse */"); - emit("public static " + fullName + " parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }"); - emit(""); - - emit("/** @param file the file from which to load an xml document */"); - emit("public static " + fullName + " parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }"); - emit(""); - - emit("public static " + fullName + " parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }"); - emit(""); - - emit("public static " + fullName + " parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }"); - emit(""); - - emit("public static " + fullName + " parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }"); - emit(""); - - emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */"); - if (_useJava15) - emit("@Deprecated"); - emit("public static " + fullName + " parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }"); - emit(""); - - emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */"); - if (_useJava15) - emit("@Deprecated"); - emit("public static " + fullName + " parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {"); - emit(" return (" + fullName + ") org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }"); - emit(""); - - // Don't have XMLInputStream anymore - emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */"); - if (_useJava15) - emit("@Deprecated"); - emit("public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {"); - emit(" return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }"); - emit(""); - - // Don't have XMLInputStream anymore - emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */"); - if (_useJava15) - emit("@Deprecated"); - emit("public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {"); - emit(" return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }"); - emit(""); - } - - emit("private Factory() { } // No instance of this class allowed"); - outdent(); - emit("}"); - } - - void printNestedInnerTypes(SchemaType sType, SchemaTypeSystem system) throws IOException - { - boolean redefinition = sType.getName() != null && - sType.getName().equals(sType.getBaseType().getName()); - while (sType != null) - { - SchemaType[] anonTypes = sType.getAnonymousTypes(); - for (int i = 0; i < anonTypes.length; i++) - { - if (anonTypes[i].isSkippedAnonymousType()) - printNestedInnerTypes(anonTypes[i], system); - else - printInnerType(anonTypes[i], system); - } - // For redefinition other than by extension for complex types, go ahead and print - // the anonymous types in the base - if (!redefinition || - (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType())) - break; - sType = sType.getBaseType(); - } - } - - void printTopComment(SchemaType sType) throws IOException - { - emit("/*"); - if (sType.getName() != null) - { - emit(" * XML Type: " + sType.getName().getLocalPart()); - emit(" * Namespace: " + sType.getName().getNamespaceURI()); - } - else - { - QName thename = null; - - if (sType.isDocumentType()) - { - thename = sType.getDocumentElementName(); - emit(" * An XML document type."); - } - else if (sType.isAttributeType()) - { - thename = sType.getAttributeTypeAttributeName(); - emit(" * An XML attribute type."); - } - else - assert false; - - assert( thename != null ); - - emit(" * Localname: " + thename.getLocalPart()); - emit(" * Namespace: " + thename.getNamespaceURI()); - } - emit(" * Java type: " + sType.getFullJavaName()); - emit(" *"); - emit(" * Automatically generated - do not modify."); - emit(" */"); - } - - void printPackage(SchemaType sType, boolean intf) throws IOException - { - String fqjn; - if (intf) - fqjn = sType.getFullJavaName(); - else - fqjn = sType.getFullJavaImplName(); - - int lastdot = fqjn.lastIndexOf('.'); - if (lastdot < 0) - return; - String pkg = fqjn.substring(0, lastdot); - emit("package " + pkg + ";"); - } - - void startInterface(SchemaType sType) throws IOException - { - String shortName = sType.getShortJavaName(); - - String baseInterface = findJavaType(sType.getBaseType()); - - /* - StringBuffer specializedInterfaces = new StringBuffer(); - - if (sType.getSimpleVariety() == SchemaType.ATOMIC && - sType.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) - { - int bits = sType.getDecimalSize(); - if (bits == SchemaType.SIZE_BIG_INTEGER) - specializedInterfaces.append(", org.apache.xmlbeans.BigIntegerValue"); - if (bits == SchemaType.SIZE_LONG) - specializedInterfaces.append(", org.apache.xmlbeans.LongValue"); - if (bits <= SchemaType.SIZE_INT) - specializedInterfaces.append(", org.apache.xmlbeans.IntValue"); - } - if (sType.getSimpleVariety() == SchemaType.LIST) - specializedInterfaces.append(", org.apache.xmlbeans.ListValue"); - - if (sType.getSimpleVariety() == SchemaType.UNION) - { - SchemaType ctype = sType.getUnionCommonBaseType(); - String javaTypeHolder = javaTypeHolderForType(ctype); - if (javaTypeHolder != null) - specializedInterfaces.append(", " + javaTypeHolder); - } - */ - - emit("public interface " + shortName + " extends " + baseInterface + getExtensionInterfaces(sType)); - emit("{"); - indent(); - emitSpecializedAccessors(sType); - } - - private static String getExtensionInterfaces(SchemaType sType) - { - SchemaTypeImpl sImpl = getImpl(sType); - if (sImpl == null) - return ""; - - StringBuffer sb = new StringBuffer(); - - InterfaceExtension[] exts = sImpl.getInterfaceExtensions(); - if (exts != null) for (int i = 0; i < exts.length; i++) - sb.append(", " + exts[i].getInterface()); - - return sb.toString(); - } - - private static SchemaTypeImpl getImpl(SchemaType sType) - { - if (sType instanceof SchemaTypeImpl) - return (SchemaTypeImpl) sType; - else - return null; - } - - private void emitSpecializedAccessors(SchemaType sType) throws IOException - { - if (sType.getSimpleVariety() == SchemaType.ATOMIC && - sType.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) - { - int bits = sType.getDecimalSize(); - int parentBits = sType.getBaseType().getDecimalSize(); - if (bits != parentBits || sType.getBaseType().getFullJavaName() == null) - { - if (bits == SchemaType.SIZE_BIG_INTEGER) - { - emit("java.math.BigInteger getBigIntegerValue();"); - emit("void setBigIntegerValue(java.math.BigInteger bi);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("java.math.BigInteger bigIntegerValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void set(java.math.BigInteger bi);"); - } - else if (bits == SchemaType.SIZE_LONG) - { - emit("long getLongValue();"); - emit("void setLongValue(long l);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("long longValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void set(long l);"); - } - else if (bits == SchemaType.SIZE_INT) - { - emit("int getIntValue();"); - emit("void setIntValue(int i);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("int intValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void set(int i);"); - } - else if (bits == SchemaType.SIZE_SHORT) - { - emit("short getShortValue();"); - emit("void setShortValue(short s);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("short shortValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void set(short s);"); - } - else if (bits == SchemaType.SIZE_BYTE) - { - emit("byte getByteValue();"); - emit("void setByteValue(byte b);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("byte byteValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void set(byte b);"); - } - } - } - - if (sType.getSimpleVariety() == SchemaType.UNION) - { - emit("java.lang.Object getObjectValue();"); - emit("void setObjectValue(java.lang.Object val);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("java.lang.Object objectValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void objectSet(java.lang.Object val);"); - emit("org.apache.xmlbeans.SchemaType instanceType();"); - SchemaType ctype = sType.getUnionCommonBaseType(); - if (ctype != null && ctype.getSimpleVariety() != SchemaType.UNION); - emitSpecializedAccessors(ctype); - } - - if (sType.getSimpleVariety() == SchemaType.LIST) - { - emit("java.util.List getListValue();"); - emit("java.util.List xgetListValue();"); - emit("void setListValue(java.util.List list);"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("java.util.List listValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("java.util.List xlistValue();"); - emit("/** @deprecated */"); - if (_useJava15) - emit("@Deprecated"); - emit("void set(java.util.List list);"); - } - } - - void startBlock() throws IOException - { - emit("{"); - indent(); - } - void endBlock() throws IOException - { - outdent(); - emit("}"); - } - - void printJavaDoc(String sentence) throws IOException - { - emit(""); - emit("/**"); - emit(" * " + sentence); - emit(" */"); - } - - void printShortJavaDoc(String sentence) throws IOException - { - emit("/** " + sentence + " */"); - } - - public static String javaStringEscape(String str) - { - // forbidden: \n, \r, \", \\. - test: { - for (int i = 0; i < str.length(); i++) - { - switch (str.charAt(i)) - { - case '\n': - case '\r': - case '\"': - case '\\': - break test; - } - } - return str; - } - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < str.length(); i++) - { - char ch = str.charAt(i); - switch (ch) - { - default: - sb.append(ch); - break; - case '\n': - sb.append("\\n"); - break; - case '\r': - sb.append("\\r"); - break; - case '\"': - sb.append("\\\""); - break; - case '\\': - sb.append("\\\\"); - break; - } - } - return sb.toString(); - } - - void printStringEnumeration(SchemaType sType) throws IOException - { - SchemaType baseEnumType = sType.getBaseEnumType(); - String baseEnumClass = baseEnumType.getFullJavaName(); - boolean hasBase = hasBase(sType); - - if (!hasBase) - { - emit(""); - emit("org.apache.xmlbeans.StringEnumAbstractBase enumValue();"); - emit("void set(org.apache.xmlbeans.StringEnumAbstractBase e);"); - } - - emit(""); - SchemaStringEnumEntry[] entries = sType.getStringEnumEntries(); - HashSet seenValues = new HashSet(); - HashSet repeatValues = new HashSet(); - for (int i = 0; i < entries.length; i++) - { - String enumValue = entries[i].getString(); - if (seenValues.contains(enumValue)) - { - repeatValues.add(enumValue); - continue; - } - else - seenValues.add(enumValue); - String constName = entries[i].getEnumName(); - if (hasBase) - emit("static final " + baseEnumClass + ".Enum " + constName + " = " + baseEnumClass + "." + constName + ";"); - else - emit("static final Enum " + constName + " = Enum.forString(\"" + javaStringEscape(enumValue) + "\");"); - } - emit(""); - for (int i = 0; i < entries.length; i++) - { - if (repeatValues.contains(entries[i].getString())) - continue; - String constName = "INT_" + entries[i].getEnumName(); - if (hasBase) - emit("static final int " + constName + " = " + baseEnumClass + "." + constName + ";"); - else - emit("static final int " + constName + " = Enum." + constName + ";"); - } - if (!hasBase) - { - emit(""); - emit("/**"); - emit(" * Enumeration value class for " + baseEnumClass + "."); - emit(" * These enum values can be used as follows:"); - emit(" *
      ");
      -            emit(" * enum.toString(); // returns the string value of the enum");
      -            emit(" * enum.intValue(); // returns an int value, useful for switches");
      -            if (entries.length > 0)
      -            emit(" * // e.g., case Enum.INT_" + entries[0].getEnumName());
      -            emit(" * Enum.forString(s); // returns the enum value for a string");
      -            emit(" * Enum.forInt(i); // returns the enum value for an int");
      -            emit(" * 
      "); - emit(" * Enumeration objects are immutable singleton objects that"); - emit(" * can be compared using == object equality. They have no"); - emit(" * public constructor. See the constants defined within this"); - emit(" * class for all the valid values."); - emit(" */"); - emit("static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase"); - emit("{"); - indent(); - emit("/**"); - emit(" * Returns the enum value for a string, or null if none."); - emit(" */"); - emit("public static Enum forString(java.lang.String s)"); - emit(" { return (Enum)table.forString(s); }"); - emit("/**"); - emit(" * Returns the enum value corresponding to an int, or null if none."); - emit(" */"); - emit("public static Enum forInt(int i)"); - emit(" { return (Enum)table.forInt(i); }"); - emit(""); - emit("private Enum(java.lang.String s, int i)"); - emit(" { super(s, i); }"); - emit(""); - for (int i = 0; i < entries.length; i++) - { - String constName = "INT_" + entries[i].getEnumName(); - int intValue = entries[i].getIntValue(); - emit("static final int " + constName + " = " + intValue + ";"); - } - emit(""); - emit("public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table ="); - emit(" new org.apache.xmlbeans.StringEnumAbstractBase.Table"); - emit("("); - indent(); - emit("new Enum[]"); - emit("{"); - indent(); - for (int i = 0; i < entries.length; i++) - { - String enumValue = entries[i].getString(); - String constName = "INT_" + entries[i].getEnumName(); - emit("new Enum(\"" + javaStringEscape(enumValue) + "\", " + constName + "),"); - } - outdent(); - emit("}"); - outdent(); - emit(");"); - emit("private static final long serialVersionUID = 1L;"); - emit("private java.lang.Object readResolve() { return forInt(intValue()); } "); - outdent(); - emit("}"); - } - } - - private boolean hasBase(SchemaType sType) - { - boolean hasBase; - SchemaType baseEnumType = sType.getBaseEnumType(); - if (baseEnumType.isAnonymousType() && baseEnumType.isSkippedAnonymousType()) - { - if (sType.getContentBasedOnType() != null) - hasBase = sType.getContentBasedOnType().getBaseType() != baseEnumType; - else - hasBase = sType.getBaseType() != baseEnumType; - } - else - hasBase = baseEnumType != sType; - return hasBase; - } - - String xmlTypeForProperty(SchemaProperty sProp) - { - SchemaType sType = sProp.javaBasedOnType(); - return findJavaType(sType).replace('$', '.'); - } - - static boolean xmlTypeForPropertyIsUnion(SchemaProperty sProp) - { - SchemaType sType = sProp.javaBasedOnType(); - return (sType.isSimpleType() && sType.getSimpleVariety() == SchemaType.UNION); - } - - static boolean isJavaPrimitive(int javaType) - { - return (javaType < SchemaProperty.JAVA_FIRST_PRIMITIVE ? false : - (javaType > SchemaProperty.JAVA_LAST_PRIMITIVE ? false : true)); - } - - /** Returns the wrapped type for a java primitive. */ - static String javaWrappedType(int javaType) - { - switch (javaType) - { - case SchemaProperty.JAVA_BOOLEAN: - return "java.lang.Boolean"; - case SchemaProperty.JAVA_FLOAT: - return "java.lang.Float"; - case SchemaProperty.JAVA_DOUBLE: - return "java.lang.Double"; - case SchemaProperty.JAVA_BYTE: - return "java.lang.Byte"; - case SchemaProperty.JAVA_SHORT: - return "java.lang.Short"; - case SchemaProperty.JAVA_INT: - return "java.lang.Integer"; - case SchemaProperty.JAVA_LONG: - return "java.lang.Long"; - - // anything else is not a java primitive - default: - assert false; - throw new IllegalStateException(); - } - } - - String javaTypeForProperty(SchemaProperty sProp) - { - // The type to use is the XML object.... - if (sProp.getJavaTypeCode() == SchemaProperty.XML_OBJECT) - { - SchemaType sType = sProp.javaBasedOnType(); - return findJavaType(sType).replace('$', '.'); - } - - if (sProp.getJavaTypeCode() == SchemaProperty.JAVA_USER) - { - return ((SchemaTypeImpl)sProp.getType()).getUserTypeName(); - } - - switch (sProp.getJavaTypeCode()) - { - case SchemaProperty.JAVA_BOOLEAN: - return "boolean"; - case SchemaProperty.JAVA_FLOAT: - return "float"; - case SchemaProperty.JAVA_DOUBLE: - return "double"; - case SchemaProperty.JAVA_BYTE: - return "byte"; - case SchemaProperty.JAVA_SHORT: - return "short"; - case SchemaProperty.JAVA_INT: - return "int"; - case SchemaProperty.JAVA_LONG: - return "long"; - - case SchemaProperty.JAVA_BIG_DECIMAL: - return "java.math.BigDecimal"; - case SchemaProperty.JAVA_BIG_INTEGER: - return "java.math.BigInteger"; - case SchemaProperty.JAVA_STRING: - return "java.lang.String"; - case SchemaProperty.JAVA_BYTE_ARRAY: - return "byte[]"; - case SchemaProperty.JAVA_GDATE: - return "org.apache.xmlbeans.GDate"; - case SchemaProperty.JAVA_GDURATION: - return "org.apache.xmlbeans.GDuration"; - case SchemaProperty.JAVA_DATE: - return "java.util.Date"; - case SchemaProperty.JAVA_QNAME: - return "javax.xml.namespace.QName"; - case SchemaProperty.JAVA_LIST: - return "java.util.List"; - case SchemaProperty.JAVA_CALENDAR: - return "java.util.Calendar"; - - case SchemaProperty.JAVA_ENUM: - SchemaType sType = sProp.javaBasedOnType(); - if (sType.getSimpleVariety() == SchemaType.UNION) - sType = sType.getUnionCommonBaseType(); - assert sType.getBaseEnumType() != null; - if (hasBase(sType)) - return findJavaType(sType.getBaseEnumType()).replace('$', '.') + ".Enum"; - else - return findJavaType(sType).replace('$', '.') + ".Enum"; - - case SchemaProperty.JAVA_OBJECT: - return "java.lang.Object"; - - default: - assert(false); - throw new IllegalStateException(); - } - } - - void printPropertyGetters(QName qName, boolean isAttr, - String propertyName, int javaType, - String type, String xtype, - boolean nillable, boolean optional, - boolean several, boolean singleton) - throws IOException - { - String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); - boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); - - if (singleton) - { - printJavaDoc((several ? "Gets first " : "Gets the ") + propdesc); - emit(type + " get" + propertyName + "();"); - - if (!xmltype) - { - printJavaDoc((several ? "Gets (as xml) first " : "Gets (as xml) the ") + propdesc); - emit(xtype + " xget" + propertyName + "();"); - } - - if (nillable) - { - printJavaDoc((several ? "Tests for nil first " : "Tests for nil ") + propdesc); - emit("boolean isNil" + propertyName + "();"); - } - } - - if (optional) - { - printJavaDoc((several ? "True if has at least one " : "True if has ") + propdesc); - emit("boolean isSet" + propertyName + "();"); - } - - if (several) - { - String arrayName = propertyName + "Array"; - - if (_useJava15) - { - String wrappedType = type; - if (isJavaPrimitive(javaType)) - wrappedType = javaWrappedType(javaType); - - printJavaDoc("Gets a List of " + propdesc + "s"); - emit("java.util.List<" + wrappedType + "> get" + propertyName + "List();"); - } - - if (_useJava15) - { - emit(""); - emit("/**"); - emit(" * Gets array of all " + propdesc + "s"); - emit(" * @deprecated"); - emit(" */"); - emit("@Deprecated"); - } - else - printJavaDoc("Gets array of all " + propdesc + "s"); - emit(type + "[] get" + arrayName + "();"); - - printJavaDoc("Gets ith " + propdesc); - emit(type + " get" + arrayName + "(int i);"); - - if (!xmltype) - { - if (_useJava15) - { - printJavaDoc("Gets (as xml) a List of " + propdesc + "s"); - emit("java.util.List<" + xtype + "> xget" + propertyName + "List();"); - } - - if (_useJava15) - { - emit(""); - emit("/**"); - emit(" * Gets (as xml) array of all " + propdesc + "s"); - emit(" * @deprecated"); - emit(" */"); - emit("@Deprecated"); - } - else - printJavaDoc("Gets (as xml) array of all " + propdesc + "s"); - emit(xtype + "[] xget" + arrayName + "();"); - - printJavaDoc("Gets (as xml) ith " + propdesc); - emit(xtype + " xget" + arrayName + "(int i);"); - } - - if (nillable) - { - printJavaDoc("Tests for nil ith " + propdesc); - emit("boolean isNil" + arrayName + "(int i);"); - } - - printJavaDoc("Returns number of " + propdesc); - emit("int sizeOf" + arrayName + "();"); - } - } - - void printPropertySetters(QName qName, boolean isAttr, - String propertyName, int javaType, String type, String xtype, - boolean nillable, boolean optional, - boolean several, boolean singleton) - throws IOException - { - String safeVarName = NameUtil.nonJavaKeyword(NameUtil.lowerCamelCase(propertyName)); - if (safeVarName.equals("i")) - safeVarName = "iValue"; - boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); - - String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); - - if (singleton) - { - printJavaDoc((several ? "Sets first " : "Sets the ") + propdesc); - emit("void set" + propertyName + "(" + type + " " + safeVarName + ");"); - - if (!xmltype) - { - printJavaDoc((several ? "Sets (as xml) first " : "Sets (as xml) the ") + propdesc); - emit("void xset" + propertyName + "(" + xtype + " " + safeVarName + ");"); - } - - if (xmltype && !several) - { - printJavaDoc("Appends and returns a new empty " + propdesc); - emit(xtype + " addNew" + propertyName + "();"); - } - - if (nillable) - { - printJavaDoc((several ? "Nils the first " : "Nils the ") + propdesc); - emit("void setNil" + propertyName + "();"); - } - } - - if (optional) - { - printJavaDoc((several ? "Removes first " : "Unsets the ") + propdesc); - emit("void unset" + propertyName + "();"); - } - - if (several) - { - String arrayName = propertyName + "Array"; - - printJavaDoc("Sets array of all " + propdesc); - emit("void set" + arrayName + "(" + type + "[] " + safeVarName + "Array);"); - - printJavaDoc("Sets ith " + propdesc); - emit("void set" + arrayName + "(int i, " + type + " " + safeVarName + ");"); - - if (!xmltype) - { - printJavaDoc("Sets (as xml) array of all " + propdesc); - emit("void xset" + arrayName + "(" + xtype + "[] " + safeVarName + "Array);"); - - printJavaDoc("Sets (as xml) ith " + propdesc); - emit("void xset" + arrayName + "(int i, " + xtype + " " + safeVarName + ");"); - } - - if (nillable) - { - printJavaDoc("Nils the ith " + propdesc); - emit("void setNil" + arrayName + "(int i);"); - } - - if (!xmltype) - { - printJavaDoc("Inserts the value as the ith " + propdesc); - emit("void insert" + propertyName + "(int i, " + type + " " + safeVarName + ");"); - - printJavaDoc("Appends the value as the last " + propdesc); - emit("void add" + propertyName + "(" + type + " " + safeVarName + ");"); - } - - printJavaDoc("Inserts and returns a new empty value (as xml) as the ith " + propdesc); - emit(xtype + " insertNew" + propertyName + "(int i);"); - - printJavaDoc("Appends and returns a new empty value (as xml) as the last " + propdesc); - emit(xtype + " addNew" + propertyName + "();"); - - printJavaDoc("Removes the ith " + propdesc); - emit("void remove" + propertyName + "(int i);"); - } - } - - String getAtomicRestrictionType(SchemaType sType) { - SchemaType pType = sType.getPrimitiveType(); - switch (pType.getBuiltinTypeCode()) - { - case SchemaType.BTC_ANY_SIMPLE: - return "org.apache.xmlbeans.impl.values.XmlAnySimpleTypeImpl"; - case SchemaType.BTC_BOOLEAN: - return "org.apache.xmlbeans.impl.values.JavaBooleanHolderEx"; - case SchemaType.BTC_BASE_64_BINARY: - return "org.apache.xmlbeans.impl.values.JavaBase64HolderEx"; - case SchemaType.BTC_HEX_BINARY: - return "org.apache.xmlbeans.impl.values.JavaHexBinaryHolderEx"; - case SchemaType.BTC_ANY_URI: - return "org.apache.xmlbeans.impl.values.JavaUriHolderEx"; - case SchemaType.BTC_QNAME: - return "org.apache.xmlbeans.impl.values.JavaQNameHolderEx"; - case SchemaType.BTC_NOTATION: - return "org.apache.xmlbeans.impl.values.JavaNotationHolderEx"; - case SchemaType.BTC_FLOAT: - return "org.apache.xmlbeans.impl.values.JavaFloatHolderEx"; - case SchemaType.BTC_DOUBLE: - return "org.apache.xmlbeans.impl.values.JavaDoubleHolderEx"; - case SchemaType.BTC_DECIMAL: - switch (sType.getDecimalSize()) - { - default: - assert(false); - case SchemaType.SIZE_BIG_DECIMAL: - return "org.apache.xmlbeans.impl.values.JavaDecimalHolderEx"; - case SchemaType.SIZE_BIG_INTEGER: - return "org.apache.xmlbeans.impl.values.JavaIntegerHolderEx"; - case SchemaType.SIZE_LONG: - return "org.apache.xmlbeans.impl.values.JavaLongHolderEx"; - case SchemaType.SIZE_INT: - case SchemaType.SIZE_SHORT: - case SchemaType.SIZE_BYTE: - return "org.apache.xmlbeans.impl.values.JavaIntHolderEx"; - } - case SchemaType.BTC_STRING: - if (sType.hasStringEnumValues()) - return "org.apache.xmlbeans.impl.values.JavaStringEnumerationHolderEx"; - else - return "org.apache.xmlbeans.impl.values.JavaStringHolderEx"; - - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - return "org.apache.xmlbeans.impl.values.JavaGDateHolderEx"; - - case SchemaType.BTC_DURATION: - return "org.apache.xmlbeans.impl.values.JavaGDurationHolderEx"; - default: - assert(false) : "unrecognized primitive type"; - return null; - } - } - - static SchemaType findBaseType(SchemaType sType) - { - while (sType.getFullJavaName() == null) - sType = sType.getBaseType(); - return sType; - } - - String getBaseClass(SchemaType sType) { - SchemaType baseType = findBaseType(sType.getBaseType()); - - switch (sType.getSimpleVariety()) - { - case SchemaType.NOT_SIMPLE: - // non-simple-content: inherit from base type impl - if (!XmlObject.type.equals(baseType)) - return baseType.getFullJavaImplName(); - return "org.apache.xmlbeans.impl.values.XmlComplexContentImpl"; - - case SchemaType.ATOMIC: - // We should only get called for restrictions - assert(! sType.isBuiltinType()); - return getAtomicRestrictionType(sType); - - case SchemaType.LIST: - return "org.apache.xmlbeans.impl.values.XmlListImpl"; - - case SchemaType.UNION: - return "org.apache.xmlbeans.impl.values.XmlUnionImpl"; - - default: - throw new IllegalStateException(); - } - } - - void printConstructor(SchemaType sType, String shortName) throws IOException { - emit(""); - emit("public " + shortName + "(org.apache.xmlbeans.SchemaType sType)"); - startBlock(); - emit("super(sType" + (sType.getSimpleVariety() == SchemaType.NOT_SIMPLE ? - "": - ", " + !sType.isSimpleType()) + - ");"); - endBlock(); - - if (sType.getSimpleVariety() != SchemaType.NOT_SIMPLE) - { - emit(""); - emit("protected " + shortName + "(org.apache.xmlbeans.SchemaType sType, boolean b)"); - startBlock(); - emit("super(sType, b);"); - endBlock(); - } - } - - void startClass(SchemaType sType, boolean isInner) throws IOException - { - String shortName = sType.getShortJavaImplName(); - String baseClass = getBaseClass(sType); - StringBuffer interfaces = new StringBuffer(); - interfaces.append(sType.getFullJavaName().replace('$', '.')); - - if (sType.getSimpleVariety() == SchemaType.UNION) { - SchemaType[] memberTypes = sType.getUnionMemberTypes(); - for (int i = 0 ; i < memberTypes.length ; i++) - interfaces.append(", " + memberTypes[i].getFullJavaName().replace('$', '.')); - } - - emit("public " + ( isInner ? "static ": "" ) + "class " + shortName + - " extends " + baseClass + " implements " + interfaces.toString()); - - startBlock(); - - emit("private static final long serialVersionUID = 1L;"); - } - - void makeAttributeDefaultValue(String jtargetType, SchemaProperty prop, String identifier) throws IOException - { - String fullName = jtargetType; - if (fullName == null) - fullName = prop.javaBasedOnType().getFullJavaName().replace('$', '.'); - - emit("target = (" + fullName + ")get_default_attribute_value(" + identifier + ");"); - } - - void makeMissingValue(int javaType) throws IOException - { - switch (javaType) - { - case SchemaProperty.JAVA_BOOLEAN: - emit("return false;"); break; - - case SchemaProperty.JAVA_FLOAT: - emit("return 0.0f;"); break; - - case SchemaProperty.JAVA_DOUBLE: - emit("return 0.0;"); break; - - case SchemaProperty.JAVA_BYTE: - case SchemaProperty.JAVA_SHORT: - case SchemaProperty.JAVA_INT: - emit("return 0;"); break; - - case SchemaProperty.JAVA_LONG: - emit("return 0L;"); break; - - default: - case SchemaProperty.XML_OBJECT: - case SchemaProperty.JAVA_BIG_DECIMAL: - case SchemaProperty.JAVA_BIG_INTEGER: - case SchemaProperty.JAVA_STRING: - case SchemaProperty.JAVA_BYTE_ARRAY: - case SchemaProperty.JAVA_GDATE: - case SchemaProperty.JAVA_GDURATION: - case SchemaProperty.JAVA_DATE: - case SchemaProperty.JAVA_QNAME: - case SchemaProperty.JAVA_LIST: - case SchemaProperty.JAVA_CALENDAR: - case SchemaProperty.JAVA_ENUM: - case SchemaProperty.JAVA_OBJECT: - emit("return null;"); break; - } - } - - void printJGetArrayValue(int javaType, String type, SchemaTypeImpl stype) throws IOException { - switch (javaType) - { - case SchemaProperty.XML_OBJECT: - emit(type + "[] result = new " + type + "[targetList.size()];"); - emit("targetList.toArray(result);"); - break; - - case SchemaProperty.JAVA_ENUM: - emit(type + "[] result = new " + type + "[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = (" + type + ")((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getEnumValue();"); - break; - - case SchemaProperty.JAVA_BOOLEAN: - emit("boolean[] result = new boolean[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getBooleanValue();"); - break; - - case SchemaProperty.JAVA_FLOAT: - emit("float[] result = new float[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getFloatValue();"); - break; - - case SchemaProperty.JAVA_DOUBLE: - emit("double[] result = new double[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getDoubleValue();"); - break; - - case SchemaProperty.JAVA_BYTE: - emit("byte[] result = new byte[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getByteValue();"); - break; - - case SchemaProperty.JAVA_SHORT: - emit("short[] result = new short[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getShortValue();"); - break; - - case SchemaProperty.JAVA_INT: - emit("int[] result = new int[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getIntValue();"); - break; - - case SchemaProperty.JAVA_LONG: - emit("long[] result = new long[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getLongValue();"); - break; - - case SchemaProperty.JAVA_BIG_DECIMAL: - emit("java.math.BigDecimal[] result = new java.math.BigDecimal[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getBigDecimalValue();"); - break; - - case SchemaProperty.JAVA_BIG_INTEGER: - emit("java.math.BigInteger[] result = new java.math.BigInteger[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getBigIntegerValue();"); - break; - - case SchemaProperty.JAVA_STRING: - emit("java.lang.String[] result = new java.lang.String[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getStringValue();"); - break; - - case SchemaProperty.JAVA_BYTE_ARRAY: - emit("byte[][] result = new byte[targetList.size()][];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getByteArrayValue();"); - break; - - case SchemaProperty.JAVA_CALENDAR: - emit("java.util.Calendar[] result = new java.util.Calendar[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getCalendarValue();"); - break; - - case SchemaProperty.JAVA_DATE: - emit("java.util.Date[] result = new java.util.Date[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getDateValue();"); - break; - - case SchemaProperty.JAVA_GDATE: - emit("org.apache.xmlbeans.GDate[] result = new org.apache.xmlbeans.GDate[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getGDateValue();"); - break; - - case SchemaProperty.JAVA_GDURATION: - emit("org.apache.xmlbeans.GDuration[] result = new org.apache.xmlbeans.GDuration[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getGDurationValue();"); - break; - - case SchemaProperty.JAVA_QNAME: - emit("javax.xml.namespace.QName[] result = new javax.xml.namespace.QName[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getQNameValue();"); - break; - - case SchemaProperty.JAVA_LIST: - emit("java.util.List[] result = new java.util.List[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getListValue();"); - break; - - case SchemaProperty.JAVA_OBJECT: - emit("java.lang.Object[] result = new java.lang.Object[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = ((org.apache.xmlbeans.SimpleValue)targetList.get(i)).getObjectValue();"); - break; - - case SchemaProperty.JAVA_USER: - emit(stype.getUserTypeName() + "[] result = new " + stype.getUserTypeName() + "[targetList.size()];"); - emit("for (int i = 0, len = targetList.size() ; i < len ; i++)"); - emit(" result[i] = " + getUserTypeStaticHandlerMethod(false, stype) - + "((org.apache.xmlbeans.SimpleValue)targetList.get(i));"); - break; - - default: - throw new IllegalStateException(); - } - emit("return result;"); - } - void printJGetValue(int javaType, String type, SchemaTypeImpl stype) throws IOException { - switch (javaType) - { - case SchemaProperty.XML_OBJECT: - emit("return target;"); break; - - case SchemaProperty.JAVA_BOOLEAN: - emit("return target.getBooleanValue();"); break; - - case SchemaProperty.JAVA_FLOAT: - emit("return target.getFloatValue();"); break; - - case SchemaProperty.JAVA_DOUBLE: - emit("return target.getDoubleValue();"); break; - - case SchemaProperty.JAVA_BYTE: - emit("return target.getByteValue();"); break; - - case SchemaProperty.JAVA_SHORT: - emit("return target.getShortValue();"); break; - - case SchemaProperty.JAVA_INT: - emit("return target.getIntValue();"); break; - - case SchemaProperty.JAVA_LONG: - emit("return target.getLongValue();"); break; - - case SchemaProperty.JAVA_BIG_DECIMAL: - emit("return target.getBigDecimalValue();"); break; - - case SchemaProperty.JAVA_BIG_INTEGER: - emit("return target.getBigIntegerValue();"); break; - - case SchemaProperty.JAVA_STRING: - emit("return target.getStringValue();"); break; - - case SchemaProperty.JAVA_BYTE_ARRAY: - emit("return target.getByteArrayValue();"); break; - - case SchemaProperty.JAVA_GDATE: - emit("return target.getGDateValue();"); break; - - case SchemaProperty.JAVA_GDURATION: - emit("return target.getGDurationValue();"); break; - - case SchemaProperty.JAVA_CALENDAR: - emit("return target.getCalendarValue();"); break; - - case SchemaProperty.JAVA_DATE: - emit("return target.getDateValue();"); break; - - case SchemaProperty.JAVA_QNAME: - emit("return target.getQNameValue();"); break; - - case SchemaProperty.JAVA_LIST: - emit("return target.getListValue();"); break; - - case SchemaProperty.JAVA_ENUM: - emit("return (" + type + ")target.getEnumValue();"); break; - - case SchemaProperty.JAVA_OBJECT: - emit("return target.getObjectValue();"); break; - - case SchemaProperty.JAVA_USER: - emit("return " + getUserTypeStaticHandlerMethod(false, stype) - + "(target);"); - break; - - default: - throw new IllegalStateException(); - } - } - void printJSetValue(int javaType, String safeVarName, SchemaTypeImpl stype) throws IOException { - switch (javaType) - { - case SchemaProperty.XML_OBJECT: - emit("target.set(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_BOOLEAN: - emit("target.setBooleanValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_FLOAT: - emit("target.setFloatValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_DOUBLE: - emit("target.setDoubleValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_BYTE: - emit("target.setByteValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_SHORT: - emit("target.setShortValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_INT: - emit("target.setIntValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_LONG: - emit("target.setLongValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_BIG_DECIMAL: - emit("target.setBigDecimalValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_BIG_INTEGER: - emit("target.setBigIntegerValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_STRING: - emit("target.setStringValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_BYTE_ARRAY: - emit("target.setByteArrayValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_GDATE: - emit("target.setGDateValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_GDURATION: - emit("target.setGDurationValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_CALENDAR: - emit("target.setCalendarValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_DATE: - emit("target.setDateValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_QNAME: - emit("target.setQNameValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_LIST: - emit("target.setListValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_ENUM: - emit("target.setEnumValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_OBJECT: - emit("target.setObjectValue(" + safeVarName + ");"); break; - - case SchemaProperty.JAVA_USER: - emit(getUserTypeStaticHandlerMethod(true, stype) - + "(" + safeVarName + ", target);"); - break; - - default: - throw new IllegalStateException(); - } - } - - String getIdentifier(Map qNameMap, QName qName) { - return ((String[])qNameMap.get(qName))[0]; - } - - String getSetIdentifier(Map qNameMap, QName qName) { - String[] identifiers = (String[])qNameMap.get(qName); - return identifiers[1] == null ? identifiers[0] : identifiers[1]; - } - - Map printStaticFields(SchemaProperty[] properties) throws IOException { - final Map results = new HashMap(); - - emit(""); - for (int i = 0; i < properties.length; i++) - { - final String[] identifiers = new String[2]; - final SchemaProperty prop = properties[i]; - final QName name = prop.getName(); - results.put(name, identifiers); - final String javaName = prop.getJavaPropertyName(); - identifiers[0] = (javaName + "$" + (i * 2)).toUpperCase(); - final String uriString = "\"" + name.getNamespaceURI() + "\""; - - emit("private static final javax.xml.namespace.QName " + identifiers[0] + - " = " ); - indent(); - emit("new javax.xml.namespace.QName(" + - uriString + ", \"" + name.getLocalPart() + "\");"); - outdent(); - - if (properties[i].acceptedNames() != null) - { - final QName[] qnames = properties[i].acceptedNames(); - - if (qnames.length > 1) - { - identifiers[1] = (javaName + "$" + (i*2+1)).toUpperCase(); - - emit("private static final org.apache.xmlbeans.QNameSet " + identifiers[1] + - " = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { " ); - indent(); - for (int j = 0 ; j < qnames.length ; j++) - { - emit("new javax.xml.namespace.QName(\"" + qnames[j].getNamespaceURI() + - "\", \"" + qnames[j].getLocalPart() + "\"),"); - } - - outdent(); - - emit("});"); - } - } - } - emit(""); - return results; - } - - void emitImplementationPreamble() throws IOException - { - emit("synchronized (monitor())"); - emit("{"); - indent(); - emit("check_orphaned();"); - } - - void emitImplementationPostamble() throws IOException - { - outdent(); - emit("}"); - } - - void emitDeclareTarget(boolean declareTarget, String xtype) - throws IOException - { - if (declareTarget) - emit(xtype + " target = null;"); - } - - void emitAddTarget(String identifier, boolean isAttr, boolean declareTarget, String xtype) - throws IOException - { - if (isAttr) - emit("target = (" + xtype + ")get_store().add_attribute_user(" + identifier + ");"); - else - emit("target = (" + xtype + ")get_store().add_element_user(" + identifier + ");"); - } - - void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException - { - emitPre(sType, opType, identifier, isAttr, "-1"); - } - - void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException - { - SchemaTypeImpl sImpl = getImpl(sType); - if (sImpl == null) - return; - - PrePostExtension ext = sImpl.getPrePostExtension(); - if (ext != null) - { - if (ext.hasPreCall()) - { - emit("if ( " + ext.getStaticHandler() + ".preSet(" + prePostOpString(opType) + ", this, " + identifier + ", " + isAttr + ", " + index + "))"); - startBlock(); - } - } - } - - void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException - { - emitPost(sType, opType, identifier, isAttr, "-1"); - } - - void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException - { - SchemaTypeImpl sImpl = getImpl(sType); - if (sImpl == null) - return; - - PrePostExtension ext = sImpl.getPrePostExtension(); - if (ext != null) - { - if (ext.hasPreCall()) - { - endBlock(); - } - - if (ext.hasPostCall()) - emit(ext.getStaticHandler() + ".postSet(" + prePostOpString(opType) + ", this, " + identifier + ", " + isAttr + ", " + index + ");"); - } - } - - String prePostOpString(int opType) - { - switch (opType) - { - default: - assert false; - - case PrePostExtension.OPERATION_SET: - return "org.apache.xmlbeans.PrePostExtension.OPERATION_SET"; - - case PrePostExtension.OPERATION_INSERT: - return "org.apache.xmlbeans.PrePostExtension.OPERATION_INSERT"; - - case PrePostExtension.OPERATION_REMOVE: - return "org.apache.xmlbeans.PrePostExtension.OPERATION_REMOVE"; - } - } - - private static final int NOTHING = 1; - private static final int ADD_NEW_VALUE = 3; - private static final int THROW_EXCEPTION = 4; - - void emitGetTarget(String setIdentifier, - String identifier, - boolean isAttr, - String index, - int nullBehaviour, - String xtype) - throws IOException - { - assert setIdentifier != null && identifier != null; - - emit(xtype + " target = null;"); - - if (isAttr) - emit("target = (" + xtype + ")get_store().find_attribute_user(" + identifier + ");"); - else - emit("target = (" + xtype + ")get_store().find_element_user(" + setIdentifier + ", " + index + ");"); - - if (nullBehaviour == NOTHING) - return; - - emit("if (target == null)"); - - startBlock(); - - switch (nullBehaviour) - { - case ADD_NEW_VALUE: - // target already emited, no need for emitDeclareTarget(false, xtype); - emitAddTarget(identifier, isAttr, false, xtype); - break; - - case THROW_EXCEPTION: - emit("throw new IndexOutOfBoundsException();"); - break; - - case NOTHING: - break; - - default: - assert false : "Bad behaviour type: " + nullBehaviour; - } - - endBlock(); - } - - void printListGetter15Impl(String parentJavaName, - String propdesc, String propertyName, - String wrappedType, String xtype, - boolean xmltype, boolean xget) - throws IOException - { - String arrayName = propertyName + "Array"; - String listName = propertyName + "List"; - String parentThis = parentJavaName + ".this."; - - String xgetMethod = (xget ? "x" : "") + "get"; - String xsetMethod = (xget ? "x" : "") + "set"; - - printJavaDoc("Gets " + (xget ? "(as xml) " : "") + "a List of " + propdesc + "s"); - - emit("public java.util.List<" + wrappedType + "> " + xgetMethod + listName + "()"); - startBlock(); - - emit("final class " + listName + " extends java.util.AbstractList<" + wrappedType + ">"); - startBlock(); - - // Object get(i) - if (_useJava15) - emit("@Override"); - emit("public " + wrappedType + " get(int i)"); - emit(" { return " + parentThis + xgetMethod + arrayName + "(i); }"); - emit(""); - - // Object set(i, o) - if (_useJava15) - emit("@Override"); - emit("public " + wrappedType + " set(int i, " + wrappedType + " o)"); - startBlock(); - emit(wrappedType + " old = " + parentThis + xgetMethod + arrayName + "(i);"); - emit(parentThis + xsetMethod + arrayName + "(i, o);"); - emit("return old;"); - endBlock(); - emit(""); - - // void add(i, o) - if (_useJava15) - emit("@Override"); - emit("public void add(int i, " + wrappedType +" o)"); - if (xmltype || xget) - emit(" { " + parentThis + "insertNew" + propertyName + "(i).set(o); }"); - else - emit(" { " + parentThis + "insert" + propertyName + "(i, o); }"); - emit(""); - - // Object remove(i) - if (_useJava15) - emit("@Override"); - emit("public " + wrappedType +" remove(int i)"); - startBlock(); - emit(wrappedType + " old = " + parentThis + xgetMethod + arrayName + "(i);"); - emit(parentThis + "remove" + propertyName + "(i);"); - emit("return old;"); - endBlock(); - emit(""); - - // int size() - if (_useJava15) - emit("@Override"); - emit("public int size()"); - emit(" { return " + parentThis + "sizeOf" + arrayName + "(); }"); - emit(""); - - endBlock(); - - emit(""); - - emitImplementationPreamble(); - - emit("return new " + listName + "();"); - - emitImplementationPostamble(); - endBlock(); - } - - void printGetterImpls(String parentJavaName, - SchemaProperty prop, QName qName, boolean isAttr, String propertyName, - int javaType, String type, String xtype, boolean nillable, - boolean optional, boolean several, boolean singleton, - boolean isunion, - String identifier, String setIdentifier ) - throws IOException - { - String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); - boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); - String jtargetType = (isunion || !xmltype) ? "org.apache.xmlbeans.SimpleValue" : xtype; - - if (singleton) - { - // Value getProp() - printJavaDoc((several ? "Gets first " : "Gets the ") + propdesc); - emit("public " + type + " get" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - - emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, jtargetType); - - if (isAttr && (prop.hasDefault() == SchemaProperty.CONSISTENTLY || - prop.hasFixed() == SchemaProperty.CONSISTENTLY)) - { - emit("if (target == null)"); - startBlock(); - makeAttributeDefaultValue(jtargetType, prop, identifier); - endBlock(); - } - emit("if (target == null)"); - startBlock(); - makeMissingValue(javaType); - endBlock(); - - - printJGetValue(javaType, type, (SchemaTypeImpl)prop.getType()); - - - emitImplementationPostamble(); - - endBlock(); - - if (!xmltype) - { - // Value xgetProp() - printJavaDoc((several ? "Gets (as xml) first " : "Gets (as xml) the ") + propdesc); - emit("public " + xtype + " xget" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, xtype); - - if (isAttr && (prop.hasDefault() == SchemaProperty.CONSISTENTLY || - prop.hasFixed() == SchemaProperty.CONSISTENTLY)) - { - emit("if (target == null)"); - startBlock(); - makeAttributeDefaultValue(xtype, prop, identifier); - endBlock(); - } - - emit("return target;"); - emitImplementationPostamble(); - endBlock(); - } - - if (nillable) - { - // boolean isNilProp() - printJavaDoc((several ? "Tests for nil first " : "Tests for nil ") + propdesc); - emit("public boolean isNil" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, xtype); - - emit("if (target == null) return false;"); - emit("return target.isNil();"); - emitImplementationPostamble(); - endBlock(); - } - } - - if (optional) - { - // boolean isSetProp() - printJavaDoc((several ? "True if has at least one " : "True if has ") + propdesc); - emit("public boolean isSet" + propertyName + "()"); - - startBlock(); - emitImplementationPreamble(); - - if (isAttr) - emit("return get_store().find_attribute_user(" + identifier +") != null;"); - else - emit("return get_store().count_elements(" + setIdentifier + ") != 0;"); - - emitImplementationPostamble(); - endBlock(); - } - - if (several) - { - String arrayName = propertyName + "Array"; - - if (_useJava15) - { - // use boxed type if the java type is a primitive and jdk1.5 - // jdk1.5 will box/unbox for us - String wrappedType = type; - if (isJavaPrimitive(javaType)) - wrappedType = javaWrappedType(javaType); - - printListGetter15Impl(parentJavaName, propdesc, propertyName, wrappedType, xtype, xmltype, false); - } - - // Value[] getProp() - if (_useJava15) - { - emit(""); - emit("/**"); - emit(" * Gets array of all " + propdesc + "s"); - emit(" * @deprecated"); - emit(" */"); - emit("@Deprecated"); - } - else - printJavaDoc("Gets array of all " + propdesc + "s"); - emit("public " + type + "[] get" + arrayName + "()"); - startBlock(); - emitImplementationPreamble(); - - if (_useJava15) - emit("java.util.List<" + xtype + "> targetList = new java.util.ArrayList<" + xtype + ">();"); - else - emit("java.util.List targetList = new java.util.ArrayList();"); - emit("get_store().find_all_element_users(" + setIdentifier + ", targetList);"); - - printJGetArrayValue(javaType, type, (SchemaTypeImpl)prop.getType()); - - emitImplementationPostamble(); - endBlock(); - - // Value getProp(int i) - printJavaDoc("Gets ith " + propdesc); - emit("public " + type + " get" + arrayName + "(int i)"); - startBlock(); - emitImplementationPreamble(); - - emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, jtargetType); - printJGetValue(javaType, type, (SchemaTypeImpl)prop.getType()); - - emitImplementationPostamble(); - endBlock(); - - if (!xmltype) - { - if (_useJava15) - { - printListGetter15Impl(parentJavaName, propdesc, propertyName, xtype, xtype, xmltype, true); - } - - // Value[] xgetProp() - if (_useJava15) - { - emit(""); - emit("/**"); - emit(" * Gets array of all " + propdesc + "s"); - emit(" * @deprecated"); - emit(" */"); - emit("@Deprecated"); - } - else - printJavaDoc("Gets (as xml) array of all " + propdesc + "s"); - emit("public " + xtype + "[] xget" + arrayName + "()"); - startBlock(); - emitImplementationPreamble(); - if (_useJava15) - emit("java.util.List<" + xtype + "> targetList = new java.util.ArrayList<" + xtype + ">();"); - else - emit("java.util.List targetList = new java.util.ArrayList();"); - emit("get_store().find_all_element_users(" + setIdentifier + ", targetList);"); - emit(xtype + "[] result = new " + xtype + "[targetList.size()];"); - emit("targetList.toArray(result);"); - emit("return result;"); - emitImplementationPostamble(); - endBlock(); - - // Value xgetProp(int i) - printJavaDoc("Gets (as xml) ith " + propdesc); - emit("public " + xtype + " xget" + arrayName + "(int i)"); - startBlock(); - emitImplementationPreamble(); - emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); - emit("return target;"); - emitImplementationPostamble(); - endBlock(); - - } - - if (nillable) - { - // boolean isNil(int i); - printJavaDoc("Tests for nil ith " + propdesc); - emit("public boolean isNil" + arrayName + "(int i)"); - startBlock(); - emitImplementationPreamble(); - emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); - emit("return target.isNil();"); - emitImplementationPostamble(); - endBlock(); - } - - // int countProp(); - printJavaDoc("Returns number of " + propdesc); - emit("public int sizeOf" + arrayName + "()"); - startBlock(); - emitImplementationPreamble(); - emit("return get_store().count_elements(" + setIdentifier +");"); - emitImplementationPostamble(); - endBlock(); - } - } - - void printSetterImpls(QName qName, SchemaProperty prop, boolean isAttr, - String propertyName, int javaType, String type, String xtype, - boolean nillable, boolean optional, boolean several, boolean singleton, - boolean isunion, String identifier, String setIdentifier, SchemaType sType) - throws IOException - { - String safeVarName = NameUtil.nonJavaKeyword(NameUtil.lowerCamelCase(propertyName)); - safeVarName = NameUtil.nonExtraKeyword(safeVarName); - - boolean xmltype = (javaType == SchemaProperty.XML_OBJECT); - boolean isobj = (javaType == SchemaProperty.JAVA_OBJECT); - boolean isSubstGroup = identifier != setIdentifier; - String jtargetType = (isunion || !xmltype) ? "org.apache.xmlbeans.SimpleValue" : xtype; - - String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element"); - - if (singleton) - { - // void setProp(Value v); - printJavaDoc((several ? "Sets first " : "Sets the ") + propdesc); - emit("public void set" + propertyName + "(" + type + " " + safeVarName + ")"); - startBlock(); - if ( xmltype && !isSubstGroup ) - { - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emit("generatedSetterHelperImpl(" + safeVarName + ", " + setIdentifier + ", 0, " + - "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);"); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - } - else - { - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, jtargetType); - printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType()); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emitImplementationPostamble(); - } - endBlock(); - - if (!xmltype) - { - // void xsetProp(Value v) - printJavaDoc((several ? "Sets (as xml) first " : "Sets (as xml) the ") + propdesc); - emit("public void xset" + propertyName + "(" + xtype + " " + safeVarName + ")"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, xtype); - emit("target.set(" + safeVarName + ");"); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emitImplementationPostamble(); - endBlock(); - - } - - if (xmltype && !several) - { - // Value addNewProp() - printJavaDoc("Appends and returns a new empty " + propdesc); - emit("public " + xtype + " addNew" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - emitDeclareTarget(true, xtype); - emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); - emitAddTarget(identifier, isAttr, true, xtype); - emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); - emit("return target;"); - emitImplementationPostamble(); - endBlock(); - } - - if (nillable) - { - printJavaDoc((several ? "Nils the first " : "Nils the ") + propdesc); - emit("public void setNil" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, xtype); - emit("target.setNil();"); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1"); - emitImplementationPostamble(); - endBlock(); - } - } - - if (optional) - { - printJavaDoc((several ? "Removes first " : "Unsets the ") + propdesc); - emit("public void unset" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, several ? "0" : "-1"); - if (isAttr) - emit("get_store().remove_attribute(" + identifier + ");"); - else - emit("get_store().remove_element(" + setIdentifier + ", 0);"); - emitPost(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, several ? "0" : "-1"); - emitImplementationPostamble(); - endBlock(); - } - - if (several) - { - String arrayName = propertyName + "Array"; - - if ( xmltype ) - { - printJavaDoc("Sets array of all " + propdesc + " WARNING: This method is not atomicaly synchronized."); - emit("public void set" + arrayName + "(" + type + "[] " + safeVarName + "Array)"); - startBlock(); - // do not use synchronize (monitor()) { and GlobalLock inside } !!! deadlock - //emitImplementationPreamble(); - emit("check_orphaned();"); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); - - if (isobj) - { - if (!isSubstGroup) - emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" ); - else - emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" ); - } - else - { - if (!isSubstGroup) - emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" ); - else - emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" ); - } - - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); - //emitImplementationPostamble(); to avoid deadlock - endBlock(); - } - else - { - printJavaDoc("Sets array of all " + propdesc ); - emit("public void set" + arrayName + "(" + type + "[] " + safeVarName + "Array)"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); - - if (isobj) - { - if (!isSubstGroup) - emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" ); - else - emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" ); - } - else if (prop.getJavaTypeCode() == SchemaProperty.JAVA_USER) - { - if (!isSubstGroup) - { - emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ");" ); - emit("for ( int i = 0 ; i < dests.length ; i++ ) {"); - emit(" " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl)prop.getType()) - + "(" + safeVarName + "Array[i], dests[i]);"); - emit("}"); - } - else - { - emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ", " + setIdentifier + ");" ); - emit("for ( int i = 0 ; i < dests.length ; i++ ) {"); - emit(" " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl)prop.getType()) - + "(" + safeVarName + "Array[i], dests[i]);"); - emit("}"); - } - } - else - { - if (!isSubstGroup) - emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" ); - else - emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" ); - } - - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); - emitImplementationPostamble(); - endBlock(); - } - - printJavaDoc("Sets ith " + propdesc); - emit("public void set" + arrayName + "(int i, " + type + " " + safeVarName + ")"); - startBlock(); - if ( xmltype && !isSubstGroup ) - { - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emit("generatedSetterHelperImpl(" + safeVarName + ", " + setIdentifier + ", i, " + - "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);"); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - } - else - { - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, jtargetType); - printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType()); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emitImplementationPostamble(); - } - endBlock(); - - if (!xmltype) - { - printJavaDoc("Sets (as xml) array of all " + propdesc); - emit("public void xset" + arrayName + "(" + xtype + "[]" + safeVarName + "Array)"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); - emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" ); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr); - emitImplementationPostamble(); - endBlock(); - - printJavaDoc("Sets (as xml) ith " + propdesc); - emit("public void xset" + arrayName + "(int i, " + xtype + " " + safeVarName + ")"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); - emit("target.set(" + safeVarName + ");"); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emitImplementationPostamble(); - endBlock(); - } - - if (nillable) - { - printJavaDoc("Nils the ith " + propdesc); - emit("public void setNil" + arrayName + "(int i)"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, xtype); - emit("target.setNil();"); - emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i"); - emitImplementationPostamble(); - endBlock(); - } - - if (!xmltype) - { - printJavaDoc("Inserts the value as the ith " + propdesc); - emit("public void insert" + propertyName + "(int i, " + type + " " + safeVarName + ")"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); - emit(jtargetType + " target = "); - indent(); - if (!isSubstGroup) - emit("(" + jtargetType + ")get_store().insert_element_user(" + identifier + ", i);"); - else // This is a subst group case - emit ("(" + jtargetType +")get_store().insert_element_user(" + setIdentifier + ", " + - identifier + ", i);"); - outdent(); - printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType()); - emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); - emitImplementationPostamble(); - endBlock(); - - printJavaDoc("Appends the value as the last " + propdesc); - emit("public void add" + propertyName + "(" + type + " " + safeVarName + ")"); - startBlock(); - emitImplementationPreamble(); - emitDeclareTarget(true, jtargetType); - emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); - emitAddTarget(identifier, isAttr, true, jtargetType); - printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType()); - emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); - emitImplementationPostamble(); - endBlock(); - } - - printJavaDoc("Inserts and returns a new empty value (as xml) as the ith " + propdesc); - emit("public " + xtype + " insertNew" + propertyName + "(int i)"); - startBlock(); - emitImplementationPreamble(); - emitDeclareTarget(true, xtype); - emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); - if (!isSubstGroup) - { - emit("target = (" + xtype + ")get_store().insert_element_user(" + identifier + ", i);"); - } - else // This is a subst group case - { - emit("target = (" + xtype + ")get_store().insert_element_user(" + - setIdentifier + ", " + identifier + ", i);"); - } - emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i"); - emit("return target;"); - emitImplementationPostamble(); - endBlock(); - - printJavaDoc("Appends and returns a new empty value (as xml) as the last " + propdesc); - emit("public " + xtype + " addNew" + propertyName + "()"); - startBlock(); - emitImplementationPreamble(); - emitDeclareTarget(true, xtype); - emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); - emitAddTarget(identifier, isAttr, true, xtype); - emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr); - emit("return target;"); - emitImplementationPostamble(); - endBlock(); - - printJavaDoc("Removes the ith " + propdesc); - emit("public void remove" + propertyName + "(int i)"); - startBlock(); - emitImplementationPreamble(); - emitPre(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, "i"); - emit("get_store().remove_element(" + setIdentifier + ", i);"); - emitPost(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, "i"); - emitImplementationPostamble(); - endBlock(); - } - } - - static void getTypeName(Class c, StringBuffer sb) { - int arrayCount = 0; - while (c.isArray()) { - c = c.getComponentType(); - arrayCount++; - } - - sb.append(c.getName()); - - for (int i = 0 ; i < arrayCount; i++) - sb.append("[]"); - - } - - void printInnerTypeImpl( - SchemaType sType, SchemaTypeSystem system, boolean isInner ) throws IOException - { - String shortName = sType.getShortJavaImplName(); - - printInnerTypeJavaDoc(sType); - - startClass(sType, isInner); - - printConstructor(sType, shortName); - - printExtensionImplMethods(sType); - - if (!sType.isSimpleType()) - { - SchemaProperty[] properties; - - if (sType.getContentType() == SchemaType.SIMPLE_CONTENT) - { - // simple content types impls derive directly from "holder" impls - // in order to handle the case (for ints or string enums e.g.) where - // there is a simple type restriction. So property getters need to - // be implemented "from scratch" for each derived complex type - // Moreover, attribute or element properties can be removed via restriction, - // but we still need to implement them because this class is supposed to - // also implement all the interfaces - SchemaType baseType = sType.getBaseType(); - List extraProperties = null; - while (!baseType.isSimpleType() && !baseType.isBuiltinType()) - { - SchemaProperty[] baseProperties = baseType.getDerivedProperties(); - for (int i = 0; i < baseProperties.length; i++) - if (!(baseProperties[i].isAttribute() && - sType.getAttributeProperty(baseProperties[i].getName()) != null)) - { - if (extraProperties == null) - extraProperties = new ArrayList(); - extraProperties.add(baseProperties[i]); - } - baseType = baseType.getBaseType(); - } - - properties = sType.getProperties(); - if (extraProperties != null) - { - for (int i = 0; i < properties.length; i++) - extraProperties.add(properties[i]); - properties = (SchemaProperty[]) extraProperties. - toArray(new SchemaProperty[extraProperties.size()]); - } - } - else - { - // complex content type implementations derive from base type impls - // so derived property impls can be reused - - properties = getDerivedProperties(sType); - } - - Map qNameMap = printStaticFields(properties); - - for (int i = 0; i < properties.length; i++) - { - SchemaProperty prop = properties[i]; - - QName name = prop.getName(); - String xmlType = xmlTypeForProperty( prop ); - - printGetterImpls( - shortName, - prop, - name, - prop.isAttribute(), - prop.getJavaPropertyName(), - prop.getJavaTypeCode(), - javaTypeForProperty(prop), - xmlType, - prop.hasNillable() != SchemaProperty.NEVER, - prop.extendsJavaOption(), - prop.extendsJavaArray(), - prop.extendsJavaSingleton(), - xmlTypeForPropertyIsUnion(prop), - getIdentifier(qNameMap, name), - getSetIdentifier(qNameMap, name) - ); - - if (!prop.isReadOnly()) - { - printSetterImpls( - name, - prop, - prop.isAttribute(), - prop.getJavaPropertyName(), - prop.getJavaTypeCode(), - javaTypeForProperty(prop), - xmlType, - prop.hasNillable() != SchemaProperty.NEVER, - prop.extendsJavaOption(), - prop.extendsJavaArray(), - prop.extendsJavaSingleton(), - xmlTypeForPropertyIsUnion(prop), - getIdentifier(qNameMap, name), - getSetIdentifier(qNameMap, name), - sType - ); - } - } - } - - printNestedTypeImpls(sType, system); - - endBlock(); - } - - private SchemaProperty[] getDerivedProperties(SchemaType sType) - { - // We have to see if this is redefined, because if it is we have - // to include all properties associated to its supertypes - QName name = sType.getName(); - if (name != null && name.equals(sType.getBaseType().getName())) - { - SchemaType sType2 = sType.getBaseType(); - // Walk all the redefined types and record any properties - // not present in sType, because the redefined types do not - // have a generated class to represent them - SchemaProperty[] props = sType.getDerivedProperties(); - Map propsByName = new LinkedHashMap(); - for (int i = 0; i < props.length; i++) - propsByName.put(props[i].getName(), props[i]); - while (sType2 != null && name.equals(sType2.getName())) - { - props = sType2.getDerivedProperties(); - for (int i = 0; i < props.length; i++) - if (!propsByName.containsKey(props[i].getName())) - propsByName.put(props[i].getName(), props[i]); - sType2 = sType2.getBaseType(); - } - return (SchemaProperty[]) propsByName.values().toArray(new SchemaProperty[0]); - } - else - return sType.getDerivedProperties(); - } - - private void printExtensionImplMethods(SchemaType sType) throws IOException - { - SchemaTypeImpl sImpl = getImpl(sType); - if (sImpl == null) - return; - - InterfaceExtension[] exts = sImpl.getInterfaceExtensions(); - if (exts != null) for (int i = 0; i < exts.length; i++) - { - InterfaceExtension.MethodSignature[] methods = exts[i].getMethods(); - if (methods != null) - { - for (int j = 0; j < methods.length; j++) - { - printJavaDoc("Implementation method for interface " + exts[i].getStaticHandler()); - printInterfaceMethodDecl(methods[j]); - startBlock(); - printInterfaceMethodImpl(exts[i].getStaticHandler(), methods[j]); - endBlock(); - } - } - } - } - - void printInterfaceMethodDecl(InterfaceExtension.MethodSignature method) throws IOException - { - StringBuffer decl = new StringBuffer(60); - - decl.append("public ").append(method.getReturnType()); - decl.append(" ").append(method.getName()).append("("); - - String[] paramTypes = method.getParameterTypes(); - for (int i = 0; i < paramTypes.length; i++) - { - if (i != 0) - decl.append(", "); - decl.append(paramTypes[i]).append(" p").append(i); - } - - decl.append(")"); - - String[] exceptions = method.getExceptionTypes(); - for (int i = 0; i < exceptions.length; i++) - decl.append((i == 0 ? " throws " : ", ") + exceptions[i]); - - emit(decl.toString()); - } - - void printInterfaceMethodImpl(String handler, InterfaceExtension.MethodSignature method) throws IOException - { - StringBuffer impl = new StringBuffer(60); - - if (!method.getReturnType().equals("void")) - impl.append("return "); - - impl.append(handler).append(".").append(method.getName()).append("(this"); - - String[] params = method.getParameterTypes(); - for (int i = 0; i < params.length; i++) - impl.append(", p" + i); - - impl.append(");"); - - emit(impl.toString()); - } - - void printNestedTypeImpls(SchemaType sType, SchemaTypeSystem system) throws IOException - { - boolean redefinition = sType.getName() != null && - sType.getName().equals(sType.getBaseType().getName()); - while (sType != null) - { - SchemaType[] anonTypes = sType.getAnonymousTypes(); - for (int i = 0; i < anonTypes.length; i++) - { - if (anonTypes[i].isSkippedAnonymousType()) - printNestedTypeImpls(anonTypes[i], system); - else - printInnerTypeImpl(anonTypes[i], system, true); - } - // For redefinition by extension, go ahead and print the anonymous - // types in the base - if (!redefinition || - (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType())) - break; - sType = sType.getBaseType(); - } - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java deleted file mode 100644 index 531055a..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java +++ /dev/null @@ -1,2471 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.QNameSetBuilder; -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaLocalElement; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.SchemaStringEnumEntry; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeElementSequencer; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.StringEnumAbstractBase; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.InterfaceExtension; -import org.apache.xmlbeans.PrePostExtension; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.values.*; - -import javax.xml.namespace.QName; -import java.lang.reflect.Constructor; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public final class SchemaTypeImpl implements SchemaType, TypeStoreUserFactory -{ - // global types have names - private QName _name; - - // annotation on the type - private SchemaAnnotation _annotation; - - // compilation support - private int _resolvePhase; - private static final int UNRESOLVED = 0; - private static final int RESOLVING_SGS = 1; // For document types only - private static final int RESOLVED_SGS = 2; // For document types only - private static final int RESOLVING = 3; - private static final int RESOLVED = 4; - private static final int JAVAIZING = 5; - private static final int JAVAIZED = 6; - - // anonymous type support - private SchemaType.Ref _outerSchemaTypeRef; - private volatile SchemaComponent.Ref _containerFieldRef; - private volatile SchemaField _containerField; - private volatile int _containerFieldCode; - private volatile int _containerFieldIndex; - private volatile QName[] _groupReferenceContext; - private SchemaType.Ref[] _anonymousTyperefs; - private boolean _isDocumentType; - private boolean _isAttributeType; - // private boolean _skippedAnonymousType; - - // compiletime java type support - private boolean _isCompiled; - private String _shortJavaName; - private String _fullJavaName; - private String _shortJavaImplName; - private String _fullJavaImplName; - private InterfaceExtension[] _interfaces; - private PrePostExtension _prepost; - - // runtime java type support: volatile because they're cached - private volatile Class _javaClass; - private volatile Class _javaEnumClass; - private volatile Class _javaImplClass; - private volatile Constructor _javaImplConstructor; - private volatile Constructor _javaImplConstructor2; - private volatile boolean _implNotAvailable; - private volatile Class _userTypeClass; - private volatile Class _userTypeHandlerClass; - - // user data objects not persisted - private volatile Object _userData; - - private final Object[] _ctrArgs = new Object[] { this }; - - // reflective support - private SchemaContainer _container; - private String _filename; - - // complex content support - private SchemaParticle _contentModel; - private volatile SchemaLocalElement[] _localElts; // lazily computed - private volatile Map _eltToIndexMap; // lazily computed - private volatile Map _attrToIndexMap; // lazily computed - private Map _propertyModelByElementName; - private Map _propertyModelByAttributeName; - private boolean _hasAllContent; - private boolean _orderSensitive; - private QNameSet _typedWildcardElements; - private QNameSet _typedWildcardAttributes; - private boolean _hasWildcardElements; - private boolean _hasWildcardAttributes; - // set of valid QNames that can be substituted for a property - private Set _validSubstitutions = Collections.EMPTY_SET; - - // simple content support - private int _complexTypeVariety; - private SchemaAttributeModel _attributeModel; - - // simple type support - private int _builtinTypeCode; - - private int _simpleTypeVariety; - private boolean _isSimpleType; - - private SchemaType.Ref _baseTyperef; // via restriction or extension - private int _baseDepth; // how many inheritance steps to AnyType - private int _derivationType; - - // user type support - private String _userTypeName; - private String _userTypeHandler; - - // for complex types with simple content - private SchemaType.Ref _contentBasedOnTyperef; - - // facets - private XmlValueRef[] _facetArray; - private boolean[] _fixedFacetArray; - - // fundamental facets - private int _ordered; - private boolean _isFinite; - private boolean _isBounded; - private boolean _isNumeric; - - private boolean _abs; - private boolean _finalExt; - private boolean _finalRest; - private boolean _finalList; - private boolean _finalUnion; - private boolean _blockExt; - private boolean _blockRest; - - // whitespace facet - private int _whiteSpaceRule; - - // regex patterns - private boolean _hasPatterns; // also takes into account base classes - private org.apache.xmlbeans.impl.regex.RegularExpression[] _patterns; - - // enumerated values - private XmlValueRef[] _enumerationValues; - private SchemaType.Ref _baseEnumTyperef; - private boolean _stringEnumEnsured; - private volatile Map _lookupStringEnum; - private volatile List _listOfStringEnum; - private volatile Map _lookupStringEnumEntry; - private SchemaStringEnumEntry[] _stringEnumEntries; - - // for lists only - private SchemaType.Ref _listItemTyperef; - - // for unions only - private boolean _isUnionOfLists; - private SchemaType.Ref[] _unionMemberTyperefs; - private int _anonymousUnionMemberOrdinal; - private volatile SchemaType[] _unionConstituentTypes; - private volatile SchemaType[] _unionSubTypes; - private volatile SchemaType _unionCommonBaseType; - - // for atomic types only - private SchemaType.Ref _primitiveTypeRef; - - // for decimal restrictions only - private int _decimalSize; - - // lazy loading support - private volatile boolean _unloaded; - - // for document types only - only valid during compilation - private QName _sg; - private List _sgMembers = new ArrayList(); - - public boolean isUnloaded() - { - return _unloaded; - } - - public void finishLoading() - { - _unloaded = false; - } - - - - SchemaTypeImpl(SchemaContainer container) - { - _container = container; - } - - SchemaTypeImpl(SchemaContainer container, boolean unloaded) - { - _container = container; - _unloaded = unloaded; - if (unloaded) - finishQuick(); - } - - public boolean isSGResolved() - { return _resolvePhase >= RESOLVED_SGS; } - - public boolean isSGResolving() - { return _resolvePhase >= RESOLVING_SGS; } - - public boolean isResolved() - { return _resolvePhase >= RESOLVED; } - - public boolean isResolving() - { return _resolvePhase == RESOLVING; } - - public boolean isUnjavaized() - { return _resolvePhase < JAVAIZED; } - - public boolean isJavaized() - { return _resolvePhase == JAVAIZED; } - - public void startResolvingSGs() - { - if (_resolvePhase != UNRESOLVED) - throw new IllegalStateException(); - _resolvePhase = RESOLVING_SGS; - } - - public void finishResolvingSGs() - { - if (_resolvePhase != RESOLVING_SGS) - throw new IllegalStateException(); - _resolvePhase = RESOLVED_SGS; - } - - public void startResolving() - { - if ( (_isDocumentType && _resolvePhase != RESOLVED_SGS) || - (!_isDocumentType && _resolvePhase != UNRESOLVED)) - throw new IllegalStateException(); - _resolvePhase = RESOLVING; - } - - public void finishResolving() - { - if (_resolvePhase != RESOLVING) - throw new IllegalStateException(); - _resolvePhase = RESOLVED; - } - - public void startJavaizing() - { - if (_resolvePhase != RESOLVED) - throw new IllegalStateException(); - _resolvePhase = JAVAIZING; - } - - public void finishJavaizing() - { - if (_resolvePhase != JAVAIZING) - throw new IllegalStateException(); - _resolvePhase = JAVAIZED; - } - - private void finishQuick() - { - _resolvePhase = JAVAIZED; - } - - private void assertUnresolved() - { - if (_resolvePhase != UNRESOLVED && !_unloaded) - throw new IllegalStateException(); - } - - private void assertSGResolving() - { - if (_resolvePhase != RESOLVING_SGS && !_unloaded) - throw new IllegalStateException(); - } - - private void assertSGResolved() - { - if (_resolvePhase != RESOLVED_SGS && !_unloaded) - throw new IllegalStateException(); - } - - private void assertResolving() - { - if (_resolvePhase != RESOLVING && !_unloaded) - throw new IllegalStateException(); - } - - private void assertResolved() - { - if (_resolvePhase != RESOLVED && !_unloaded) - throw new IllegalStateException(); - } - - private void assertJavaizing() - { - if (_resolvePhase != JAVAIZING && !_unloaded) - throw new IllegalStateException(); - } - - public QName getName() - { return _name; } - - public void setName(QName name) - { assertUnresolved(); _name = name; } - - public String getSourceName() - { - if (_filename != null) - return _filename; - if (getOuterType() != null) - return getOuterType().getSourceName(); - - SchemaField field = getContainerField(); - if (field != null) - { - if (field instanceof SchemaGlobalElement) - return ((SchemaGlobalElement)field).getSourceName(); - if (field instanceof SchemaGlobalAttribute) - return ((SchemaGlobalAttribute)field).getSourceName(); - } - return null; - } - - public void setFilename(String filename) - { assertUnresolved(); _filename = filename; } - - public int getComponentType() - { return SchemaComponent.TYPE; } - - public boolean isAnonymousType() - { return _name == null; } - - public boolean isDocumentType() - { return _isDocumentType; } - - public boolean isAttributeType() - { return _isAttributeType; } - - public QName getDocumentElementName() - { - if (_isDocumentType) - { - SchemaParticle sp = getContentModel(); - if (sp != null) - return sp.getName(); - } - - return null; - } - - public QName getAttributeTypeAttributeName() - { - if (_isAttributeType) - { - SchemaAttributeModel sam = getAttributeModel(); - if (sam != null) - { - SchemaLocalAttribute[] slaArray = sam.getAttributes(); - if (slaArray != null && slaArray.length > 0) - { - SchemaLocalAttribute sla = slaArray[0]; - return sla.getName(); - } - } - } - - return null; - } - - public void setAnnotation(SchemaAnnotation ann) - { assertUnresolved(); _annotation = ann; } - - public SchemaAnnotation getAnnotation() - { return _annotation; } - - public void setDocumentType(boolean isDocument) - { assertUnresolved(); _isDocumentType = isDocument; } - - public void setAttributeType(boolean isAttribute) - { assertUnresolved(); _isAttributeType = isAttribute; } - - public int getContentType() - { return _complexTypeVariety; } - - public void setComplexTypeVariety(int complexTypeVariety) - { assertResolving(); _complexTypeVariety = complexTypeVariety; } - - public SchemaTypeElementSequencer getElementSequencer() - { - if (_complexTypeVariety == NOT_COMPLEX_TYPE) - return new SequencerImpl(null); - - return new SequencerImpl(new SchemaTypeVisitorImpl(_contentModel)); - } - - /** Set the abstract and final flags for a complex type */ - void setAbstractFinal( - boolean abs, boolean finalExt, boolean finalRest, boolean finalList, boolean finalUnion) - { - assertResolving(); - _abs = abs; - _finalExt = finalExt; _finalRest = finalRest; - _finalList = finalList; _finalUnion = finalUnion; - } - - /** Set the final flags for a simple type */ - void setSimpleFinal(boolean finalRest, boolean finalList, boolean finalUnion) - { - assertResolving(); _finalRest = finalRest; _finalList = finalList ; _finalUnion = finalUnion; - } - - void setBlock(boolean blockExt, boolean blockRest) - { - assertResolving(); _blockExt = blockExt ; _blockRest = blockRest; - } - - public boolean blockRestriction() - { return _blockRest; } - - public boolean blockExtension() - { return _blockExt; } - - public boolean isAbstract() - { return _abs; } - - public boolean finalExtension() - { return _finalExt; } - - public boolean finalRestriction() - { return _finalRest; } - - public boolean finalList() - { return _finalList; } - - public boolean finalUnion() - { return _finalUnion; } - - public synchronized SchemaField getContainerField() - { - if (_containerFieldCode != -1) - { - SchemaType outer = getOuterType(); - if (_containerFieldCode == 0) - _containerField = _containerFieldRef == null ? null : (SchemaField)_containerFieldRef.getComponent(); - else if (_containerFieldCode == 1) - _containerField = outer.getAttributeModel().getAttributes()[_containerFieldIndex]; - else - _containerField = ((SchemaTypeImpl)outer).getLocalElementByIndex(_containerFieldIndex); - _containerFieldCode = -1; - } - return _containerField; - } - - public void setContainerField(SchemaField field) - { - assertUnresolved(); - _containerField = field; - _containerFieldCode = -1; - } - - public void setContainerFieldRef(SchemaComponent.Ref ref) - { - assertUnresolved(); - _containerFieldRef = ref; - _containerFieldCode = 0; - } - - public void setContainerFieldIndex(short code, int index) - { - assertUnresolved(); - _containerFieldCode = code; - _containerFieldIndex = index; - } - - /* package */ void setGroupReferenceContext(QName[] groupNames) - { - assertUnresolved(); - _groupReferenceContext = groupNames; - } - - /* package */ QName[] getGroupReferenceContext() - { return _groupReferenceContext; } - - public SchemaType getOuterType() - { return _outerSchemaTypeRef == null ? null : _outerSchemaTypeRef.get(); } - - public void setOuterSchemaTypeRef(SchemaType.Ref typeref) - { assertUnresolved(); _outerSchemaTypeRef = typeref; } - - public boolean isCompiled() - { return _isCompiled; } - - public void setCompiled(boolean f) - { assertJavaizing(); _isCompiled = f; } - - public boolean isSkippedAnonymousType() - { - SchemaType outerType = getOuterType(); - return ((outerType == null) ? false : - (outerType.getBaseType() == this || - outerType.getContentBasedOnType() == this)); - } - - public String getShortJavaName() - { return _shortJavaName; } - - public void setShortJavaName(String name) - { - assertResolved(); - _shortJavaName = name; - SchemaType outer = _outerSchemaTypeRef.get(); - while (outer.getFullJavaName() == null) - outer = outer.getOuterType(); - - _fullJavaName = outer.getFullJavaName() + "$" + _shortJavaName; - } - - public String getFullJavaName() - { return _fullJavaName; } - - public void setFullJavaName(String name) - { - assertResolved(); - _fullJavaName = name; - int index = Math.max(_fullJavaName.lastIndexOf('$'), - _fullJavaName.lastIndexOf('.')) + 1; - _shortJavaName = _fullJavaName.substring(index); - } - - public void setShortJavaImplName(String name) - { - assertResolved(); - _shortJavaImplName = name; - SchemaType outer = _outerSchemaTypeRef.get(); - while (outer.getFullJavaImplName() == null) - outer = outer.getOuterType(); - - _fullJavaImplName = outer.getFullJavaImplName() + "$" + _shortJavaImplName; - } - - public void setFullJavaImplName(String name) - { - assertResolved(); - _fullJavaImplName = name; - int index = Math.max(_fullJavaImplName.lastIndexOf('$'), - _fullJavaImplName.lastIndexOf('.')) + 1; - _shortJavaImplName = _fullJavaImplName.substring(index); - } - - public String getFullJavaImplName() { return _fullJavaImplName;} - public String getShortJavaImplName() { return _shortJavaImplName;} - - public String getUserTypeName() - { - return _userTypeName; - } - - public void setUserTypeName(String userTypeName) - { - _userTypeName = userTypeName; - } - - public String getUserTypeHandlerName() - { - return _userTypeHandler; - } - - public void setUserTypeHandlerName(String typeHandler) - { - _userTypeHandler = typeHandler; - } - - public void setInterfaceExtensions(InterfaceExtension[] interfaces) - { - assertResolved(); - _interfaces = interfaces; - } - - public InterfaceExtension[] getInterfaceExtensions() - { - return _interfaces; - } - - public void setPrePostExtension(PrePostExtension prepost) - { - assertResolved(); - _prepost = prepost; - } - - public PrePostExtension getPrePostExtension() - { - return _prepost; - } - - public Object getUserData() - { return _userData; } - - public void setUserData(Object data) - { _userData = data; } - - /* Only used for asserts */ - SchemaContainer getContainer() - { return _container; } - - void setContainer(SchemaContainer container) - { _container = container; } - - public SchemaTypeSystem getTypeSystem() - { return _container.getTypeSystem(); } - - public SchemaParticle getContentModel() - { return _contentModel; } - - private static void buildEltList(List eltList, SchemaParticle contentModel) - { - if (contentModel == null) - return; - - switch (contentModel.getParticleType()) - { - case SchemaParticle.ELEMENT: - eltList.add(contentModel); - return; - case SchemaParticle.ALL: - case SchemaParticle.CHOICE: - case SchemaParticle.SEQUENCE: - for (int i = 0; i < contentModel.countOfParticleChild(); i++) - buildEltList(eltList, contentModel.getParticleChild(i)); - return; - default: - return; - } - } - - private void buildLocalElts() - { - List eltList = new ArrayList(); - buildEltList(eltList, _contentModel); - _localElts = (SchemaLocalElement[])eltList.toArray(new SchemaLocalElement[eltList.size()]); - } - - public SchemaLocalElement getLocalElementByIndex(int i) - { - SchemaLocalElement[] elts = _localElts; - if (elts == null) - { - buildLocalElts(); - elts = _localElts; - } - return elts[i]; - } - - public int getIndexForLocalElement(SchemaLocalElement elt) - { - Map localEltMap = _eltToIndexMap; - if (localEltMap == null) - { - if (_localElts == null) - buildLocalElts(); - localEltMap = new HashMap(); - for (int i = 0; i < _localElts.length; i++) - { - localEltMap.put(_localElts[i], new Integer(i)); - } - _eltToIndexMap = localEltMap; - } - return ((Integer)localEltMap.get(elt)).intValue(); - } - - public int getIndexForLocalAttribute(SchemaLocalAttribute attr) - { - Map localAttrMap = _attrToIndexMap; - if (localAttrMap == null) - { - localAttrMap = new HashMap(); - SchemaLocalAttribute[] attrs = this._attributeModel.getAttributes(); - for (int i = 0; i < attrs.length; i++) - { - localAttrMap.put(attrs[i], new Integer(i)); - } - _attrToIndexMap = localAttrMap; - } - return ((Integer)localAttrMap.get(attr)).intValue(); - } - - public SchemaAttributeModel getAttributeModel() - { return _attributeModel; } - - public SchemaProperty[] getProperties() - { - if (_propertyModelByElementName == null) - return getAttributeProperties(); - - if (_propertyModelByAttributeName == null) - return getElementProperties(); - - List list = new ArrayList(); - list.addAll(_propertyModelByElementName.values()); - list.addAll(_propertyModelByAttributeName.values()); - return (SchemaProperty[])list.toArray(new SchemaProperty[list.size()]); - } - - private static final SchemaProperty[] NO_PROPERTIES = new SchemaProperty[0]; - - public SchemaProperty[] getDerivedProperties() - { - SchemaType baseType = getBaseType(); - if (baseType == null) - return getProperties(); - - List results = new ArrayList(); - - if (_propertyModelByElementName != null) - results.addAll(_propertyModelByElementName.values()); - - if (_propertyModelByAttributeName != null) - results.addAll(_propertyModelByAttributeName.values()); - - for (Iterator it = results.iterator() ; it.hasNext() ; ) - { - SchemaProperty prop = (SchemaProperty)it.next(); - SchemaProperty baseProp = prop.isAttribute() ? - baseType.getAttributeProperty(prop.getName()) : - baseType.getElementProperty(prop.getName()); - - - // Remove the derived property from the results if it is - // A) present in the base type and - // B) all the details are the same (cardinality, nillability, default) - - if (baseProp != null) - { - if ( eq(prop.getMinOccurs(), baseProp.getMinOccurs()) && - eq(prop.getMaxOccurs(), baseProp.getMaxOccurs()) && - prop.hasNillable() == baseProp.hasNillable() && - eq(prop.getDefaultText(), baseProp.getDefaultText())) - { - it.remove(); - } - - } - - } - - return (SchemaProperty[])results.toArray(new SchemaProperty[results.size()]); - } - - private static boolean eq(BigInteger a, BigInteger b) - { - if (a == null && b == null) - return true; - if (a== null || b == null) - return false; - return a.equals(b); - } - - private static boolean eq(String a, String b) - { - if (a == null && b == null) - return true; - if (a== null || b == null) - return false; - return a.equals(b); - } - - public SchemaProperty[] getElementProperties() - { - if (_propertyModelByElementName == null) - return NO_PROPERTIES; - - return (SchemaProperty[]) - _propertyModelByElementName.values().toArray(new SchemaProperty[_propertyModelByElementName.size()]); - } - - public SchemaProperty[] getAttributeProperties() - { - if (_propertyModelByAttributeName == null) - return NO_PROPERTIES; - - return (SchemaProperty[]) - _propertyModelByAttributeName.values().toArray(new SchemaProperty[_propertyModelByAttributeName.size()]); - } - - public SchemaProperty getElementProperty(QName eltName) - { return _propertyModelByElementName == null ? null : (SchemaProperty)_propertyModelByElementName.get(eltName); } - - public SchemaProperty getAttributeProperty(QName attrName) - { return _propertyModelByAttributeName == null ? null : (SchemaProperty)_propertyModelByAttributeName.get(attrName); } - - public boolean hasAllContent() - { return _hasAllContent; } - - public boolean isOrderSensitive() - { return _orderSensitive; } - - public void setOrderSensitive(boolean sensitive) - { assertJavaizing(); _orderSensitive = sensitive; } - - public void setContentModel( - SchemaParticle contentModel, - SchemaAttributeModel attrModel, - Map propertyModelByElementName, - Map propertyModelByAttributeName, - boolean isAll) - { - assertResolving(); - _contentModel = contentModel; - _attributeModel = attrModel; - _propertyModelByElementName = propertyModelByElementName; - _propertyModelByAttributeName = propertyModelByAttributeName; - _hasAllContent = isAll; - - - // Add entries for each element property for substitution group members - if (_propertyModelByElementName != null) - { - _validSubstitutions = new LinkedHashSet(); - Collection eltProps = _propertyModelByElementName.values(); - for (Iterator it = eltProps.iterator() ; it.hasNext() ; ) - { - SchemaProperty prop = (SchemaProperty)it.next(); - QName[] names = prop.acceptedNames(); - for (int i = 0 ; i < names.length ; i++) - { - if (! _propertyModelByElementName.containsKey(names[i])) - _validSubstitutions.add(names[i]); - } - } - } - } - - private boolean containsElements() - { - return getContentType() == ELEMENT_CONTENT || - getContentType() == MIXED_CONTENT; - } - - public boolean hasAttributeWildcards() - { - return _hasWildcardAttributes; - } - - public boolean hasElementWildcards() - { - return _hasWildcardElements; - } - - public boolean isValidSubstitution(QName name) - { - return _validSubstitutions.contains(name); - } - - public SchemaType getElementType(QName eltName, QName xsiType, SchemaTypeLoader wildcardTypeLoader) - { - if (isSimpleType() || !containsElements() || isNoType()) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - - SchemaType type = null; - SchemaProperty prop = (SchemaProperty)_propertyModelByElementName.get(eltName); - if (prop != null) - { - type = prop.getType(); - } - else - { - if (wildcardTypeLoader == null) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - - if (_typedWildcardElements.contains(eltName) || - _validSubstitutions.contains(eltName)) - { - SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); - if (elt == null) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - // According to http://www.w3.org/TR/xmlschema-1/#key-lva, - // the line above should return ST_ANY_TYPE. - type = elt.getType(); - } - else - { - // Substitution groups - // Actually, better not enable this yet - /*SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); - SchemaGlobalElement sghead = elt == null ? null : elt.substitutionGroup(); - while (sghead != null) - { - prop = (SchemaProperty)_propertyModelByElementName.get(sghead.getName()); - if (prop != null) - { - type = elt.getType(); - break; - } - sghead = sghead.substitutionGroup(); - } - */ - if (type == null) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - } - - if (xsiType != null && wildcardTypeLoader != null) - { - SchemaType itype = wildcardTypeLoader.findType(xsiType); - - // NOTE: a previous version of XMLBeans used ST_NO_TYPE if the - // xsiType was not derived from 'type', but this results in a - // ClassCastException. Instead we ignore xsi:type if it's not - // found or a derived type. - if (itype != null && type.isAssignableFrom(itype)) { - return itype; - } - } - - return type; - } - - public SchemaType getAttributeType(QName attrName, SchemaTypeLoader wildcardTypeLoader) - { - if (isSimpleType() || isNoType()) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - - if (isURType()) - return BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - - SchemaProperty prop = (SchemaProperty)_propertyModelByAttributeName.get(attrName); - if (prop != null) - return prop.getType(); - - if (!_typedWildcardAttributes.contains(attrName) || wildcardTypeLoader == null) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - // For symmetry with the element case (as well as with URType), perhaps - // the above line should be returning ST_ANY_SIMPLE - - SchemaGlobalAttribute attr = wildcardTypeLoader.findAttribute(attrName); - if (attr == null) - return BuiltinSchemaTypeSystem.ST_NO_TYPE; - return attr.getType(); - } - - /* These two methods, createElementType and getElementType have to stay - * synchronized, because they create an XmlObject and return the type - * for that object, respectively. But since they do slightly different - * things, they can't be refactored to share code, so exercise caution - */ - public XmlObject createElementType(QName eltName, QName xsiType, SchemaTypeLoader wildcardTypeLoader) - { - SchemaType type = null; - SchemaProperty prop = null; - if (isSimpleType() || !containsElements() || isNoType()) - { - type = BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - else - { - prop = (SchemaProperty)_propertyModelByElementName.get(eltName); - if (prop != null) - { - type = prop.getType(); - } - else if (_typedWildcardElements.contains(eltName) || - _validSubstitutions.contains(eltName)) - { - SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); - if (elt != null) - { - type = elt.getType(); - SchemaType docType = wildcardTypeLoader.findDocumentType(eltName); - if (docType != null) - prop = docType.getElementProperty(eltName); - } - else - type = BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - else - { - // Check if the requested element isn't by any chance part of a - // substitution group headed by one of the declared elements - // Better not enable this yet - /* - SchemaGlobalElement elt = wildcardTypeLoader.findElement(eltName); - SchemaGlobalElement sghead = elt == null ? null : elt.substitutionGroup(); - while (sghead != null) - { - if (_propertyModelByElementName.containsKey(sghead.getName())) - { - type = elt.getType(); - SchemaType docType = wildcardTypeLoader.findDocumentType(elt.getName()); - if (docType != null) - prop = docType.getElementProperty(elt.getName()); - break; - } - sghead = sghead.substitutionGroup(); - } - */ - if (type == null) - type = BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - - if (xsiType != null) - { - SchemaType itype = wildcardTypeLoader.findType(xsiType); - - // NOTE: a previous version of XMLBeans used ST_NO_TYPE if the - // xsiType was not derived from 'type', but this results in a - // ClassCastException. Instead we ignore xsi:type if it's not - // found or a derived type. - if (itype != null && type.isAssignableFrom(itype)) { - type = itype; - } - } - } - - if (type != null) - return ((SchemaTypeImpl)type).createUnattachedNode(prop); - return null; - } - - public XmlObject createAttributeType(QName attrName, SchemaTypeLoader wildcardTypeLoader) - { - SchemaTypeImpl type = null; - SchemaProperty prop = null; - if (isSimpleType() || isNoType()) - { - type = BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - else if (isURType()) - { - type = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - else - { - prop = (SchemaProperty)_propertyModelByAttributeName.get(attrName); - if (prop != null) - { - type = (SchemaTypeImpl)prop.getType(); - } - else if (!_typedWildcardAttributes.contains(attrName)) - { - type = BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - else - { - SchemaGlobalAttribute attr = wildcardTypeLoader.findAttribute(attrName); - if (attr != null) - type = (SchemaTypeImpl)attr.getType(); - else - type = BuiltinSchemaTypeSystem.ST_NO_TYPE; - } - } - - if (type != null) - return type.createUnattachedNode(prop); - - return null; - } - - public void setWildcardSummary(QNameSet elementSet, boolean haswcElt, QNameSet attributeSet, boolean haswcAtt) - { - assertResolving(); _typedWildcardElements = elementSet; _hasWildcardElements = haswcElt; _typedWildcardAttributes = attributeSet; _hasWildcardAttributes = haswcAtt; - } - - public SchemaType[] getAnonymousTypes() - { - SchemaType[] result = new SchemaType[_anonymousTyperefs.length]; - for (int i = 0; i < result.length; i++) - result[i] = _anonymousTyperefs[i].get(); - return result; - } - - public void setAnonymousTypeRefs(SchemaType.Ref[] anonymousTyperefs) - { - _anonymousTyperefs = anonymousTyperefs; - } - - - private static SchemaType[] staCopy(SchemaType[] a) - { - if (a == null) - return null; - - SchemaType[] result = new SchemaType[a.length]; - System.arraycopy(a, 0, result, 0, a.length); - return result; - } - - private static boolean[] boaCopy(boolean[] a) - { - if (a == null) - return null; - - boolean[] result = new boolean[a.length]; - System.arraycopy(a, 0, result, 0, a.length); - return result; - } - - - - public void setSimpleTypeVariety(int variety) - { assertResolving(); _simpleTypeVariety = variety; } - - public int getSimpleVariety() - { return _simpleTypeVariety; } - - public boolean isURType() - { return _builtinTypeCode == BTC_ANY_TYPE || _builtinTypeCode == BTC_ANY_SIMPLE; } - - public boolean isNoType() - { return this == BuiltinSchemaTypeSystem.ST_NO_TYPE; } - - public boolean isSimpleType() - { return _isSimpleType; } - - public void setSimpleType(boolean f) - { assertUnresolved(); _isSimpleType = f; } - - public boolean isUnionOfLists() - { return _isUnionOfLists; } - - public void setUnionOfLists(boolean f) - { assertResolving(); _isUnionOfLists = f; } - - public SchemaType getPrimitiveType() - { return _primitiveTypeRef == null ? null : _primitiveTypeRef.get(); } - - public void setPrimitiveTypeRef(SchemaType.Ref typeref) - { assertResolving(); _primitiveTypeRef = typeref; } - - public int getDecimalSize() - { return _decimalSize; } - - public void setDecimalSize(int bits) - { assertResolving(); _decimalSize = bits; } - - public SchemaType getBaseType() - { return _baseTyperef == null ? null : _baseTyperef.get(); } - - public void setBaseTypeRef(SchemaType.Ref typeref) - { assertResolving(); _baseTyperef = typeref; } - - public int getBaseDepth() - { return _baseDepth; } - - public void setBaseDepth(int depth) - { assertResolving(); _baseDepth = depth; } - - public SchemaType getContentBasedOnType() - { return _contentBasedOnTyperef == null ? null : _contentBasedOnTyperef.get(); } - - public void setContentBasedOnTypeRef(SchemaType.Ref typeref) - { assertResolving(); _contentBasedOnTyperef = typeref; } - - public int getDerivationType() - { return _derivationType; } - - public void setDerivationType(int type) - { assertResolving(); _derivationType = type; } - - public SchemaType getListItemType() - { return _listItemTyperef == null ? null : _listItemTyperef.get(); } - - public void setListItemTypeRef(SchemaType.Ref typeref) - { assertResolving(); _listItemTyperef = typeref; } - - public SchemaType[] getUnionMemberTypes() - { - SchemaType[] result = new SchemaType[_unionMemberTyperefs ==null ? 0 : _unionMemberTyperefs.length]; - for (int i = 0; i < result.length; i++) - result[i] = _unionMemberTyperefs[i].get(); - return result; - } - - public void setUnionMemberTypeRefs(SchemaType.Ref[] typerefs) - { assertResolving(); _unionMemberTyperefs = typerefs; } - - public int getAnonymousUnionMemberOrdinal() - { return _anonymousUnionMemberOrdinal; } - - public void setAnonymousUnionMemberOrdinal(int i) - { assertUnresolved(); _anonymousUnionMemberOrdinal = i; } - - public synchronized SchemaType[] getUnionConstituentTypes() - { - if (_unionCommonBaseType == null) - computeFlatUnionModel(); - return staCopy(_unionConstituentTypes); - } - - private void setUnionConstituentTypes(SchemaType[] types) - { _unionConstituentTypes = types; } - - public synchronized SchemaType[] getUnionSubTypes() - { - if (_unionCommonBaseType == null) - computeFlatUnionModel(); - return staCopy(_unionSubTypes); - } - - private void setUnionSubTypes(SchemaType[] types) - { _unionSubTypes = types; } - - public synchronized SchemaType getUnionCommonBaseType() - { - if (_unionCommonBaseType == null) - computeFlatUnionModel(); - return _unionCommonBaseType; - } - - private void setUnionCommonBaseType(SchemaType type) - { _unionCommonBaseType = type; } - - private void computeFlatUnionModel() - { - if (getSimpleVariety() != SchemaType.UNION) - throw new IllegalStateException("Operation is only supported on union types"); - Set constituentMemberTypes = new LinkedHashSet(); - Set allSubTypes = new LinkedHashSet(); - SchemaType commonBaseType = null; - - allSubTypes.add(this); - - for (int i = 0; i < _unionMemberTyperefs.length; i++) - { - SchemaTypeImpl mImpl = (SchemaTypeImpl)_unionMemberTyperefs[i].get(); - - switch (mImpl.getSimpleVariety()) - { - case SchemaType.LIST: - constituentMemberTypes.add(mImpl); - allSubTypes.add(mImpl); - commonBaseType = mImpl.getCommonBaseType(commonBaseType); - break; - case SchemaType.UNION: - constituentMemberTypes.addAll(Arrays.asList(mImpl.getUnionConstituentTypes())); - allSubTypes.addAll(Arrays.asList(mImpl.getUnionSubTypes())); - SchemaType otherCommonBaseType = mImpl.getUnionCommonBaseType(); - if (otherCommonBaseType != null) - commonBaseType = otherCommonBaseType.getCommonBaseType(commonBaseType); - break; - case SchemaType.ATOMIC: - constituentMemberTypes.add(mImpl); - allSubTypes.add(mImpl); - commonBaseType = mImpl.getCommonBaseType(commonBaseType); - break; - default: - assert(false); - } - } - - setUnionConstituentTypes((SchemaType[]) - constituentMemberTypes.toArray(StscState.EMPTY_ST_ARRAY)); - setUnionSubTypes((SchemaType[]) - allSubTypes.toArray(StscState.EMPTY_ST_ARRAY)); - setUnionCommonBaseType(commonBaseType); - } - - public QName getSubstitutionGroup() - { return _sg; } - - public void setSubstitutionGroup(QName sg) - { assertSGResolving(); _sg = sg; } - - public void addSubstitutionGroupMember(QName member) - { assertSGResolved(); _sgMembers.add(member); } - - public QName[] getSubstitutionGroupMembers() - { - QName[] result = new QName[_sgMembers.size()]; - return (QName[])_sgMembers.toArray(result); - } - - public int getWhiteSpaceRule() - { return _whiteSpaceRule; } - - public void setWhiteSpaceRule(int ws) - { assertResolving(); _whiteSpaceRule = ws; } - - public XmlAnySimpleType getFacet(int facetCode) - { - if (_facetArray == null) - return null; - XmlValueRef ref = _facetArray[facetCode]; - if (ref == null) - return null; - return ref.get(); - } - - public boolean isFacetFixed(int facetCode) - { - return _fixedFacetArray[facetCode]; - } - - public XmlAnySimpleType[] getBasicFacets() - { - XmlAnySimpleType[] result = new XmlAnySimpleType[SchemaType.LAST_FACET + 1]; - for (int i = 0; i <= SchemaType.LAST_FACET; i++) - { - result[i] = getFacet(i); - } - return result; - } - - public boolean[] getFixedFacets() - { - return boaCopy(_fixedFacetArray); - } - - public void setBasicFacets(XmlValueRef[] values, boolean[] fixed) - { - assertResolving(); - _facetArray = values; - _fixedFacetArray = fixed; - } - - public int ordered() - { return _ordered; } - - public void setOrdered(int ordering) - { assertResolving(); _ordered = ordering; } - - public boolean isBounded() - { return _isBounded; } - - public void setBounded(boolean f) - { assertResolving(); _isBounded = f; } - - public boolean isFinite() - { return _isFinite; } - - public void setFinite(boolean f) - { assertResolving(); _isFinite = f; } - - public boolean isNumeric() - { return _isNumeric; } - - public void setNumeric(boolean f) - { assertResolving(); _isNumeric = f; } - - - public boolean hasPatternFacet() - { return _hasPatterns; } - - public void setPatternFacet(boolean hasPatterns) - { assertResolving(); _hasPatterns = hasPatterns; } - - public boolean matchPatternFacet(String s) - { - if (!_hasPatterns) - return true; - - if (_patterns != null && _patterns.length > 0) - { - int i; - for (i = 0; i < _patterns.length; i++) - { - if (_patterns[i].matches(s)) - break; - } - if (i >= _patterns.length) - return false; - } - - return getBaseType().matchPatternFacet(s); - } - - public String[] getPatterns() - { - if (_patterns == null) - return new String[0]; - String[] patterns = new String[_patterns.length]; - for (int i=0; i< _patterns.length; i++) - patterns[i] = _patterns[i].getPattern(); - return patterns; - } - - public org.apache.xmlbeans.impl.regex.RegularExpression[] getPatternExpressions() - { - if (_patterns == null) - return new org.apache.xmlbeans.impl.regex.RegularExpression[0]; - org.apache.xmlbeans.impl.regex.RegularExpression[] result = new org.apache.xmlbeans.impl.regex.RegularExpression[_patterns.length]; - System.arraycopy(_patterns, 0, result, 0, _patterns.length); - return result; - } - - public void setPatterns(org.apache.xmlbeans.impl.regex.RegularExpression[] list) - { assertResolving(); _patterns = list; } - - public XmlAnySimpleType[] getEnumerationValues() - { - if (_enumerationValues == null) - return null; - XmlAnySimpleType[] result = new XmlAnySimpleType[_enumerationValues.length]; - for (int i = 0; i < result.length; i++) - { - XmlValueRef ref = _enumerationValues[i]; - result[i] = (ref == null ? null : ref.get()); - - } - return result; - } - - public void setEnumerationValues(XmlValueRef[] a) - { assertResolving(); _enumerationValues = a; } - - public StringEnumAbstractBase enumForString(String s) - { - ensureStringEnumInfo(); - if (_lookupStringEnum == null) - return null; - return (StringEnumAbstractBase)_lookupStringEnum.get(s); - } - - public StringEnumAbstractBase enumForInt(int i) - { - ensureStringEnumInfo(); - if (_listOfStringEnum == null || i < 0 || i >= _listOfStringEnum.size()) - return null; - return (StringEnumAbstractBase)_listOfStringEnum.get(i); - } - - public SchemaStringEnumEntry enumEntryForString(String s) - { - ensureStringEnumInfo(); - if (_lookupStringEnumEntry == null) - return null; - return (SchemaStringEnumEntry)_lookupStringEnumEntry.get(s); - } - - public SchemaType getBaseEnumType() - { - return _baseEnumTyperef == null ? null : _baseEnumTyperef.get(); - } - - public void setBaseEnumTypeRef(SchemaType.Ref baseEnumTyperef) - { - _baseEnumTyperef = baseEnumTyperef; - } - - public SchemaStringEnumEntry[] getStringEnumEntries() - { - if (_stringEnumEntries == null) - return null; - SchemaStringEnumEntry[] result = new SchemaStringEnumEntry[_stringEnumEntries.length]; - System.arraycopy(_stringEnumEntries, 0, result, 0, result.length); - return result; - } - - public void setStringEnumEntries(SchemaStringEnumEntry sEnums[]) - { - assertJavaizing(); - _stringEnumEntries = sEnums; - } - - private void ensureStringEnumInfo() - { - if (_stringEnumEnsured) - return; - - SchemaStringEnumEntry[] sEnums = _stringEnumEntries; - if (sEnums == null) - { - _stringEnumEnsured = true; - return; - } - - Map lookupStringEnum = new HashMap(sEnums.length); - List listOfStringEnum = new ArrayList(sEnums.length + 1); - Map lookupStringEnumEntry = new HashMap(sEnums.length); - - for (int i = 0; i < sEnums.length; i++) - { - lookupStringEnumEntry.put(sEnums[i].getString(), sEnums[i]); - } - - Class jc = _baseEnumTyperef.get().getEnumJavaClass(); - if (jc != null) - { - try - { - StringEnumAbstractBase.Table table = (StringEnumAbstractBase.Table)jc.getField("table").get(null); - for (int i = 0; i < sEnums.length; i++) - { - int j = sEnums[i].getIntValue(); - StringEnumAbstractBase enumVal = table.forInt(j); - lookupStringEnum.put(sEnums[i].getString(), enumVal); - while (listOfStringEnum.size() <= j) - listOfStringEnum.add(null); - listOfStringEnum.set(j, enumVal); - } - } - catch (Exception e) - { - System.err.println("Something wrong: could not locate enum table for " + jc); - jc = null; - lookupStringEnum.clear(); - listOfStringEnum.clear(); - } - } - - if (jc == null) - { - for (int i = 0; i < sEnums.length; i++) - { - int j = sEnums[i].getIntValue(); - String s = sEnums[i].getString(); - StringEnumAbstractBase enumVal = new StringEnumValue(s, j); - lookupStringEnum.put(s, enumVal); - while (listOfStringEnum.size() <= j) - listOfStringEnum.add(null); - listOfStringEnum.set(j, enumVal); - } - } - - synchronized (this) - { - if (!_stringEnumEnsured) - { - _lookupStringEnum = lookupStringEnum; - _listOfStringEnum = listOfStringEnum; - _lookupStringEnumEntry = lookupStringEnumEntry; - } - } - // HACKHACK: two syncrhonized blocks force a memory barrier: - // BUGBUG: this behavior is likely to change in future VMs - synchronized (this) - { - _stringEnumEnsured = true; - } - } - - public boolean hasStringEnumValues() - { - return _stringEnumEntries != null; - } - - public void copyEnumerationValues(SchemaTypeImpl baseImpl) - { - assertResolving(); - _enumerationValues = baseImpl._enumerationValues; - _baseEnumTyperef = baseImpl._baseEnumTyperef; - } - - public int getBuiltinTypeCode() - { return _builtinTypeCode; } // special: set up pre-init - - public void setBuiltinTypeCode(int builtinTypeCode) - { assertResolving(); _builtinTypeCode = builtinTypeCode; } - - synchronized void assignJavaElementSetterModel() - { - // To compute the element setter model, we need to compute the - // delimiting elements for each element. - - SchemaProperty[] eltProps = getElementProperties(); - SchemaParticle contentModel = getContentModel(); - Map state = new HashMap(); - QNameSet allContents = computeAllContainedElements(contentModel, state); - - for (int i = 0; i < eltProps.length; i++) - { - SchemaPropertyImpl sImpl = (SchemaPropertyImpl)eltProps[i]; - QNameSet nde = computeNondelimitingElements(sImpl.getName(), contentModel, state); - QNameSetBuilder builder = new QNameSetBuilder(allContents); - builder.removeAll(nde); - sImpl.setJavaSetterDelimiter(builder.toQNameSet()); - } - } - - /** - * Used to compute setter model. - * - * Returns the QNameSet of all elements that can possibly come before an - * element whose name is given by the target in a valid instance of the - * contentModel. When appending an element, it comes before the first - * one that is not in this set. - */ - private static QNameSet computeNondelimitingElements(QName target, SchemaParticle contentModel, Map state) - { - QNameSet allContents = computeAllContainedElements(contentModel, state); - if (!allContents.contains(target)) - return QNameSet.EMPTY; - - // If iterated, then all contents are delimiting. - if (contentModel.getMaxOccurs() == null || - contentModel.getMaxOccurs().compareTo(BigInteger.ONE) > 0) - return allContents; - - QNameSetBuilder builder; - - switch (contentModel.getParticleType()) - { - case SchemaParticle.ALL: - case SchemaParticle.ELEMENT: - default: - return allContents; - - case SchemaParticle.WILDCARD: - return QNameSet.singleton(target); - - case SchemaParticle.CHOICE: - builder = new QNameSetBuilder(); - for (int i = 0; i < contentModel.countOfParticleChild(); i++) - { - QNameSet childContents = computeAllContainedElements(contentModel.getParticleChild(i), state); - if (childContents.contains(target)) - builder.addAll(computeNondelimitingElements(target, contentModel.getParticleChild(i), state)); - } - return builder.toQNameSet(); - - case SchemaParticle.SEQUENCE: - builder = new QNameSetBuilder(); - boolean seenTarget = false; - for (int i = contentModel.countOfParticleChild(); i > 0; ) - { - i--; - QNameSet childContents = computeAllContainedElements(contentModel.getParticleChild(i), state); - if (seenTarget) - { - builder.addAll(childContents); - } - else if (childContents.contains(target)) - { - builder.addAll(computeNondelimitingElements(target, contentModel.getParticleChild(i), state)); - seenTarget = true; - } - } - return builder.toQNameSet(); - } - } - - /** - * Used to compute the setter model. - * - * Returns the set of all QNames of elements that could possibly be - * contained in the given contentModel. The state variable is used - * to record the results, so that if they are needed again later, - * they do not need to be recomputed. - */ - private static QNameSet computeAllContainedElements(SchemaParticle contentModel, Map state) - { - // Remember previously computed results to avoid complexity explosion - QNameSet result = (QNameSet)state.get(contentModel); - if (result != null) - return result; - - QNameSetBuilder builder; - - switch (contentModel.getParticleType()) - { - case SchemaParticle.ALL: - case SchemaParticle.CHOICE: - case SchemaParticle.SEQUENCE: - default: - builder = new QNameSetBuilder(); - for (int i = 0; i < contentModel.countOfParticleChild(); i++) - { - builder.addAll(computeAllContainedElements(contentModel.getParticleChild(i), state)); - } - result = builder.toQNameSet(); - break; - - case SchemaParticle.WILDCARD: - result = contentModel.getWildcardSet(); - break; - - case SchemaParticle.ELEMENT: - // Fix for XMLBEANS-228 - result = ((SchemaLocalElementImpl) contentModel).acceptedStartNames(); - break; - } - state.put(contentModel, result); - return result; - } - - public Class getJavaClass() - { - // This field is declared volatile and Class is immutable so this is allowed. - if (_javaClass == null && getFullJavaName() != null) - { - try - { _javaClass = Class.forName(getFullJavaName(), false, getTypeSystem().getClassLoader()); } - catch (ClassNotFoundException e) - { -// This is a legitimate use, when users get a SchemaTypeSystem without compiling classes -// System.err.println("Could not find class name " + getFullJavaName()); -// System.err.println("Searched in classloader " + getTypeSystem().getClassLoader()); -// e.printStackTrace(System.err); - _javaClass = null; - } - } - - return _javaClass; - } - - public Class getJavaImplClass() { - if (_implNotAvailable) - return null; - - if (_javaImplClass == null) - { - try { - if (getFullJavaImplName() != null) - _javaImplClass = Class.forName(getFullJavaImplName(), false, getTypeSystem().getClassLoader()); - else - _implNotAvailable = true; - } - catch (ClassNotFoundException e) { - _implNotAvailable = true; - } - } - - return _javaImplClass; - } - - public Class getUserTypeClass() - { - // This field is declared volatile and Class is immutable so this is allowed. - if (_userTypeClass == null && getUserTypeName() != null) - { - try - { - _userTypeClass = Class.forName(_userTypeName, false, - getTypeSystem().getClassLoader()); - } - catch (ClassNotFoundException e) - { - _userTypeClass = null; - } - } - - return _userTypeClass; - } - - public Class getUserTypeHandlerClass() - { - // This field is declared volatile and Class is immutable so this is allowed. - if (_userTypeHandlerClass == null && getUserTypeHandlerName() != null) - { - try - { - _userTypeHandlerClass = Class.forName(_userTypeHandler, false, - getTypeSystem().getClassLoader()); - } - catch (ClassNotFoundException e) - { - _userTypeHandlerClass = null; - } - } - - return _userTypeHandlerClass; - } - - public Constructor getJavaImplConstructor() - { - if (_javaImplConstructor == null && !_implNotAvailable) - { - final Class impl = getJavaImplClass(); - if (impl == null) return null; - try - { - _javaImplConstructor = impl.getConstructor(new Class[] { SchemaType.class }); - } - catch (NoSuchMethodException e) - { - e.printStackTrace(); - } - } - - return _javaImplConstructor; - - } - - public Constructor getJavaImplConstructor2() - { - if (_javaImplConstructor2 == null && !_implNotAvailable) - { - final Class impl = getJavaImplClass(); - if (impl == null) return null; - try - { - _javaImplConstructor2 = impl.getDeclaredConstructor(new Class[] { SchemaType.class, boolean.class }); - } - catch (NoSuchMethodException e) - { - e.printStackTrace(); - } - } - - return _javaImplConstructor2; - - } - - public Class getEnumJavaClass() - { - // This field is declared volatile and Class is immutable so this is allowed. - if (_javaEnumClass == null) - { - if ( getBaseEnumType() != null ) - { - try - { - _javaEnumClass = Class.forName(getBaseEnumType().getFullJavaName() + "$Enum", false, getTypeSystem().getClassLoader()); - } - catch (ClassNotFoundException e) - { - _javaEnumClass = null; - } - } - } - - return _javaEnumClass; - } - - public void setJavaClass(Class javaClass) - { - assertResolved(); - _javaClass = javaClass; - setFullJavaName(javaClass.getName()); - } - - public boolean isPrimitiveType() - { - return (getBuiltinTypeCode() >= BTC_FIRST_PRIMITIVE && - getBuiltinTypeCode() <= BTC_LAST_PRIMITIVE); - } - - public boolean isBuiltinType() - { - return getBuiltinTypeCode() != 0; - } - - public XmlObject createUnwrappedNode() - { - // Todo: attach a new xml store! - XmlObject result = createUnattachedNode(null); - return result; - } - - /** - * TypeStoreUserFactory implementation - */ - public TypeStoreUser createTypeStoreUser() - { - return (TypeStoreUser)createUnattachedNode(null); - } - - - public XmlAnySimpleType newValidatingValue(Object obj) - { - return newValue(obj, true); - } - /** - * Creates an immutable simple value. - */ - public XmlAnySimpleType newValue(Object obj) - { - return newValue(obj, false); - } - - public XmlAnySimpleType newValue(Object obj, boolean validateOnSet) - { - if (!isSimpleType() && getContentType() != SchemaType.SIMPLE_CONTENT) - throw new XmlValueOutOfRangeException(); // values must be simple - - XmlObjectBase result = (XmlObjectBase)createUnattachedNode(null); - if (validateOnSet) - result.setValidateOnSet(); - - // In the case of tree copy, need to call a specla setter to avoid - // set(XmlObject) - if (obj instanceof XmlObject) - result.set_newValue((XmlObject)obj); - else - result.objectSet(obj); - - result.check_dated(); - result.setImmutable(); - - return (XmlAnySimpleType) result; - } - - /** - * Creates an instance of this type. - */ - private XmlObject createUnattachedNode(SchemaProperty prop) - { - XmlObject result = null; - - if (!isBuiltinType() && !isNoType()) - { - // System.out.println("Attempting to load impl class: " + getFullJavaImplName()); - Constructor ctr = getJavaImplConstructor(); - if (ctr != null) - { - try - { - // System.out.println("Succeeded!"); - return (XmlObject)ctr.newInstance(_ctrArgs); - } - catch (Exception e) - { - System.out.println("Exception trying to instantiate impl class."); - e.printStackTrace(); - } - } - } - else - { - result = createBuiltinInstance(); - } - - // if no result, we must be a restriction of some compiled type - for (SchemaType sType = this; result == null; sType = sType.getBaseType()) - result = ((SchemaTypeImpl)sType).createUnattachedSubclass(this); - - ((XmlObjectBase)result).init_flags(prop); - return result; - } - - private XmlObject createUnattachedSubclass(SchemaType sType) - { - if (!isBuiltinType() && !isNoType()) - { - // System.out.println("Attempting to load impl class: " + getFullJavaImplName()); - Constructor ctr = getJavaImplConstructor2(); - if (ctr != null) - { - boolean accessible = ctr.isAccessible(); - try - { - ctr.setAccessible(true); - // System.out.println("Succeeded!"); - try - { - return (XmlObject)ctr.newInstance(new Object[] { sType, sType.isSimpleType() ? Boolean.FALSE : Boolean.TRUE }); - } - catch (Exception e) - { - System.out.println("Exception trying to instantiate impl class."); - e.printStackTrace(); - } - finally - { - // Make a best-effort try to set the accessibility back to what it was - try - { ctr.setAccessible(accessible); } - catch (SecurityException se) - { } - } - } - catch (Exception e) - { - System.out.println("Exception trying to instantiate impl class."); - e.printStackTrace(); - } - } - return null; - } - else - { - return createBuiltinSubclass(sType); - } - } - - private XmlObject createBuiltinInstance() - { - switch (getBuiltinTypeCode()) - { - case BTC_NOT_BUILTIN: - return new XmlAnyTypeImpl(BuiltinSchemaTypeSystem.ST_NO_TYPE); - case BTC_ANY_TYPE: - return new XmlAnyTypeImpl(); - case BTC_ANY_SIMPLE: - return new XmlAnySimpleTypeImpl(); - case BTC_BOOLEAN: - return new XmlBooleanImpl(); - case BTC_BASE_64_BINARY: - return new XmlBase64BinaryImpl(); - case BTC_HEX_BINARY: - return new XmlHexBinaryImpl(); - case BTC_ANY_URI: - return new XmlAnyUriImpl(); - case BTC_QNAME: - return new XmlQNameImpl(); - case BTC_NOTATION: - return new XmlNotationImpl(); - case BTC_FLOAT: - return new XmlFloatImpl(); - case BTC_DOUBLE: - return new XmlDoubleImpl(); - case BTC_DECIMAL: - return new XmlDecimalImpl(); - case BTC_STRING: - return new XmlStringImpl(); - case BTC_DURATION: - return new XmlDurationImpl(); - case BTC_DATE_TIME: - return new XmlDateTimeImpl(); - case BTC_TIME: - return new XmlTimeImpl(); - case BTC_DATE: - return new XmlDateImpl(); - case BTC_G_YEAR_MONTH: - return new XmlGYearMonthImpl(); - case BTC_G_YEAR: - return new XmlGYearImpl(); - case BTC_G_MONTH_DAY: - return new XmlGMonthDayImpl(); - case BTC_G_DAY: - return new XmlGDayImpl(); - case BTC_G_MONTH: - return new XmlGMonthImpl(); - case BTC_INTEGER: - return new XmlIntegerImpl(); - case BTC_LONG: - return new XmlLongImpl(); - case BTC_INT: - return new XmlIntImpl(); - case BTC_SHORT: - return new XmlShortImpl(); - case BTC_BYTE: - return new XmlByteImpl(); - case BTC_NON_POSITIVE_INTEGER: - return new XmlNonPositiveIntegerImpl(); - case BTC_NEGATIVE_INTEGER: - return new XmlNegativeIntegerImpl(); - case BTC_NON_NEGATIVE_INTEGER: - return new XmlNonNegativeIntegerImpl(); - case BTC_POSITIVE_INTEGER: - return new XmlPositiveIntegerImpl(); - case BTC_UNSIGNED_LONG: - return new XmlUnsignedLongImpl(); - case BTC_UNSIGNED_INT: - return new XmlUnsignedIntImpl(); - case BTC_UNSIGNED_SHORT: - return new XmlUnsignedShortImpl(); - case BTC_UNSIGNED_BYTE: - return new XmlUnsignedByteImpl(); - case BTC_NORMALIZED_STRING: - return new XmlNormalizedStringImpl(); - case BTC_TOKEN: - return new XmlTokenImpl(); - case BTC_NAME: - return new XmlNameImpl(); - case BTC_NCNAME: - return new XmlNCNameImpl(); - case BTC_LANGUAGE: - return new XmlLanguageImpl(); - case BTC_ID: - return new XmlIdImpl(); - case BTC_IDREF: - return new XmlIdRefImpl(); - case BTC_IDREFS: - return new XmlIdRefsImpl(); - case BTC_ENTITY: - return new XmlEntityImpl(); - case BTC_ENTITIES: - return new XmlEntitiesImpl(); - case BTC_NMTOKEN: - return new XmlNmTokenImpl(); - case BTC_NMTOKENS: - return new XmlNmTokensImpl(); - default: - throw new IllegalStateException("Unrecognized builtin type: " + getBuiltinTypeCode()); - } - } - - private XmlObject createBuiltinSubclass(SchemaType sType) - { - boolean complex = !sType.isSimpleType(); - switch (getBuiltinTypeCode()) - { - case BTC_NOT_BUILTIN: - return new XmlAnyTypeImpl(BuiltinSchemaTypeSystem.ST_NO_TYPE); - case BTC_ANY_TYPE: - case BTC_ANY_SIMPLE: - switch (sType.getSimpleVariety()) - { - case NOT_SIMPLE: - return new XmlComplexContentImpl(sType); - case ATOMIC: - return new XmlAnySimpleTypeRestriction(sType, complex); - case LIST: - return new XmlListImpl(sType, complex); - case UNION: - return new XmlUnionImpl(sType, complex); - default: - throw new IllegalStateException(); - } - case BTC_BOOLEAN: - return new XmlBooleanRestriction(sType, complex); - case BTC_BASE_64_BINARY: - return new XmlBase64BinaryRestriction(sType, complex); - case BTC_HEX_BINARY: - return new XmlHexBinaryRestriction(sType, complex); - case BTC_ANY_URI: - return new XmlAnyUriRestriction(sType, complex); - case BTC_QNAME: - return new XmlQNameRestriction(sType, complex); - case BTC_NOTATION: - return new XmlNotationRestriction(sType, complex); - case BTC_FLOAT: - return new XmlFloatRestriction(sType, complex); - case BTC_DOUBLE: - return new XmlDoubleRestriction(sType, complex); - case BTC_DECIMAL: - return new XmlDecimalRestriction(sType, complex); - case BTC_STRING: - if (sType.hasStringEnumValues()) - return new XmlStringEnumeration(sType, complex); - else - return new XmlStringRestriction(sType, complex); - case BTC_DURATION: - return new XmlDurationImpl(sType, complex); - case BTC_DATE_TIME: - return new XmlDateTimeImpl(sType, complex); - case BTC_TIME: - return new XmlTimeImpl(sType, complex); - case BTC_DATE: - return new XmlDateImpl(sType, complex); - case BTC_G_YEAR_MONTH: - return new XmlGYearMonthImpl(sType, complex); - case BTC_G_YEAR: - return new XmlGYearImpl(sType, complex); - case BTC_G_MONTH_DAY: - return new XmlGMonthDayImpl(sType, complex); - case BTC_G_DAY: - return new XmlGDayImpl(sType, complex); - case BTC_G_MONTH: - return new XmlGMonthImpl(sType, complex); - case BTC_INTEGER: - return new XmlIntegerRestriction(sType, complex); - case BTC_LONG: - return new XmlLongRestriction(sType, complex); - case BTC_INT: - return new XmlIntRestriction(sType, complex); - case BTC_SHORT: - return new XmlShortImpl(sType, complex); - case BTC_BYTE: - return new XmlByteImpl(sType, complex); - case BTC_NON_POSITIVE_INTEGER: - return new XmlNonPositiveIntegerImpl(sType, complex); - case BTC_NEGATIVE_INTEGER: - return new XmlNegativeIntegerImpl(sType, complex); - case BTC_NON_NEGATIVE_INTEGER: - return new XmlNonNegativeIntegerImpl(sType, complex); - case BTC_POSITIVE_INTEGER: - return new XmlPositiveIntegerImpl(sType, complex); - case BTC_UNSIGNED_LONG: - return new XmlUnsignedLongImpl(sType, complex); - case BTC_UNSIGNED_INT: - return new XmlUnsignedIntImpl(sType, complex); - case BTC_UNSIGNED_SHORT: - return new XmlUnsignedShortImpl(sType, complex); - case BTC_UNSIGNED_BYTE: - return new XmlUnsignedByteImpl(sType, complex); - case BTC_NORMALIZED_STRING: - return new XmlNormalizedStringImpl(sType, complex); - case BTC_TOKEN: - return new XmlTokenImpl(sType, complex); - case BTC_NAME: - return new XmlNameImpl(sType, complex); - case BTC_NCNAME: - return new XmlNCNameImpl(sType, complex); - case BTC_LANGUAGE: - return new XmlLanguageImpl(sType, complex); - case BTC_ID: - return new XmlIdImpl(sType, complex); - case BTC_IDREF: - return new XmlIdRefImpl(sType, complex); - case BTC_IDREFS: - return new XmlIdRefsImpl(sType, complex); - case BTC_ENTITY: - return new XmlEntityImpl(sType, complex); - case BTC_ENTITIES: - return new XmlEntitiesImpl(sType, complex); - case BTC_NMTOKEN: - return new XmlNmTokenImpl(sType, complex); - case BTC_NMTOKENS: - return new XmlNmTokensImpl(sType, complex); - default: - throw new IllegalStateException("Unrecognized builtin type: " + getBuiltinTypeCode()); - } - } - - public SchemaType getCommonBaseType(SchemaType type) - { - // null type is treated as the no-type - if (this == BuiltinSchemaTypeSystem.ST_ANY_TYPE || type == null || type.isNoType()) - return this; - - // any type is the universal base type; noType is the universal derived type - if (type == BuiltinSchemaTypeSystem.ST_ANY_TYPE || isNoType()) - return type; - - // the regular case: - SchemaTypeImpl sImpl1 = (SchemaTypeImpl)type; - while (sImpl1.getBaseDepth() > getBaseDepth()) - sImpl1 = (SchemaTypeImpl)sImpl1.getBaseType(); - SchemaTypeImpl sImpl2 = this; - while (sImpl2.getBaseDepth() > sImpl1.getBaseDepth()) - sImpl2 = (SchemaTypeImpl)sImpl2.getBaseType(); - for (;;) - { - if (sImpl1.equals(sImpl2)) - break; - sImpl1 = (SchemaTypeImpl)sImpl1.getBaseType(); - sImpl2 = (SchemaTypeImpl)sImpl2.getBaseType(); - assert(sImpl1 != null && sImpl2 != null); // must meet at anyType - } - return sImpl1; - } - - public boolean isAssignableFrom(SchemaType type) - { - if (type == null || type.isNoType()) - return true; - - if (isNoType()) - return false; - - if (getSimpleVariety() == UNION) - { - SchemaType[] members = getUnionMemberTypes(); - for (int i = 0; i < members.length; i++) - if (members[i].isAssignableFrom(type)) - return true; - } - - int depth = ((SchemaTypeImpl)type).getBaseDepth() - getBaseDepth(); - if (depth < 0) - return false; - while (depth > 0) - { - type = type.getBaseType(); - depth -= 1; - } - return (type != null && type.equals(this)); - } - - - public String toString() - { - if (getName() != null) - return "T=" + QNameHelper.pretty(getName()); - - if (isDocumentType()) - return "D=" + QNameHelper.pretty(getDocumentElementName()); - - if (isAttributeType()) - return "R=" + QNameHelper.pretty(getAttributeTypeAttributeName()); - - String prefix; - - if (getContainerField() != null) - { - prefix = (getContainerField().getName().getNamespaceURI().length() > 0 ? - (getContainerField().isAttribute() ? "Q=" : "E=") : - (getContainerField().isAttribute() ? "A=" : "U=")) - + getContainerField().getName().getLocalPart(); - if (getOuterType() == null) - return prefix + "@" + getContainerField().getName().getNamespaceURI(); - } - else if (isNoType()) - return "N="; - else if (getOuterType() == null) - return "noouter"; - else if (getOuterType().getBaseType() == this) - prefix = "B="; - else if (getOuterType().getContentBasedOnType() == this) - prefix = "S="; - else if (getOuterType().getSimpleVariety() == SchemaType.LIST) - prefix = "I="; - else if (getOuterType().getSimpleVariety() == SchemaType.UNION) - prefix = "M=" + getAnonymousUnionMemberOrdinal(); - else - prefix = "strange="; - - return prefix + "|" + getOuterType().toString(); - } - - private XmlObject _parseObject; - private String _parseTNS; - private String _elemFormDefault; - private String _attFormDefault; - private boolean _chameleon; - private boolean _redefinition; - - public void setParseContext(XmlObject parseObject, String targetNamespace, boolean chameleon, String elemFormDefault, String attFormDefault, boolean redefinition) - { - _parseObject = parseObject; - _parseTNS = targetNamespace; - _chameleon = chameleon; - _elemFormDefault = elemFormDefault; - _attFormDefault = attFormDefault; - _redefinition = redefinition; - } - - public XmlObject getParseObject() - { return _parseObject; } - - public String getTargetNamespace() - { return _parseTNS; } - - public boolean isChameleon ( ) - { return _chameleon; } - - public String getElemFormDefault() - { return _elemFormDefault; } - - public String getAttFormDefault() - { return _attFormDefault; } - - public String getChameleonNamespace() - { return _chameleon ? _parseTNS : null; } - - public boolean isRedefinition() - { return _redefinition; } - - private SchemaType.Ref _selfref = new SchemaType.Ref(this); - - public SchemaType.Ref getRef() - { return _selfref; } - - public SchemaComponent.Ref getComponentRef() - { return getRef(); } - - /** - * Gives access to the internals of element validation - */ - private static class SequencerImpl implements SchemaTypeElementSequencer - { - private SchemaTypeVisitorImpl _visitor; - - private SequencerImpl(SchemaTypeVisitorImpl visitor) - { - _visitor = visitor; - } - - public boolean next(QName elementName) - { - if (_visitor == null) - return false; - - return _visitor.visit(elementName); - } - - public boolean peek(QName elementName) - { - if (_visitor == null) - return false; - - return _visitor.testValid(elementName); - } - } - - /** - * Returns a QNameSet of elements that may exist in wildcard - * buchets and are not explicitly defined in this schema type. - * Note: In this example: - * - * - * - * - * - * - * the returned QNameSet will not contain the qname of 'someElement'. - * @return the constructed QNameSet - */ - public QNameSet qnameSetForWildcardElements() - { - SchemaParticle model = this.getContentModel(); - QNameSetBuilder wildcardSet = new QNameSetBuilder(); - computeWildcardSet(model, wildcardSet); - - QNameSetBuilder qnsb = new QNameSetBuilder( wildcardSet ); - SchemaProperty[] props = this.getElementProperties(); - - for (int i = 0; i < props.length; i++) - { - SchemaProperty prop = props[i]; - qnsb.remove(prop.getName()); - } - - return qnsb.toQNameSet(); - } - - private static void computeWildcardSet(SchemaParticle model, QNameSetBuilder result) - { - if (model.getParticleType() == SchemaParticle.WILDCARD) - { - QNameSet cws = model.getWildcardSet(); - result.addAll(cws); - return; - } - for (int i = 0; i < model.countOfParticleChild(); i++) - { - SchemaParticle child = model.getParticleChild(i); - computeWildcardSet(child, result); - } - } - - /** - * Returns a QNameSet of attributes that may exist in wildcard - * buchets and are not explicitly defined in this schema type. - * Note: In this example: - * - * ... - * - * - * - * the returned QNameSet will not contain the qname of 'someAttribute'. - * @return the constructed QNameSet - */ - public QNameSet qnameSetForWildcardAttributes() - { - SchemaAttributeModel model = this.getAttributeModel(); - QNameSet wildcardSet = model.getWildcardSet(); - - if (wildcardSet==null) - return QNameSet.EMPTY; - - QNameSetBuilder qnsb = new QNameSetBuilder( wildcardSet ); - - SchemaProperty[] props = this.getAttributeProperties(); - - for (int i = 0; i < props.length; i++) - { - SchemaProperty prop = props[i]; - qnsb.remove(prop.getName()); - } - - return qnsb.toQNameSet(); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java deleted file mode 100644 index d0c2b46..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java +++ /dev/null @@ -1,609 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.validator.ValidatingXMLInputStream; - -import org.apache.xmlbeans.impl.store.Locale; - -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlSaxHandler; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlFactoryHook; -import org.apache.xmlbeans.XmlBeans; - -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.io.InputStream; -import java.io.Reader; -import java.io.File; -import java.io.IOException; -import java.io.FileInputStream; -import java.util.List; -import java.util.ArrayList; -import java.net.URL; -import java.net.URLConnection; -import java.net.HttpURLConnection; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamReader; - -import org.w3c.dom.Node; -import org.w3c.dom.DOMImplementation; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLStreamException; - -public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader -{ - private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")"; - - private static final Method _pathCompiler = getMethod( "org.apache.xmlbeans.impl.store.Path", "compilePath", new Class[] { String.class, XmlOptions.class } ); - private static final Method _queryCompiler = getMethod( "org.apache.xmlbeans.impl.store.Query", "compileQuery", new Class[] { String.class, XmlOptions.class } ); - - private static Method getMethod ( String className, String methodName, Class[] args ) - { - try - { - return - Class.forName( className ). - getDeclaredMethod( methodName, args ); - } - catch (Exception e) - { - throw new IllegalStateException( - "Cannot find " + className + "." + methodName + - ". verify that xmlstore " + - "(from xbean.jar) is on classpath" ); - } - } - - private static Object invokeMethod ( Method method, Object[] args ) - { - try - { - return method.invoke( method, args ); - } - catch ( InvocationTargetException e ) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException( t.getMessage() ); - ise.initCause( t ); // need initCause() to support Java1.4 - throw ise; - } - catch ( Exception e ) - { - IllegalStateException ise = new IllegalStateException( e.getMessage() ); - ise.initCause( e ); - throw ise; - } - } - - private static String doCompilePath ( String pathExpr, XmlOptions options ) - { - return (String) invokeMethod( _pathCompiler, new Object[] { pathExpr, options } ); - } - - private static String doCompileQuery ( String queryExpr, XmlOptions options ) - { - return (String) invokeMethod( _queryCompiler, new Object[] { queryExpr, options } ); - } - - public SchemaType findType(QName name) - { - SchemaType.Ref ref = findTypeRef(name); - if (ref == null) - return null; - SchemaType result = ref.get(); - assert(result != null); - return result; - } - - public SchemaType findDocumentType(QName name) - { - SchemaType.Ref ref = findDocumentTypeRef(name); - if (ref == null) - return null; - SchemaType result = ref.get(); - assert(result != null); - return result; - } - - public SchemaType findAttributeType(QName name) - { - SchemaType.Ref ref = findAttributeTypeRef(name); - if (ref == null) - return null; - SchemaType result = ref.get(); - assert(result != null); - return result; - } - - public SchemaModelGroup findModelGroup(QName name) - { - SchemaModelGroup.Ref ref = findModelGroupRef(name); - if (ref == null) - return null; - SchemaModelGroup result = ref.get(); - assert(result != null); - return result; - } - - public SchemaAttributeGroup findAttributeGroup(QName name) - { - SchemaAttributeGroup.Ref ref = findAttributeGroupRef(name); - if (ref == null) - return null; - SchemaAttributeGroup result = ref.get(); - assert(result != null); - return result; - } - - public SchemaGlobalElement findElement(QName name) - { - SchemaGlobalElement.Ref ref = findElementRef(name); - if (ref == null) - return null; - SchemaGlobalElement result = ref.get(); - assert(result != null); - return result; - } - - public SchemaGlobalAttribute findAttribute(QName name) - { - SchemaGlobalAttribute.Ref ref = findAttributeRef(name); - if (ref == null) - return null; - SchemaGlobalAttribute result = ref.get(); - assert(result != null); - return result; - } - - // - // - // - - public XmlObject newInstance ( SchemaType type, XmlOptions options ) - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.newInstance( this, type, options ); - - return Locale.newInstance( this, type, options ); - } - - public XmlObject parse ( String xmlText, SchemaType type, XmlOptions options ) throws XmlException - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.parse( this, xmlText, type, options ); - - return Locale.parseToXmlObject( this, xmlText, type, options ); - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XmlObject parse ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.parse( this, xis, type, options ); - - return Locale.parseToXmlObject( this, xis, type, options ); - } - - public XmlObject parse ( XMLStreamReader xsr, SchemaType type, XmlOptions options ) throws XmlException - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.parse( this, xsr, type, options ); - - return Locale.parseToXmlObject( this, xsr, type, options ); - } - - public XmlObject parse ( File file, SchemaType type, XmlOptions options ) throws XmlException, IOException - { - if (options == null) - { - options = new XmlOptions(); - options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() ); - } - - else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME)) - { - options = new XmlOptions( options ); - options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() ); - } - - InputStream fis = new FileInputStream( file ); - - try - { - return parse( fis, type, options ); - } - finally - { - fis.close(); - } - } - - public XmlObject parse ( URL url, SchemaType type, XmlOptions options ) throws XmlException, IOException - { - if (options == null) - { - options = new XmlOptions(); - options.put( XmlOptions.DOCUMENT_SOURCE_NAME, url.toString() ); - } - - else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME)) - { - options = new XmlOptions( options ); - options.put( XmlOptions.DOCUMENT_SOURCE_NAME, url.toString() ); - } - - URLConnection conn = null; - InputStream stream = null; - download: try - { - - boolean redirected = false; - int count = 0; - - do { - conn = url.openConnection(); - conn.addRequestProperty("User-Agent", USER_AGENT); - conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); - if (conn instanceof HttpURLConnection) - { - HttpURLConnection httpcon = (HttpURLConnection)conn; - int code = httpcon.getResponseCode(); - redirected = (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP); - if (redirected && count > 5) - redirected = false; - - if (redirected) - { - String newLocation = httpcon.getHeaderField("Location"); - if (newLocation == null) - redirected = false; - else - { - url = new URL(newLocation); - count ++; - } - } - } - } while (redirected); - - stream = conn.getInputStream(); - return parse( stream, type, options ); - } - finally - { - if (stream != null) - stream.close(); - } - } - - public XmlObject parse ( InputStream jiois, SchemaType type, XmlOptions options ) throws XmlException, IOException - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - DigestInputStream digestStream = null; - - setupDigest: - if (options != null && options.hasOption( XmlOptions.LOAD_MESSAGE_DIGEST )) - { - MessageDigest sha; - - try - { - sha = MessageDigest.getInstance("SHA"); - } - catch (NoSuchAlgorithmException e) - { - break setupDigest; - } - - digestStream = new DigestInputStream( jiois, sha ); - jiois = digestStream; - } - - if (hook != null) - return hook.parse( this, jiois, type, options ); - - XmlObject result = Locale.parseToXmlObject( this, jiois, type, options ); - - if (digestStream != null) - result.documentProperties().setMessageDigest( digestStream.getMessageDigest().digest() ); - - return result; - } - - public XmlObject parse ( Reader jior, SchemaType type, XmlOptions options ) throws XmlException, IOException - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.parse( this, jior, type, options ); - - return Locale.parseToXmlObject( this, jior, type, options ); - } - - public XmlObject parse ( Node node, SchemaType type, XmlOptions options ) throws XmlException - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.parse( this, node, type, options ); - - return Locale.parseToXmlObject( this, node, type, options ); - } - - public XmlSaxHandler newXmlSaxHandler ( SchemaType type, XmlOptions options ) - { - XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook(); - - if (hook != null) - return hook.newXmlSaxHandler( this, type, options ); - - return Locale.newSaxHandler( this, type, options ); - } - - public DOMImplementation newDomImplementation ( XmlOptions options ) - { - return Locale.newDomImplementation( this, options ); - } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException - { - return new ValidatingXMLInputStream( xis, this, type, options ); - } - - // - // - // - - public String compilePath ( String pathExpr ) - { - return compilePath( pathExpr, null ); - } - - public String compilePath ( String pathExpr, XmlOptions options ) - { - return doCompilePath( pathExpr, options ); - } - - public String compileQuery ( String queryExpr ) - { - return compileQuery( queryExpr, null ); - } - - public String compileQuery ( String queryExpr, XmlOptions options ) - { - return doCompileQuery( queryExpr, options ); - } - - /** - * Utility function to load a type from a signature. - * - * A signature is the string you get from type.toString(). - */ - public SchemaType typeForSignature(String signature) - { - int end = signature.indexOf('@'); - String uri; - - if (end < 0) - { - uri = ""; - end = signature.length(); - } - else - { - uri = signature.substring(end + 1); - } - - List parts = new ArrayList(); - - for (int index = 0; index < end; ) - { - int nextc = signature.indexOf(':', index); - int nextd = signature.indexOf('|', index); - int next = (nextc < 0 ? nextd : nextd < 0 ? nextc : nextc < nextd ? nextc : nextd); - if (next < 0 || next > end) - next = end; - String part = signature.substring(index, next); - parts.add(part); - index = next + 1; - } - - SchemaType curType = null; - - outer: for (int i = parts.size() - 1; i >= 0; i -= 1) - { - String part = (String)parts.get(i); - if (part.length() < 1) - throw new IllegalArgumentException(); - int offset = (part.length() >= 2 && part.charAt(1) == '=') ? 2 : 1; - cases: switch (part.charAt(0)) - { - case 'T': - if (curType != null) - throw new IllegalArgumentException(); - curType = findType(QNameHelper.forLNS(part.substring(offset), uri)); - if (curType == null) - return null; - break; - - case 'D': - if (curType != null) - throw new IllegalArgumentException(); - curType = findDocumentType(QNameHelper.forLNS(part.substring(offset), uri)); - if (curType == null) - return null; - break; - - case 'C': // deprecated - case 'R': // current - if (curType != null) - throw new IllegalArgumentException(); - curType = findAttributeType(QNameHelper.forLNS(part.substring(offset), uri)); - if (curType == null) - return null; - break; - - case 'E': - case 'U': // distinguish qualified/unqualified TBD - if (curType != null) - { - if (curType.getContentType() < SchemaType.ELEMENT_CONTENT) - return null; - SchemaType[] subTypes = curType.getAnonymousTypes(); - String localName = part.substring(offset); - for (int j = 0; j < subTypes.length; j++) - { - SchemaField field = subTypes[j].getContainerField(); - if (field != null && !field.isAttribute() && field.getName().getLocalPart().equals(localName)) - { - curType = subTypes[j]; - break cases; - } - } - return null; - } - else - { - SchemaGlobalElement elt = findElement(QNameHelper.forLNS(part.substring(offset), uri)); - if (elt == null) - return null; - curType = elt.getType(); - } - break; - - case 'A': - case 'Q': // distinguish qualified/unqualified TBD - if (curType != null) - { - if (curType.isSimpleType()) - return null; - SchemaType[] subTypes = curType.getAnonymousTypes(); - String localName = part.substring(offset); - for (int j = 0; j < subTypes.length; j++) - { - SchemaField field = subTypes[j].getContainerField(); - if (field != null && field.isAttribute() && field.getName().getLocalPart().equals(localName)) - { - curType = subTypes[j]; - break cases; - } - } - return null; - } - else - { - SchemaGlobalAttribute attr = findAttribute(QNameHelper.forLNS(part.substring(offset), uri)); - if (attr == null) - return null; - curType = attr.getType(); - } - break; - - case 'B': - if (curType == null) - { - throw new IllegalArgumentException(); - } - else - { - if (curType.getSimpleVariety() != SchemaType.ATOMIC) - return null; - SchemaType[] subTypes = curType.getAnonymousTypes(); - if (subTypes.length != 1) - return null; - curType = subTypes[0]; - } - break; - - case 'I': - if (curType == null) - { - throw new IllegalArgumentException(); - } - else - { - if (curType.getSimpleVariety() != SchemaType.LIST) - return null; - SchemaType[] subTypes = curType.getAnonymousTypes(); - if (subTypes.length != 1) - return null; - curType = subTypes[0]; - } - break; - - case 'M': - if (curType == null) - { - throw new IllegalArgumentException(); - } - else - { - int index; - try - { - index = Integer.parseInt(part.substring(offset)); - } - catch (Exception e) - { - throw new IllegalArgumentException(); - } - - if (curType.getSimpleVariety() != SchemaType.UNION) - return null; - SchemaType[] subTypes = curType.getAnonymousTypes(); - if (subTypes.length <= index) - return null; - curType = subTypes[index]; - } - break; - - default: - throw new IllegalArgumentException(); - } - } - return curType; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java deleted file mode 100644 index b669069..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java +++ /dev/null @@ -1,615 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.ResourceLoader; -import org.apache.xmlbeans.impl.common.SystemCache; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.XBeanDebug; -import javax.xml.namespace.QName; - -import java.io.InputStream; -import java.util.Map; -import java.util.HashMap; -import java.util.Collections; -import java.util.ArrayList; -import java.util.List; -import java.util.IdentityHashMap; - -import java.lang.ref.SoftReference; - -public class SchemaTypeLoaderImpl extends SchemaTypeLoaderBase -{ - private ResourceLoader _resourceLoader; - private ClassLoader _classLoader; - private SchemaTypeLoader[] _searchPath; - - private Map _classpathTypeSystems; - private Map _classLoaderTypeSystems; - private Map _elementCache; - private Map _attributeCache; - private Map _modelGroupCache; - private Map _attributeGroupCache; - private Map _idConstraintCache; - private Map _typeCache; - private Map _documentCache; - private Map _attributeTypeCache; - private Map _classnameCache; - - public static String METADATA_PACKAGE_LOAD = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN; - private static final Object CACHED_NOT_FOUND = new Object(); - - private static class SchemaTypeLoaderCache extends SystemCache - { - // The following maintains a cache of SchemaTypeLoaders per ClassLoader per Thread. - // I use soft references to allow the garbage collector to reclain the type loaders - // and/pr class loaders at will. - - private ThreadLocal _cachedTypeSystems = - new ThreadLocal() { protected Object initialValue() { return new ArrayList(); } }; - - public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) - { - ArrayList a = (ArrayList) _cachedTypeSystems.get(); - - int candidate = -1; - SchemaTypeLoaderImpl result = null; - - for ( int i = 0 ; i < a.size() ; i++ ) - { - SchemaTypeLoaderImpl tl = (SchemaTypeLoaderImpl) ((SoftReference) a.get( i )).get(); - - if (tl == null) - { - assert i > candidate; - a.remove( i-- ); - } - else if (tl._classLoader == cl) - { - assert candidate == -1 && result == null; - - candidate = i; - result = tl; - - break; - } - } - - // Make sure the most recently accessed entry is at the beginning of the array - - if (candidate > 0) - { - Object t = a.get( 0 ); - a.set( 0, a.get( candidate ) ); - a.set( candidate, t ); - } - - return result; - } - - public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) - { - assert (stl instanceof SchemaTypeLoaderImpl) && - ((SchemaTypeLoaderImpl) stl)._classLoader == cl; - - ArrayList a = (ArrayList) _cachedTypeSystems.get(); - // Make sure this entry is at the top of the stack - if (a.size() > 0) - { - Object t = a.get( 0 ); - a.set( 0, new SoftReference( stl ) ); - a.add( t ); - } - else - a.add( new SoftReference( stl ) ); - } - } - - public static SchemaTypeLoaderImpl getContextTypeLoader ( ) - { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - SchemaTypeLoaderImpl result = (SchemaTypeLoaderImpl) - SystemCache.get().getFromTypeLoaderCache(cl); - - if (result == null) - { - result = - new SchemaTypeLoaderImpl( - new SchemaTypeLoader[] { BuiltinSchemaTypeSystem.get() }, null, cl ); - SystemCache.get().addToTypeLoaderCache(result, cl); - } - - return result; - } - - public static SchemaTypeLoader build(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader) - { - if (searchPath == null) - { - searchPath = EMPTY_SCHEMATYPELOADER_ARRAY; - } - else - { - // assemble a flattened search path with no duplicates - SubLoaderList list = new SubLoaderList(); - for (int i = 0; i < searchPath.length; i++) - { - if (searchPath[i] == null) - throw new IllegalArgumentException("searchPath[" + i + "] is null"); - if (!(searchPath[i] instanceof SchemaTypeLoaderImpl)) - list.add(searchPath[i]); - else - { - SchemaTypeLoaderImpl sub = (SchemaTypeLoaderImpl)searchPath[i]; - if (sub._classLoader != null || sub._resourceLoader != null) - list.add(sub); - else for (int j = 0; j < sub._searchPath.length; j++) - list.add(sub._searchPath[j]); - } - } - searchPath = list.toArray(); - } - - if (searchPath.length == 1 && resourceLoader == null && classLoader == null) - return searchPath[0]; - - return new SchemaTypeLoaderImpl(searchPath, resourceLoader, classLoader); - } - - /** - * Just used to avoid duplicate path entries - */ - private static class SubLoaderList - { - private List theList = new ArrayList(); - private Map seen = new IdentityHashMap(); - - private boolean add(SchemaTypeLoader loader) - { - if (seen.containsKey(loader)) - return false; - theList.add(loader); - seen.put(loader, null); - return true; - } - - private SchemaTypeLoader[] toArray() - { - return (SchemaTypeLoader[])theList.toArray(EMPTY_SCHEMATYPELOADER_ARRAY); - } - } - - /** - * Constructs a SchemaTypeLoaderImpl that searches for objects - * in the following order: - * - * (1) First on the searchPath of other SchemaTypeSystems supplied, - * in order that they are listed. - * (2) Next on the classpath of .jar files or directories supplied, - * in the order that they are listed. When types are returned in - * this way, they are instantiated from a private typesystem. - * In other words, if a type is loaded from another SchemaTypeLoaderImpl - * that was initialized on the same file, the instance of the type will - * be different. - * (3) Finally on the classloader supplied. - */ - private SchemaTypeLoaderImpl(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader) - { - if (searchPath == null) - _searchPath = EMPTY_SCHEMATYPELOADER_ARRAY; - else - _searchPath = searchPath; - _resourceLoader = resourceLoader; - _classLoader = classLoader; - - initCaches(); - } - - /** - * Initializes the caches. - */ - private final void initCaches() - { - _classpathTypeSystems = Collections.synchronizedMap(new HashMap()); - _classLoaderTypeSystems = Collections.synchronizedMap(new HashMap()); - _elementCache = Collections.synchronizedMap(new HashMap()); - _attributeCache = Collections.synchronizedMap(new HashMap()); - _modelGroupCache = Collections.synchronizedMap(new HashMap()); - _attributeGroupCache = Collections.synchronizedMap(new HashMap()); - _idConstraintCache = Collections.synchronizedMap(new HashMap()); - _typeCache = Collections.synchronizedMap(new HashMap()); - _documentCache = Collections.synchronizedMap(new HashMap()); - _attributeTypeCache = Collections.synchronizedMap(new HashMap()); - _classnameCache = Collections.synchronizedMap(new HashMap()); - } - - SchemaTypeSystemImpl typeSystemForComponent(String searchdir, QName name) - { - String searchfor = searchdir + QNameHelper.hexsafedir(name) + ".xsb"; - String tsname = null; - - if (_resourceLoader != null) - tsname = crackEntry(_resourceLoader, searchfor); - - if (_classLoader != null) - tsname = crackEntry(_classLoader, searchfor); - - if (tsname != null) - return (SchemaTypeSystemImpl)typeSystemForName(tsname); - - return null; - } - - public SchemaTypeSystem typeSystemForName(String name) - { - if (_resourceLoader != null) - { - SchemaTypeSystem result = getTypeSystemOnClasspath(name); - if (result != null) - return result; - } - - if (_classLoader != null) - { - SchemaTypeSystem result = getTypeSystemOnClassloader(name); - if (result != null) - return result; - } - return null; - } - - SchemaTypeSystemImpl typeSystemForClassname(String searchdir, String name) - { - String searchfor = searchdir + name.replace('.', '/') + ".xsb"; - - if (_resourceLoader != null) - { - String tsname = crackEntry(_resourceLoader, searchfor); - if (tsname != null) - return getTypeSystemOnClasspath(tsname); - } - - if (_classLoader != null) - { - String tsname = crackEntry(_classLoader, searchfor); - if (tsname != null) - return getTypeSystemOnClassloader(tsname); - } - - return null; - } - - SchemaTypeSystemImpl getTypeSystemOnClasspath(String name) - { - SchemaTypeSystemImpl result = (SchemaTypeSystemImpl)_classpathTypeSystems.get(name); - if (result == null) - { - result = new SchemaTypeSystemImpl(_resourceLoader, name, this); - _classpathTypeSystems.put(name, result); - } - return result; - } - - SchemaTypeSystemImpl getTypeSystemOnClassloader(String name) - { - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finding type system " + name + " on classloader", 0); - SchemaTypeSystemImpl result = (SchemaTypeSystemImpl)_classLoaderTypeSystems.get(name); - if (result == null) - { - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Type system " + name + " not cached - consulting field", 0); - result = SchemaTypeSystemImpl.forName(name, _classLoader); - _classLoaderTypeSystems.put(name, result); - } - return result; - } - - static String crackEntry(ResourceLoader loader, String searchfor) - { - InputStream is = loader.getResourceAsStream(searchfor); - if (is == null) - return null; - return crackPointer(is); - } - - static String crackEntry(ClassLoader loader, String searchfor) - { - InputStream stream = loader.getResourceAsStream(searchfor); - if (stream == null) - return null; - return crackPointer(stream); - } - - static String crackPointer(InputStream stream) - { - return SchemaTypeSystemImpl.crackPointer(stream); - } - - public boolean isNamespaceDefined(String namespace) - { - for (int i = 0; i < _searchPath.length; i++) - if (_searchPath[i].isNamespaceDefined(namespace)) - return true; - - SchemaTypeSystem sts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/namespace/", new QName(namespace, "xmlns")); - return (sts != null); - } - - public SchemaType.Ref findTypeRef(QName name) - { - /** - * The maps are synchronized, we use two accesses to the cache (one read - * and one write), but the code inbetween is not synchronized. The - * assumption is that the underlying datastructures (the search path and - * the classloader) do not change, so two threads running the code in - * parallel will come up with the same result. - */ - Object cached = _typeCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaType.Ref result = (SchemaType.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findTypeRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/type/", name); - if (ts != null) - { - result = ts.findTypeRef(name); - assert(result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it"; - } - } - _typeCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaType typeForClassname(String classname) - { - classname = classname.replace('$', '.'); - - Object cached = _classnameCache.get(classname); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaType result = (SchemaType) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].typeForClassname(classname))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForClassname("schema" + METADATA_PACKAGE_LOAD + "/javaname/", classname); - if (ts != null) - { - result = ts.typeForClassname(classname); - assert(result != null) : "Type system registered type " + classname + " but does not return it"; - } - } - _classnameCache.put(classname, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaType.Ref findDocumentTypeRef(QName name) - { - Object cached = _documentCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaType.Ref result = (SchemaType.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findDocumentTypeRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/element/", name); - if (ts != null) - { - result = ts.findDocumentTypeRef(name); - assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type"; - } - } - _documentCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaType.Ref findAttributeTypeRef(QName name) - { - Object cached = _attributeTypeCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaType.Ref result = (SchemaType.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findAttributeTypeRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/attribute/", name); - if (ts != null) - { - result = ts.findAttributeTypeRef(name); - assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type"; - } - } - _attributeTypeCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaGlobalElement.Ref findElementRef(QName name) - { - Object cached = _elementCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaGlobalElement.Ref result = (SchemaGlobalElement.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findElementRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/element/", name); - if (ts != null) - { - result = ts.findElementRef(name); - assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it"; - } - } - _elementCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaGlobalAttribute.Ref findAttributeRef(QName name) - { - Object cached = _attributeCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaGlobalAttribute.Ref result = (SchemaGlobalAttribute.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findAttributeRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/attribute/", name); - if (ts != null) - { - result = ts.findAttributeRef(name); - assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it"; - } - } - _attributeCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaModelGroup.Ref findModelGroupRef(QName name) - { - Object cached = _modelGroupCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaModelGroup.Ref result = (SchemaModelGroup.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findModelGroupRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/modelgroup/", name); - if (ts != null) - { - result = ts.findModelGroupRef(name); - assert(result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it"; - } - } - _modelGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) - { - Object cached = _attributeGroupCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaAttributeGroup.Ref result = (SchemaAttributeGroup.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findAttributeGroupRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/attributegroup/", name); - if (ts != null) - { - result = ts.findAttributeGroupRef(name); - assert(result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it"; - } - } - _attributeGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) - { - Object cached = _idConstraintCache.get(name); - if (cached == CACHED_NOT_FOUND) - return null; - SchemaIdentityConstraint.Ref result = (SchemaIdentityConstraint.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findIdentityConstraintRef(name))) - break; - if (result == null) - { - SchemaTypeSystem ts = typeSystemForComponent("schema" + METADATA_PACKAGE_LOAD + "/identityconstraint/", name); - if (ts != null) - { - result = ts.findIdentityConstraintRef(name); - assert(result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it"; - } - } - _idConstraintCache.put(name, result == null ? CACHED_NOT_FOUND : result); - } - return result; - } - - public InputStream getSourceAsStream(String sourceName) - { - InputStream result = null; - - if (!sourceName.startsWith("/")) - sourceName = "/" + sourceName; - - if (_resourceLoader != null) - result = _resourceLoader.getResourceAsStream("schema" + METADATA_PACKAGE_LOAD + "/src" + sourceName); - - if (result == null && _classLoader != null) - return _classLoader.getResourceAsStream("schema" + METADATA_PACKAGE_LOAD + "/src" + sourceName); - - return result; - } - - private static final SchemaTypeLoader[] EMPTY_SCHEMATYPELOADER_ARRAY = new SchemaTypeLoader[0]; - - static - { - if (SystemCache.get() instanceof SystemCache) - SystemCache.set(new SchemaTypeLoaderCache()); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java deleted file mode 100644 index 6f2e734..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java +++ /dev/null @@ -1,491 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.Filer; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.BindingConfig; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.HashMap; -import java.util.Map; -import java.util.List; -import java.util.Set; -import java.util.Arrays; -import java.net.URI; - -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.impl.common.XmlErrorWatcher; - -import java.util.Collection; -import java.util.Iterator; -import java.io.File; -import java.io.IOException; -import java.io.Writer; - -public class SchemaTypeSystemCompiler -{ - public static class Parameters - { - private SchemaTypeSystem existingSystem; - private String name; - private Schema[] schemas; - private BindingConfig config; - private SchemaTypeLoader linkTo; - private XmlOptions options; - private Collection errorListener; - private boolean javaize; - private URI baseURI; - private Map sourcesToCopyMap; - private File schemasDir; - - public SchemaTypeSystem getExistingTypeSystem() - { - return existingSystem; - } - - public void setExistingTypeSystem(SchemaTypeSystem system) - { - this.existingSystem = system; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public SchemaDocument.Schema[] getSchemas() - { - return schemas; - } - - public void setSchemas(SchemaDocument.Schema[] schemas) - { - this.schemas = schemas; - } - - public BindingConfig getConfig() - { - return config; - } - - public void setConfig(BindingConfig config) - { - this.config = config; - } - - public SchemaTypeLoader getLinkTo() - { - return linkTo; - } - - public void setLinkTo(SchemaTypeLoader linkTo) - { - this.linkTo = linkTo; - } - - public XmlOptions getOptions() - { - return options; - } - - public void setOptions(XmlOptions options) - { - this.options = options; - } - - public Collection getErrorListener() - { - return errorListener; - } - - public void setErrorListener(Collection errorListener) - { - this.errorListener = errorListener; - } - - public boolean isJavaize() - { - return javaize; - } - - public void setJavaize(boolean javaize) - { - this.javaize = javaize; - } - - public URI getBaseURI() - { - return baseURI; - } - - public void setBaseURI(URI baseURI) - { - this.baseURI = baseURI; - } - - public Map getSourcesToCopyMap() - { - return sourcesToCopyMap; - } - - public void setSourcesToCopyMap(Map sourcesToCopyMap) - { - this.sourcesToCopyMap = sourcesToCopyMap; - } - - public File getSchemasDir() - { - return schemasDir; - } - - public void setSchemasDir(File schemasDir) - { - this.schemasDir = schemasDir; - } - - } - - /** - * Compiles a SchemaTypeSystem. Use XmlBeans.compileXmlBeans() if you can. - */ - public static SchemaTypeSystem compile(Parameters params) - { - return compileImpl(params.getExistingTypeSystem(), params.getName(), - params.getSchemas(), params.getConfig(), params.getLinkTo(), - params.getOptions(), params.getErrorListener(), params.isJavaize(), - params.getBaseURI(), params.getSourcesToCopyMap(), params.getSchemasDir()); - } - - /** - * Please do not invoke this method directly as the signature could change unexpectedly. - * Use one of - * {@link XmlBeans#loadXsd(XmlObject[])}, - * {@link XmlBeans#compileXsd(XmlObject[], SchemaTypeLoader, XmlOptions)}, - * or - * {@link XmlBeans#compileXmlBeans(String, SchemaTypeSystem, XmlObject[], BindingConfig, SchemaTypeLoader, Filer, XmlOptions)} - */ - public static SchemaTypeSystemImpl compile(String name, SchemaTypeSystem existingSTS, - XmlObject[] input, BindingConfig config, SchemaTypeLoader linkTo, Filer filer, XmlOptions options) - throws XmlException - { - options = XmlOptions.maskNull(options); - ArrayList schemas = new ArrayList(); - - if (input != null) - { - for (int i = 0; i < input.length; i++) - { - if (input[i] instanceof Schema) - schemas.add(input[i]); - else if (input[i] instanceof SchemaDocument && ((SchemaDocument)input[i]).getSchema() != null) - schemas.add(((SchemaDocument)input[i]).getSchema()); - else - throw new XmlException("Thread " + Thread.currentThread().getName() + ": The " + i + "th supplied input is not a schema document: its type is " + input[i].schemaType()); - } - } - - Collection userErrors = (Collection)options.get(XmlOptions.ERROR_LISTENER); - XmlErrorWatcher errorWatcher = new XmlErrorWatcher(userErrors); - - SchemaTypeSystemImpl stsi = compileImpl(existingSTS, name, - (Schema[])schemas.toArray(new Schema[schemas.size()]), - config, linkTo, options, errorWatcher, filer!=null, (URI) options.get(XmlOptions.BASE_URI), - null, null); - - // if there is an error and compile didn't recover (stsi==null), throw exception - if (errorWatcher.hasError() && stsi == null) - { - throw new XmlException(errorWatcher.firstError()); - } - - if (stsi != null && !stsi.isIncomplete() && filer != null) - { - stsi.save(filer); - generateTypes(stsi, filer, options); - } - - return stsi; - } - - // - // Compiles a SchemaTypeSystem - // - /* package */ static SchemaTypeSystemImpl compileImpl( SchemaTypeSystem system, String name, - Schema[] schemas, BindingConfig config, SchemaTypeLoader linkTo, - XmlOptions options, Collection outsideErrors, boolean javaize, - URI baseURI, Map sourcesToCopyMap, File schemasDir) - { - if (linkTo == null) - throw new IllegalArgumentException("Must supply linkTo"); - - XmlErrorWatcher errorWatcher = new XmlErrorWatcher(outsideErrors); - boolean incremental = system != null; - - // construct the state - StscState state = StscState.start(); - boolean validate = (options == null || !options.hasOption(XmlOptions.COMPILE_NO_VALIDATION)); - try - { - state.setErrorListener(errorWatcher); - state.setBindingConfig(config); - state.setOptions(options); - state.setGivenTypeSystemName(name); - state.setSchemasDir(schemasDir); - if (baseURI != null) - state.setBaseUri(baseURI); - - // construct the classpath (you always get the builtin types) - linkTo = SchemaTypeLoaderImpl.build(new SchemaTypeLoader[] { BuiltinSchemaTypeSystem.get(), linkTo }, null, null); - state.setImportingTypeLoader(linkTo); - - List validSchemas = new ArrayList(schemas.length); - - // load all the xsd files into it - if (validate) - { - XmlOptions validateOptions = new XmlOptions().setErrorListener(errorWatcher); - if (options.hasOption(XmlOptions.VALIDATE_TREAT_LAX_AS_SKIP)) - validateOptions.setValidateTreatLaxAsSkip(); - for (int i = 0; i < schemas.length; i++) - { - if (schemas[i].validate(validateOptions)) - validSchemas.add(schemas[i]); - } - } - else - { - validSchemas.addAll(Arrays.asList(schemas)); - } - - Schema[] startWith = (Schema[])validSchemas.toArray(new Schema[validSchemas.size()]); - - if (incremental) - { - Set namespaces = new HashSet(); - startWith = getSchemasToRecompile((SchemaTypeSystemImpl)system, startWith, namespaces); - state.initFromTypeSystem((SchemaTypeSystemImpl)system, namespaces); - } - else - { - state.setDependencies(new SchemaDependencies()); - } - - // deal with imports and includes - StscImporter.SchemaToProcess[] schemasAndChameleons = StscImporter.resolveImportsAndIncludes(startWith, incremental); - - // call the translator so that it may also perform magic - StscTranslator.addAllDefinitions(schemasAndChameleons); - - // call the resolver to do its magic - StscResolver.resolveAll(); - - // call the checker to check both restrictions and defaults - StscChecker.checkAll(); - - // call the javaizer to do its magic - StscJavaizer.javaizeAllTypes(javaize); - - // construct the loader out of the state - state.get().sts().loadFromStscState(state); - - // fill in the source-copy map - if (sourcesToCopyMap != null) - sourcesToCopyMap.putAll(state.sourceCopyMap()); - - if (errorWatcher.hasError()) - { - // EXPERIMENTAL: recovery from compilation errors and partial type system - if (state.allowPartial() && state.getRecovered() == errorWatcher.size()) - { - // if partial type system allowed and all errors were recovered - state.get().sts().setIncomplete(true); - } - else - { - // if any non-recoverable errors, return null - return null; - } - } - - if (system != null) - ((SchemaTypeSystemImpl) system).setIncomplete(true); - - return state.get().sts(); - } - finally - { - StscState.end(); - } - } - - /** - * Get the list of Schemas to be recompiled, based on the list of Schemas that - * were modified. - * We make use of the depencency information that we stored in the typesystem - * and of the entity resolvers that have been set up - */ - private static Schema[] getSchemasToRecompile(SchemaTypeSystemImpl system, - Schema[] modified, Set namespaces) - { - Set modifiedFiles = new HashSet(); - Map haveFile = new HashMap(); - List result = new ArrayList(); - for (int i = 0; i < modified.length; i++) - { - String fileURL = modified[i].documentProperties().getSourceName(); - if (fileURL == null) - throw new IllegalArgumentException("One of the Schema files passed in" + - " doesn't have the source set, which prevents it to be incrementally" + - " compiled"); - modifiedFiles.add(fileURL); - haveFile.put(fileURL, modified[i]); - result.add(modified[i]); - } - SchemaDependencies dep = system.getDependencies(); - List nss = dep.getNamespacesTouched(modifiedFiles); - namespaces.addAll(dep.computeTransitiveClosure(nss)); - List needRecompilation = dep.getFilesTouched(namespaces); - StscState.get().setDependencies(new SchemaDependencies(dep, namespaces)); - for (int i = 0; i < needRecompilation.size(); i++) - { - String url = (String) needRecompilation.get(i); - Schema have = (Schema) haveFile.get(url); - if (have == null) - { - // We have to load the file from the entity resolver - try - { - XmlObject xdoc = StscImporter.DownloadTable. - downloadDocument(StscState.get().getS4SLoader(), null, url); - XmlOptions voptions = new XmlOptions(); - voptions.setErrorListener(StscState.get().getErrorListener()); - if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) - { - StscState.get().error("Referenced document is not a valid schema, URL = " + url, XmlErrorCodes.CANNOT_FIND_RESOURCE, null); - continue; - } - - SchemaDocument sDoc = (SchemaDocument)xdoc; - - result.add(sDoc.getSchema()); - } - catch (java.net.MalformedURLException mfe) - { - StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[] { "MalformedURLException", url, mfe.getMessage() }, null); - continue; - } - catch (java.io.IOException ioe) - { - StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[] { "IOException", url, ioe.getMessage() }, null); - continue; - } - catch (XmlException xmle) - { - StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[] { "XmlException", url, xmle.getMessage() }, null); - continue; - } - } - } - return (Schema[]) result.toArray(new Schema[result.size()]); - } - - - /** - * Generate java source files for a SchemaTypeSystem. - * Please do not invoke this method directly as the signature could change unexpectedly. - * Use {@link org.apache.xmlbeans.XmlBeans#compileXmlBeans} - * - * @param system the SchemaTypeSystem to generated java source for - * @param filer to create the java source files - * @param options See {@link XmlOptions#setSchemaCodePrinter(org.apache.xmlbeans.SchemaCodePrinter)} - * @return true if saving the generated source succeeded. - */ - public static boolean generateTypes(SchemaTypeSystem system, Filer filer, XmlOptions options) - { - // partial type systems not allowed to be saved - if (system instanceof SchemaTypeSystemImpl && ((SchemaTypeSystemImpl)system).isIncomplete()) - return false; - - boolean success = true; - - List types = new ArrayList(); - types.addAll(Arrays.asList(system.globalTypes())); - types.addAll(Arrays.asList(system.documentTypes())); - types.addAll(Arrays.asList(system.attributeTypes())); - - for (Iterator i = types.iterator(); i.hasNext(); ) - { - SchemaType type = (SchemaType)i.next(); - if (type.isBuiltinType()) - continue; - if (type.getFullJavaName() == null) - continue; - - String fjn = type.getFullJavaName(); - - Writer writer = null; - - try - { - // Generate interface class - writer = filer.createSourceFile(fjn); - SchemaTypeCodePrinter.printType(writer, type, options); - } - catch (IOException e) - { - System.err.println("IO Error " + e); - success = false; - } - finally { - try { if (writer != null) writer.close(); } catch (IOException e) {} - } - - try - { - // Generate Implementation class - fjn = type.getFullJavaImplName(); - writer = filer.createSourceFile(fjn); - - SchemaTypeCodePrinter.printTypeImpl(writer, type, options); - } - catch (IOException e) - { - System.err.println("IO Error " + e); - success = false; - } - finally { - try { if (writer != null) writer.close(); } catch (IOException e) {} - } - } - - return success; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java deleted file mode 100644 index fd6f250..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java +++ /dev/null @@ -1,3807 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.Filer; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaLocalElement; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.SchemaStringEnumEntry; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SchemaTypeLoaderException; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.ResourceLoader; -import org.apache.xmlbeans.impl.common.NameUtil; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.XBeanDebug; -import org.apache.xmlbeans.impl.util.FilerImpl; -import org.apache.xmlbeans.impl.util.HexBin; -import org.apache.xmlbeans.impl.values.XmlObjectBase; -import org.apache.xmlbeans.impl.xb.xsdschema.AttributeGroupDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.GroupDocument; -import org.apache.xmlbeans.soap.SOAPArrayType; -import org.apache.xmlbeans.soap.SchemaWSDLArrayType; -import repackage.Repackager; - -import javax.xml.namespace.QName; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -public class SchemaTypeSystemImpl extends SchemaTypeLoaderBase implements SchemaTypeSystem -{ - public static final int DATA_BABE = 0xDA7ABABE; - public static final int MAJOR_VERSION = 2; // must match == to be compatible - public static final int MINOR_VERSION = 24; // must be <= to be compatible - public static final int RELEASE_NUMBER = 0; // should be compatible even if < or > - - public static final int FILETYPE_SCHEMAINDEX = 1; - public static final int FILETYPE_SCHEMATYPE = 2; - public static final int FILETYPE_SCHEMAELEMENT = 3; - public static final int FILETYPE_SCHEMAATTRIBUTE = 4; - public static final int FILETYPE_SCHEMAPOINTER = 5; - public static final int FILETYPE_SCHEMAMODELGROUP = 6; - public static final int FILETYPE_SCHEMAATTRIBUTEGROUP = 7; - public static final int FILETYPE_SCHEMAIDENTITYCONSTRAINT = 8; - - public static final int FLAG_PART_SKIPPABLE = 1; - public static final int FLAG_PART_FIXED = 4; - public static final int FLAG_PART_NILLABLE = 8; - public static final int FLAG_PART_BLOCKEXT = 16; - public static final int FLAG_PART_BLOCKREST = 32; - public static final int FLAG_PART_BLOCKSUBST = 64; - public static final int FLAG_PART_ABSTRACT = 128; - public static final int FLAG_PART_FINALEXT = 256; - public static final int FLAG_PART_FINALREST = 512; - - public static final int FLAG_PROP_ISATTR = 1; - public static final int FLAG_PROP_JAVASINGLETON = 2; - public static final int FLAG_PROP_JAVAOPTIONAL = 4; - public static final int FLAG_PROP_JAVAARRAY = 8; - - public static final int FIELD_NONE = 0; - public static final int FIELD_GLOBAL = 1; - public static final int FIELD_LOCALATTR = 2; - public static final int FIELD_LOCALELT = 3; - - // type flags - static final int FLAG_SIMPLE_TYPE = 0x1; - static final int FLAG_DOCUMENT_TYPE = 0x2; - static final int FLAG_ORDERED = 0x4; - static final int FLAG_BOUNDED = 0x8; - static final int FLAG_FINITE = 0x10; - static final int FLAG_NUMERIC = 0x20; - static final int FLAG_STRINGENUM = 0x40; - static final int FLAG_UNION_OF_LISTS = 0x80; - static final int FLAG_HAS_PATTERN = 0x100; - static final int FLAG_ORDER_SENSITIVE = 0x200; - static final int FLAG_TOTAL_ORDER = 0x400; - static final int FLAG_COMPILED = 0x800; - static final int FLAG_BLOCK_EXT = 0x1000; - static final int FLAG_BLOCK_REST = 0x2000; - static final int FLAG_FINAL_EXT = 0x4000; - static final int FLAG_FINAL_REST = 0x8000; - static final int FLAG_FINAL_UNION = 0x10000; - static final int FLAG_FINAL_LIST = 0x20000; - static final int FLAG_ABSTRACT = 0x40000; - static final int FLAG_ATTRIBUTE_TYPE = 0x80000; - - /** - * This is to support the feature of a separate/private XMLBeans - * distribution that will not colide with the public org apache - * xmlbeans one. - * METADATA_PACKAGE_GEN will be "" for the original and something like - * com_mycompany_private_xmlbeans for a private distribution of XMLBeans. - * - * There are two properties: - * METADATA_PACKAGE_GEN - used for generating metadata - * and METADATA_PACKAGE_LOAD - used for loading the metadata. - * Most of the time they have the same value, with one exception, during the - * repackage process scomp needs to load from old package and generate into - * a new package. - */ - public static String METADATA_PACKAGE_GEN; - static - { - // fix for maven classloader - Package stsPackage = SchemaTypeSystem.class.getPackage(); - String stsPackageName = (stsPackage==null) ? - SchemaTypeSystem.class.getName().substring(0, SchemaTypeSystem.class.getName().lastIndexOf(".")) : - stsPackage.getName(); - - METADATA_PACKAGE_GEN = stsPackageName.replaceAll("\\.", "_"); - } - - private static String nameToPathString(String nameForSystem) - { - nameForSystem = nameForSystem.replace('.', '/'); - - if (!nameForSystem.endsWith("/") && nameForSystem.length() > 0) - nameForSystem = nameForSystem + "/"; - - return nameForSystem; - } - - public SchemaTypeSystemImpl(Class indexclass) - { - String fullname = indexclass.getName(); - _name = fullname.substring(0, fullname.lastIndexOf('.')); - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Loading type system " + _name, 1); - _basePackage = nameToPathString(_name); - _classloader = indexclass.getClassLoader(); - _linker = SchemaTypeLoaderImpl.build(null, null, _classloader); - _resourceLoader = new ClassLoaderResourceLoader(_classloader); - try - { - initFromHeader(); - } - catch (RuntimeException e) - { - XBeanDebug.logException(e); - throw e; - } - catch (Error e) - { - XBeanDebug.logException(e); - throw e; - } - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finished loading type system " + _name, -1); - } - - public static boolean fileContainsTypeSystem(File file, String name) - { - String indexname = nameToPathString(name) + "index.xsb"; - - if (file.isDirectory()) - { - return (new File(file, indexname)).isFile(); - } - else - { - ZipFile zipfile = null; - try - { - zipfile = new ZipFile(file); - ZipEntry entry = zipfile.getEntry(indexname); - return (entry != null && !entry.isDirectory()); - } - catch (IOException e) - { - XBeanDebug.log("Problem loading SchemaTypeSystem, zipfilename " + file); - XBeanDebug.logException(e); - throw new SchemaTypeLoaderException(e.getMessage(), name, "index", SchemaTypeLoaderException.IO_EXCEPTION); - } - finally - { - if (zipfile != null) - try { zipfile.close(); } catch (IOException e) {} - } - } - } - - public static SchemaTypeSystemImpl forName(String name, ClassLoader loader) - { - try - { - Class c = Class.forName(name + "." + SchemaTypeCodePrinter.INDEX_CLASSNAME, true, loader); - return (SchemaTypeSystemImpl)c.getField("typeSystem").get(null); - } - catch (Exception e) - { - return null; - } - } - - public SchemaTypeSystemImpl(ResourceLoader resourceLoader, String name, SchemaTypeLoader linker) - { - _name = name; - _basePackage = nameToPathString(_name); - _linker = linker; - _resourceLoader = resourceLoader; - try - { - initFromHeader(); - } - catch (RuntimeException e) - { - XBeanDebug.logException(e); - throw e; - } - catch (Error e) - { - XBeanDebug.logException(e); - throw e; - } - } - - private void initFromHeader() - { - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Reading unresolved handles for type system " + _name, 0); - XsbReader reader = null; - try - { - // Read the index file, which starts with a header. - reader = new XsbReader("index", FILETYPE_SCHEMAINDEX); - - // has a handle pool (count, handle/type, handle/type...) - _localHandles = new HandlePool(); - reader.readHandlePool(_localHandles); - - // then a qname map of global elements (count, qname/handle, qname/handle...) - _globalElements = reader.readQNameRefMap(); - - // qname map of global attributes - _globalAttributes = reader.readQNameRefMap(); - - // qname map of model groups - _modelGroups = reader.readQNameRefMap(); - - // qname map of attribute groups - _attributeGroups = reader.readQNameRefMap(); - - _identityConstraints = reader.readQNameRefMap(); - - // qname map of global types - _globalTypes = reader.readQNameRefMap(); - - // qname map of document types, by the qname of the contained element - _documentTypes = reader.readQNameRefMap(); - - // qname mape of attribute types, by the qname of the contained attribute - _attributeTypes = reader.readQNameRefMap(); - - // string map of all types, by fully qualified classname - _typeRefsByClassname = reader.readClassnameRefMap(); - - _namespaces = reader.readNamespaces(); - - // support for redefine, at the end of the file - List typeNames = new ArrayList(); - List modelGroupNames = new ArrayList(); - List attributeGroupNames = new ArrayList(); - if (reader.atLeast(2, 15, 0)) - { - _redefinedGlobalTypes = reader.readQNameRefMapAsList(typeNames); - _redefinedModelGroups = reader.readQNameRefMapAsList(modelGroupNames); - _redefinedAttributeGroups = reader.readQNameRefMapAsList(attributeGroupNames); - } - if (reader.atLeast(2, 19, 0)) - { - _annotations = reader.readAnnotations(); - } - - buildContainers(typeNames, modelGroupNames, attributeGroupNames); - } - finally - { - if (reader != null) - reader.readEnd(); - } - } - - void saveIndex() - { - String handle = "index"; - XsbReader saver = new XsbReader(handle); - saver.writeIndexData(); - saver.writeRealHeader(handle, FILETYPE_SCHEMAINDEX); - saver.writeIndexData(); - saver.writeEnd(); - } - - void savePointers() - { - savePointersForComponents(globalElements(), "schema" + METADATA_PACKAGE_GEN + "/element/"); - savePointersForComponents(globalAttributes(), "schema" + METADATA_PACKAGE_GEN + "/attribute/"); - savePointersForComponents(modelGroups(), "schema" + METADATA_PACKAGE_GEN + "/modelgroup/"); - savePointersForComponents(attributeGroups(), "schema" + METADATA_PACKAGE_GEN + "/attributegroup/"); - savePointersForComponents(globalTypes(), "schema" + METADATA_PACKAGE_GEN + "/type/"); - savePointersForComponents(identityConstraints(), "schema" + METADATA_PACKAGE_GEN + "/identityconstraint/"); - savePointersForNamespaces(_namespaces, "schema" + METADATA_PACKAGE_GEN + "/namespace/"); - savePointersForClassnames(_typeRefsByClassname.keySet(), "schema" + METADATA_PACKAGE_GEN + "/javaname/"); - savePointersForComponents(redefinedModelGroups(), "schema" + METADATA_PACKAGE_GEN + "/redefinedmodelgroup/"); - savePointersForComponents(redefinedAttributeGroups(), "schema" + METADATA_PACKAGE_GEN + "/redefinedattributegroup/"); - savePointersForComponents(redefinedGlobalTypes(), "schema" + METADATA_PACKAGE_GEN + "/redefinedtype/"); - } - - void savePointersForComponents(SchemaComponent[] components, String dir) - { - for (int i = 0; i < components.length; i++) - { - savePointerFile(dir + QNameHelper.hexsafedir(components[i].getName()), _name); - } - } - - void savePointersForClassnames(Set classnames, String dir) - { - for (Iterator i = classnames.iterator(); i.hasNext(); ) - { - String classname = (String)i.next(); - savePointerFile(dir + classname.replace('.', '/'), _name); - } - } - - void savePointersForNamespaces(Set namespaces, String dir) - { - for (Iterator i = namespaces.iterator(); i.hasNext(); ) - { - String ns = (String)i.next(); - savePointerFile(dir + QNameHelper.hexsafedir(new QName(ns, "xmlns")), _name); - } - } - - void savePointerFile(String filename, String name) - { - XsbReader saver = new XsbReader(filename); - saver.writeString(name); - saver.writeRealHeader(filename, FILETYPE_SCHEMAPOINTER); - saver.writeString(name); - saver.writeEnd(); - } - - /** - * The strategy here is to copy the compiled TypeSystemHolder.template class - * to a new TypeSystemHolder.class needed by the schema type system. When - * saving a loader, we read the TypeSystemHolder.template class file and - * swap out the utf8 string constants with new ones to create a new - * TypeSystemHolder class file. This saves us the need to rely on javac - * to compile a generated .java file into the class file. - * - * See the JVM spec on how to interpret the bytes of a class file. - */ - void saveLoader() - { - String indexClassName = SchemaTypeCodePrinter.indexClassForSystem(this); - String[] replace = makeClassStrings(indexClassName); - assert replace.length == HOLDER_TEMPLATE_NAMES.length; - - InputStream is = null; - OutputStream os = null; - - DataInputStream in = null; - DataOutputStream out = null; - - Repackager repackager = null; - if (_filer instanceof FilerImpl) - repackager = ((FilerImpl)_filer).getRepackager(); - - try - { - is = SchemaTypeSystemImpl.class.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE); - if (is == null) - throw new SchemaTypeLoaderException("couldn't find resource: " + HOLDER_TEMPLATE_CLASSFILE, _name, null, SchemaTypeLoaderException.IO_EXCEPTION); - in = new DataInputStream(is); - - os = _filer.createBinaryFile(indexClassName.replace('.', '/') + ".class"); - out = new DataOutputStream(os); - - // java magic - out.writeInt(in.readInt()); - - // java minor and major version - out.writeShort(in.readUnsignedShort()); - out.writeShort(in.readUnsignedShort()); - - int poolsize = in.readUnsignedShort(); - out.writeShort(poolsize); - - // the constant pool is indexed from 1 to poolsize-1 - for (int i = 1; i < poolsize; i++) - { - int tag = in.readUnsignedByte(); - out.writeByte(tag); - - switch (tag) - { - case CONSTANT_UTF8: - String value = in.readUTF(); - out.writeUTF(repackageConstant(value, replace, repackager)); - break; - - case CONSTANT_CLASS: - case CONSTANT_STRING: - out.writeShort(in.readUnsignedShort()); - break; - - case CONSTANT_NAMEANDTYPE: - case CONSTANT_METHOD: - case CONSTANT_FIELD: - case CONSTANT_INTERFACEMETHOD: - out.writeShort(in.readUnsignedShort()); - out.writeShort(in.readUnsignedShort()); - break; - - case CONSTANT_INTEGER: - case CONSTANT_FLOAT: - out.writeInt(in.readInt()); - break; - - case CONSTANT_LONG: - case CONSTANT_DOUBLE: - out.writeInt(in.readInt()); - out.writeInt(in.readInt()); - break; - - default: - throw new RuntimeException("Unexpected constant type: " + tag); - } - } - - // we're done with the class' constant pool, - // we can just copy the rest of the bytes - try - { - while (true) - out.writeByte(in.readByte()); - } - catch (java.io.EOFException e) - { - // ok - } - - } - catch (IOException e) - { - // ok - } - finally - { - if (is != null) try { is.close(); } catch (Exception e) { } - if (os != null) try { os.close(); } catch (Exception e) { } - } - } - - private static final String HOLDER_TEMPLATE_CLASS = "org.apache.xmlbeans.impl.schema.TypeSystemHolder"; - private static final String HOLDER_TEMPLATE_CLASSFILE = "TypeSystemHolder.template"; - private static final String[] HOLDER_TEMPLATE_NAMES = makeClassStrings(HOLDER_TEMPLATE_CLASS); - - // constant pool entry types - private static final int CONSTANT_UTF8 = 1; - private static final int CONSTANT_UNICODE = 2; - private static final int CONSTANT_INTEGER = 3; - private static final int CONSTANT_FLOAT = 4; - private static final int CONSTANT_LONG = 5; - private static final int CONSTANT_DOUBLE = 6; - private static final int CONSTANT_CLASS = 7; - private static final int CONSTANT_STRING = 8; - private static final int CONSTANT_FIELD = 9; - private static final int CONSTANT_METHOD = 10; - private static final int CONSTANT_INTERFACEMETHOD = 11; - private static final int CONSTANT_NAMEANDTYPE = 12; - - // MAX_UNSIGNED_SHORT - private static final int MAX_UNSIGNED_SHORT = Short.MAX_VALUE * 2 + 1; - - private static String repackageConstant(String value, String[] replace, Repackager repackager) - { - for (int i = 0; i < HOLDER_TEMPLATE_NAMES.length; i++) - if (HOLDER_TEMPLATE_NAMES[i].equals(value)) - return replace[i]; - - if (repackager != null) - return repackager.repackage(new StringBuffer(value)).toString(); - - return value; - } - - /** - * Construct an array of Strings found in a class file for a classname. - * For the class name 'a.b.C' it will generate an array of: - * 'a.b.C', 'a/b/C', 'La/b/C;', and 'class$a$b$C'. - */ - private static String[] makeClassStrings(String classname) - { - String[] result = new String[4]; - - result[0] = classname; - result[1] = classname.replace('.', '/'); - result[2] = "L" + result[1] + ";"; - result[3] = "class$" + classname.replace('.', '$'); - - return result; - } - - /** - * Only used in the nonbootstrapped case. - */ - private Map buildTypeRefsByClassname() - { - List allSeenTypes = new ArrayList(); - Map result = new LinkedHashMap(); - allSeenTypes.addAll(Arrays.asList(documentTypes())); - allSeenTypes.addAll(Arrays.asList(attributeTypes())); - allSeenTypes.addAll(Arrays.asList(globalTypes())); - - // now fully javaize everything deeply. - for (int i = 0; i < allSeenTypes.size(); i++) - { - SchemaType gType = (SchemaType)allSeenTypes.get(i); - String className = gType.getFullJavaName(); - if (className != null) - { - result.put(className.replace('$', '.'), gType.getRef()); - } - allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); - } - return result; - } - - private Map buildTypeRefsByClassname(Map typesByClassname) - { - Map result = new LinkedHashMap(); - for (Iterator i = typesByClassname.keySet().iterator(); i.hasNext(); ) - { - String className = (String)i.next(); - result.put(className, ((SchemaType)typesByClassname.get(className)).getRef()); - } - return result; - } - - private static Map buildComponentRefMap(SchemaComponent[] components) - { - Map result = new LinkedHashMap(); - for (int i = 0; i < components.length; i++) - result.put(components[i].getName(), components[i].getComponentRef()); - return result; - } - - private static List buildComponentRefList(SchemaComponent[] components) - { - List result = new ArrayList(); - for (int i = 0; i < components.length; i++) - result.add(components[i].getComponentRef()); - return result; - } - - private static Map buildDocumentMap(SchemaType[] types) - { - Map result = new LinkedHashMap(); - for (int i = 0; i < types.length; i++) - result.put(types[i].getDocumentElementName(), types[i].getRef()); - return result; - } - - private static Map buildAttributeTypeMap(SchemaType[] types) - { - Map result = new LinkedHashMap(); - for (int i = 0; i < types.length; i++) - result.put(types[i].getAttributeTypeAttributeName(), types[i].getRef()); - return result; - } - - // Container operation - private SchemaContainer getContainer(String namespace) - { - return (SchemaContainer) _containers.get(namespace); - } - - private void addContainer(String namespace) - { - SchemaContainer c = new SchemaContainer(namespace); - c.setTypeSystem(this); - _containers.put(namespace, c); - } - - private SchemaContainer getContainerNonNull(String namespace) - { - SchemaContainer result = getContainer(namespace); - if (result == null) - { - addContainer(namespace); - result = getContainer(namespace); - } - return result; - } - - // Only called during init - private void buildContainers(List redefTypeNames, List redefModelGroupNames, List redefAttributeGroupNames) - { - // This method walks the reference maps and copies said references - // into the appropriate container - for (Iterator it = _globalElements.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addGlobalElement((SchemaGlobalElement.Ref) entry.getValue()); - } - for (Iterator it = _globalAttributes.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addGlobalAttribute((SchemaGlobalAttribute.Ref) entry.getValue()); - } - for (Iterator it = _modelGroups.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addModelGroup((SchemaModelGroup.Ref) entry.getValue()); - } - for (Iterator it = _attributeGroups.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addAttributeGroup((SchemaAttributeGroup.Ref) entry.getValue()); - } - for (Iterator it = _identityConstraints.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addIdentityConstraint((SchemaIdentityConstraint.Ref) entry.getValue()); - } - for (Iterator it = _globalTypes.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addGlobalType((SchemaType.Ref) entry.getValue()); - } - for (Iterator it = _documentTypes.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addDocumentType((SchemaType.Ref) entry.getValue()); - } - for (Iterator it = _attributeTypes.entrySet().iterator(); it.hasNext(); ) - { - Map.Entry entry = (Map.Entry) it.next(); - String ns = ((QName) entry.getKey()).getNamespaceURI(); - getContainerNonNull(ns).addAttributeType((SchemaType.Ref) entry.getValue()); - } - // Some earlier .xsb versions don't have records for redefinitions - if (_redefinedGlobalTypes != null && _redefinedModelGroups != null && - _redefinedAttributeGroups != null) - { - assert _redefinedGlobalTypes.size() == redefTypeNames.size(); - for (Iterator it = _redefinedGlobalTypes.iterator(), itname = redefTypeNames.iterator(); it.hasNext(); ) - { - String ns = ((QName) itname.next()).getNamespaceURI(); - getContainerNonNull(ns).addRedefinedType((SchemaType.Ref) it.next()); - } - for (Iterator it = _redefinedModelGroups.iterator(), itname = redefModelGroupNames.iterator(); it.hasNext(); ) - { - String ns = ((QName) itname.next()).getNamespaceURI(); - getContainerNonNull(ns).addRedefinedModelGroup((SchemaModelGroup.Ref) it.next()); - } - for (Iterator it = _redefinedAttributeGroups.iterator(), itname = redefAttributeGroupNames.iterator(); it.hasNext(); ) - { - String ns = ((QName) itname.next()).getNamespaceURI(); - getContainerNonNull(ns).addRedefinedAttributeGroup((SchemaAttributeGroup.Ref) it.next()); - } - } - // Some earlier .xsb versions don't have records for annotations - if (_annotations != null) - { - for (Iterator it = _annotations.iterator(); it.hasNext(); ) - { - SchemaAnnotation ann = (SchemaAnnotation) it.next(); - // BUGBUG(radup) - getContainerNonNull("").addAnnotation(ann); - } - } - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - ((SchemaContainer) it.next()).setImmutable(); - } - - /** - * This is the crux of the container work and role. - * It makes a sweep over all containers and fixes each container's - * typesystem to point to this typesystem. - * Because SchemaComponents have a link to their containers, this has as - * effect all components now indirectly pointing to this typesystem - * even though they (as well as the typesystem itself) are immutable. - */ - private void fixupContainers() - { - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - { - SchemaContainer container = (SchemaContainer) it.next(); - container.setTypeSystem(this); - container.setImmutable(); - } - } - - private void assertContainersSynchronized() - { - boolean assertEnabled = false; - // This code basically checks whether asserts are enabled so we don't do - // all the work if they arent - assert assertEnabled = true; - if (!assertEnabled) - return; - // global elements - Map temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).globalElements().toArray(new SchemaComponent[0]))); - assert _globalElements.equals(temp); - // global attributes - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).globalAttributes().toArray(new SchemaComponent[0]))); - assert _globalAttributes.equals(temp); - // model groups - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).modelGroups().toArray(new SchemaComponent[0]))); - assert _modelGroups.equals(temp); - // redefined model groups - Set temp2 = new HashSet(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp2.addAll(buildComponentRefList((SchemaComponent[]) ((SchemaContainer) it.next()).redefinedModelGroups().toArray(new SchemaComponent[0]))); - assert new HashSet(_redefinedModelGroups).equals(temp2); - // attribute groups - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).attributeGroups().toArray(new SchemaComponent[0]))); - assert _attributeGroups.equals(temp); - // redefined attribute groups - temp2 = new HashSet(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp2.addAll(buildComponentRefList((SchemaComponent[]) ((SchemaContainer) it.next()).redefinedAttributeGroups().toArray(new SchemaComponent[0]))); - assert new HashSet(_redefinedAttributeGroups).equals(temp2); - // global types - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).globalTypes().toArray(new SchemaComponent[0]))); - assert _globalTypes.equals(temp); - // redefined global types - temp2 = new HashSet(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp2.addAll(buildComponentRefList((SchemaComponent[]) ((SchemaContainer) it.next()).redefinedGlobalTypes().toArray(new SchemaComponent[0]))); - assert new HashSet(_redefinedGlobalTypes).equals(temp2); - // document types - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildDocumentMap((SchemaType[]) ((SchemaContainer) it.next()).documentTypes().toArray(new SchemaType[0]))); - assert _documentTypes.equals(temp); - // attribute types - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildAttributeTypeMap((SchemaType[]) ((SchemaContainer) it.next()).attributeTypes().toArray(new SchemaType[0]))); - assert _attributeTypes.equals(temp); - // identity constraints - temp = new HashMap(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).identityConstraints().toArray(new SchemaComponent[0]))); - assert _identityConstraints.equals(temp); - // annotations - temp2 = new HashSet(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp2.addAll(((SchemaContainer) it.next()).annotations()); - assert new HashSet(_annotations).equals(temp2); - // namespaces - temp2 = new HashSet(); - for (Iterator it = _containers.values().iterator(); it.hasNext(); ) - temp2.add(((SchemaContainer) it.next()).getNamespace()); - assert _namespaces.equals(temp2); - } - - private static Random _random; - private static byte[] _mask = new byte[128 / 8]; - - /** - * Fun, fun. Produce 128 bits of uniqueness randomly. - * We used to use SecureRandom, but now we don't because SecureRandom - * hits the filesystem and hangs us on a filesystem lock. It also eats - * a thread and other expensive resources.. :-). - * - * We don't really care that non-secure Random() can only do 48 bits of - * randomness, since we're certainly not going to be called more than 2^48 - * times within our process lifetime. - * - * Our real concern is that by seeding Random() with the current - * time, two users will end up with the same bits if they start a - * schema compilation within the same millisecond. That makes the - * probability of collision in the real world slightly too high. - * We're going to have millions of users, remember? With a million - * users, and one-compilation-per-day each, we'd see a collision every - * few months. - * - * So we'll just xor the results of random with our few extra - * bits of information computed below to help reduce the probability - * of collision by a few decimal places. To collide, you will have had - * to have the same amount of free memory, the same user name, timezone, - * and country, the same current directory, the same java classpath, - * the same operating system and jvm version, and the same choices of - * identity hashcodes for a few objects. And be started within the same - * millisecond. Or you can collide if you have a cosmic 128-bit mathematical - * coincidence. No worries. - */ - private static synchronized void nextBytes(byte[] result) - { - if (_random == null) - { - try - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream daos = new DataOutputStream(baos); - - // at least 10 bits of unqieueness, right? Maybe even 50 or 60. - daos.writeInt(System.identityHashCode(SchemaTypeSystemImpl.class)); - String[] props = new String[] { "user.name", "user.dir", "user.timezone", "user.country", "java.class.path", "java.home", "java.vendor", "java.version", "os.version" }; - for (int i = 0; i < props.length; i++) - { - String prop = SystemProperties.getProperty(props[i]); - if (prop != null) - { - daos.writeUTF(prop); - daos.writeInt(System.identityHashCode(prop)); - } - } - daos.writeLong(Runtime.getRuntime().freeMemory()); - daos.close(); - byte[] bytes = baos.toByteArray(); - for (int i = 0; i < bytes.length; i++) - { - int j = i % _mask.length; - _mask[j] *= 21; - _mask[j] += i; - } - } - catch (IOException e) - { - XBeanDebug.logException(e); - } - - _random = new Random(System.currentTimeMillis()); - } - _random.nextBytes(result); - for (int i = 0; i < result.length; i++) - { - int j = i & _mask.length; - result[i] ^= _mask[j]; - } - } - - public SchemaTypeSystemImpl(String nameForSystem) - { - // if we have no name, select a random one - if (nameForSystem == null) - { - // get 128 random bits (that'll be 32 hex digits) - byte[] bytes = new byte[128/8]; - nextBytes(bytes); - nameForSystem = "s" + new String(HexBin.encode(bytes)); - } - - _name = "schema" + METADATA_PACKAGE_GEN + ".system." + nameForSystem; - _basePackage = nameToPathString(_name); - _classloader = null; - //System.out.println(" _base: " + _basePackage); - } - - public void loadFromBuilder(SchemaGlobalElement[] globalElements, - SchemaGlobalAttribute[] globalAttributes, - SchemaType[] globalTypes, - SchemaType[] documentTypes, - SchemaType[] attributeTypes) - { - assert(_classloader == null); - _localHandles = new HandlePool(); - _globalElements = buildComponentRefMap(globalElements); - _globalAttributes = buildComponentRefMap(globalAttributes); - _globalTypes = buildComponentRefMap(globalTypes); - _documentTypes = buildDocumentMap(documentTypes); - _attributeTypes = buildAttributeTypeMap(attributeTypes); - _typeRefsByClassname = buildTypeRefsByClassname(); - buildContainers(Collections.EMPTY_LIST, Collections.EMPTY_LIST, - Collections.EMPTY_LIST); - _namespaces = new HashSet(); - } - - public void loadFromStscState(StscState state) - { - assert(_classloader == null); - _localHandles = new HandlePool(); - _globalElements = buildComponentRefMap(state.globalElements()); - _globalAttributes = buildComponentRefMap(state.globalAttributes()); - _modelGroups = buildComponentRefMap(state.modelGroups()); - _redefinedModelGroups = buildComponentRefList(state.redefinedModelGroups()); - _attributeGroups = buildComponentRefMap(state.attributeGroups()); - _redefinedAttributeGroups = buildComponentRefList(state.redefinedAttributeGroups()); - _globalTypes = buildComponentRefMap(state.globalTypes()); - _redefinedGlobalTypes = buildComponentRefList(state.redefinedGlobalTypes()); - _documentTypes = buildDocumentMap(state.documentTypes()); - _attributeTypes = buildAttributeTypeMap(state.attributeTypes()); - _typeRefsByClassname = buildTypeRefsByClassname(state.typesByClassname()); - _identityConstraints = buildComponentRefMap(state.idConstraints()); - _annotations = state.annotations(); - _namespaces = new HashSet(Arrays.asList(state.getNamespaces())); - _containers = state.getContainerMap(); - fixupContainers(); - // Checks that data in the containers matches the lookup maps - assertContainersSynchronized(); - setDependencies(state.getDependencies()); - } - - final SchemaTypeSystemImpl getTypeSystem() - { - return this; - } - - void setDependencies(SchemaDependencies deps) - { _deps = deps; } - - SchemaDependencies getDependencies() - { return _deps; } - - // EXPERIMENTAL - public boolean isIncomplete() { return _incomplete; } - - // EXPERIMENTAL - void setIncomplete(boolean incomplete) { _incomplete = incomplete; } - - static class StringPool - { - private List intsToStrings = new ArrayList(); - private Map stringsToInts = new HashMap(); - private String _handle; - private String _name; - - /** - * Constructs an empty StringPool to be filled with strings. - */ - StringPool(String handle, String name) - { - _handle = handle; - _name = name; - intsToStrings.add(null); - } - - int codeForString(String str) - { - if (str == null) - return 0; - Integer result = (Integer)stringsToInts.get(str); - if (result == null) - { - result = new Integer(intsToStrings.size()); - intsToStrings.add(str); - stringsToInts.put(str, result); - } - return result.intValue(); - } - - String stringForCode(int code) - { - if (code == 0) - return null; - return (String)intsToStrings.get(code); - } - - void writeTo(DataOutputStream output) - { - if (intsToStrings.size() >= MAX_UNSIGNED_SHORT) - throw new SchemaTypeLoaderException("Too many strings (" + intsToStrings.size() + ")", _name, _handle, SchemaTypeLoaderException.INT_TOO_LARGE); - - try - { - output.writeShort(intsToStrings.size()); - Iterator i = intsToStrings.iterator(); - for (i.next(); i.hasNext(); ) - { - String str = (String)i.next(); - output.writeUTF(str); - } - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - void readFrom(DataInputStream input) - { - if (intsToStrings.size() != 1 || stringsToInts.size() != 0) - throw new IllegalStateException(); - - try - { - int size = input.readUnsignedShort(); - for (int i = 1; i < size; i++) - { - String str = input.readUTF().intern(); - int code = codeForString(str); - if (code != i) - throw new IllegalStateException(); - } - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage() == null ? e.getMessage() : "IO Exception", _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e); - } - } - } - - class HandlePool - { - private Map _handlesToRefs = new LinkedHashMap(); - private Map _componentsToHandles = new LinkedHashMap(); // populated on write - private boolean _started; - - /** - * Constructs an empty HandlePool to be populated. - */ - HandlePool() - { - } - - private String addUniqueHandle(SchemaComponent obj, String base) - { - base = base.toLowerCase(); // we lowercase handles because of case-insensitive Windows filenames!!! - String handle = base; - for (int index = 2; _handlesToRefs.containsKey(handle); index++) - { - handle = base + index; - } - _handlesToRefs.put(handle, obj.getComponentRef()); - _componentsToHandles.put(obj, handle); - return handle; - } - - String handleForComponent(SchemaComponent comp) - { - if (comp == null) - return null; - if (comp.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - if (comp instanceof SchemaType) - return handleForType((SchemaType)comp); - if (comp instanceof SchemaGlobalElement) - return handleForElement((SchemaGlobalElement)comp); - if (comp instanceof SchemaGlobalAttribute) - return handleForAttribute((SchemaGlobalAttribute)comp); - if (comp instanceof SchemaModelGroup) - return handleForModelGroup((SchemaModelGroup)comp); - if (comp instanceof SchemaAttributeGroup) - return handleForAttributeGroup((SchemaAttributeGroup)comp); - if (comp instanceof SchemaIdentityConstraint) - return handleForIdentityConstraint((SchemaIdentityConstraint)comp); - throw new IllegalStateException("Component type cannot have a handle"); - } - - String handleForElement(SchemaGlobalElement element) - { - if (element == null) - return null; - if (element.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - String handle = (String)_componentsToHandles.get(element); - if (handle == null) - handle = addUniqueHandle(element, NameUtil.upperCamelCase(element.getName().getLocalPart()) + "Element"); - return handle; - } - - String handleForAttribute(SchemaGlobalAttribute attribute) - { - if (attribute == null) - return null; - if (attribute.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - String handle = (String)_componentsToHandles.get(attribute); - if (handle == null) - handle = addUniqueHandle(attribute, NameUtil.upperCamelCase(attribute.getName().getLocalPart()) + "Attribute"); - return handle; - } - - String handleForModelGroup(SchemaModelGroup group) - { - if (group == null) - return null; - if (group.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - String handle = (String)_componentsToHandles.get(group); - if (handle == null) - handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "ModelGroup"); - return handle; - } - - String handleForAttributeGroup(SchemaAttributeGroup group) - { - if (group == null) - return null; - if (group.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - String handle = (String)_componentsToHandles.get(group); - if (handle == null) - handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "AttributeGroup"); - return handle; - } - - String handleForIdentityConstraint(SchemaIdentityConstraint idc) - { - if (idc == null) - return null; - if (idc.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - String handle = (String)_componentsToHandles.get(idc); - if (handle == null) - handle = addUniqueHandle(idc, NameUtil.upperCamelCase(idc.getName().getLocalPart()) + "IdentityConstraint"); - return handle; - } - - String handleForType(SchemaType type) - { - if (type == null) - return null; - if (type.getTypeSystem() != getTypeSystem()) - throw new IllegalArgumentException("Cannot supply handles for types from another type system"); - String handle = (String)_componentsToHandles.get(type); - if (handle == null) - { - QName name = type.getName(); - String suffix = ""; - if (name == null) - { - if (type.isDocumentType()) - { - name = type.getDocumentElementName(); - suffix = "Doc"; - } - else if (type.isAttributeType()) - { - name = type.getAttributeTypeAttributeName(); - suffix = "AttrType"; - } - else if (type.getContainerField() != null) - { - name = type.getContainerField().getName(); - suffix = type.getContainerField().isAttribute() ? "Attr" : "Elem"; - } - } - - String baseName; - String uniq = Integer.toHexString(type.toString().hashCode() | 0x80000000).substring(4).toUpperCase(); - if (name == null) - baseName = "Anon" + uniq + "Type"; - else - baseName = NameUtil.upperCamelCase(name.getLocalPart()) + uniq + suffix + "Type"; - - handle = addUniqueHandle(type, baseName); - } - - return handle; - } - - SchemaComponent.Ref refForHandle(String handle) - { - if (handle == null) - return null; - - return (SchemaComponent.Ref)_handlesToRefs.get(handle); - } - - Set getAllHandles() - { - return _handlesToRefs.keySet(); - } - - void startWriteMode() - { - _started = true; - _componentsToHandles = new LinkedHashMap(); - for (Iterator i = _handlesToRefs.keySet().iterator(); i.hasNext(); ) - { - String handle = (String)i.next(); -// System.err.println("Writing preexisting handle " + handle); - SchemaComponent comp = ((SchemaComponent.Ref)_handlesToRefs.get(handle)).getComponent(); - _componentsToHandles.put(comp, handle); - } - } - - } - - private String _name; - private String _basePackage; - - // EXPERIMENTAL: recovery from compilation errors and partial type systems - private boolean _incomplete = false; - - // classloader is available for sts's that were compiled and loaded, not dynamic ones - private ClassLoader _classloader; - - // the loader for loading .xsb resources - private ResourceLoader _resourceLoader; - - // the following is used to link references during load - SchemaTypeLoader _linker; - - private HandlePool _localHandles; - private Filer _filer; - - // top-level annotations - private List _annotations; - - // container - private Map _containers = new HashMap(); - // dependencies - private SchemaDependencies _deps; - - private List _redefinedModelGroups; - private List _redefinedAttributeGroups; - private List _redefinedGlobalTypes; - - // actual type system data, map QNames -> SchemaComponent.Ref - private Map _globalElements; - private Map _globalAttributes; - private Map _modelGroups; - private Map _attributeGroups; - private Map _globalTypes; - private Map _documentTypes; - private Map _attributeTypes; - private Map _identityConstraints = Collections.EMPTY_MAP; - private Map _typeRefsByClassname = new HashMap(); - private Set _namespaces; - - static private final SchemaType[] EMPTY_ST_ARRAY = new SchemaType[0]; - static private final SchemaGlobalElement[] EMPTY_GE_ARRAY = new SchemaGlobalElement[0]; - static private final SchemaGlobalAttribute[] EMPTY_GA_ARRAY = new SchemaGlobalAttribute[0]; - static private final SchemaModelGroup[] EMPTY_MG_ARRAY = new SchemaModelGroup[0]; - static private final SchemaAttributeGroup[] EMPTY_AG_ARRAY = new SchemaAttributeGroup[0]; - static private final SchemaIdentityConstraint[] EMPTY_IC_ARRAY = new SchemaIdentityConstraint[0]; - static private final SchemaAnnotation[] EMPTY_ANN_ARRAY = new SchemaAnnotation[0]; - - public void saveToDirectory(File classDir) - { - save(new FilerImpl(classDir, null, null, false, false)); - } - - public void save(Filer filer) - { - if (_incomplete) - throw new IllegalStateException("Incomplete SchemaTypeSystems cannot be saved."); - - if (filer == null) - throw new IllegalArgumentException("filer must not be null"); - _filer = filer; - - _localHandles.startWriteMode(); - saveTypesRecursively(globalTypes()); - saveTypesRecursively(documentTypes()); - saveTypesRecursively(attributeTypes()); - saveGlobalElements(globalElements()); - saveGlobalAttributes(globalAttributes()); - saveModelGroups(modelGroups()); - saveAttributeGroups(attributeGroups()); - saveIdentityConstraints(identityConstraints()); - - saveTypesRecursively(redefinedGlobalTypes()); - saveModelGroups(redefinedModelGroups()); - saveAttributeGroups(redefinedAttributeGroups()); - - saveIndex(); - savePointers(); - - saveLoader(); - } - - void saveTypesRecursively(SchemaType[] types) - { - for (int i = 0; i < types.length; i++) - { - if (types[i].getTypeSystem() != getTypeSystem()) - continue; - saveType(types[i]); - saveTypesRecursively(types[i].getAnonymousTypes()); - } - } - - public void saveGlobalElements(SchemaGlobalElement[] elts) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - for (int i = 0; i < elts.length; i++) - { - saveGlobalElement(elts[i]); - } - } - - public void saveGlobalAttributes(SchemaGlobalAttribute[] attrs) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - for (int i = 0; i < attrs.length; i++) - { - saveGlobalAttribute(attrs[i]); - } - } - - public void saveModelGroups(SchemaModelGroup[] groups) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - for (int i = 0; i < groups.length; i++) - { - saveModelGroup(groups[i]); - } - } - - public void saveAttributeGroups(SchemaAttributeGroup[] groups) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - for (int i = 0; i < groups.length; i++) - { - saveAttributeGroup(groups[i]); - } - } - - public void saveIdentityConstraints(SchemaIdentityConstraint[] idcs) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - for (int i = 0; i < idcs.length; i++) - { - saveIdentityConstraint(idcs[i]); - } - } - - public void saveGlobalElement(SchemaGlobalElement elt) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - String handle = _localHandles.handleForElement(elt); - XsbReader saver = new XsbReader(handle); - saver.writeParticleData((SchemaParticle)elt); - saver.writeString(elt.getSourceName()); - saver.writeRealHeader(handle, FILETYPE_SCHEMAELEMENT); - saver.writeParticleData((SchemaParticle)elt); - saver.writeString(elt.getSourceName()); - saver.writeEnd(); - } - - public void saveGlobalAttribute(SchemaGlobalAttribute attr) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - String handle = _localHandles.handleForAttribute(attr); - XsbReader saver = new XsbReader(handle); - saver.writeAttributeData(attr); - saver.writeString(attr.getSourceName()); - saver.writeRealHeader(handle, FILETYPE_SCHEMAATTRIBUTE); - saver.writeAttributeData(attr); - saver.writeString(attr.getSourceName()); - saver.writeEnd(); - } - - public void saveModelGroup(SchemaModelGroup grp) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - String handle = _localHandles.handleForModelGroup(grp); - XsbReader saver = new XsbReader(handle); - saver.writeModelGroupData(grp); - saver.writeRealHeader(handle, FILETYPE_SCHEMAMODELGROUP); - saver.writeModelGroupData(grp); - saver.writeEnd(); - } - - public void saveAttributeGroup(SchemaAttributeGroup grp) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - String handle = _localHandles.handleForAttributeGroup(grp); - XsbReader saver = new XsbReader(handle); - saver.writeAttributeGroupData(grp); - saver.writeRealHeader(handle, FILETYPE_SCHEMAATTRIBUTEGROUP); - saver.writeAttributeGroupData(grp); - saver.writeEnd(); - } - - public void saveIdentityConstraint(SchemaIdentityConstraint idc) - { - if (_incomplete) - throw new IllegalStateException("This SchemaTypeSystem cannot be saved."); - String handle = _localHandles.handleForIdentityConstraint(idc); - XsbReader saver = new XsbReader(handle); - saver.writeIdConstraintData(idc); - saver.writeRealHeader(handle, FILETYPE_SCHEMAIDENTITYCONSTRAINT); - saver.writeIdConstraintData(idc); - saver.writeEnd(); - } - - void saveType(SchemaType type) - { - String handle = _localHandles.handleForType(type); - XsbReader saver = new XsbReader(handle); - saver.writeTypeData(type); - saver.writeRealHeader(handle, FILETYPE_SCHEMATYPE); - saver.writeTypeData(type); - saver.writeEnd(); - } - - public static String crackPointer(InputStream stream) - { - DataInputStream input = null; - try - { - input = new DataInputStream(stream); - - int magic = input.readInt(); - if (magic != DATA_BABE) - return null; - - int majorver = input.readShort(); - int minorver = input.readShort(); - - if (majorver != MAJOR_VERSION) - return null; - - if (minorver > MINOR_VERSION) - return null; - - if (majorver > 2 || majorver == 2 && minorver >= 18) - input.readShort(); // release number present in atLeast(2, 18, 0) - - int actualfiletype = input.readShort(); - if (actualfiletype != FILETYPE_SCHEMAPOINTER) - return null; - - StringPool stringPool = new StringPool("pointer", "unk"); - stringPool.readFrom(input); - - return stringPool.stringForCode(input.readShort()); - } - catch (IOException e) - { - return null; - } - finally - { - if (input != null) - try { input.close(); } catch (IOException e) {} - } - } - - private class XsbReader - { - DataInputStream _input; - DataOutputStream _output; - StringPool _stringPool; - String _handle; - private int _majorver; - private int _minorver; - private int _releaseno; - int _actualfiletype; - - public XsbReader(String handle, int filetype) - { - String resourcename = _basePackage + handle + ".xsb"; - InputStream rawinput = getLoaderStream(resourcename); - if (rawinput == null) - throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Could not locate compiled schema resource " + resourcename, _name, handle, SchemaTypeLoaderException.NO_RESOURCE); - - _input = new DataInputStream(rawinput); - _handle = handle; - - int magic = readInt(); - if (magic != DATA_BABE) - throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Wrong magic cookie", _name, handle, SchemaTypeLoaderException.WRONG_MAGIC_COOKIE); - - _majorver = readShort(); - _minorver = readShort(); - - if (_majorver != MAJOR_VERSION) - throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Wrong major version - expecting " + MAJOR_VERSION + ", got " + _majorver, _name, handle, SchemaTypeLoaderException.WRONG_MAJOR_VERSION); - - if (_minorver > MINOR_VERSION) - throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Incompatible minor version - expecting up to " + MINOR_VERSION + ", got " + _minorver, _name, handle, SchemaTypeLoaderException.WRONG_MINOR_VERSION); - - // Clip to 14 because we're not backward compatible with earlier - // minor versions. Remove this when upgrading to a new major - // version - - if (_minorver < 14) - throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Incompatible minor version - expecting at least 14, got " + _minorver, _name, handle, SchemaTypeLoaderException.WRONG_MINOR_VERSION); - - if (atLeast(2, 18, 0)) - _releaseno = readShort(); - - int actualfiletype = readShort(); - if (actualfiletype != filetype && filetype != 0xFFFF) - throw new SchemaTypeLoaderException("XML-BEANS compiled schema: File has the wrong type - expecting type " + filetype + ", got type " + actualfiletype, _name, handle, SchemaTypeLoaderException.WRONG_FILE_TYPE); - - _stringPool = new StringPool(_handle, _name); - _stringPool.readFrom(_input); - - _actualfiletype = actualfiletype; - } - - protected boolean atLeast(int majorver, int minorver, int releaseno) - { - if (_majorver > majorver) - return true; - if (_majorver < majorver) - return false; - if (_minorver > minorver) - return true; - if (_minorver < minorver) - return false; - return (_releaseno >= releaseno); - } - - protected boolean atMost(int majorver, int minorver, int releaseno) - { - if (_majorver > majorver) - return false; - if (_majorver < majorver) - return true; - if (_minorver > minorver) - return false; - if (_minorver < minorver) - return true; - return (_releaseno <= releaseno); - } - - int getActualFiletype() - { - return _actualfiletype; - } - - XsbReader(String handle) - { - _handle = handle; - _stringPool = new StringPool(_handle, _name); - } - - void writeRealHeader(String handle, int filetype) - { - // hackeroo: if handle contains a "/" it's not relative. - String resourcename; - - if (handle.indexOf('/') >= 0) - resourcename = handle + ".xsb"; - else - resourcename = _basePackage + handle + ".xsb"; - - OutputStream rawoutput = getSaverStream(resourcename); - if (rawoutput == null) - throw new SchemaTypeLoaderException("Could not write compiled schema resource " + resourcename, _name, handle, SchemaTypeLoaderException.NOT_WRITEABLE); - - _output = new DataOutputStream(rawoutput); - _handle = handle; - - writeInt(DATA_BABE); - writeShort(MAJOR_VERSION); - writeShort(MINOR_VERSION); - writeShort(RELEASE_NUMBER); - writeShort(filetype); - - _stringPool.writeTo(_output); - } - - void readEnd() - { - try - { - if (_input != null) - _input.close(); - } - catch (IOException e) - { - // oh, well. - } - _input = null; - _stringPool = null; - _handle = null; - } - - void writeEnd() - { - try - { - if (_output != null) - { - _output.flush(); - _output.close(); - } - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - _output = null; - _stringPool = null; - _handle = null; - } - - int fileTypeFromComponentType(int componentType) - { - switch (componentType) - { - case SchemaComponent.TYPE: - return SchemaTypeSystemImpl.FILETYPE_SCHEMATYPE; - case SchemaComponent.ELEMENT: - return SchemaTypeSystemImpl.FILETYPE_SCHEMAELEMENT; - case SchemaComponent.ATTRIBUTE: - return SchemaTypeSystemImpl.FILETYPE_SCHEMAATTRIBUTE; - case SchemaComponent.MODEL_GROUP: - return SchemaTypeSystemImpl.FILETYPE_SCHEMAMODELGROUP; - case SchemaComponent.ATTRIBUTE_GROUP: - return SchemaTypeSystemImpl.FILETYPE_SCHEMAATTRIBUTEGROUP; - case SchemaComponent.IDENTITY_CONSTRAINT: - return SchemaTypeSystemImpl.FILETYPE_SCHEMAIDENTITYCONSTRAINT; - default: - throw new IllegalStateException("Unexpected component type"); - } - } - - void writeIndexData() - { - // has a handle pool (count, handle/type, handle/type...) - writeHandlePool(_localHandles); - - // then a qname map of global elements (count, qname/handle, qname/handle...) - writeQNameMap(globalElements()); - - // qname map of global attributes - writeQNameMap(globalAttributes()); - - // qname map of model groups - writeQNameMap(modelGroups()); - - // qname map of attribute groups - writeQNameMap(attributeGroups()); - - // qname map of identity constraints - writeQNameMap(identityConstraints()); - - // qname map of global types - writeQNameMap(globalTypes()); - - // qname map of document types, by the qname of the contained element - writeDocumentTypeMap(documentTypes()); - - // qname map of attribute types, by the qname of the contained attribute - writeAttributeTypeMap(attributeTypes()); - - // all the types by classname - writeClassnameMap(_typeRefsByClassname); - - // all the namespaces - writeNamespaces(_namespaces); - - // VERSION 2.15 and newer below - writeQNameMap(redefinedGlobalTypes()); - writeQNameMap(redefinedModelGroups()); - writeQNameMap(redefinedAttributeGroups()); - writeAnnotations(annotations()); - } - - void writeHandlePool(HandlePool pool) - { - writeShort(pool._componentsToHandles.size()); - for (Iterator i = pool._componentsToHandles.keySet().iterator(); i.hasNext(); ) - { - SchemaComponent comp = (SchemaComponent)i.next(); - String handle = (String)pool._componentsToHandles.get(comp); - int code = fileTypeFromComponentType(comp.getComponentType()); - writeString(handle); - writeShort(code); - } - } - - void readHandlePool(HandlePool pool) - { - if (pool._handlesToRefs.size() != 0 || pool._started) - throw new IllegalStateException("Nonempty handle set before read"); - - int size = readShort(); - for (int i = 0; i < size; i++) - { - String handle = readString(); - int code = readShort(); - Object result; - switch (code) - { - case FILETYPE_SCHEMATYPE: - result = new SchemaType.Ref(getTypeSystem(), handle); - break; - case FILETYPE_SCHEMAELEMENT: - result = new SchemaGlobalElement.Ref(getTypeSystem(), handle); - break; - case FILETYPE_SCHEMAATTRIBUTE: - result = new SchemaGlobalAttribute.Ref(getTypeSystem(), handle); - break; - case FILETYPE_SCHEMAMODELGROUP: - result = new SchemaModelGroup.Ref(getTypeSystem(), handle); - break; - case FILETYPE_SCHEMAATTRIBUTEGROUP: - result = new SchemaAttributeGroup.Ref(getTypeSystem(), handle); - break; - case FILETYPE_SCHEMAIDENTITYCONSTRAINT: - result = new SchemaIdentityConstraint.Ref(getTypeSystem(), handle); - break; - default: - throw new SchemaTypeLoaderException("Schema index has an unrecognized entry of type " + code, _name, handle, SchemaTypeLoaderException.UNRECOGNIZED_INDEX_ENTRY); - } - pool._handlesToRefs.put(handle, result); - } - } - - int readShort() - { - try - { - return _input.readUnsignedShort(); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - void writeShort(int s) - { - if (s >= MAX_UNSIGNED_SHORT || s < -1) - throw new SchemaTypeLoaderException("Value " + s + " out of range: must fit in a 16-bit unsigned short.", _name, _handle, SchemaTypeLoaderException.INT_TOO_LARGE); - if (_output != null) - { - try - { - _output.writeShort(s); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - } - - int readInt() - { - try - { - return _input.readInt(); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - void writeInt(int i) - { - if (_output != null) - { - try - { - _output.writeInt(i); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - } - - String readString() - { - return _stringPool.stringForCode(readShort()); - } - - void writeString(String str) - { - int code = _stringPool.codeForString(str); - writeShort(code); - } - - QName readQName() - { - String namespace = readString(); - String localname = readString(); - if (localname == null) - return null; - return new QName(namespace, localname); - } - - void writeQName(QName qname) - { - if (qname == null) - { - writeString(null); - writeString(null); - return; - } - writeString(qname.getNamespaceURI()); - writeString(qname.getLocalPart()); - } - - SOAPArrayType readSOAPArrayType() - { - QName qName = readQName(); - String dimensions = readString(); - if (qName == null) - return null; - return new SOAPArrayType(qName, dimensions); - } - - void writeSOAPArrayType(SOAPArrayType arrayType) - { - if (arrayType == null) - { - writeQName(null); - writeString(null); - } - else - { - writeQName(arrayType.getQName()); - writeString(arrayType.soap11DimensionString()); - } - } - - void writeAnnotation(SchemaAnnotation a) - { - // Write attributes - if (a == null) - { - writeInt(-1); - return; - } - SchemaAnnotation.Attribute[] attributes = a.getAttributes(); - writeInt(attributes.length); - for (int i = 0; i < attributes.length; i++) - { - QName name = attributes[i].getName(); - String value = attributes[i].getValue(); - String valueURI = attributes[i].getValueUri(); - writeQName(name); - writeString(value); - writeString(valueURI); - } - - // Write documentation items - XmlObject[] documentationItems = a.getUserInformation(); - writeInt(documentationItems.length); - XmlOptions opt = new XmlOptions().setSaveOuter(). - setSaveAggressiveNamespaces(); - for (int i = 0; i < documentationItems.length; i++) - { - XmlObject doc = documentationItems[i]; - writeString(doc.xmlText(opt)); - } - - // Write application info items - XmlObject[] appInfoItems = a.getApplicationInformation(); - writeInt(appInfoItems.length); - for (int i = 0; i < appInfoItems.length; i++) - { - XmlObject doc = appInfoItems[i]; - writeString(doc.xmlText(opt)); - } - } - - SchemaAnnotation readAnnotation(SchemaContainer c) - { - if (!atLeast(2, 19, 0)) - return null; // no annotations for this version of the file - // Read attributes - int n = readInt(); - if (n == -1) - return null; - SchemaAnnotation.Attribute[] attributes = - new SchemaAnnotation.Attribute[n]; - for (int i = 0; i < n; i++) - { - QName name = readQName(); - String value = readString(); - String valueUri = null; - if (atLeast(2, 24, 0)) - valueUri = readString(); - attributes[i] = new SchemaAnnotationImpl.AttributeImpl(name, value, valueUri); - } - - // Read documentation items - n = readInt(); - String[] docStrings = new String[n]; - for (int i = 0; i < n; i++) - { - docStrings[i] = readString(); - } - - // Read application info items - n = readInt(); - String[] appInfoStrings = new String[n]; - for (int i = 0; i < n; i++) - { - appInfoStrings[i] = readString(); - } - - return new SchemaAnnotationImpl(c, appInfoStrings, - docStrings, attributes); - } - - void writeAnnotations(SchemaAnnotation[] anns) - { - writeInt(anns.length); - for (int i = 0; i < anns.length; i++) - writeAnnotation(anns[i]); - } - - List readAnnotations() - { - int n = readInt(); - List result = new ArrayList(n); - // BUGBUG(radup) - SchemaContainer container = getContainerNonNull(""); - for (int i = 0; i < n; i++) - result.add(readAnnotation(container)); - return result; - } - - SchemaComponent.Ref readHandle() - { - String handle = readString(); - if (handle == null) - return null; - - if (handle.charAt(0) != '_') - return _localHandles.refForHandle(handle); - - switch (handle.charAt(2)) - { - case 'I': // _BI_ - built-in schema type system - SchemaType st = (SchemaType) BuiltinSchemaTypeSystem.get().resolveHandle(handle); - if (st != null) - return st.getRef(); - st = (SchemaType) XQuerySchemaTypeSystem.get().resolveHandle(handle); - return st.getRef(); - case 'T': // _XT_ - external type - return _linker.findTypeRef(QNameHelper.forPretty(handle, 4)); - case 'E': // _XE_ - external element - return _linker.findElementRef(QNameHelper.forPretty(handle, 4)); - case 'A': // _XA_ - external attribute - return _linker.findAttributeRef(QNameHelper.forPretty(handle, 4)); - case 'M': // _XM_ - external model group - return _linker.findModelGroupRef(QNameHelper.forPretty(handle, 4)); - case 'N': // _XN_ - external attribute group - return _linker.findAttributeGroupRef(QNameHelper.forPretty(handle, 4)); - case 'D': // _XD_ - external identity constraint - return _linker.findIdentityConstraintRef(QNameHelper.forPretty(handle, 4)); - case 'R': // _XR_ - external ref to attribute's type - // deprecated: replaced by _XY_ - SchemaGlobalAttribute attr = _linker.findAttribute(QNameHelper.forPretty(handle, 4)); - if (attr == null) - throw new SchemaTypeLoaderException("Cannot resolve attribute for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); - return attr.getType().getRef(); - case 'S': // _XS_ - external ref to element's type - // deprecated: replaced by _XY_ - SchemaGlobalElement elem = _linker.findElement(QNameHelper.forPretty(handle, 4)); - if (elem == null) - throw new SchemaTypeLoaderException("Cannot resolve element for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); - return elem.getType().getRef(); - case 'O': // _XO_ - external ref to document type - return _linker.findDocumentTypeRef(QNameHelper.forPretty(handle, 4)); - case 'Y': // _XY_ - external ref to any possible type - SchemaType type = _linker.typeForSignature(handle.substring(4)); - if (type == null) - throw new SchemaTypeLoaderException("Cannot resolve type for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); - return type.getRef(); - default: - throw new SchemaTypeLoaderException("Cannot resolve handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); - } - } - - void writeHandle(SchemaComponent comp) - { - if (comp == null || comp.getTypeSystem() == getTypeSystem()) - { - writeString(_localHandles.handleForComponent(comp)); - return; - } - - switch (comp.getComponentType()) - { - case SchemaComponent.ATTRIBUTE: - writeString("_XA_" + QNameHelper.pretty(comp.getName())); - return; - case SchemaComponent.MODEL_GROUP: - writeString("_XM_" + QNameHelper.pretty(comp.getName())); - return; - case SchemaComponent.ATTRIBUTE_GROUP: - writeString("_XN_" + QNameHelper.pretty(comp.getName())); - return; - case SchemaComponent.ELEMENT: - writeString("_XE_" + QNameHelper.pretty(comp.getName())); - return; - case SchemaComponent.IDENTITY_CONSTRAINT: - writeString("_XD_" + QNameHelper.pretty(comp.getName())); - return; - case SchemaComponent.TYPE: - SchemaType type = (SchemaType)comp; - if (type.isBuiltinType()) - { - writeString("_BI_" + type.getName().getLocalPart()); - return; - } - - // fix for CR120759 - added output of types _XR_ & _XS_ - // when an attribute (_XR_) or element (_XS_) declaration - // uses ref to refer to an attribute or element in another - // schema and the type of that attribute or element - // is an anonymous (local) type - // kkrouse 02/1/2005: _XR_ and _XS_ refs are replaced by _XY_ - if (type.getName() != null) - { - writeString("_XT_" + QNameHelper.pretty(type.getName())); - } - else if (type.isDocumentType()) - { - // Substitution groups will create document types that - // extend from other document types, possibly in - // different jars - writeString("_XO_" + QNameHelper.pretty(type.getDocumentElementName())); - } - else - { - // fix for XMLBEANS-105: - // save out the external type reference using the type's signature. - writeString("_XY_" + type.toString()); - } - - return; - - default: - assert(false); - throw new SchemaTypeLoaderException("Cannot write handle for component " + comp, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE); - } - } - - SchemaType.Ref readTypeRef() - { - return (SchemaType.Ref)readHandle(); - } - - void writeType(SchemaType type) - { - writeHandle(type); - } - - Map readQNameRefMap() - { - Map result = new HashMap(); - int size = readShort(); - for (int i = 0; i < size; i++) - { - QName name = readQName(); - SchemaComponent.Ref obj = readHandle(); - result.put(name, obj); - } - return result; - } - - List readQNameRefMapAsList(List names) - { - int size = readShort(); - List result = new ArrayList(size); - for (int i = 0; i < size; i++) - { - QName name = readQName(); - SchemaComponent.Ref obj = readHandle(); - result.add(obj); - names.add(name); - } - return result; - } - - void writeQNameMap(SchemaComponent[] components) - { - writeShort(components.length); - for (int i = 0; i < components.length; i++) - { - writeQName(components[i].getName()); - writeHandle(components[i]); - } - } - - void writeDocumentTypeMap(SchemaType[] doctypes) - { - writeShort(doctypes.length); - for (int i = 0; i < doctypes.length; i++) - { - writeQName(doctypes[i].getDocumentElementName()); - writeHandle(doctypes[i]); - } - } - - void writeAttributeTypeMap(SchemaType[] attrtypes) - { - writeShort(attrtypes.length); - for (int i = 0; i < attrtypes.length; i++) - { - writeQName(attrtypes[i].getAttributeTypeAttributeName()); - writeHandle(attrtypes[i]); - } - } - - SchemaType.Ref[] readTypeRefArray() - { - int size = readShort(); - SchemaType.Ref[] result = new SchemaType.Ref[size]; - for (int i = 0; i < size; i++) - { - result[i] = readTypeRef(); - } - return result; - } - - void writeTypeArray(SchemaType[] array) - { - writeShort(array.length); - for (int i = 0; i < array.length; i++) - { - writeHandle(array[i]); - } - } - - Map readClassnameRefMap() - { - Map result = new HashMap(); - int size = readShort(); - for (int i = 0; i < size; i++) - { - String name = readString(); - SchemaComponent.Ref obj = readHandle(); - result.put(name, obj); - } - return result; - } - - void writeClassnameMap(Map typesByClass) - { - writeShort(typesByClass.size()); - for (Iterator i = typesByClass.keySet().iterator(); i.hasNext(); ) - { - String className = (String)i.next(); - writeString(className); - writeHandle(((SchemaType.Ref)typesByClass.get(className)).get()); - } - } - - Set readNamespaces() - { - Set result = new HashSet(); - int size = readShort(); - for (int i = 0; i < size; i++) - { - String ns = readString(); - result.add(ns); - } - return result; - } - - void writeNamespaces(Set namespaces) - { - writeShort(namespaces.size()); - for (Iterator i = namespaces.iterator(); i.hasNext(); ) - { - String ns = (String)i.next(); - writeString(ns); - } - } - - OutputStream getSaverStream(String name) - { - try - { - return _filer.createBinaryFile(name); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - InputStream getLoaderStream(String resourcename) - { - return _resourceLoader.getResourceAsStream(resourcename); - } - - void checkContainerNotNull(SchemaContainer container, QName name) - { - if (container == null) - { - throw new LinkageError("Loading of resource " + _name + '.' + _handle + - "failed, information from " + _name + ".index.xsb is " + - " out of sync (or conflicting index files found)"); - } - } - - /** - * Finishes loading an element after the header has already been loaded. - */ - public SchemaGlobalElement finishLoadingElement() - { - String handle = null; - try - { - int particleType = readShort(); - if (particleType != SchemaParticle.ELEMENT) - throw new SchemaTypeLoaderException("Wrong particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE); - int particleFlags = readShort(); - BigInteger minOccurs = readBigInteger(); - BigInteger maxOccurs = readBigInteger(); - QNameSet transitionRules = readQNameSet(); - QName name = readQName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - SchemaGlobalElementImpl impl = new SchemaGlobalElementImpl(container); - impl.setParticleType(particleType); - impl.setMinOccurs(minOccurs); - impl.setMaxOccurs(maxOccurs); - impl.setTransitionRules(transitionRules, - (particleFlags & FLAG_PART_SKIPPABLE) != 0); - impl.setNameAndTypeRef(name, readTypeRef()); - impl.setDefault(readString(), (particleFlags & FLAG_PART_FIXED) != 0, null); - if (atLeast(2, 16, 0)) - impl.setDefaultValue(readXmlValueObject()); - impl.setNillable((particleFlags & FLAG_PART_NILLABLE) != 0); - impl.setBlock((particleFlags & FLAG_PART_BLOCKEXT) != 0, - (particleFlags & FLAG_PART_BLOCKREST) != 0, - (particleFlags & FLAG_PART_BLOCKSUBST) != 0); - impl.setWsdlArrayType(readSOAPArrayType()); - impl.setAbstract((particleFlags & FLAG_PART_ABSTRACT) != 0); - impl.setAnnotation(readAnnotation(container)); - impl.setFinal( - (particleFlags & FLAG_PART_FINALEXT) != 0, - (particleFlags & FLAG_PART_FINALREST) != 0); - - if (atLeast(2, 17, 0)) - impl.setSubstitutionGroup((SchemaGlobalElement.Ref)readHandle()); - - int substGroupCount = readShort(); - for (int i = 0; i < substGroupCount; i++) - { - impl.addSubstitutionGroupMember(readQName()); - } - SchemaIdentityConstraint.Ref[] idcs = new SchemaIdentityConstraint.Ref[readShort()]; - - for (int i = 0 ; i < idcs.length ; i++) - idcs[i] = (SchemaIdentityConstraint.Ref)readHandle(); - - impl.setIdentityConstraints(idcs); - impl.setFilename(readString()); - return impl; - } - catch (SchemaTypeLoaderException e) - { - throw e; - } - catch (Exception e) - { - throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); - } - finally - { - readEnd(); - } - } - - public SchemaGlobalAttribute finishLoadingAttribute() - { - try - { - QName name = readQName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - SchemaGlobalAttributeImpl impl = new SchemaGlobalAttributeImpl(container); - loadAttribute(impl, name, container); - impl.setFilename(readString()); - - return impl; - } - catch (SchemaTypeLoaderException e) - { - throw e; - } - catch (Exception e) - { - throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); - } - finally - { - readEnd(); - } - } - - SchemaModelGroup finishLoadingModelGroup() - { - QName name = readQName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - SchemaModelGroupImpl impl = new SchemaModelGroupImpl(container); - - try - { - impl.init(name, readString(), readShort() == 1, - atLeast(2, 22, 0) ? readString() : null, - atLeast(2, 22, 0) ? readString() : null, - atLeast(2, 15, 0) ? readShort() == 1 : false, - GroupDocument.Factory.parse( readString() ).getGroup(), readAnnotation(container), null); - if (atLeast(2, 21, 0)) - impl.setFilename(readString()); - return impl; - } - catch (SchemaTypeLoaderException e) - { - throw e; - } - catch (Exception e) - { - throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); - } - finally - { - readEnd(); - } - } - - SchemaIdentityConstraint finishLoadingIdentityConstraint() - { - try { - QName name = readQName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - SchemaIdentityConstraintImpl impl = new SchemaIdentityConstraintImpl(container); - impl.setName(name); - impl.setConstraintCategory(readShort()); - impl.setSelector(readString()); - impl.setAnnotation(readAnnotation(container)); - - String[] fields = new String[readShort()]; - for (int i = 0 ; i < fields.length ; i++) - fields[i] = readString(); - impl.setFields(fields); - - if (impl.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) - impl.setReferencedKey((SchemaIdentityConstraint.Ref)readHandle()); - - int mapCount = readShort(); - Map nsMappings = new HashMap(); - for (int i = 0 ; i < mapCount ; i++) - { - String prefix = readString(); - String uri = readString(); - nsMappings.put(prefix, uri); - } - impl.setNSMap(nsMappings); - - if (atLeast(2, 21, 0)) - impl.setFilename(readString()); - - return impl; - } - catch (SchemaTypeLoaderException e) - { - throw e; - } - catch (Exception e) - { - throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); - } - finally - { - readEnd(); - } - } - - SchemaAttributeGroup finishLoadingAttributeGroup() - { - QName name = readQName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - SchemaAttributeGroupImpl impl = new SchemaAttributeGroupImpl(container); - - try - { - impl.init( name, readString(), readShort() == 1, - atLeast(2, 22, 0) ? readString() : null, - atLeast(2, 15, 0) ? readShort() == 1 : false, - AttributeGroupDocument.Factory.parse( readString() ).getAttributeGroup(), - readAnnotation(container), null); - if (atLeast(2, 21, 0)) - impl.setFilename(readString()); - return impl; - } - catch (SchemaTypeLoaderException e) - { - throw e; - } - catch (Exception e) - { - throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); - } - finally - { - readEnd(); - } - } - - public SchemaType finishLoadingType() - { - try - { - SchemaContainer cNonNull = getContainerNonNull(""); //HACKHACK - SchemaTypeImpl impl = new SchemaTypeImpl(cNonNull, true); - impl.setName(readQName()); - impl.setOuterSchemaTypeRef(readTypeRef()); - impl.setBaseDepth(readShort()); - impl.setBaseTypeRef(readTypeRef()); - impl.setDerivationType(readShort()); - impl.setAnnotation(readAnnotation(null)); - - switch (readShort()) - { - case FIELD_GLOBAL: - impl.setContainerFieldRef(readHandle()); - break; - case FIELD_LOCALATTR: - impl.setContainerFieldIndex((short)1, readShort()); - break; - case FIELD_LOCALELT: - impl.setContainerFieldIndex((short)2, readShort()); - break; - } - // TODO (radup) find the right solution here - String jn = readString(); - impl.setFullJavaName(jn == null ? "" : jn); - jn = readString(); - impl.setFullJavaImplName(jn == null? "" : jn); - - impl.setAnonymousTypeRefs(readTypeRefArray()); - - impl.setAnonymousUnionMemberOrdinal(readShort()); - - int flags; - flags = readInt(); - - - boolean isComplexType = ((flags & FLAG_SIMPLE_TYPE) == 0); - impl.setCompiled((flags & FLAG_COMPILED) != 0); - impl.setDocumentType((flags & FLAG_DOCUMENT_TYPE) != 0); - impl.setAttributeType((flags & FLAG_ATTRIBUTE_TYPE) != 0); - impl.setSimpleType(!isComplexType); - - int complexVariety = SchemaType.NOT_COMPLEX_TYPE; - if (isComplexType) - { - impl.setAbstractFinal((flags & FLAG_ABSTRACT) != 0, - (flags & FLAG_FINAL_EXT) != 0, - (flags & FLAG_FINAL_REST) != 0, - (flags & FLAG_FINAL_LIST) != 0, - (flags & FLAG_FINAL_UNION) != 0); - impl.setBlock((flags & FLAG_BLOCK_EXT) != 0, - (flags & FLAG_BLOCK_REST) != 0); - - impl.setOrderSensitive((flags & FLAG_ORDER_SENSITIVE) != 0); - complexVariety = readShort(); - impl.setComplexTypeVariety(complexVariety); - - if (atLeast(2, 23, 0)) - impl.setContentBasedOnTypeRef(readTypeRef()); - - // Attribute Model Table - SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); - - int attrCount = readShort(); - for (int i = 0; i < attrCount; i++) - attrModel.addAttribute(readAttributeData()); - - attrModel.setWildcardSet(readQNameSet()); - attrModel.setWildcardProcess(readShort()); - - // Attribute Property Table - Map attrProperties = new LinkedHashMap(); - int attrPropCount = readShort(); - for (int i = 0; i < attrPropCount; i++) - { - SchemaProperty prop = readPropertyData(); - if (!prop.isAttribute()) - throw new SchemaTypeLoaderException("Attribute property " + i + " is not an attribute", _name, _handle, SchemaTypeLoaderException.WRONG_PROPERTY_TYPE); - attrProperties.put(prop.getName(), prop); - } - - SchemaParticle contentModel = null; - Map elemProperties = null; - int isAll = 0; - - if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT) - { - // Content Model Tree - isAll = readShort(); - SchemaParticle[] parts = readParticleArray(); - if (parts.length == 1) - contentModel = parts[0]; - else if (parts.length == 0) - contentModel = null; - else - throw new SchemaTypeLoaderException("Content model not well-formed", _name, _handle, SchemaTypeLoaderException.MALFORMED_CONTENT_MODEL); - - // Element Property Table - - elemProperties = new LinkedHashMap(); - int elemPropCount = readShort(); - for (int i = 0; i < elemPropCount; i++) - { - SchemaProperty prop = readPropertyData(); - if (prop.isAttribute()) - throw new SchemaTypeLoaderException("Element property " + i + " is not an element", _name, _handle, SchemaTypeLoaderException.WRONG_PROPERTY_TYPE); - elemProperties.put(prop.getName(), prop); - } - } - - impl.setContentModel(contentModel, attrModel, elemProperties, attrProperties, isAll == 1); - StscComplexTypeResolver.WildcardResult wcElt = StscComplexTypeResolver.summarizeEltWildcards(contentModel); - StscComplexTypeResolver.WildcardResult wcAttr = StscComplexTypeResolver.summarizeAttrWildcards(attrModel); - impl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); - } - - if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT) - { - int simpleVariety = readShort(); - impl.setSimpleTypeVariety(simpleVariety); - - boolean isStringEnum = ((flags & FLAG_STRINGENUM) != 0); - - impl.setOrdered((flags & FLAG_ORDERED) != 0 ? SchemaType.UNORDERED : ((flags & FLAG_TOTAL_ORDER) != 0 ? SchemaType.TOTAL_ORDER : SchemaType.PARTIAL_ORDER)); - impl.setBounded((flags & FLAG_BOUNDED) != 0); - impl.setFinite((flags & FLAG_FINITE) != 0); - impl.setNumeric((flags & FLAG_NUMERIC) != 0); - impl.setUnionOfLists((flags & FLAG_UNION_OF_LISTS) != 0); - impl.setSimpleFinal((flags & FLAG_FINAL_REST) != 0, - (flags & FLAG_FINAL_LIST) != 0, - (flags & FLAG_FINAL_UNION) != 0); - - XmlValueRef[] facets = new XmlValueRef[SchemaType.LAST_FACET + 1]; - boolean[] fixedFacets = new boolean[SchemaType.LAST_FACET + 1]; - int facetCount = readShort(); - for (int i = 0; i < facetCount; i++) - { - int facetCode = readShort(); - facets[facetCode] = readXmlValueObject(); - fixedFacets[facetCode] = (readShort() == 1); - } - impl.setBasicFacets(facets, fixedFacets); - - impl.setWhiteSpaceRule(readShort()); - - impl.setPatternFacet((flags & FLAG_HAS_PATTERN) != 0); - - int patternCount = readShort(); - org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = new org.apache.xmlbeans.impl.regex.RegularExpression[patternCount]; - for (int i = 0; i < patternCount; i++) - { - patterns[i] = new org.apache.xmlbeans.impl.regex.RegularExpression(readString(), "X"); - } - impl.setPatterns(patterns); - - int enumCount = readShort(); - XmlValueRef[] enumValues = new XmlValueRef[enumCount]; - for (int i = 0; i < enumCount; i++) - { - enumValues[i] = readXmlValueObject(); - } - impl.setEnumerationValues(enumCount == 0 ? null : enumValues); - - impl.setBaseEnumTypeRef(readTypeRef()); - if (isStringEnum) - { - int seCount = readShort(); - SchemaStringEnumEntry[] entries = new SchemaStringEnumEntry[seCount]; - for (int i = 0; i < seCount; i++) - { - entries[i] = new SchemaStringEnumEntryImpl(readString(), readShort(), readString()); - } - impl.setStringEnumEntries(entries); - } - - switch (simpleVariety) - { - case SchemaType.ATOMIC: - impl.setPrimitiveTypeRef(readTypeRef()); - impl.setDecimalSize(readInt()); - break; - - case SchemaType.LIST: - impl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - impl.setListItemTypeRef(readTypeRef()); - break; - - case SchemaType.UNION: - impl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - impl.setUnionMemberTypeRefs(readTypeRefArray()); - break; - - default: - throw new SchemaTypeLoaderException("Simple type does not have a recognized variety", _name, _handle, SchemaTypeLoaderException.WRONG_SIMPLE_VARIETY); - } - } - - impl.setFilename(readString()); - // Set the container for global, attribute or document types - if (impl.getName() != null) - { - SchemaContainer container = getContainer(impl.getName().getNamespaceURI()); - checkContainerNotNull(container, impl.getName()); - impl.setContainer(container); - } - else if (impl.isDocumentType()) - { - QName name = impl.getDocumentElementName(); - if (name != null) - { - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - impl.setContainer(container); - } - } - else if (impl.isAttributeType()) - { - QName name = impl.getAttributeTypeAttributeName(); - if (name != null) - { - SchemaContainer container = getContainer(name.getNamespaceURI()); - checkContainerNotNull(container, name); - impl.setContainer(container); - } - } - - return impl; - } - catch (SchemaTypeLoaderException e) - { - throw e; - } - catch (Exception e) - { - throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e); - } - finally - { - readEnd(); - } - } - - void writeTypeData(SchemaType type) - { - writeQName(type.getName()); - writeType(type.getOuterType()); - writeShort(((SchemaTypeImpl)type).getBaseDepth()); - writeType(type.getBaseType()); - writeShort(type.getDerivationType()); - writeAnnotation(type.getAnnotation()); - if (type.getContainerField() == null) - { - writeShort(FIELD_NONE); - } - else if (type.getOuterType().isAttributeType() || type.getOuterType().isDocumentType()) - { - writeShort(FIELD_GLOBAL); - writeHandle((SchemaComponent)type.getContainerField()); - } - else if (type.getContainerField().isAttribute()) - { - writeShort(FIELD_LOCALATTR); - writeShort(((SchemaTypeImpl)type.getOuterType()).getIndexForLocalAttribute((SchemaLocalAttribute)type.getContainerField())); - } - else - { - writeShort(FIELD_LOCALELT); - writeShort(((SchemaTypeImpl)type.getOuterType()).getIndexForLocalElement((SchemaLocalElement)type.getContainerField())); - } - writeString(type.getFullJavaName()); - writeString(type.getFullJavaImplName()); - writeTypeArray(type.getAnonymousTypes()); - writeShort(type.getAnonymousUnionMemberOrdinal()); - - int flags = 0; - if (type.isSimpleType()) - flags |= FLAG_SIMPLE_TYPE; - if (type.isDocumentType()) - flags |= FLAG_DOCUMENT_TYPE; - if (type.isAttributeType()) - flags |= FLAG_ATTRIBUTE_TYPE; - if (type.ordered() != SchemaType.UNORDERED) - flags |= FLAG_ORDERED; - if (type.ordered() == SchemaType.TOTAL_ORDER) - flags |= FLAG_TOTAL_ORDER; - if (type.isBounded()) - flags |= FLAG_BOUNDED; - if (type.isFinite()) - flags |= FLAG_FINITE; - if (type.isNumeric()) - flags |= FLAG_NUMERIC; - if (type.hasStringEnumValues()) - flags |= FLAG_STRINGENUM; - if (((SchemaTypeImpl)type).isUnionOfLists()) - flags |= FLAG_UNION_OF_LISTS; - if (type.hasPatternFacet()) - flags |= FLAG_HAS_PATTERN; - if (type.isOrderSensitive()) - flags |= FLAG_ORDER_SENSITIVE; - - if (type.blockExtension()) - flags |= FLAG_BLOCK_EXT; - if (type.blockRestriction()) - flags |= FLAG_BLOCK_REST; - if (type.finalExtension()) - flags |= FLAG_FINAL_EXT; - if (type.finalRestriction()) - flags |= FLAG_FINAL_EXT; - if (type.finalList()) - flags |= FLAG_FINAL_LIST; - if (type.finalUnion()) - flags |= FLAG_FINAL_UNION; - if (type.isAbstract()) - flags |= FLAG_ABSTRACT; - - writeInt(flags); - - if (!type.isSimpleType()) - { - writeShort(type.getContentType()); - - writeType(type.getContentBasedOnType()); - - // Attribute Model Table - SchemaAttributeModel attrModel = type.getAttributeModel(); - SchemaLocalAttribute[] attrs = attrModel.getAttributes(); - - writeShort(attrs.length); - for (int i = 0; i < attrs.length; i++) - writeAttributeData(attrs[i]); - - writeQNameSet(attrModel.getWildcardSet()); - writeShort(attrModel.getWildcardProcess()); - - // Attribute Property Table - SchemaProperty[] attrProperties = type.getAttributeProperties(); - writeShort(attrProperties.length); - for (int i = 0; i < attrProperties.length; i++) - writePropertyData(attrProperties[i]); - - if (type.getContentType() == SchemaType.ELEMENT_CONTENT || - type.getContentType() == SchemaType.MIXED_CONTENT) - { - // Content Model Tree - writeShort(type.hasAllContent() ? 1 : 0); - SchemaParticle[] parts; - if (type.getContentModel() != null) - parts = new SchemaParticle[] { type.getContentModel() }; - else - parts = new SchemaParticle[0]; - - writeParticleArray(parts); - - // Element Property Table - SchemaProperty[] eltProperties = type.getElementProperties(); - writeShort(eltProperties.length); - for (int i = 0; i < eltProperties.length; i++) - writePropertyData(eltProperties[i]); - } - } - - if (type.isSimpleType() || type.getContentType() == SchemaType.SIMPLE_CONTENT) - { - writeShort(type.getSimpleVariety()); - - int facetCount = 0; - for (int i = 0; i <= SchemaType.LAST_FACET; i++) - if (type.getFacet(i) != null) - facetCount++; - writeShort(facetCount); - for (int i = 0; i <= SchemaType.LAST_FACET; i++) - { - XmlAnySimpleType facet = type.getFacet(i); - if (facet != null) - { - writeShort(i); - writeXmlValueObject(facet); - writeShort(type.isFacetFixed(i) ? 1 : 0); - } - } - - writeShort(type.getWhiteSpaceRule()); - - org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = ((SchemaTypeImpl)type).getPatternExpressions(); - writeShort(patterns.length); - for (int i = 0; i < patterns.length; i++) - writeString(patterns[i].getPattern()); - - XmlAnySimpleType[] enumValues = type.getEnumerationValues(); - if (enumValues == null) - writeShort(0); - else - { - writeShort(enumValues.length); - for (int i = 0; i < enumValues.length; i++) - writeXmlValueObject(enumValues[i]); - } - - // new for version 2.3 - writeType(type.getBaseEnumType()); - if (type.hasStringEnumValues()) - { - SchemaStringEnumEntry[] entries = type.getStringEnumEntries(); - writeShort(entries.length); - for (int i = 0; i < entries.length; i++) - { - writeString(entries[i].getString()); - writeShort(entries[i].getIntValue()); - writeString(entries[i].getEnumName()); - } - } - - switch (type.getSimpleVariety()) - { - case SchemaType.ATOMIC: - writeType(type.getPrimitiveType()); - writeInt(type.getDecimalSize()); - break; - - case SchemaType.LIST: - writeType(type.getListItemType()); - break; - - case SchemaType.UNION: - writeTypeArray(type.getUnionMemberTypes()); - break; - } - } - - writeString(type.getSourceName()); - } - - void readExtensionsList() - { - int count = readShort(); - assert count == 0; - - for (int i = 0; i < count; i++) - { - readString(); - readString(); - readString(); - } - } - - SchemaLocalAttribute readAttributeData() - { - SchemaLocalAttributeImpl result = new SchemaLocalAttributeImpl(); - loadAttribute(result, readQName(), null); - return result; - } - - - void loadAttribute(SchemaLocalAttributeImpl result, QName name, SchemaContainer container) - { - // name, type, use, deftext, defval, fixed, soaparraytype, annotation - result.init(name, readTypeRef(), readShort(), readString(), null, atLeast(2, 16, 0) ? readXmlValueObject() : null, readShort() == 1, readSOAPArrayType(), readAnnotation(container), null); - } - - void writeAttributeData(SchemaLocalAttribute attr) - { - writeQName(attr.getName()); - writeType(attr.getType()); - writeShort(attr.getUse()); - writeString(attr.getDefaultText()); - writeXmlValueObject(attr.getDefaultValue()); - writeShort(attr.isFixed() ? 1 : 0); - writeSOAPArrayType(((SchemaWSDLArrayType)attr).getWSDLArrayType()); - writeAnnotation(attr.getAnnotation()); - } - - void writeIdConstraintData(SchemaIdentityConstraint idc) - { - writeQName(idc.getName()); - writeShort(idc.getConstraintCategory()); - writeString(idc.getSelector()); - writeAnnotation(idc.getAnnotation()); - - String[] fields = idc.getFields(); - writeShort(fields.length); - for (int i = 0 ; i < fields.length ; i++) - writeString(fields[i]); - - - if (idc.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) - writeHandle(idc.getReferencedKey()); - - Set mappings = idc.getNSMap().entrySet(); - writeShort(mappings.size()); - for (Iterator it = mappings.iterator() ; it.hasNext() ; ) { - Map.Entry e = (Map.Entry)it.next(); - String prefix = (String)e.getKey(); - String uri = (String)e.getValue(); - - writeString(prefix); - writeString(uri); - } - writeString(idc.getSourceName()); - } - - SchemaParticle[] readParticleArray() - { - SchemaParticle[] result = new SchemaParticle[readShort()]; - for (int i = 0; i < result.length; i++) - result[i] = readParticleData(); - return result; - } - - void writeParticleArray(SchemaParticle[] spa) - { - writeShort(spa.length); - for (int i = 0; i < spa.length; i++) - writeParticleData(spa[i]); - } - - SchemaParticle readParticleData() - { - int particleType = readShort(); - SchemaParticleImpl result; - if (particleType != SchemaParticle.ELEMENT) - result = new SchemaParticleImpl(); - else - result = new SchemaLocalElementImpl(); - loadParticle(result, particleType); - return result; - } - - void loadParticle(SchemaParticleImpl result, int particleType) - { - int particleFlags = readShort(); - - result.setParticleType(particleType); - result.setMinOccurs(readBigInteger()); - result.setMaxOccurs(readBigInteger()); - - result.setTransitionRules(readQNameSet(), - (particleFlags & FLAG_PART_SKIPPABLE) != 0); - - switch (particleType) - { - case SchemaParticle.WILDCARD: - result.setWildcardSet(readQNameSet()); - result.setWildcardProcess(readShort()); - break; - - case SchemaParticle.ELEMENT: - SchemaLocalElementImpl lresult = (SchemaLocalElementImpl)result; - lresult.setNameAndTypeRef(readQName(), readTypeRef()); - lresult.setDefault(readString(), (particleFlags & FLAG_PART_FIXED) != 0, null); - if (atLeast(2, 16, 0)) - lresult.setDefaultValue(readXmlValueObject()); - lresult.setNillable((particleFlags & FLAG_PART_NILLABLE) != 0); - lresult.setBlock((particleFlags & FLAG_PART_BLOCKEXT) != 0, - (particleFlags & FLAG_PART_BLOCKREST) != 0, - (particleFlags & FLAG_PART_BLOCKSUBST) != 0); - lresult.setWsdlArrayType(readSOAPArrayType()); - lresult.setAbstract((particleFlags & FLAG_PART_ABSTRACT) != 0); - lresult.setAnnotation(readAnnotation(null)); - - SchemaIdentityConstraint.Ref[] idcs = new SchemaIdentityConstraint.Ref[readShort()]; - - for (int i = 0 ; i < idcs.length ; i++) - idcs[i] = (SchemaIdentityConstraint.Ref)readHandle(); - - lresult.setIdentityConstraints(idcs); - - break; - - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - case SchemaParticle.CHOICE: - result.setParticleChildren(readParticleArray()); - break; - - default: - throw new SchemaTypeLoaderException("Unrecognized particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE); - } - } - - void writeParticleData(SchemaParticle part) - { - writeShort(part.getParticleType()); - short flags = 0; - if (part.isSkippable()) - flags |= FLAG_PART_SKIPPABLE; - if (part.getParticleType() == SchemaParticle.ELEMENT) - { - SchemaLocalElement lpart = (SchemaLocalElement)part; - if (lpart.isFixed()) - flags |= FLAG_PART_FIXED; - if (lpart.isNillable()) - flags |= FLAG_PART_NILLABLE; - if (lpart.blockExtension()) - flags |= FLAG_PART_BLOCKEXT; - if (lpart.blockRestriction()) - flags |= FLAG_PART_BLOCKREST; - if (lpart.blockSubstitution()) - flags |= FLAG_PART_BLOCKSUBST; - if (lpart.isAbstract()) - flags |= FLAG_PART_ABSTRACT; - - if (lpart instanceof SchemaGlobalElement) - { - SchemaGlobalElement gpart = (SchemaGlobalElement)lpart; - if (gpart.finalExtension()) - flags |= FLAG_PART_FINALEXT; - if (gpart.finalRestriction()) - flags |= FLAG_PART_FINALREST; - } - } - writeShort(flags); - writeBigInteger(part.getMinOccurs()); - writeBigInteger(part.getMaxOccurs()); - writeQNameSet(part.acceptedStartNames()); - - switch (part.getParticleType()) - { - case SchemaParticle.WILDCARD: - writeQNameSet(part.getWildcardSet()); - writeShort(part.getWildcardProcess()); - break; - - case SchemaParticle.ELEMENT: - SchemaLocalElement lpart = (SchemaLocalElement)part; - writeQName(lpart.getName()); - writeType(lpart.getType()); - writeString(lpart.getDefaultText()); - writeXmlValueObject(lpart.getDefaultValue()); - writeSOAPArrayType(((SchemaWSDLArrayType)lpart).getWSDLArrayType()); - writeAnnotation(lpart.getAnnotation()); - if (lpart instanceof SchemaGlobalElement) - { - SchemaGlobalElement gpart = (SchemaGlobalElement)lpart; - - writeHandle(gpart.substitutionGroup()); - - QName[] substGroupMembers = gpart.substitutionGroupMembers(); - writeShort(substGroupMembers.length); - for (int i = 0; i < substGroupMembers.length; i++) - writeQName(substGroupMembers[i]); - } - - SchemaIdentityConstraint[] idcs = lpart.getIdentityConstraints(); - - writeShort(idcs.length); - for (int i = 0 ; i < idcs.length ; i++) - writeHandle(idcs[i]); - - break; - - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - case SchemaParticle.CHOICE: - writeParticleArray(part.getParticleChildren()); - break; - - default: - throw new SchemaTypeLoaderException("Unrecognized particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE); - } - } - - SchemaProperty readPropertyData() - { - SchemaPropertyImpl prop = new SchemaPropertyImpl(); - prop.setName(readQName()); - prop.setTypeRef(readTypeRef()); - int propflags = readShort(); - prop.setAttribute((propflags & FLAG_PROP_ISATTR) != 0); - prop.setContainerTypeRef(readTypeRef()); - prop.setMinOccurs(readBigInteger()); - prop.setMaxOccurs(readBigInteger()); - prop.setNillable(readShort()); - prop.setDefault(readShort()); - prop.setFixed(readShort()); - prop.setDefaultText(readString()); - - prop.setJavaPropertyName(readString()); - prop.setJavaTypeCode(readShort()); - prop.setExtendsJava(readTypeRef(), - (propflags & FLAG_PROP_JAVASINGLETON) != 0, - (propflags & FLAG_PROP_JAVAOPTIONAL) != 0, - (propflags & FLAG_PROP_JAVAARRAY) != 0); - if (atMost(2, 19, 0)) - prop.setJavaSetterDelimiter(readQNameSet()); - if (atLeast(2, 16, 0)) - prop.setDefaultValue(readXmlValueObject()); - - if (!prop.isAttribute() && atLeast(2, 17, 0)) - { - int size = readShort(); - LinkedHashSet qnames = new LinkedHashSet(size); - for (int i = 0 ; i < size ; i++) - qnames.add(readQName()); - prop.setAcceptedNames(qnames); - } - prop.setImmutable(); - return prop; - } - - void writePropertyData(SchemaProperty prop) - { - writeQName(prop.getName()); - writeType(prop.getType()); - writeShort((prop.isAttribute() ? FLAG_PROP_ISATTR : 0) | - (prop.extendsJavaSingleton() ? FLAG_PROP_JAVASINGLETON : 0) | - (prop.extendsJavaOption() ? FLAG_PROP_JAVAOPTIONAL : 0) | - (prop.extendsJavaArray() ? FLAG_PROP_JAVAARRAY : 0)); - writeType(prop.getContainerType()); - writeBigInteger(prop.getMinOccurs()); - writeBigInteger(prop.getMaxOccurs()); - writeShort(prop.hasNillable()); - writeShort(prop.hasDefault()); - writeShort(prop.hasFixed()); - writeString(prop.getDefaultText()); - - writeString(prop.getJavaPropertyName()); - writeShort(prop.getJavaTypeCode()); - writeType(prop.javaBasedOnType()); - writeXmlValueObject(prop.getDefaultValue()); - - if (! prop.isAttribute()) - { - QName[] names = prop.acceptedNames(); - writeShort(names.length); - for (int i = 0 ; i < names.length ; i++) - writeQName(names[i]); - } - } - - void writeModelGroupData(SchemaModelGroup grp) - { - SchemaModelGroupImpl impl = (SchemaModelGroupImpl)grp; - writeQName(impl.getName()); - writeString(impl.getTargetNamespace()); - writeShort(impl.getChameleonNamespace() != null ? 1 : 0); - writeString(impl.getElemFormDefault()); // new for version 2.22 - writeString(impl.getAttFormDefault()); // new for version 2.22 - writeShort(impl.isRedefinition() ? 1 : 0); // new for version 2.15 - writeString(impl.getParseObject().xmlText(new XmlOptions().setSaveOuter())); - writeAnnotation(impl.getAnnotation()); - writeString(impl.getSourceName()); - } - - void writeAttributeGroupData(SchemaAttributeGroup grp) - { - SchemaAttributeGroupImpl impl = (SchemaAttributeGroupImpl)grp; - writeQName(impl.getName()); - writeString(impl.getTargetNamespace()); - writeShort(impl.getChameleonNamespace() != null ? 1 : 0); - writeString(impl.getFormDefault()); // new for version 2.22 - writeShort(impl.isRedefinition() ? 1 : 0); // new for version 2.15 - writeString(impl.getParseObject().xmlText(new XmlOptions().setSaveOuter())); - writeAnnotation(impl.getAnnotation()); - writeString(impl.getSourceName()); - } - - XmlValueRef readXmlValueObject() - { - SchemaType.Ref typeref = readTypeRef(); - if (typeref == null) - return null; - int btc = readShort(); - switch (btc) - { - default: - assert(false); - case 0: - return new XmlValueRef(typeref, null); - case 0xFFFF: - { - int size = readShort(); - List values = new ArrayList(); - writeShort(values.size()); - for (int i = 0; i < size; i++) - { - values.add(readXmlValueObject()); - } - return new XmlValueRef(typeref, values); - } - - - case SchemaType.BTC_ANY_SIMPLE: - case SchemaType.BTC_ANY_URI: - case SchemaType.BTC_STRING: - case SchemaType.BTC_DURATION: - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - case SchemaType.BTC_DECIMAL: - case SchemaType.BTC_BOOLEAN: - return new XmlValueRef(typeref, readString()); - - case SchemaType.BTC_BASE_64_BINARY: - case SchemaType.BTC_HEX_BINARY: - return new XmlValueRef(typeref, readByteArray()); - - case SchemaType.BTC_QNAME: - case SchemaType.BTC_NOTATION: - return new XmlValueRef(typeref, readQName()); - - case SchemaType.BTC_FLOAT: - case SchemaType.BTC_DOUBLE: - return new XmlValueRef(typeref, new Double(readDouble())); - } - } - - void writeXmlValueObject(XmlAnySimpleType value) - { - SchemaType type = value == null ? null : value.schemaType(); - writeType(type); - if (type == null) - return; - - SchemaType iType = ((SimpleValue)value).instanceType(); - if (iType == null) - { - writeShort(0); - } - else if (iType.getSimpleVariety() == SchemaType.LIST) - { - writeShort(-1); - List values = ((XmlObjectBase)value).xgetListValue(); - writeShort(values.size()); - for (Iterator i = values.iterator(); i.hasNext(); ) - { - writeXmlValueObject((XmlAnySimpleType)i.next()); - } - } - else - { - int btc = iType.getPrimitiveType().getBuiltinTypeCode(); - writeShort(btc); - switch (btc) - { - case SchemaType.BTC_ANY_SIMPLE: - case SchemaType.BTC_ANY_URI: - case SchemaType.BTC_STRING: - case SchemaType.BTC_DURATION: - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - case SchemaType.BTC_DECIMAL: - case SchemaType.BTC_BOOLEAN: - writeString(value.getStringValue()); - break; - - case SchemaType.BTC_BASE_64_BINARY: - case SchemaType.BTC_HEX_BINARY: - writeByteArray(((SimpleValue)value).getByteArrayValue()); - break; - - case SchemaType.BTC_QNAME: - case SchemaType.BTC_NOTATION: - writeQName(((SimpleValue)value).getQNameValue()); - break; - - case SchemaType.BTC_FLOAT: - writeDouble(((SimpleValue)value).getFloatValue()); - break; - - case SchemaType.BTC_DOUBLE: - writeDouble(((SimpleValue)value).getDoubleValue()); - break; - } - } - } - - double readDouble() - { - try - { - return _input.readDouble(); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - void writeDouble(double d) - { - if (_output != null) - { - try - { - _output.writeDouble(d); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - } - - QNameSet readQNameSet() - { - int flag = readShort(); - - Set uriSet = new HashSet(); - int uriCount = readShort(); - for (int i = 0; i < uriCount; i++) - uriSet.add(readString()); - - Set qnameSet1 = new HashSet(); - int qncount1 = readShort(); - for (int i = 0; i < qncount1; i++) - qnameSet1.add(readQName()); - - Set qnameSet2 = new HashSet(); - int qncount2 = readShort(); - for (int i = 0; i < qncount2; i++) - qnameSet2.add(readQName()); - - if (flag == 1) - return QNameSet.forSets(uriSet, null, qnameSet1, qnameSet2); - else - return QNameSet.forSets(null, uriSet, qnameSet2, qnameSet1); - } - - void writeQNameSet(QNameSet set) - { - boolean invert = (set.excludedURIs() != null); - writeShort(invert ? 1 : 0); - - Set uriSet = invert ? set.excludedURIs() : set.includedURIs(); - writeShort(uriSet.size()); - for (Iterator i = uriSet.iterator(); i.hasNext(); ) - writeString((String)i.next()); - - Set qnameSet1 = invert ? set.excludedQNamesInIncludedURIs() : set.includedQNamesInExcludedURIs(); - writeShort(qnameSet1.size()); - for (Iterator i = qnameSet1.iterator(); i.hasNext(); ) - writeQName((QName)i.next()); - - Set qnameSet2 = invert ? set.includedQNamesInExcludedURIs() : set.excludedQNamesInIncludedURIs(); - writeShort(qnameSet2.size()); - for (Iterator i = qnameSet2.iterator(); i.hasNext(); ) - writeQName((QName)i.next()); - } - - byte[] readByteArray() - { - try - { - int len = _input.readShort(); - byte[] result = new byte[len]; - _input.readFully(result); - return result; - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - void writeByteArray(byte[] ba) - { - try - { - writeShort(ba.length); - if (_output != null) - _output.write(ba); - } - catch (IOException e) - { - throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION); - } - } - - BigInteger readBigInteger() - { - byte[] result = readByteArray(); - if (result.length == 0) - return null; - if (result.length == 1 && result[0] == 0) - return BigInteger.ZERO; - if (result.length == 1 && result[0] == 1) - return BigInteger.ONE; - return new BigInteger(result); - } - - void writeBigInteger(BigInteger bi) - { - if (bi == null) - { - writeShort(0); - } - else if (bi.signum() == 0) - { - writeByteArray(SINGLE_ZERO_BYTE); - } - else - { - writeByteArray(bi.toByteArray()); - } - } - - } - - static final byte[] SINGLE_ZERO_BYTE = new byte[] { (byte)0 }; - - public SchemaType typeForHandle(String handle) - { - synchronized (_resolvedHandles) - { - return (SchemaType)_resolvedHandles.get(handle); - } - } - - public SchemaType typeForClassname(String classname) - { - SchemaType.Ref ref = (SchemaType.Ref)_typeRefsByClassname.get(classname); - return (ref != null) ? ref.get() : null; - } - - public SchemaComponent resolveHandle(String handle) - { - SchemaComponent result; - - synchronized (_resolvedHandles) - { - result = (SchemaComponent)_resolvedHandles.get(handle); - } - if (result == null) - { - XsbReader reader = new XsbReader(handle, 0xFFFF); - int filetype = reader.getActualFiletype(); - switch (filetype) - { - case FILETYPE_SCHEMATYPE: - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving type for handle " + handle, 0); - result = reader.finishLoadingType(); - break; - case FILETYPE_SCHEMAELEMENT: - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving element for handle " + handle, 0); - result = reader.finishLoadingElement(); - break; - case FILETYPE_SCHEMAATTRIBUTE: - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving attribute for handle " + handle, 0); - result = reader.finishLoadingAttribute(); - break; - case FILETYPE_SCHEMAMODELGROUP: - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving model group for handle " + handle, 0); - result = reader.finishLoadingModelGroup(); - break; - case FILETYPE_SCHEMAATTRIBUTEGROUP: - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving attribute group for handle " + handle, 0); - result = reader.finishLoadingAttributeGroup(); - break; - case FILETYPE_SCHEMAIDENTITYCONSTRAINT: - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving id constraint for handle " + handle, 0); - result = reader.finishLoadingIdentityConstraint(); - break; - default: - throw new IllegalStateException("Illegal handle type"); - } - - synchronized (_resolvedHandles) - { - if (!_resolvedHandles.containsKey(handle)) - _resolvedHandles.put(handle, result); - else - result = (SchemaComponent)_resolvedHandles.get(handle); - } - } - return result; - } - - private final Map _resolvedHandles = new HashMap(); - private boolean _allNonGroupHandlesResolved = false; - - public void resolve() - { - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolve called type system " + _name, 0); - if (_allNonGroupHandlesResolved) - return; - - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving all handles for type system " + _name, 1); - - List refs = new ArrayList(); - refs.addAll(_globalElements.values()); - refs.addAll(_globalAttributes.values()); - refs.addAll(_globalTypes.values()); - refs.addAll(_documentTypes.values()); - refs.addAll(_attributeTypes.values()); - refs.addAll(_identityConstraints.values()); - - for (Iterator i = refs.iterator(); i.hasNext(); ) - { - SchemaComponent.Ref ref = (SchemaComponent.Ref)i.next(); - ref.getComponent(); // Forces ref to be resolved - } - - XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finished resolving type system " + _name, -1); - _allNonGroupHandlesResolved = true; - } - - - public boolean isNamespaceDefined(String namespace) - { - return _namespaces.contains(namespace); - } - - public SchemaType.Ref findTypeRef(QName name) - { - return (SchemaType.Ref)_globalTypes.get(name); - } - - public SchemaType.Ref findDocumentTypeRef(QName name) - { - return (SchemaType.Ref)_documentTypes.get(name); - } - - public SchemaType.Ref findAttributeTypeRef(QName name) - { - return (SchemaType.Ref)_attributeTypes.get(name); - } - - public SchemaGlobalElement.Ref findElementRef(QName name) - { - return (SchemaGlobalElement.Ref)_globalElements.get(name); - } - - public SchemaGlobalAttribute.Ref findAttributeRef(QName name) - { - return (SchemaGlobalAttribute.Ref)_globalAttributes.get(name); - } - - public SchemaModelGroup.Ref findModelGroupRef(QName name) - { - return (SchemaModelGroup.Ref)_modelGroups.get(name); - } - - public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) - { - return (SchemaAttributeGroup.Ref)_attributeGroups.get(name); - } - - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) - { - return (SchemaIdentityConstraint.Ref)_identityConstraints.get(name); - } - - public SchemaType[] globalTypes() - { - if (_globalTypes.isEmpty()) - return EMPTY_ST_ARRAY; - - SchemaType[] result = new SchemaType[_globalTypes.size()]; - int j = 0; - for (Iterator i = _globalTypes.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaType.Ref)i.next()).get(); - return result; - } - - public SchemaType[] redefinedGlobalTypes() - { - if (_redefinedGlobalTypes == null || _redefinedGlobalTypes.isEmpty()) - return EMPTY_ST_ARRAY; - - SchemaType[] result = new SchemaType[_redefinedGlobalTypes.size()]; - int j = 0; - for (Iterator i = _redefinedGlobalTypes.iterator(); i.hasNext(); j++) - result[j] = ((SchemaType.Ref)i.next()).get(); - return result; - } - - public InputStream getSourceAsStream(String sourceName) - { - if (!sourceName.startsWith("/")) - sourceName = "/" + sourceName; - - return _resourceLoader.getResourceAsStream("schema" + METADATA_PACKAGE_GEN + "/src" + sourceName); - } - - SchemaContainer[] containers() - { - SchemaContainer[] result = new SchemaContainer[_containers.size()]; - int j = 0; - for (Iterator i = _containers.values().iterator(); i.hasNext(); j++) - result[j] = (SchemaContainer) i.next(); - return result; - } - - public SchemaType[] documentTypes() - { - if (_documentTypes.isEmpty()) - return EMPTY_ST_ARRAY; - - SchemaType[] result = new SchemaType[_documentTypes.size()]; - int j = 0; - for (Iterator i = _documentTypes.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaType.Ref)i.next()).get(); - return result; - } - - public SchemaType[] attributeTypes() - { - if (_attributeTypes.isEmpty()) - return EMPTY_ST_ARRAY; - - SchemaType[] result = new SchemaType[_attributeTypes.size()]; - int j = 0; - for (Iterator i = _attributeTypes.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaType.Ref)i.next()).get(); - return result; - } - - public SchemaGlobalElement[] globalElements() - { - if (_globalElements.isEmpty()) - return EMPTY_GE_ARRAY; - - SchemaGlobalElement[] result = new SchemaGlobalElement[_globalElements.size()]; - int j = 0; - for (Iterator i = _globalElements.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaGlobalElement.Ref)i.next()).get(); - return result; - } - - public SchemaGlobalAttribute[] globalAttributes() - { - if (_globalAttributes.isEmpty()) - return EMPTY_GA_ARRAY; - - SchemaGlobalAttribute[] result = new SchemaGlobalAttribute[_globalAttributes.size()]; - int j = 0; - for (Iterator i = _globalAttributes.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaGlobalAttribute.Ref)i.next()).get(); - return result; - } - - public SchemaModelGroup[] modelGroups() - { - if (_modelGroups.isEmpty()) - return EMPTY_MG_ARRAY; - - SchemaModelGroup[] result = new SchemaModelGroup[_modelGroups.size()]; - int j = 0; - for (Iterator i = _modelGroups.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaModelGroup.Ref)i.next()).get(); - return result; - } - - public SchemaModelGroup[] redefinedModelGroups() - { - if (_redefinedModelGroups == null || _redefinedModelGroups.isEmpty()) - return EMPTY_MG_ARRAY; - - SchemaModelGroup[] result = new SchemaModelGroup[_redefinedModelGroups.size()]; - int j = 0; - for (Iterator i = _redefinedModelGroups.iterator(); i.hasNext(); j++) - result[j] = ((SchemaModelGroup.Ref)i.next()).get(); - return result; - } - - public SchemaAttributeGroup[] attributeGroups() - { - if (_attributeGroups.isEmpty()) - return EMPTY_AG_ARRAY; - - SchemaAttributeGroup[] result = new SchemaAttributeGroup[_attributeGroups.size()]; - int j = 0; - for (Iterator i = _attributeGroups.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaAttributeGroup.Ref)i.next()).get(); - return result; - } - - public SchemaAttributeGroup[] redefinedAttributeGroups() - { - if (_redefinedAttributeGroups == null || _redefinedAttributeGroups.isEmpty()) - return EMPTY_AG_ARRAY; - - SchemaAttributeGroup[] result = new SchemaAttributeGroup[_redefinedAttributeGroups.size()]; - int j = 0; - for (Iterator i = _redefinedAttributeGroups.iterator(); i.hasNext(); j++) - result[j] = ((SchemaAttributeGroup.Ref)i.next()).get(); - return result; - } - - public SchemaAnnotation[] annotations() - { - if (_annotations == null || _annotations.isEmpty()) - return EMPTY_ANN_ARRAY; - - SchemaAnnotation[] result = new SchemaAnnotation[_annotations.size()]; - result = (SchemaAnnotation[]) _annotations.toArray(result); - return result; - } - - public SchemaIdentityConstraint[] identityConstraints() - { - if (_identityConstraints.isEmpty()) - return EMPTY_IC_ARRAY; - - SchemaIdentityConstraint[] result = new SchemaIdentityConstraint[_identityConstraints.size()]; - int j = 0; - for (Iterator i = _identityConstraints.values().iterator(); i.hasNext(); j++) - result[j] = ((SchemaIdentityConstraint.Ref)i.next()).get(); - return result; - } - - public ClassLoader getClassLoader() - { - return _classloader; - } - - /** - * Used INTERNALLY ONLY by the code output AFTER the type system has - * been saved and a handle has been established for each type. - */ - public String handleForType(SchemaType type) - { - return _localHandles.handleForType(type); - } - - public String getName() - { - return _name; - } - - public SchemaTypeSystem typeSystemForName(String name) - { - if (_name != null && name.equals(_name)) - return this; - return null; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java deleted file mode 100644 index 0bb9edb..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/SoapEncSchemaTypeSystem.java +++ /dev/null @@ -1,348 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import java.io.InputStream; -import java.io.File; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Collections; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.SchemaAnnotation; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.Filer; - -public class SoapEncSchemaTypeSystem extends SchemaTypeLoaderBase - implements SchemaTypeSystem -{ - public static final String SOAPENC = "http://schemas.xmlsoap.org/soap/encoding/"; - public static final String SOAP_ARRAY = "Array"; - public static final String ARRAY_TYPE = "arrayType"; - private static final String ATTR_ID = "id"; - private static final String ATTR_HREF = "href"; - private static final String ATTR_OFFSET = "offset"; - - private static final SchemaType[] EMPTY_SCHEMATYPE_ARRAY = new SchemaType[0]; - private static final SchemaGlobalElement[] EMPTY_SCHEMAELEMENT_ARRAY = new SchemaGlobalElement[0]; - private static final SchemaModelGroup[] EMPTY_SCHEMAMODELGROUP_ARRAY = new SchemaModelGroup[0]; - private static final SchemaAttributeGroup[] EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY = new SchemaAttributeGroup[0]; - private static final SchemaAnnotation[] EMPTY_SCHEMAANNOTATION_ARRAY = new SchemaAnnotation[0]; - - // The global builtin type system - public static SchemaTypeSystem get() - { return _global; } - - private static SoapEncSchemaTypeSystem _global = new SoapEncSchemaTypeSystem(); - - private SchemaTypeImpl soapArray; - private SchemaGlobalAttributeImpl arrayType; - private Map _handlesToObjects = new HashMap(); - private String soapArrayHandle; - private SchemaContainer _container = new SchemaContainer(SOAPENC); - - private SoapEncSchemaTypeSystem() - { - // soapenc:Array - _container.setTypeSystem(this); - soapArray = new SchemaTypeImpl(_container, true); - _container.addGlobalType(soapArray.getRef()); - soapArray.setName(new QName(SOAPENC, SOAP_ARRAY)); - soapArrayHandle = SOAP_ARRAY.toLowerCase() + "type"; - soapArray.setComplexTypeVariety(SchemaType.ELEMENT_CONTENT); - soapArray.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef()); - soapArray.setBaseDepth(1); - soapArray.setDerivationType(SchemaType.DT_EXTENSION); - soapArray.setSimpleTypeVariety(SchemaType.NOT_SIMPLE); - SchemaParticleImpl contentModel = new SchemaParticleImpl(); - contentModel.setParticleType(SchemaParticle.SEQUENCE); - contentModel.setMinOccurs(BigInteger.ZERO); - contentModel.setMaxOccurs(BigInteger.ONE); - contentModel.setTransitionRules(QNameSet.ALL, true); - SchemaParticleImpl[] children = new SchemaParticleImpl[1]; - contentModel.setParticleChildren(children); - SchemaParticleImpl contentModel2 = new SchemaParticleImpl(); - contentModel2.setParticleType(SchemaParticle.WILDCARD); - contentModel2.setWildcardSet(QNameSet.ALL); - contentModel2.setWildcardProcess(SchemaParticle.LAX); - contentModel2.setMinOccurs(BigInteger.ZERO); - contentModel2.setMaxOccurs(null); - contentModel2.setTransitionRules(QNameSet.ALL, true); - children[0] = contentModel2; - - SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); - attrModel.setWildcardProcess(SchemaAttributeModel.LAX); - HashSet excludedURI = new HashSet(); - excludedURI.add(SOAPENC); - attrModel.setWildcardSet(QNameSet.forSets(excludedURI, null, Collections.EMPTY_SET, - Collections.EMPTY_SET)); - SchemaLocalAttributeImpl attr = new SchemaLocalAttributeImpl(); - attr.init(new QName("", ATTR_ID), BuiltinSchemaTypeSystem.ST_ID.getRef(), - SchemaLocalAttribute.OPTIONAL, null, null, null, false, null, null, null); - attrModel.addAttribute(attr); - attr = new SchemaLocalAttributeImpl(); - attr.init(new QName("", ATTR_HREF), BuiltinSchemaTypeSystem.ST_ANY_URI.getRef(), - SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); - attrModel.addAttribute(attr); - attr = new SchemaLocalAttributeImpl(); - attr.init(new QName(SOAPENC, ARRAY_TYPE), BuiltinSchemaTypeSystem.ST_STRING.getRef(), - SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); - attrModel.addAttribute(attr); - attr = new SchemaLocalAttributeImpl(); - attr.init(new QName(SOAPENC, ATTR_OFFSET), BuiltinSchemaTypeSystem.ST_STRING.getRef(), - SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); - attrModel.addAttribute(attr); - soapArray.setContentModel(contentModel, attrModel, Collections.EMPTY_MAP, Collections.EMPTY_MAP, false); - - // soapenc:arrayType - arrayType = new SchemaGlobalAttributeImpl(_container); - _container.addGlobalAttribute(arrayType.getRef()); - arrayType.init(new QName(SOAPENC, ARRAY_TYPE), BuiltinSchemaTypeSystem.ST_STRING.getRef(), - SchemaLocalAttributeImpl.OPTIONAL, null, null, null, false, null, null, null); - _handlesToObjects.put(soapArrayHandle, soapArray); - _handlesToObjects.put(ARRAY_TYPE.toLowerCase() + "attribute", arrayType); - _container.setImmutable(); - } - - /** - * Returns the name of this loader. - */ - public String getName() - { - return "schema.typesystem.soapenc.builtin"; - } - - public SchemaType findType(QName qName) - { - if (SOAPENC.equals(qName.getNamespaceURI()) && - SOAP_ARRAY.equals(qName.getLocalPart())) - return soapArray; - else - return null; - } - - public SchemaType findDocumentType(QName qName) - { - return null; - } - - public SchemaType findAttributeType(QName qName) - { - return null; - } - - public SchemaGlobalElement findElement(QName qName) - { - return null; - } - - public SchemaGlobalAttribute findAttribute(QName qName) - { - if (SOAPENC.equals(qName.getNamespaceURI()) && - ARRAY_TYPE.equals(qName.getLocalPart())) - return arrayType; - else - return null; - } - - public SchemaModelGroup findModelGroup(QName qName) - { - return null; - } - - public SchemaAttributeGroup findAttributeGroup(QName qName) - { - return null; - } - - public boolean isNamespaceDefined(String string) - { - return SOAPENC.equals(string); - } - - public SchemaType.Ref findTypeRef(QName qName) - { - SchemaType type = findType(qName); - return (type == null ? null : type.getRef()); - } - - public SchemaType.Ref findDocumentTypeRef(QName qName) - { - return null; - } - - public SchemaType.Ref findAttributeTypeRef(QName qName) - { - return null; - } - - public SchemaGlobalElement.Ref findElementRef(QName qName) - { - return null; - } - - public SchemaGlobalAttribute.Ref findAttributeRef(QName qName) - { - SchemaGlobalAttribute attr = findAttribute(qName); - return (attr == null ? null : attr.getRef()); - } - - public SchemaModelGroup.Ref findModelGroupRef(QName qName) - { - return null; - } - - public SchemaAttributeGroup.Ref findAttributeGroupRef(QName qName) - { - return null; - } - - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName qName) - { - return null; - } - - public SchemaType typeForClassname(String string) - { - return null; - } - - public InputStream getSourceAsStream(String string) - { - return null; // no source - } - - /** - * Returns the classloader used by this loader for resolving types. - */ - public ClassLoader getClassLoader() - { - return SoapEncSchemaTypeSystem.class.getClassLoader(); - } - - /** - * Describe resolve method here. - * - */ - public void resolve() - { - // don't need to do anything; already resolved - } - - /** - * @return an array consisting of a single type - */ - public SchemaType[] globalTypes() - { - return new SchemaType[] {soapArray}; - } - - public SchemaType[] documentTypes() - { - return EMPTY_SCHEMATYPE_ARRAY; - } - - public SchemaType[] attributeTypes() - { - return EMPTY_SCHEMATYPE_ARRAY; - } - - public SchemaGlobalElement[] globalElements() - { - return EMPTY_SCHEMAELEMENT_ARRAY; - } - - public SchemaGlobalAttribute[] globalAttributes() - { - return new SchemaGlobalAttribute[] {arrayType}; - } - - public SchemaModelGroup[] modelGroups() - { - return EMPTY_SCHEMAMODELGROUP_ARRAY; - } - - public SchemaAttributeGroup[] attributeGroups() - { - return EMPTY_SCHEMAATTRIBUTEGROUP_ARRAY; - } - - public SchemaAnnotation[] annotations() - { - return EMPTY_SCHEMAANNOTATION_ARRAY; - } - - /** - * Returns the handle for the given type within this loader. - */ - public String handleForType(SchemaType type) - { - if (soapArray.equals(type)) - return soapArrayHandle; - else - return null; - } - - /** - * - */ - public SchemaComponent resolveHandle(String string) - { - return (SchemaComponent) _handlesToObjects.get(string); - } - - /** - * - */ - public SchemaType typeForHandle(String string) - { - return (SchemaType) _handlesToObjects.get(string); - } - - /** - * Describe saveToDirectory method here. - * - * @param file a File value - */ - public void saveToDirectory(File file) - { - throw new UnsupportedOperationException("The builtin soap encoding schema type system cannot be saved."); - } - - public void save(Filer filer) - { - throw new UnsupportedOperationException("The builtin soap encoding schema type system cannot be saved."); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java deleted file mode 100644 index ebcf979..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java +++ /dev/null @@ -1,1732 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SchemaLocalElement; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.XmlID; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlNOTATION; -import org.apache.xmlbeans.XmlString; -import org.apache.xmlbeans.impl.common.XBeanDebug; -import org.apache.xmlbeans.impl.common.QNameHelper; - -import javax.xml.namespace.QName; -import java.util.List; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.math.BigInteger; - -public class StscChecker -{ - public static void checkAll() - { - // walk the tree of types - StscState state = StscState.get(); - - List allSeenTypes = new ArrayList(); - allSeenTypes.addAll(Arrays.asList(state.documentTypes())); - allSeenTypes.addAll(Arrays.asList(state.attributeTypes())); - allSeenTypes.addAll(Arrays.asList(state.redefinedGlobalTypes())); - allSeenTypes.addAll(Arrays.asList(state.globalTypes())); - - for (int i = 0; i < allSeenTypes.size(); i++) - { - SchemaType gType = (SchemaType)allSeenTypes.get(i); - if (!state.noPvr() && // option to turn off particle restriction checking - !gType.isDocumentType()) // Don't check doc types for restriction. - { - checkRestriction((SchemaTypeImpl)gType); - } - checkFields((SchemaTypeImpl)gType); - allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); - } - - checkSubstitutionGroups(state.globalElements()); - } - - /** - * The following code checks rule #5 of http://www.w3.org/TR/xmlschema-1/#coss-ct - * as well as attribute + element default/fixed validity.

      - * Checks that xs:NOTATION is not used directly - */ - public static void checkFields(SchemaTypeImpl sType) - { - if (sType.isSimpleType()) - return; - - XmlObject location = sType.getParseObject(); - - SchemaAttributeModel sAttrModel = sType.getAttributeModel(); - if (sAttrModel != null) - { - SchemaLocalAttribute[] sAttrs = sAttrModel.getAttributes(); - QName idAttr = null; - for (int i = 0; i < sAttrs.length; i++) - { - XmlObject attrLocation = ((SchemaLocalAttributeImpl)sAttrs[i])._parseObject; - if (XmlID.type.isAssignableFrom(sAttrs[i].getType())) - { - if (idAttr == null) - { - idAttr = sAttrs[i].getName(); - } - else - { - StscState.get().error(XmlErrorCodes.ATTR_GROUP_PROPERTIES$TWO_IDS, - new Object[]{ QNameHelper.pretty(idAttr), sAttrs[i].getName() }, - attrLocation != null ? attrLocation : location); - } - if (sAttrs[i].getDefaultText() != null) - { - StscState.get().error(XmlErrorCodes.ATTR_PROPERTIES$ID_FIXED_OR_DEFAULT, - null, attrLocation != null ? attrLocation : location); - } - } - else if (XmlNOTATION.type.isAssignableFrom(sAttrs[i].getType())) - { - if (sAttrs[i].getType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION) - { - StscState.get().recover(XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN, - new Object[]{ QNameHelper.pretty(sAttrs[i].getName()) }, - attrLocation != null ? attrLocation : location); - } - else - { - if (sAttrs[i].getType().getSimpleVariety() == SchemaType.UNION) - { - SchemaType[] members = sAttrs[i].getType().getUnionConstituentTypes(); - for (int j = 0; j < members.length; j++) - if (members[j].getBuiltinTypeCode() == SchemaType.BTC_NOTATION) - StscState.get().recover(XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN, - new Object[]{ QNameHelper.pretty(sAttrs[i].getName()) }, - attrLocation != null ? attrLocation : location); - } - // Check that the Schema in which this is present doesn't have a targetNS - boolean hasNS; - if (sType.isAttributeType()) - hasNS = sAttrs[i].getName().getNamespaceURI().length() > 0; - else - { - SchemaType t = sType; - while (t.getOuterType() != null) - t = t.getOuterType(); - if (t.isDocumentType()) - hasNS = t.getDocumentElementName().getNamespaceURI().length() > 0; - else hasNS = t.getName().getNamespaceURI().length() > 0; - } - if (hasNS) - StscState.get().warning(XmlErrorCodes.ATTR_COMPATIBILITY_TARGETNS, - new Object[] {QNameHelper.pretty(sAttrs[i].getName()) }, - attrLocation != null ? attrLocation : location); - } - } - else - { - String valueConstraint = sAttrs[i].getDefaultText(); - if (valueConstraint != null) - { - try - { - XmlAnySimpleType val = sAttrs[i].getDefaultValue(); - if (!val.validate()) - throw new Exception(); - - SchemaPropertyImpl sProp = (SchemaPropertyImpl)sType.getAttributeProperty(sAttrs[i].getName()); - if (sProp != null && sProp.getDefaultText() != null) - { - sProp.setDefaultValue(new XmlValueRef(val)); - } - } - catch (Exception e) - { - // move to 'fixed' or 'default' attribute on the attribute definition - String constraintName = (sAttrs[i].isFixed() ? "fixed" : "default"); - XmlObject constraintLocation = location; - if (attrLocation != null) - { - constraintLocation = attrLocation.selectAttribute("", constraintName); - if (constraintLocation == null) - constraintLocation = attrLocation; - } - - StscState.get().error(XmlErrorCodes.ATTR_PROPERTIES$CONSTRAINT_VALID, - new Object[] { QNameHelper.pretty(sAttrs[i].getName()), - constraintName, - valueConstraint, - QNameHelper.pretty(sAttrs[i].getType().getName()) }, - constraintLocation); - } - } - } - } - } - - checkElementDefaults(sType.getContentModel(), location, sType); - } - - /** - * Checks the default values of elements.

      - * Also checks that the type of elements is not one of ID, IDREF, IDREFS, ENTITY, ENTITIES or - * NOTATION as per XMLSchema part 2. - * @param model - * @param location - * @param parentType - */ - private static void checkElementDefaults(SchemaParticle model, XmlObject location, SchemaType parentType) - { - if (model == null) - return; - switch (model.getParticleType()) - { - case SchemaParticle.SEQUENCE: - case SchemaParticle.CHOICE: - case SchemaParticle.ALL: - SchemaParticle[] children = model.getParticleChildren(); - for (int i = 0; i < children.length; i++) - { - checkElementDefaults(children[i], location, parentType); - } - break; - case SchemaParticle.ELEMENT: - String valueConstraint = model.getDefaultText(); - if (valueConstraint != null) - { - if (model.getType().isSimpleType() || model.getType().getContentType() == SchemaType.SIMPLE_CONTENT) - { - try - { - XmlAnySimpleType val = model.getDefaultValue(); - XmlOptions opt = new XmlOptions(); - opt.put(XmlOptions.VALIDATE_TEXT_ONLY); - if (!val.validate(opt)) - throw new Exception(); - - SchemaPropertyImpl sProp = (SchemaPropertyImpl)parentType.getElementProperty(model.getName()); - if (sProp != null && sProp.getDefaultText() != null) - { - sProp.setDefaultValue(new XmlValueRef(val)); - } - } - catch (Exception e) - { - // move to 'fixed' or 'default' attribute on the element definition - String constraintName = (model.isFixed() ? "fixed" : "default"); - XmlObject constraintLocation = location.selectAttribute("", constraintName); - - StscState.get().error(XmlErrorCodes.ELEM_PROPERTIES$CONSTRAINT_VALID, - new Object[] { QNameHelper.pretty(model.getName()), - constraintName, - valueConstraint, - QNameHelper.pretty(model.getType().getName()) }, - (constraintLocation==null ? location : constraintLocation)); - } - } - else if (model.getType().getContentType() == SchemaType.MIXED_CONTENT) - { - if (!model.getType().getContentModel().isSkippable()) - { - String constraintName = (model.isFixed() ? "fixed" : "default"); - XmlObject constraintLocation = location.selectAttribute("", constraintName); - - StscState.get().error(XmlErrorCodes.ELEM_DEFAULT_VALID$MIXED_AND_EMPTIABLE, - new Object[] { QNameHelper.pretty(model.getName()), - constraintName, - valueConstraint }, - (constraintLocation==null ? location : constraintLocation)); - } - else - { - // Element Default Valid (Immediate): cos-valid-default.2.2.2 - // no need to validate the value; type is a xs:string - SchemaPropertyImpl sProp = (SchemaPropertyImpl)parentType.getElementProperty(model.getName()); - if (sProp != null && sProp.getDefaultText() != null) - { - sProp.setDefaultValue(new XmlValueRef(XmlString.type.newValue(valueConstraint))); - } - } - } - else if (model.getType().getContentType() == SchemaType.ELEMENT_CONTENT) - { - XmlObject constraintLocation = location.selectAttribute("", "default"); - StscState.get().error(XmlErrorCodes.ELEM_DEFAULT_VALID$SIMPLE_TYPE_OR_MIXED, - new Object[] { QNameHelper.pretty(model.getName()), - valueConstraint, - "element" }, - (constraintLocation==null ? location : constraintLocation)); - } - else if (model.getType().getContentType() == SchemaType.EMPTY_CONTENT) - { - XmlObject constraintLocation = location.selectAttribute("", "default"); - StscState.get().error(XmlErrorCodes.ELEM_DEFAULT_VALID$SIMPLE_TYPE_OR_MIXED, - new Object[] { QNameHelper.pretty(model.getName()), - valueConstraint, - "empty" }, - (constraintLocation==null ? location : constraintLocation)); - } - } - // Checks if the type is one of the "attribute-specific" types - String warningType = null; - if (BuiltinSchemaTypeSystem.ST_ID.isAssignableFrom(model.getType())) - warningType = BuiltinSchemaTypeSystem.ST_ID.getName().getLocalPart(); - else if (BuiltinSchemaTypeSystem.ST_IDREF.isAssignableFrom(model.getType())) - warningType = BuiltinSchemaTypeSystem.ST_IDREF.getName().getLocalPart(); - else if (BuiltinSchemaTypeSystem.ST_IDREFS.isAssignableFrom(model.getType())) - warningType = BuiltinSchemaTypeSystem.ST_IDREFS.getName().getLocalPart(); - else if (BuiltinSchemaTypeSystem.ST_ENTITY.isAssignableFrom(model.getType())) - warningType = BuiltinSchemaTypeSystem.ST_ENTITY.getName().getLocalPart(); - else if (BuiltinSchemaTypeSystem.ST_ENTITIES.isAssignableFrom(model.getType())) - warningType = BuiltinSchemaTypeSystem.ST_ENTITIES.getName().getLocalPart(); - else if (BuiltinSchemaTypeSystem.ST_NOTATION.isAssignableFrom(model.getType())) - { - if (model.getType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION) - { - StscState.get().recover(XmlErrorCodes.ELEM_NOTATION_TYPE_FORBIDDEN, - new Object[]{ QNameHelper.pretty(model.getName()) }, - ((SchemaLocalElementImpl) model)._parseObject == null ? location : - ((SchemaLocalElementImpl) model)._parseObject.selectAttribute("", "type")); - } - else - { - if (model.getType().getSimpleVariety() == SchemaType.UNION) - { - SchemaType[] members = model.getType().getUnionConstituentTypes(); - for (int i = 0; i < members.length; i++) - if (members[i].getBuiltinTypeCode() == SchemaType.BTC_NOTATION) - StscState.get().recover(XmlErrorCodes.ELEM_NOTATION_TYPE_FORBIDDEN, - new Object[]{ QNameHelper.pretty(model.getName()) }, - ((SchemaLocalElementImpl) model)._parseObject == null ? location : - ((SchemaLocalElementImpl) model)._parseObject.selectAttribute("", "type")); - } - warningType = BuiltinSchemaTypeSystem.ST_NOTATION.getName().getLocalPart(); - } - - // Check that the Schema in which this is present doesn't have a targetNS - boolean hasNS; - SchemaType t = parentType; - while (t.getOuterType() != null) - t = t.getOuterType(); - if (t.isDocumentType()) - hasNS = t.getDocumentElementName().getNamespaceURI().length() > 0; - else - hasNS = t.getName().getNamespaceURI().length() > 0; - if (hasNS) - StscState.get().warning(XmlErrorCodes.ELEM_COMPATIBILITY_TARGETNS, - new Object[] {QNameHelper.pretty(model.getName()) }, - ((SchemaLocalElementImpl) model)._parseObject == null ? location : - ((SchemaLocalElementImpl) model)._parseObject); - } - - if (warningType != null) - StscState.get().warning(XmlErrorCodes.ELEM_COMPATIBILITY_TYPE, new Object[] - { QNameHelper.pretty(model.getName()), warningType }, - ((SchemaLocalElementImpl) model)._parseObject == null ? location : - ((SchemaLocalElementImpl) model)._parseObject.selectAttribute("", "type")); - - break; - - default: - // nothing to do. - break; - } - } - - /** - * The following code only checks rule #5 of http://www.w3.org/TR/xmlschema-1/#derivation-ok-restriction - * (Everything else can and should be done in StscResolver, because we can give more detailed line # info there - */ - public static boolean checkRestriction(SchemaTypeImpl sType) - { - if (sType.getDerivationType() == SchemaType.DT_RESTRICTION && !sType.isSimpleType()) - { - StscState state = StscState.get(); - - // we don't remember very precise line number information, but it's better than nothin. - XmlObject location = sType.getParseObject(); - - SchemaType baseType = sType.getBaseType(); - if (baseType.isSimpleType()) - { - state.error(XmlErrorCodes.SCHEMA_COMPLEX_TYPE$COMPLEX_CONTENT, - new Object[] { QNameHelper.pretty(baseType.getName()) }, - location); - return false; - } - - // 5 The appropriate case among the following must be true: - switch (sType.getContentType()) - { - case SchemaType.SIMPLE_CONTENT: - // 5.1 If the {content type} of the complex type definition is a simple type definition, then one of the following must be true: - switch (baseType.getContentType()) - { - case SchemaType.SIMPLE_CONTENT: - // 5.1.1 The {content type} of the {base type definition} must be a simple type definition of which the {content type} is a �valid restriction� as defined in Derivation Valid (Restriction, Simple) (�3.14.6). - SchemaType cType = sType.getContentBasedOnType(); - if (cType != baseType) - { - // We have to check that the contentType is legally derived - // from the base simple type in the hierarchy - SchemaType bType = baseType; - while (bType != null && !bType.isSimpleType()) - bType = bType.getContentBasedOnType(); - if (bType != null && !bType.isAssignableFrom(cType)) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$SC_NOT_DERIVED, - null, location); - return false; - } - } - break; - - case SchemaType.MIXED_CONTENT: - // 5.1.2 The {base type definition} must be mixed and have a particle which is �emptiable� as defined in Particle Emptiable (�3.9.6). - if (baseType.getContentModel() != null && !baseType.getContentModel().isSkippable()) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$SC_AND_MIXED_EMPTIABLE, - null, location); - return false; - } - break; - - default: - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$SC_AND_SIMPLE_TYPE_OR_MIXED, - null, location); - return false; - } - break; - - case SchemaType.EMPTY_CONTENT: - // 5.2 If the {content type} of the complex type itself is empty , then one of the following must be true: - switch (baseType.getContentType()) - { - case SchemaType.EMPTY_CONTENT: - // 5.2.1 The {content type} of the {base type definition} must also be empty. - break; - case SchemaType.MIXED_CONTENT: - case SchemaType.ELEMENT_CONTENT: - // 5.2.2 The {content type} of the {base type definition} must be elementOnly or mixed and have a particle which is �emptiable� as defined in Particle Emptiable (�3.9.6). - if (baseType.getContentModel() != null && !baseType.getContentModel().isSkippable()) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$EMPTY_AND_ELEMENT_OR_MIXED_EMPTIABLE, - null, location); - return false; - } - break; - default: - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$EMPTY_AND_NOT_SIMPLE, - null, location); - return false; - } - break; - - case SchemaType.MIXED_CONTENT: - // 5.3 If the {content type} of the {base type definition} is mixed... - if (baseType.getContentType() != SchemaType.MIXED_CONTENT) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_MIXED, - null, location); - return false; - } - - // FALLTHROUGH - case SchemaType.ELEMENT_CONTENT: - // 5.3 ... or the {content type} of the complex type definition itself is element-only,... - if (baseType.getContentType() == SchemaType.EMPTY_CONTENT) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_EMPTY, - null, location); - return false; - } - if (baseType.getContentType() == SchemaType.SIMPLE_CONTENT) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_SIMPLE, - null, location); - return false; - } - - // 5.3 ... then the particle of the complex type definition itself must be a �valid restriction� of the particle of the {content type} of the {base type definition} - SchemaParticle baseModel = baseType.getContentModel(); - SchemaParticle derivedModel = sType.getContentModel(); - - if ( derivedModel == null && sType.getDerivationType()==SchemaType.DT_RESTRICTION ) - { - // it is ok to have an empty contentModel if it's a restriction - // see Particle Valid (Restriction) (3.9.6) all three bulets 2.2.1 - return true; - } - else if (baseModel == null || derivedModel == null) - { - XBeanDebug.logStackTrace("Null models that weren't caught by EMPTY_CONTENT: " + baseType + " (" + baseModel + "), " + sType + " (" + derivedModel + ")"); - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_VALID, null, location); - return false; - } - - // 5.3 ... as defined in Particle Valid (Restriction) (�3.9.6). - List errors = new ArrayList(); - boolean isValid = isParticleValidRestriction(baseModel, derivedModel, errors, location); - if (!isValid) - { - // we only add the last error, because isParticleValidRestriction may add errors - // to the collection that it later changes its mind about, or it may (inadvertently) - // forget to describe an error into the collection.... - if (errors.size() == 0) - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ELEMENT_OR_MIXED_AND_VALID, null, location); - else - state.getErrorListener().add(errors.get(errors.size() - 1)); - //state.getErrorListener().addAll(errors); - return false; // KHK: should return false, right? - } - } - } - return true; - } - - /** - * This function takes in two schema particle types, a baseModel, and a derived model and returns true if the - * derivedModel can be egitimately be used for restriction. Errors are put into the errors collections. - * @param baseModel - The base schema particle - * @param derivedModel - The derived (restricted) schema particle - * @param errors - Invalid restriction errors are put into this collection - * @param context - * @return boolean, true if valid restruction, false if invalid restriction - * @ - */ - public static boolean isParticleValidRestriction(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - boolean restrictionValid = false; - // 1 They are the same particle. - if (baseModel.equals(derivedModel)) { - restrictionValid = true; - } else { - // Implement table defined in schema spec on restrictions at: - // http://www.w3.org/TR/xmlschema-1/#cos-particle-restrict - switch (baseModel.getParticleType()) { - case SchemaParticle.ELEMENT: - switch (derivedModel.getParticleType()) { - case SchemaParticle.ELEMENT: - restrictionValid = nameAndTypeOK((SchemaLocalElement) baseModel, (SchemaLocalElement) derivedModel, errors, context); - break; - case SchemaParticle.WILDCARD: - case SchemaParticle.ALL: - case SchemaParticle.CHOICE: - case SchemaParticle.SEQUENCE: - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, context)); - restrictionValid = false; - break; - default: - assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); - } - break; - case SchemaParticle.WILDCARD: - switch (derivedModel.getParticleType()) { - case SchemaParticle.ELEMENT: - restrictionValid = nsCompat(baseModel, (SchemaLocalElement) derivedModel, errors, context); - break; - case SchemaParticle.WILDCARD: - restrictionValid = nsSubset(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.ALL: - restrictionValid = nsRecurseCheckCardinality(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.CHOICE: - restrictionValid = nsRecurseCheckCardinality(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.SEQUENCE: - restrictionValid = nsRecurseCheckCardinality(baseModel, derivedModel, errors, context); - break; - default: - assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); - } - break; - case SchemaParticle.ALL: - switch (derivedModel.getParticleType()) { - case SchemaParticle.ELEMENT: - restrictionValid = recurseAsIfGroup(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.WILDCARD: - case SchemaParticle.CHOICE: - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, context)); - restrictionValid = false; - break; - case SchemaParticle.ALL: - restrictionValid = recurse(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.SEQUENCE: - restrictionValid = recurseUnordered(baseModel, derivedModel, errors, context); - break; - default: - assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); - } - break; - case SchemaParticle.CHOICE: - switch (derivedModel.getParticleType()) { - case SchemaParticle.ELEMENT: - restrictionValid = recurseAsIfGroup(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.WILDCARD: - case SchemaParticle.ALL: - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, context)); - restrictionValid = false; - break; - case SchemaParticle.CHOICE: - restrictionValid = recurseLax(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.SEQUENCE: - restrictionValid = mapAndSum(baseModel, derivedModel, errors, context); - break; - default: - assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); - } - break; - case SchemaParticle.SEQUENCE: - switch (derivedModel.getParticleType()) { - case SchemaParticle.ELEMENT: - restrictionValid = recurseAsIfGroup(baseModel, derivedModel, errors, context); - break; - case SchemaParticle.WILDCARD: - case SchemaParticle.ALL: - case SchemaParticle.CHOICE: - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION$INVALID_RESTRICTION, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, context)); - restrictionValid = false; - break; - case SchemaParticle.SEQUENCE: - restrictionValid = recurse(baseModel, derivedModel, errors, context); - break; - default: - assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type"); - } - break; - default: - assert false : XBeanDebug.logStackTrace("Unknown schema type for Base Type"); - - } - } - - return restrictionValid; - } - - private static boolean mapAndSum(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // mapAndSum is call if base: CHOICE, derived: SEQUENCE - assert baseModel.getParticleType() == SchemaParticle.CHOICE; - assert derivedModel.getParticleType() == SchemaParticle.SEQUENCE; - boolean mapAndSumValid = true; - // Schema Component Constraint: Particle Derivation OK (Sequence:Choice -- MapAndSum) - // For a sequence group particle to be a �valid restriction� of a choice group particle all of the following - // must be true: - // 1 There is a complete functional mapping from the particles in the {particles} of R to the particles in the - // {particles} of B such that each particle in the {particles} of R is a �valid restriction� of the particle in - // the {particles} of B it maps to as defined by Particle Valid (Restriction) (�3.9.6). - // interpretation: each particle child in derived should have a match in base. - // 2 The pair consisting of the product of the {min occurs} of R and the length of its {particles} and unbounded - // if {max occurs} is unbounded otherwise the product of the {max occurs} of R and the length of its {particles} - // is a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). - // NOTE: This clause is in principle more restrictive than absolutely necessary, but in practice will cover - // all the likely cases, and is much easier to specify than the fully general version. - // NOTE: This case allows the "unfolding" of iterated disjunctions into sequences. It may be particularly useful - // when the disjunction is an implicit one arising from the use of substitution groups. - - // Map step - for each member of the derived model's particle children search base model's particle children - // for match - SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren(); - SchemaParticle[] baseParticleArray = baseModel.getParticleChildren(); - for (int i = 0; i < derivedParticleArray.length; i++) { - SchemaParticle derivedParticle = derivedParticleArray[i]; - boolean foundMatch = false; - for (int j = 0; j < baseParticleArray.length; j++) { - SchemaParticle baseParticle = baseParticleArray[j]; - // recurse to check if there is a match - if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) { - // if there is a match then no need to check base particles anymore - foundMatch = true; - break; - } - } - if (!foundMatch) { - mapAndSumValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$MAP, - new Object[] { printParticle(derivedParticle) }, - context)); - // KHK: if we don't return false now, this error may get swallowed by an error produced below - return false; - //break; - } - } - - // Sum step - BigInteger derivedRangeMin = derivedModel.getMinOccurs().multiply(BigInteger.valueOf(derivedModel.getParticleChildren().length)); - BigInteger derivedRangeMax = null; - BigInteger UNBOUNDED = null; - if (derivedModel.getMaxOccurs() == UNBOUNDED) { - derivedRangeMax = null; - } else { - derivedRangeMax = derivedModel.getMaxOccurs().multiply(BigInteger.valueOf(derivedModel.getParticleChildren().length)); - } - - // Now check derivedRange (derivedRangeMin and derivedRangeMax) against base model occurrence range - // Schema Component Constraint: Occurrence Range OK - // For a particle's occurrence range to be a valid restriction of another's occurrence range all of the following must be true: - // 1 Its {min occurs} is greater than or equal to the other's {min occurs}. - // 2 one of the following must be true: - // 2.1 The other's {max occurs} is unbounded. - // 2.2 Both {max occurs} are numbers, and the particle's is less than or equal to the other's. - - if (derivedRangeMin.compareTo(baseModel.getMinOccurs()) < 0) { - mapAndSumValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MIN_OCCURS_GTE_MIN_OCCURS, - new Object[] { derivedRangeMin.toString(), baseModel.getMinOccurs().toString() }, - context)); - } else if (baseModel.getMaxOccurs() != UNBOUNDED && (derivedRangeMax == UNBOUNDED || derivedRangeMax.compareTo(baseModel.getMaxOccurs()) > 0)) { - mapAndSumValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MAX_OCCURS_LTE_MAX_OCCURS, - new Object[] { derivedRangeMax == UNBOUNDED ? "unbounded" : derivedRangeMax.toString(), baseModel.getMaxOccurs().toString() }, - context)); - } - - return mapAndSumValid; - } - - private static boolean recurseAsIfGroup(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // recurseAsIfGroup is called if: - // base: ALL, derived: ELEMENT - // base: CHOICE, derived: ELEMENT - // base: SEQUENCE, derived: ELEMENT - assert (baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.ELEMENT) - || (baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.ELEMENT) - || (baseModel.getParticleType() == SchemaParticle.SEQUENCE && derivedModel.getParticleType() == SchemaParticle.ELEMENT); - // Schema Component Constraint: Particle Derivation OK (Elt:All/Choice/Sequence -- RecurseAsIfGroup) - - // For an element declaration particle to be a �valid restriction� of a group particle - // (all, choice or sequence) a group particle of the variety corresponding to B's, with {min occurs} and - // {max occurs} of 1 and with {particles} consisting of a single particle the same as the element declaration - // must be a �valid restriction� of the group as defined by Particle Derivation OK - // (All:All,Sequence:Sequence -- Recurse) (�3.9.6), Particle Derivation OK (Choice:Choice -- RecurseLax) - // (�3.9.6) or Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) (�3.9.6), depending on whether - // the group is all, choice or sequence - - // interpretation: make a fake group of the right type, with min occurs and max occurs of 1 - SchemaParticleImpl asIfPart = new SchemaParticleImpl(); - asIfPart.setParticleType(baseModel.getParticleType()); - asIfPart.setMinOccurs(BigInteger.ONE); - asIfPart.setMaxOccurs(BigInteger.ONE); - asIfPart.setParticleChildren(new SchemaParticle[] { derivedModel }); - - // the recurse - return isParticleValidRestriction(baseModel, asIfPart, errors, context); - } - - private static boolean recurseLax(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // recurseLax is called if base: CHOICE, derived: CHOICE - assert baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.CHOICE; - boolean recurseLaxValid = true; - //Schema Component Constraint: Particle Derivation OK (Choice:Choice -- RecurseLax) - // For a choice group particle to be a �valid restriction� of another choice group particle all of the - // following must be true: - // 1 R's occurrence range is a valid restriction of B's occurrence range as defined by Occurrence - // Range OK (�3.9.6); - // 2 There is a complete �order-preserving� functional mapping from the particles in the {particles} of R - // to the particles in the {particles} of B such that each particle in the {particles} of R is a - // �valid restriction� of the particle in the {particles} of B it maps to as defined by - // Particle Valid (Restriction) (�3.9.6). - // NOTE: Although the �validation� semantics of a choice group does not depend on the order of its particles, - // derived choice groups are required to match the order of their base in order to simplify - // checking that the derivation is OK. - // interpretation: check derived choices for match in order, must get an in order match on a base particle, - // don't need to check if base particles are skippable. a lot like recurse - - if (!occurrenceRangeOK(baseModel, derivedModel, errors, context)) { - return false; - } - // cycle thru both derived particle children and base particle children looking for matches - // if the derived particle does not match the base particle then base particle can be skipped - - SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren(); - SchemaParticle[] baseParticleArray = baseModel.getParticleChildren(); - int i = 0, j = 0; - for (; i < derivedParticleArray.length && j < baseParticleArray.length;) { - SchemaParticle derivedParticle = derivedParticleArray[i]; - SchemaParticle baseParticle = baseParticleArray[j]; - // try to match the two particles by recursing - if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) { - // cool found a match, increment both indexes - i++; - j++; - } else { - // did not match, increment the base particle array index only - // Ok, let's skip this base particle, increment base particle array index only - j++; - } - } - - // ok, got to the end of one of the arrays - // if at end of base particle array and not at the end of derived particle array then remaining derived - // particles must not match - if (i < derivedParticleArray.length) { - recurseLaxValid = false; - //String message = "Found derived particles that are not matched in the base content model."; - //errors.add(XmlError.forObject(formatDerivedMappingError(message, baseModel, derivedModel), context)); - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_LAX$MAP, - new Object[] { printParticles(baseParticleArray, i) }, - context)); - } - - - return recurseLaxValid; - } - - private static boolean recurseUnordered(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // recurseUnorder is called when base: ALL and derived: SEQ - assert baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.SEQUENCE; - boolean recurseUnorderedValid = true; - // Schema Component Constraint: Particle Derivation OK (Sequence:All -- RecurseUnordered) - // For a sequence group particle to be a �valid restriction� of an all group particle all of the - // following must be true: - // 1 R's occurrence range is a valid restriction of B's occurrence range as defined by - // Occurrence Range OK (�3.9.6). - // 2 There is a complete functional mapping from the particles in the {particles} of R to the particles - // in the {particles} of B such that all of the following must be true: - // 2.1 No particle in the {particles} of B is mapped to by more than one of the particles in - // the {particles} of R; - // 2.2 Each particle in the {particles} of R is a �valid restriction� of the particle in the {particles} of B - // it maps to as defined by Particle Valid (Restriction) (�3.9.6); - // 2.3 All particles in the {particles} of B which are not mapped to by any particle in the {particles} - // of R are �emptiable� as defined by Particle Emptiable (�3.9.6). - // NOTE: Although this clause allows reordering, because of the limits on the contents of all groups the - // checking process can still be deterministic. - // 1, 2.2, and 2.3 are the same as recurse, so do 2.1 and then call recurse - - if (!occurrenceRangeOK(baseModel, derivedModel, errors, context)) { - return false; - } - - // read baseParticle array QNames into hashmap - SchemaParticle[] baseParticles = baseModel.getParticleChildren(); - HashMap baseParticleMap = new HashMap(10); - Object MAPPED = new Object(); - // Initialize the hashmap - for (int i = 0; i < baseParticles.length; i++) - baseParticleMap.put(baseParticles[i].getName(), baseParticles[i]); - - // go thru the sequence (derived model's children) and check off from base particle map - SchemaParticle[] derivedParticles = derivedModel.getParticleChildren(); - for (int i = 0; i < derivedParticles.length; i++) { - Object baseParticle = baseParticleMap.get(derivedParticles[i].getName()); - if (baseParticle == null) { - recurseUnorderedValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP, - new Object[] { printParticle(derivedParticles[i]) }, context )); - break; - } else { - // got a match - if (baseParticle == MAPPED) { - // whoa, this base particle has already been matched (see 2.1 above) - recurseUnorderedValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_UNIQUE, - new Object[] { printParticle(derivedParticles[i]) }, context )); - break; - } else { - SchemaParticle matchedBaseParticle = (SchemaParticle)baseParticle; - if (derivedParticles[i].getMaxOccurs() == null || - derivedParticles[i].getMaxOccurs().compareTo(BigInteger.ONE) > 0) { - // no derived particles can have a max occurs greater than 1 - recurseUnorderedValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_MAX_OCCURS_1, - new Object[] { printParticle(derivedParticles[i]), printMaxOccurs(derivedParticles[i].getMinOccurs()) }, - context)); - break; - } - if (!isParticleValidRestriction(matchedBaseParticle, derivedParticles[i], errors, context)) - { - // already have an error - recurseUnorderedValid = false; - break; - } - // everything is cool, got a match, update to MAPPED - baseParticleMap.put(derivedParticles[i].getName(), MAPPED); - } - } - } - - // if everything is cool so far then check to see if any base particles are not matched - if (recurseUnorderedValid) { - // get all the hashmap keys and loop thru looking for NOT_MAPPED - Set baseParticleCollection = baseParticleMap.keySet(); - for (Iterator iterator = baseParticleCollection.iterator(); iterator.hasNext();) { - QName baseParticleQName = (QName) iterator.next(); - if (baseParticleMap.get(baseParticleQName) != MAPPED && !((SchemaParticle)baseParticleMap.get(baseParticleQName)).isSkippable()) { - // this base particle was not mapped and is not "particle emptiable" (skippable) - recurseUnorderedValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$UNMAPPED_ARE_EMPTIABLE, - new Object[] { printParticle((SchemaParticle)baseParticleMap.get(baseParticleQName)) }, - context)); - } - } - } - - return recurseUnorderedValid; - } - - private static boolean recurse(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // recurse is called when base: ALL derived: ALL or base: SEQUENCE derived: SEQUENCE - boolean recurseValid = true; - // For an all or sequence group particle to be a �valid restriction� of another group particle with the same - // {compositor} all of the following must be true: - // 1 R's occurrence range is a valid restriction of B's occurrence range as defined by - // Occurrence Range OK (�3.9.6). - // 2 There is a complete �order-preserving� functional mapping from the particles in the {particles} of R to - // the particles in the {particles} of B such that all of the following must be true: - // 2.1 Each particle in the {particles} of R is a �valid restriction� of the particle in the {particles} - // of B it maps to as defined by Particle Valid (Restriction) (�3.9.6). - // 2.2 All particles in the {particles} of B which are not mapped to by any particle in the {particles} - // of R are �emptiable� as defined by Particle Emptiable (�3.9.6). - // NOTE: Although the �validation� semantics of an all group does not depend on the order of its particles, - // derived all groups are required to match the order of their base in order to simplify checking that - // the derivation is OK. - // [Definition:] A complete functional mapping is order-preserving if each particle r in the domain R maps - // to a particle b in the range B which follows (not necessarily immediately) the particle in the range B - // mapped to by the predecessor of r, if any, where "predecessor" and "follows" are defined with respect to - // the order of the lists which constitute R and B. - - if (!occurrenceRangeOK(baseModel, derivedModel, errors, context)) { - // error message is formatted in occurrencRangeOK ... - return false; - } - // cycle thru both derived particle children and base particle children looking for matches - // if the derived particle does not match the base particle then base particle can be skipped if it is - // skippable (same as "particle emptiable") otherwise is an invalid restriction. - // after the derived particles have been cycled if there are any base particles left over then they - // must be skippable or invalid restriction - - SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren(); - SchemaParticle[] baseParticleArray = baseModel.getParticleChildren(); - int i = 0, j = 0; - for (; i < derivedParticleArray.length && j < baseParticleArray.length;) { - SchemaParticle derivedParticle = derivedParticleArray[i]; - SchemaParticle baseParticle = baseParticleArray[j]; - // try to match the two particles by recursing - if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) { - // cool found a match, increment both indexes - i++; - j++; - } else { - // did not match, increment the base particle array index only - // that's ok if the base particle is skippable - if (baseParticle.isSkippable()) { - // Ok, let's skip this base particle, increment base particle array index only - j++; - } else { - // whoa, particles are not valid restrictions and base is not skippable - ERROR - recurseValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE$MAP_VALID, - new Object[] { printParticle(derivedParticle), printParticle(derivedModel), - printParticle(baseParticle), printParticle(baseModel) }, - context)); - break; - } - } - } - - // ok, got to the end of one of the arrays - // if at end of base particle array and not at the end of derived particle array then remaining derived - // particles must not match - if (i < derivedParticleArray.length) { - recurseValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE$MAP, - new Object[] { printParticle(derivedModel), printParticle(baseModel), printParticles(derivedParticleArray, i) }, - context)); - } else { - // if at end of derived particle array and not at end of base particle array then chck remaining - // base particles to assure they are skippable - if (j < baseParticleArray.length) { - ArrayList particles = new ArrayList(baseParticleArray.length); - for (int k = j; k < baseParticleArray.length; k++) { - if (!baseParticleArray[k].isSkippable()) { - particles.add(baseParticleArray[k]); - } - } - if (particles.size() > 0) - { - recurseValid = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE$UNMAPPED_ARE_EMPTIABLE, - new Object[] { printParticle(baseModel), printParticle(derivedModel), printParticles(particles)}, context)); - } - } - } - - return recurseValid; - } - - private static boolean nsRecurseCheckCardinality(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // nsRecurseCheckCardinality is called when: - // base: ANY, derived: ALL - // base: ANY, derived: CHOICE - // base: ANY, derived: SEQUENCE - assert baseModel.getParticleType() == SchemaParticle.WILDCARD; - assert (derivedModel.getParticleType() == SchemaParticle.ALL) - || (derivedModel.getParticleType() == SchemaParticle.CHOICE) - || (derivedModel.getParticleType() == SchemaParticle.SEQUENCE); - boolean nsRecurseCheckCardinality = true; - // For a group particle to be a �valid restriction� of a wildcard particle all of the following must be true: - // 1 Every member of the {particles} of the group is a �valid restriction� of the wildcard as defined by Particle Valid (Restriction) (�3.9.6). - // Note: not positive what this means. Interpreting to mean that every particle of the group must adhere to wildcard derivation rules - // in a recursive manner - // Loop thru the children particles of the group and invoke the appropriate function to check for wildcard restriction validity - - // BAU - an errata should be submitted on this clause of the spec, because the - // spec makes no sense, as the xstc particlesR013.xsd test exemplifies. - // what we _should_ so is an "as if" on the wildcard, allowing it minOccurs="0" maxOccurs="unbounded" - // before recursing - SchemaParticleImpl asIfPart = new SchemaParticleImpl(); - asIfPart.setParticleType(baseModel.getParticleType()); - asIfPart.setWildcardProcess(baseModel.getWildcardProcess()); - asIfPart.setWildcardSet(baseModel.getWildcardSet()); - asIfPart.setMinOccurs(BigInteger.ZERO); - asIfPart.setMaxOccurs(null); - asIfPart.setTransitionRules(baseModel.getWildcardSet(), true); - asIfPart.setTransitionNotes(baseModel.getWildcardSet(), true); - - SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); - for (int i = 0; i < particleChildren.length; i++) { - SchemaParticle particle = particleChildren[i]; - switch (particle.getParticleType()) { - case SchemaParticle.ELEMENT: - // Check for valid Wildcard/Element derivation - nsRecurseCheckCardinality = nsCompat(asIfPart, (SchemaLocalElement) particle, errors, context); - break; - case SchemaParticle.WILDCARD: - // Check for valid Wildcard/Wildcard derivation - nsRecurseCheckCardinality = nsSubset(asIfPart, particle, errors, context); - break; - case SchemaParticle.ALL: - case SchemaParticle.CHOICE: - case SchemaParticle.SEQUENCE: - // Check for valid Wildcard/Group derivation - nsRecurseCheckCardinality = nsRecurseCheckCardinality(asIfPart, particle, errors, context); - break; - } - // If any particle is invalid then break the loop - if (!nsRecurseCheckCardinality) { - break; - } - } - - // 2 The effective total range of the group, as defined by Effective Total Range (all and sequence) (�3.8.6) - // (if the group is all or sequence) or Effective Total Range (choice) (�3.8.6) (if it is choice) is a valid - // restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). - - if (nsRecurseCheckCardinality) { - nsRecurseCheckCardinality = checkGroupOccurrenceOK(baseModel, derivedModel, errors, context); - } - - return nsRecurseCheckCardinality; - } - - private static boolean checkGroupOccurrenceOK(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - boolean groupOccurrenceOK = true; - BigInteger minRange = BigInteger.ZERO; - BigInteger maxRange = BigInteger.ZERO; - switch (derivedModel.getParticleType()) { - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - minRange = getEffectiveMinRangeAllSeq(derivedModel); - maxRange = getEffectiveMaxRangeAllSeq(derivedModel); - break; - case SchemaParticle.CHOICE: - minRange = getEffectiveMinRangeChoice(derivedModel); - maxRange = getEffectiveMaxRangeChoice(derivedModel); - break; - } - - // Check min occurs for validity - // derived min occurs is valid if its {min occurs} is greater than or equal to the other's {min occurs}. - if (minRange.compareTo(baseModel.getMinOccurs()) < 0) { - groupOccurrenceOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MIN_GTE_MIN, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, - context)); - } - // Check max occurs for validity - // one of the following must be true: - // The base model's {max occurs} is unbounded. - // or both {max occurs} are numbers, and the particle's is less than or equal to the other's - BigInteger UNBOUNDED = null; - if (baseModel.getMaxOccurs() != UNBOUNDED) { - if (maxRange == UNBOUNDED) { - groupOccurrenceOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, - context)); - } else { - if (maxRange.compareTo(baseModel.getMaxOccurs()) > 0) { - groupOccurrenceOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, - context)); - } - } - } - return groupOccurrenceOK; - } - - private static BigInteger getEffectiveMaxRangeChoice(SchemaParticle derivedModel) { - BigInteger maxRange = BigInteger.ZERO; - BigInteger UNBOUNDED = null; - // Schema Component Constraint: Effective Total Range (choice) - // The effective total range of a particle whose {term} is a group whose {compositor} is choice - // is a pair of minimum and maximum, as follows: - // MAXIMUM - // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or - // the maximum part of the effective total range of any of the group particles in the group's {particles} is - // unbounded (note: seems to be the same as Max Range All or Sequence), - // or 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded, - // otherwise 3) the product of the particle's {max occurs} and the maximum of the {max occurs} of every - // wildcard or element declaration particle in the group's {particles} and the *maximum* (note: this is the difference - // between MaxRange Choice ans MaxRange All or Sequence) part of the - // effective total range of each of the group particles in the group's {particles} - // (or 0 if there are no {particles}). - - boolean nonZeroParticleChildFound = false; - BigInteger maxOccursInWildCardOrElement = BigInteger.ZERO; - BigInteger maxOccursInGroup = BigInteger.ZERO; - SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); - for (int i = 0; i < particleChildren.length; i++) { - SchemaParticle particle = particleChildren[i]; - switch (particle.getParticleType()) { - case SchemaParticle.WILDCARD: - case SchemaParticle.ELEMENT: - // if unbounded then maxoccurs will be null - if (particle.getMaxOccurs() == UNBOUNDED) { - maxRange = UNBOUNDED; - } else { - if (particle.getIntMaxOccurs() > 0) { - // show tht at least one non-zero particle is found for later test - nonZeroParticleChildFound = true; - if (particle.getMaxOccurs().compareTo(maxOccursInWildCardOrElement) > 0) { - maxOccursInWildCardOrElement = particle.getMaxOccurs(); - } - } - } - break; - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - maxRange = getEffectiveMaxRangeAllSeq(particle); - if (maxRange != UNBOUNDED) { - // keep highest maxoccurs found - if (maxRange.compareTo(maxOccursInGroup) > 0) { - maxOccursInGroup = maxRange; - } - } - break; - case SchemaParticle.CHOICE: - maxRange = getEffectiveMaxRangeChoice(particle); - if (maxRange != UNBOUNDED) { - // keep highest maxoccurs found - if (maxRange.compareTo(maxOccursInGroup) > 0) { - maxOccursInGroup = maxRange; - } - } - break; - } - // if an unbounded has been found then we are done - if (maxRange == UNBOUNDED) { - break; - } - } - - // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or - // the maximum part of the effective total range of any of the group particles in the group's {particles} is - // unbounded - if (maxRange != UNBOUNDED) { - // 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded - if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == UNBOUNDED) { - maxRange = UNBOUNDED; - } else { - // 3) the product of the particle's {max occurs} and the maximum of the {max occurs} of every - // wildcard or element declaration particle in the group's {particles} and the *maximum* - // part of the effective total range of each of the group particles in the group's {particles} - maxRange = derivedModel.getMaxOccurs().multiply(maxOccursInWildCardOrElement.add(maxOccursInGroup)); - } - } - - return maxRange; - } - - private static BigInteger getEffectiveMaxRangeAllSeq(SchemaParticle derivedModel) { - BigInteger maxRange = BigInteger.ZERO; - BigInteger UNBOUNDED = null; - // Schema Component Constraint: Effective Total Range (all and sequence) - // The effective total range of a particle whose {term} is a group whose {compositor} is all or sequence is a - // pair of minimum and maximum, as follows: - // MAXIMUM - // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or - // the maximum part of the effective total range of any of the group particles in the group's {particles} is - // unbounded, or 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded, otherwise - // 3) the product of the particle's {max occurs} and the *sum* of the {max occurs} of every wildcard or element - // declaration particle in the group's {particles} and the maximum part of the effective total range of each of - // the group particles in the group's {particles} (or 0 if there are no {particles}). - - boolean nonZeroParticleChildFound = false; - BigInteger maxOccursTotal = BigInteger.ZERO; - BigInteger maxOccursInGroup = BigInteger.ZERO; - SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); - for (int i = 0; i < particleChildren.length; i++) { - SchemaParticle particle = particleChildren[i]; - switch (particle.getParticleType()) { - case SchemaParticle.WILDCARD: - case SchemaParticle.ELEMENT: - // if unbounded then maxoccurs will be null - if (particle.getMaxOccurs() == UNBOUNDED) { - maxRange = UNBOUNDED; - } else { - if (particle.getIntMaxOccurs() > 0) { - // show tht at least one non-zero particle is found for later test - nonZeroParticleChildFound = true; - maxOccursTotal = maxOccursTotal.add(particle.getMaxOccurs()); - } - } - break; - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - maxRange = getEffectiveMaxRangeAllSeq(particle); - if (maxRange != UNBOUNDED) { - // keep highest maxoccurs found - if (maxRange.compareTo(maxOccursInGroup) > 0) { - maxOccursInGroup = maxRange; - } - } - break; - case SchemaParticle.CHOICE: - maxRange = getEffectiveMaxRangeChoice(particle); - if (maxRange != UNBOUNDED) { - // keep highest maxoccurs found - if (maxRange.compareTo(maxOccursInGroup) > 0) { - maxOccursInGroup = maxRange; - } - } - break; - } - // if an unbounded has been found then we are done - if (maxRange == UNBOUNDED) { - break; - } - } - - // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or - // the maximum part of the effective total range of any of the group particles in the group's {particles} is - // unbounded - if (maxRange != UNBOUNDED) { - // 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded - if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == UNBOUNDED) { - maxRange = UNBOUNDED; - } else { - // 3) the product of the particle's {max occurs} and the sum of the {max occurs} of every wildcard or element - // declaration particle in the group's {particles} and the maximum part of the effective total range of each of - // the group particles in the group's {particles} - maxRange = derivedModel.getMaxOccurs().multiply(maxOccursTotal.add(maxOccursInGroup)); - } - } - - return maxRange; - - } - - private static BigInteger getEffectiveMinRangeChoice(SchemaParticle derivedModel) { - // Schema Component Constraint: Effective Total Range (choice) - // The effective total range of a particle whose {term} is a group whose {compositor} is choice is a pair of - // minimum and maximum, as follows: - // MINIMUM - // The product of the particle's {min occurs} - // and the *minimum* of the {min occurs} of every wildcard or element - // declaration particle in the group's {particles} and the minimum part of the effective total range of each of - // the group particles in the group's {particles} (or 0 if there are no {particles}). - SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); - if (particleChildren.length == 0) - return BigInteger.ZERO; - BigInteger minRange = null; - // get the minimum of every wildcard or element - // total up the effective total range for each group - for (int i = 0; i < particleChildren.length; i++) { - SchemaParticle particle = particleChildren[i]; - switch (particle.getParticleType()) { - case SchemaParticle.WILDCARD: - case SchemaParticle.ELEMENT: - if (minRange == null || minRange.compareTo(particle.getMinOccurs()) > 0) { - minRange = particle.getMinOccurs(); - } - break; - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - BigInteger mrs = getEffectiveMinRangeAllSeq(particle); - if (minRange == null || minRange.compareTo(mrs) > 0) { - minRange = mrs; - } - break; - case SchemaParticle.CHOICE: - BigInteger mrc = getEffectiveMinRangeChoice(particle); - if (minRange == null || minRange.compareTo(mrc) > 0) { - minRange = mrc; - } - break; - } - } - if (minRange == null) - minRange = BigInteger.ZERO; - - // calculate the total - minRange = derivedModel.getMinOccurs().multiply(minRange); - return minRange; - } - - private static BigInteger getEffectiveMinRangeAllSeq(SchemaParticle derivedModel) { - BigInteger minRange = BigInteger.ZERO; - // Schema Component Constraint: Effective Total Range (all and sequence) - // The effective total range of a particle whose {term} is a group whose {compositor} is all or sequence is a - // pair of minimum and maximum, as follows: - // MINIMUM - // The product of the particle's {min occurs} - // and the *sum* of the {min occurs} of every wildcard or element - // declaration particle in the group's {particles} - // and the minimum part of the effective total range of each - // of the group particles in the group's {particles} (or 0 if there are no {particles}). - SchemaParticle[] particleChildren = derivedModel.getParticleChildren(); - BigInteger particleTotalMinOccurs = BigInteger.ZERO; - for (int i = 0; i < particleChildren.length; i++) { - SchemaParticle particle = particleChildren[i]; - switch (particle.getParticleType()) { - case SchemaParticle.WILDCARD: - case SchemaParticle.ELEMENT: - particleTotalMinOccurs = particleTotalMinOccurs.add(particle.getMinOccurs()); - break; - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - particleTotalMinOccurs = particleTotalMinOccurs.add(getEffectiveMinRangeAllSeq(particle)); - break; - case SchemaParticle.CHOICE: - particleTotalMinOccurs = particleTotalMinOccurs.add(getEffectiveMinRangeChoice(particle)); - break; - } - } - - minRange = derivedModel.getMinOccurs().multiply(particleTotalMinOccurs); - - return minRange; - } - - private static boolean nsSubset(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) { - // nsSubset is called when base: ANY, derived: ANY - assert baseModel.getParticleType() == SchemaParticle.WILDCARD; - assert derivedModel.getParticleType() == SchemaParticle.WILDCARD; - boolean nsSubset = false; - // For a wildcard particle to be a �valid restriction� of another wildcard particle all of the following must be true: - // 1 R's occurrence range must be a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). - if (occurrenceRangeOK(baseModel, derivedModel, errors, context)) { - // 2 R's {namespace constraint} must be an intensional subset of B's {namespace constraint} as defined - // by Wildcard Subset (�3.10.6). - if (baseModel.getWildcardSet().inverse().isDisjoint(derivedModel.getWildcardSet())) { - nsSubset = true; - } else { - nsSubset = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_NS_SUBST$WILDCARD_SUBSET, - new Object[] { printParticle(derivedModel), printParticle(baseModel) }, context)); - } - } else { - nsSubset = false; - // error already produced by occurrenceRangeOK - //errors.add(XmlError.forObject(formatNSIsNotSubsetError(baseModel, derivedModel), context)); - } - - - return nsSubset; - } - - private static boolean nsCompat(SchemaParticle baseModel, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { - // nsCompat is called when base: ANY, derived: ELEMENT - assert baseModel.getParticleType() == SchemaParticle.WILDCARD; - boolean nsCompat = false; - // For an element declaration particle to be a �valid restriction� of a wildcard particle all of the following must be true: - // 1 The element declaration's {target namespace} is �valid� with respect to the wildcard's {namespace constraint} - // as defined by Wildcard allows Namespace Name (�3.10.4). - if (baseModel.getWildcardSet().contains(derivedElement.getName())) { - // 2 R's occurrence range is a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). - if (occurrenceRangeOK(baseModel, (SchemaParticle) derivedElement, errors, context)) { - nsCompat = true; - } else { - // error already produced by occurrenceRangeOK - //errors.add(XmlError.forObject(formatOccurenceRangeMinError(baseModel, (SchemaParticle) derivedElement), context)); - } - } else { - nsCompat = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_NS_COMPAT$WILDCARD_VALID, - new Object[] { printParticle((SchemaParticle)derivedElement), printParticle(baseModel) }, - context)); - } - - - return nsCompat; - } - - private static boolean nameAndTypeOK(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { - // nameAndTypeOK called when base: ELEMENT and derived: ELEMENT - - // Schema Component Constraint: Particle Restriction OK (Elt:Elt -- NameAndTypeOK) - // 1 The declarations' {name}s and {target namespace}s are the same. - if (!((SchemaParticle)baseElement).canStartWithElement(derivedElement.getName())) { - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$NAME, - new Object[] { printParticle((SchemaParticle)derivedElement), printParticle((SchemaParticle)baseElement) }, context)); - return false; - } - - // 2 Either B's {nillable} is true or R's {nillable} is false. - if (!baseElement.isNillable() && derivedElement.isNillable()) { - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$NILLABLE, - new Object[] { printParticle((SchemaParticle)derivedElement), printParticle((SchemaParticle)baseElement) }, context)); - return false; - } - - // 3 R's occurrence range is a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6). - if (!occurrenceRangeOK((SchemaParticle) baseElement, (SchemaParticle) derivedElement, errors, context)) { - // error already produced - return false; - } - - // 4 either B's declaration's {value constraint} is absent, or is not fixed, - // or R's declaration's {value constraint} is fixed with the same value. - if (!checkFixed(baseElement, derivedElement, errors, context)) - { - // error already produced - return false; - } - - // 5 R's declaration's {identity-constraint definitions} is a subset of B's declaration's {identity-constraint definitions}, if any. - if (!checkIdentityConstraints(baseElement, derivedElement, errors, context)) - { - // error already produced - return false; - } - - // 7 R's {type definition} is validly derived given {extension, list, union} from B's {type definition} as - // defined by Type Derivation OK (Complex) (�3.4.6) or Type Derivation OK (Simple) (�3.14.6), as appropriate. - if (!typeDerivationOK(baseElement.getType(), derivedElement.getType(), errors, context)) - { - // error already produced - return false; - } - - // 6 R's declaration's {disallowed substitutions} is a superset of B's declaration's {disallowed substitutions}. - if (!blockSetOK(baseElement, derivedElement, errors, context)) - { - // error already produced - return false; - } - - return true; - } - - private static boolean blockSetOK(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection errors, XmlObject context) - { - if (baseElement.blockRestriction() && !derivedElement.blockRestriction()) - { - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS, - new Object[] { printParticle((SchemaParticle)derivedElement), "restriction", printParticle((SchemaParticle)baseElement) }, - context)); - return false; - } - if (baseElement.blockExtension() && !derivedElement.blockExtension()) - { - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS, - new Object[] { printParticle((SchemaParticle)derivedElement), "extension", printParticle((SchemaParticle)baseElement) }, - context)); - return false; - } - if (baseElement.blockSubstitution() && !derivedElement.blockSubstitution()) - { - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$DISALLOWED_SUBSTITUTIONS, - new Object[] { printParticle((SchemaParticle)derivedElement), "substitution", printParticle((SchemaParticle)baseElement) }, - context)); - return false; - } - return true; - } - - private static boolean typeDerivationOK(SchemaType baseType, SchemaType derivedType, Collection errors, XmlObject context){ - boolean typeDerivationOK = false; - // 1 If B and D are not the same type definition, then the {derivation method} of D must not be in the subset. - // 2 One of the following must be true: - // 2.1 B and D must be the same type definition. - // 2.2 B must be D's {base type definition}. - // 2.3 All of the following must be true: - // 2.3.1 D's {base type definition} must not be the �ur-type definition�. - // 2.3.2 The appropriate case among the following must be true: - // 2.3.2.1 If D's {base type definition} is complex, then it must be validly derived from B given the subset as defined by this constraint. - // 2.3.2.2 If D's {base type definition} is simple, then it must be validly derived from B given the subset as defined in Type Derivation OK (Simple) (�3.14.6). - // This line will check if derivedType is a subType of baseType (should handle all of the 2.xx checks above) - if (baseType.isAssignableFrom(derivedType)) { - // Ok derived type is subtype but need to make sure that all of the derivations between the two types are by - // Restriction. - typeDerivationOK = checkAllDerivationsForRestriction(baseType, derivedType, errors, context); - } else { - // derived type is not a sub-type of base type - typeDerivationOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$TYPE_VALID, - new Object[] { printType(derivedType), printType(baseType) }, context)); - } - - return typeDerivationOK; - } - - private static boolean checkAllDerivationsForRestriction(SchemaType baseType, SchemaType derivedType, Collection errors, XmlObject context) { - boolean allDerivationsAreRestrictions = true; - SchemaType currentType = derivedType; - - // XMLBEANS-66: if baseType is a union, check restriction is of one of the constituant types - Set possibleTypes = null; - if (baseType.getSimpleVariety() == SchemaType.UNION) - possibleTypes = new HashSet(Arrays.asList(baseType.getUnionConstituentTypes())); - - // run up the types hierarchy from derived Type to base Type and make sure that all are derived by - // restriction. If any are not then this is not a valid restriction. - while (!baseType.equals(currentType) && - possibleTypes != null && !possibleTypes.contains(currentType)) { - if (currentType.getDerivationType() == SchemaType.DT_RESTRICTION) { - currentType = currentType.getBaseType(); - } else { - allDerivationsAreRestrictions = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$TYPE_RESTRICTED, - new Object[] { printType(derivedType), printType(baseType), printType(currentType) }, context)); - break; - } - } - return allDerivationsAreRestrictions; - } - - private static boolean checkIdentityConstraints(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection errors, XmlObject context) { - // 5 R's declaration's {identity-constraint definitions} is a subset of B's declaration's {identity-constraint definitions}, if any. - boolean identityConstraintsOK = true; - - SchemaIdentityConstraint[] baseConstraints = baseElement.getIdentityConstraints(); - SchemaIdentityConstraint[] derivedConstraints = derivedElement.getIdentityConstraints(); - // cycle thru derived's identity constraints and check each to assure they in the array of base constraints - for (int i = 0; i < derivedConstraints.length; i++) { - SchemaIdentityConstraint derivedConstraint = derivedConstraints[i]; - if (checkForIdentityConstraintExistence(baseConstraints, derivedConstraint)) { - identityConstraintsOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$IDENTITY_CONSTRAINTS, - new Object[] { printParticle((SchemaParticle)derivedElement), printParticle((SchemaParticle)baseElement) }, - context)); - break; - } - } - return identityConstraintsOK; - } - - private static boolean checkForIdentityConstraintExistence(SchemaIdentityConstraint[] baseConstraints, SchemaIdentityConstraint derivedConstraint) { - // spin thru the base identity constraints check to see if derived constraint exists - boolean identityConstraintExists = false; - for (int i = 0; i < baseConstraints.length; i++) { - SchemaIdentityConstraint baseConstraint = baseConstraints[i]; - if (baseConstraint.getName().equals(derivedConstraint.getName())) { - identityConstraintExists = true; - break; - } - } - return identityConstraintExists; - } - - - private static boolean checkFixed(SchemaLocalElement baseModel, SchemaLocalElement derivedModel, Collection errors, XmlObject context) { - // 4 either B's declaration's {value constraint} is absent, or is not fixed, - // or R's declaration's {value constraint} is fixed with the same value. - boolean checkFixed = false; - if (baseModel.isFixed()) { - if (baseModel.getDefaultText().equals(derivedModel.getDefaultText())) { - // R's declaration's {value constraint} is fixed with the same value. - checkFixed = true; - } else { - // The derived element has a fixed value that is different than the base element - errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$FIXED, - new Object[] { printParticle((SchemaParticle)derivedModel), derivedModel.getDefaultText(), - printParticle((SchemaParticle)baseModel), baseModel.getDefaultText() }, - context)); - checkFixed = false; - } - } else { - // B's declaration's {value constraint} is absent, or is not fixed, - checkFixed = true; - } - return checkFixed; - } - - private static boolean occurrenceRangeOK(SchemaParticle baseParticle, SchemaParticle derivedParticle, Collection errors, XmlObject context) { - boolean occurrenceRangeOK = false; - // Note: in the following comments (from the schema spec) other is the baseModel - // 1 Its {min occurs} is greater than or equal to the other's {min occurs}. - if (derivedParticle.getMinOccurs().compareTo(baseParticle.getMinOccurs()) >= 0) { - // 2 one of the following must be true: - // 2.1 The other's {max occurs} is unbounded. - if (baseParticle.getMaxOccurs() == null) { - occurrenceRangeOK = true; - } else { - // 2.2 Both {max occurs} are numbers, and the particle's is less than or equal to the other's. - if (derivedParticle.getMaxOccurs() != null && baseParticle.getMaxOccurs() != null && - derivedParticle.getMaxOccurs().compareTo(baseParticle.getMaxOccurs()) <= 0) { - occurrenceRangeOK = true; - } else { - occurrenceRangeOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX, - new Object[] { printParticle(derivedParticle), printMaxOccurs(derivedParticle.getMaxOccurs()), - printParticle(baseParticle), printMaxOccurs(baseParticle.getMaxOccurs()) }, - context)); - } - } - } else { - occurrenceRangeOK = false; - errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MIN_GTE_MIN, - new Object[] { printParticle(derivedParticle), derivedParticle.getMinOccurs().toString(), - printParticle(baseParticle), baseParticle.getMinOccurs().toString() }, - context)); - } - return occurrenceRangeOK; - } - - private static String printParticles(List parts) - { - return printParticles((SchemaParticle[])parts.toArray(new SchemaParticle[parts.size()])); - } - - private static String printParticles(SchemaParticle[] parts) - { - return printParticles(parts, 0, parts.length); - } - - private static String printParticles(SchemaParticle[] parts, int start) - { - return printParticles(parts, start, parts.length); - } - - private static String printParticles(SchemaParticle[] parts, int start, int end) - { - StringBuffer buf = new StringBuffer(parts.length * 30); - for (int i = start; i < end; ) - { - buf.append(printParticle(parts[i])); - if (++i != end) - buf.append(", "); - } - return buf.toString(); - } - - private static String printParticle(SchemaParticle part) - { - switch (part.getParticleType()) { - case SchemaParticle.ALL: - return ""; - case SchemaParticle.CHOICE: - return ""; - case SchemaParticle.ELEMENT: - return ""; - case SchemaParticle.SEQUENCE: - return ""; - case SchemaParticle.WILDCARD: - return ""; - default : - return "??"; - } - } - - private static String printMaxOccurs(BigInteger bi) - { - if (bi == null) - return "unbounded"; - return bi.toString(); - } - - private static String printType(SchemaType type) - { - if (type.getName() != null) - return QNameHelper.pretty(type.getName()); - return type.toString(); - } - - private static void checkSubstitutionGroups(SchemaGlobalElement[] elts) - { - StscState state = StscState.get(); - - for (int i = 0 ; i < elts.length ; i++) - { - SchemaGlobalElement elt = elts[i]; - SchemaGlobalElement head = elt.substitutionGroup(); - - if (head != null) - { - SchemaType headType = head.getType(); - SchemaType tailType = elt.getType(); - XmlObject parseTree = ((SchemaGlobalElementImpl)elt)._parseObject; - - if (! headType.isAssignableFrom(tailType)) - { - state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_VALID, - new Object[] {QNameHelper.pretty(elt.getName()), - QNameHelper.pretty(head.getName())}, - parseTree); - } - else if (head.finalExtension() && head.finalRestriction()) - { - state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_FINAL, - new Object[] {QNameHelper.pretty(elt.getName()), - QNameHelper.pretty(head.getName()), - "#all"}, parseTree); - } - else if (! headType.equals(tailType)) - { - if (head.finalExtension() && - tailType.getDerivationType() == SchemaType.DT_EXTENSION) - { - state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_FINAL, - new Object[] {QNameHelper.pretty(elt.getName()), - QNameHelper.pretty(head.getName()), - "extension"}, parseTree); - } - else if (head.finalRestriction() && - tailType.getDerivationType() == SchemaType.DT_RESTRICTION) - { - state.error(XmlErrorCodes.ELEM_PROPERTIES$SUBSTITUTION_FINAL, - new Object[] {QNameHelper.pretty(elt.getName()), - QNameHelper.pretty(head.getName()), - "restriction"}, parseTree); - } - } - } - - } - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java deleted file mode 100644 index 5f2b758..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java +++ /dev/null @@ -1,2128 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import java.math.BigInteger; -import java.util.*; -import java.util.List; - -import org.apache.xmlbeans.impl.xb.xsdschema.*; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; -import org.apache.xmlbeans.impl.xb.xsdschema.AnyDocument.Any; -import javax.xml.namespace.QName; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.QNameSetBuilder; -import org.apache.xmlbeans.XmlInteger; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.XmlNonNegativeInteger; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaLocalElement; -import org.apache.xmlbeans.QNameSetSpecification; - -public class StscComplexTypeResolver -{ - public static Group getContentModel(ComplexType parseCt) - { - if (parseCt.getAll() != null) - return parseCt.getAll(); - - if (parseCt.getSequence() != null) - return parseCt.getSequence(); - - if (parseCt.getChoice() != null) - return parseCt.getChoice(); - - if (parseCt.getGroup() != null) - return parseCt.getGroup(); - - return null; - } - - public static Group getContentModel(ComplexRestrictionType parseRest) - { - if (parseRest.getAll() != null) - return parseRest.getAll(); - - if (parseRest.getSequence() != null) - return parseRest.getSequence(); - - if (parseRest.getChoice() != null) - return parseRest.getChoice(); - - if (parseRest.getGroup() != null) - return parseRest.getGroup(); - - return null; - - } - - public static Group getContentModel(ExtensionType parseExt) - { - if (parseExt.getAll() != null) - return parseExt.getAll(); - - if (parseExt.getSequence() != null) - return parseExt.getSequence(); - - if (parseExt.getChoice() != null) - return parseExt.getChoice(); - - if (parseExt.getGroup() != null) - return parseExt.getGroup(); - - return null; - - } - - static Schema getSchema(XmlObject o) - { - XmlCursor c = o.newCursor(); - - try - { - while ( c.toParent() ) - { - o = c.getObject(); - - if (o.schemaType().equals(Schema.type)) - return (Schema) o; - } - } - finally - { - c.dispose(); - } - - return null; - } - - public static void resolveComplexType(SchemaTypeImpl sImpl) - { - ComplexType parseCt = (ComplexType)sImpl.getParseObject(); - StscState state = StscState.get(); - Schema schema = getSchema(parseCt); - - // Set abstract & final flags - boolean abs = parseCt.isSetAbstract() ? parseCt.getAbstract() : false; - boolean finalExt = false; - boolean finalRest = false; - boolean finalList = false; - boolean finalUnion = false; - - Object ds = null; - if (parseCt.isSetFinal()) - { - ds = parseCt.getFinal(); - } - // Inspect the final default attribute on the schema - else if (schema != null && schema.isSetFinalDefault()) - { - ds = schema.getFinalDefault(); - } - - if (ds != null) - { - if (ds instanceof String && ds.equals("#all")) - { - // #ALL value - finalExt = finalRest = finalList = finalUnion = true; - } - else if (ds instanceof List) - { - if (((List)ds).contains("extension")) - finalExt = true; - - if (((List)ds).contains("restriction")) - finalRest = true; - -// Since complex types don't participate in list and unions, these can remain -// false. Perhaps we should throw an error. - -// if (((List)ds).contains("list")) -// finalList = true; -// -// if (((List)ds).contains("union")) -// finalUnion = true; - } - } - - sImpl.setAbstractFinal(abs, finalExt, finalRest, finalList, finalUnion); - - // Set block flags - boolean blockExt = false; - boolean blockRest = false; - Object block = null; - - if (parseCt.isSetBlock()) - block = parseCt.getBlock(); - else if (schema != null && schema.isSetBlockDefault()) - block = schema.getBlockDefault(); - - if (block != null) - { - if (block instanceof String && block.equals("#all")) - { - // #ALL value - blockExt = blockRest = true; - } - else if (block instanceof List) - { - if (((List)block).contains("extension")) - blockExt = true; - if (((List)block).contains("restriction")) - blockRest = true; - } - } - - sImpl.setBlock(blockExt, blockRest); - - // Verify: have simpleContent, complexContent, or direct stuff - ComplexContentDocument.ComplexContent parseCc = parseCt.getComplexContent(); - SimpleContentDocument.SimpleContent parseSc = parseCt.getSimpleContent(); - Group parseGroup = getContentModel(parseCt); - int count = - (parseCc != null ? 1 : 0) + - (parseSc != null ? 1 : 0) + - (parseGroup != null ? 1 : 0); - if (count > 1) - { - // KHK: s4s should catch this? - state.error("A complex type must define either a content model, " + - "or a simpleContent or complexContent derivation: " + - "more than one found.", - XmlErrorCodes.REDUNDANT_CONTENT_MODEL, parseCt); - // recovery: treat it as the first of complexContent, simpleContent, model - parseGroup = null; - if (parseCc != null && parseSc != null) - parseSc = null; - } - - if (parseCc != null) - { - // KHK: s4s should catch this? - if (parseCc.getExtension() != null && parseCc.getRestriction() != null) - state.error("Restriction conflicts with extension", XmlErrorCodes.REDUNDANT_CONTENT_MODEL, parseCc.getRestriction()); - - // Mixed can be specified in two places: the rules are that Cc wins over Ct if present - // http://www.w3.org/TR/xmlschema-1/#c-mve - boolean mixed = parseCc.isSetMixed() ? parseCc.getMixed() : parseCt.getMixed(); - - if (parseCc.getExtension() != null) - resolveCcExtension(sImpl, parseCc.getExtension(), mixed); - else if (parseCc.getRestriction() != null) - resolveCcRestriction(sImpl, parseCc.getRestriction(), mixed); - else - { - // KHK: s4s should catch this? - state.error("Missing restriction or extension", XmlErrorCodes.MISSING_RESTRICTION_OR_EXTENSION, parseCc); - resolveErrorType(sImpl); - } - return; - } - else if (parseSc != null) - { - // KHK: s4s should catch this? - if (parseSc.getExtension() != null && parseSc.getRestriction() != null) - state.error("Restriction conflicts with extension", XmlErrorCodes.REDUNDANT_CONTENT_MODEL, parseSc.getRestriction()); - - if (parseSc.getExtension() != null) - resolveScExtension(sImpl, parseSc.getExtension()); - else if (parseSc.getRestriction() != null) - resolveScRestriction(sImpl, parseSc.getRestriction()); - else - { - // KHK: s4s should catch this? - state.error("Missing restriction or extension", XmlErrorCodes.MISSING_RESTRICTION_OR_EXTENSION, parseSc); - resolveErrorType(sImpl); - } - return; - } - else - resolveBasicComplexType(sImpl); - } - - static void resolveErrorType(SchemaTypeImpl sImpl) - { - throw new RuntimeException("This type of error recovery not yet implemented."); - } - - private static SchemaType.Ref[] makeRefArray(Collection typeList) - { - SchemaType.Ref[] result = new SchemaType.Ref[typeList.size()]; - int j = 0; - for (Iterator i = typeList.iterator(); i.hasNext(); j++) - result[j] = ((SchemaType)i.next()).getRef(); - return result; - } - - - static void resolveBasicComplexType(SchemaTypeImpl sImpl) - { - List anonymousTypes = new ArrayList(); - ComplexType parseTree = (ComplexType)sImpl.getParseObject(); - String targetNamespace = sImpl.getTargetNamespace(); - boolean chameleon = (sImpl.getChameleonNamespace() != null); - Group parseGroup = getContentModel(parseTree); - - if (sImpl.isRedefinition()) - { - StscState.get().error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, - new Object[] { "" }, parseTree); - // recovery: oh well. - } - - int particleCode = translateParticleCode(parseGroup); - - // used to ensure consistency (doesn't become part of the result) - Map elementModel = new LinkedHashMap(); - - // build content model and anonymous types - SchemaParticle contentModel = translateContentModel(sImpl, - parseGroup, targetNamespace, chameleon, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), - particleCode, anonymousTypes, elementModel, false, null); - - // detect the nonempty "all" case (empty doesn't count - it needs to be eliminated to match XSD test cases) - boolean isAll = contentModel != null && contentModel.getParticleType() == SchemaParticle.ALL; - - // build attr model and anonymous types - SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl(); - translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), - anonymousTypes, sImpl, null, attrModel, null, true, null); - - // summarize wildcard information - WildcardResult wcElt = summarizeEltWildcards(contentModel); - WildcardResult wcAttr = summarizeAttrWildcards(attrModel); - - // build state machine and verify that content model is deterministic - if (contentModel != null) - { - buildStateMachine(contentModel); - if (!StscState.get().noUpa() && !((SchemaParticleImpl)contentModel).isDeterministic()) - StscState.get().error(XmlErrorCodes.UNIQUE_PARTICLE_ATTRIBUTION, null, parseGroup); - } - - // build property model - // emitDBG("Building content Model for " + sImpl); - Map elementPropertyModel = buildContentPropertyModelByQName(contentModel, sImpl); - - // add attribute property model - Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); - - // figure out content type - int complexVariety = - parseTree.getMixed() - ? SchemaType.MIXED_CONTENT - : contentModel == null - ? SchemaType.EMPTY_CONTENT - : SchemaType.ELEMENT_CONTENT; - - // now fill in the actual schema type implementation - sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef()); - sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_TYPE.getBaseDepth() + 1); - sImpl.setDerivationType(SchemaType.DT_EXTENSION); - sImpl.setComplexTypeVariety(complexVariety); - sImpl.setContentModel(contentModel, attrModel, elementPropertyModel, attributePropertyModel, isAll); - sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); - sImpl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); - } - - static void resolveCcRestriction(SchemaTypeImpl sImpl, ComplexRestrictionType parseTree, boolean mixed) - { - StscState state = StscState.get(); - String targetNamespace = sImpl.getTargetNamespace(); - boolean chameleon = (sImpl.getChameleonNamespace() != null); - - // BUGBUG: NOT YET REALLY IMPLEMENTED - // throw new RuntimeException("Not yet implemented."); - - SchemaType baseType; - if (parseTree.getBase() == null) - { - // KHK: s4s - state.error("A complexContent must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); - baseType = null; // recovery: no inheritance. - } - else - { - if (sImpl.isRedefinition()) - { - baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); - if (baseType != null && !baseType.getName().equals(sImpl.getName())) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, - new Object[] { "", - QNameHelper.pretty(baseType.getName()), - QNameHelper.pretty(sImpl.getName()) - }, - parseTree); - } - } - else - { - baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); - } - - if (baseType == null) - state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); - } - - if (baseType == null) - baseType = BuiltinSchemaTypeSystem.ST_ANY_TYPE; - - if (baseType != null && baseType.finalRestriction()) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$FINAL, - new Object[] { QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName()) }, - parseTree.xgetBase()); - // recovery: just keep going - } - - // Recursion - if (baseType != null) - { - if (!StscResolver.resolveType((SchemaTypeImpl)baseType)) - baseType = null; // circular dependency: no inheritance - } - - List anonymousTypes = new ArrayList(); - Group parseEg = getContentModel(parseTree); - - // detect the "all" case - int particleCode = translateParticleCode(parseEg); - - // used to ensure consistency (doesn't become part of the result) - Map elementModel = new LinkedHashMap(); - - // build content model and anonymous types - SchemaParticle contentModel = translateContentModel( sImpl, - parseEg, targetNamespace, chameleon, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), - particleCode, anonymousTypes, elementModel, false, null); - - // detect the nonempty "all" case (empty doesn't count - it needs to be eliminated to match XSD test cases) - boolean isAll = contentModel != null && contentModel.getParticleType() == SchemaParticle.ALL; - - // build attr model and anonymous types - SchemaAttributeModelImpl attrModel; - if (baseType == null) - attrModel = new SchemaAttributeModelImpl(); - else - attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); - translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), - anonymousTypes, sImpl, null, attrModel, baseType, false, null); - - // summarize wildcard information - WildcardResult wcElt = summarizeEltWildcards(contentModel); - WildcardResult wcAttr = summarizeAttrWildcards(attrModel); - - // build state machine and verify that content model is deterministic - if (contentModel != null) - { - buildStateMachine(contentModel); - if (!StscState.get().noUpa() && !((SchemaParticleImpl)contentModel).isDeterministic()) - StscState.get().error(XmlErrorCodes.UNIQUE_PARTICLE_ATTRIBUTION, null, parseEg); - } - - // build property model - // emitDBG("Building content Model for " + sImpl); - Map elementPropertyModel = buildContentPropertyModelByQName(contentModel, sImpl); - - // add attribute property model - Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); - - // compute empty/element/mixed - // fix for XMLBEANS-414 - int complexVariety = (mixed ? SchemaType.MIXED_CONTENT : - (contentModel == null ? SchemaType.EMPTY_CONTENT : SchemaType.ELEMENT_CONTENT)); - - // now fill in the actual schema type implementation - sImpl.setBaseTypeRef(baseType.getRef()); - sImpl.setBaseDepth(((SchemaTypeImpl)baseType).getBaseDepth() + 1); - sImpl.setDerivationType(SchemaType.DT_RESTRICTION); - sImpl.setComplexTypeVariety(complexVariety); - sImpl.setContentModel(contentModel, attrModel, elementPropertyModel, attributePropertyModel, isAll); - sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); - sImpl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); - } - - static Map extractElementModel(SchemaType sType) - { - Map elementModel = new HashMap(); - if (sType != null) - { - SchemaProperty[] sProps = sType.getProperties(); - for (int i = 0; i < sProps.length; i++) - { - if (sProps[i].isAttribute()) - continue; - elementModel.put(sProps[i].getName(), - sProps[i].getType()); - } - } - return elementModel; - } - - static void resolveCcExtension(SchemaTypeImpl sImpl, ExtensionType parseTree, boolean mixed) - { - SchemaType baseType; - StscState state = StscState.get(); - String targetNamespace = sImpl.getTargetNamespace(); - boolean chameleon = (sImpl.getChameleonNamespace() != null); - - if (parseTree.getBase() == null) - { - // KHK: s4s - state.error("A complexContent must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); - baseType = null; // recovery: no inheritance. - } - else - { - if (sImpl.isRedefinition()) - { - baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); - if (baseType != null && !baseType.getName().equals(sImpl.getName())) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, - new Object[] { "", - QNameHelper.pretty(baseType.getName()), - QNameHelper.pretty(sImpl.getName()) - }, - parseTree); - } - } - else - { - baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); - } - if (baseType == null) - state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); - } - - // Recursion - if (baseType != null) - { - if (!StscResolver.resolveType((SchemaTypeImpl)baseType)) - baseType = null; // circular dependency: no inheritance - } - - if (baseType != null && baseType.isSimpleType()) - { - state.recover(XmlErrorCodes.SCHEMA_COMPLEX_TYPE$COMPLEX_CONTENT, - new Object[] { QNameHelper.pretty(baseType.getName()) }, - parseTree.xgetBase()); - baseType = null; // recovery: no inheritance. - } - - if (baseType != null && baseType.finalExtension()) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$FINAL, - new Object[] { QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName()) }, - parseTree.xgetBase()); - // recovery: just keep going - } - - // get base content model - SchemaParticle baseContentModel = (baseType == null ? null : baseType.getContentModel()); - // TODO: attribute model also - - List anonymousTypes = new ArrayList(); - Map baseElementModel = extractElementModel(baseType); - Group parseEg = getContentModel(parseTree); - - if (baseType != null && - (baseType.getContentType() == SchemaType.SIMPLE_CONTENT)) - if (parseEg != null) - { - // if this type has complexContent, baseType is complexType - // but with non-empty simpleContent then this type cannot - // add extra elements - state.recover(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$EXTENDING_SIMPLE_CONTENT, - new Object[] { QNameHelper.pretty(baseType.getName()) }, - parseTree.xgetBase()); - baseType = null; // recovery: no inheritance. - } - else - { - // No extra elements, the type is a complex type with simple content - resolveScExtensionPart2(sImpl, baseType, parseTree, targetNamespace, chameleon); - return; - } - - // build extension model - SchemaParticle extensionModel = translateContentModel(sImpl, - parseEg, targetNamespace, chameleon, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), - translateParticleCode(parseEg), anonymousTypes, baseElementModel, false, null); - - // apply rule #2 near http://www.w3.org/TR/xmlschema-1/#c-mve: empty ext model -> mixed taken from base - if (extensionModel == null && !mixed) - mixed = (baseType != null && baseType.getContentType() == SchemaType.MIXED_CONTENT); - - // apply Derivation Valid (Extension) rule 1.4.2.2 - if (baseType != null && (baseType.getContentType() != SchemaType.EMPTY_CONTENT) && - ((baseType.getContentType() == SchemaType.MIXED_CONTENT) != mixed)) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$BOTH_ELEMEMENT_OR_MIXED, null, parseTree.xgetBase()); - // recovery: just keep going - } - - // detect the "all" base case - if (baseType != null && baseType.hasAllContent() && extensionModel != null) - { - // KHK: which rule? cos-particle-extend.2 or cos-all-limited.1.2. I think the limited one. - state.error("Cannot extend a type with 'all' content model", XmlErrorCodes.CANNOT_EXTEND_ALL, parseTree.xgetBase()); - extensionModel = null; // recovery: drop extension - } - - // build content model and anonymous types - SchemaParticle contentModel = extendContentModel(baseContentModel, extensionModel, parseTree); - - // detect the nonempty "all" case (empty doesn't count - it needs to be eliminated to match XSD test cases) - boolean isAll = contentModel != null && contentModel.getParticleType() == SchemaParticle.ALL; - - // build attr model and anonymous types - SchemaAttributeModelImpl attrModel; - if (baseType == null) - attrModel = new SchemaAttributeModelImpl(); - else - attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); - translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), - anonymousTypes, sImpl, null, attrModel, baseType, true, null); - - // summarize wildcard information - WildcardResult wcElt = summarizeEltWildcards(contentModel); - WildcardResult wcAttr = summarizeAttrWildcards(attrModel); - - // build state machine and verify that content model is deterministic - if (contentModel != null) - { - buildStateMachine(contentModel); - if (!StscState.get().noUpa() && !((SchemaParticleImpl)contentModel).isDeterministic()) - StscState.get().error(XmlErrorCodes.UNIQUE_PARTICLE_ATTRIBUTION, null, parseEg); - } - - // build property model - // emitDBG("Building content Model for " + sImpl); - Map elementPropertyModel = buildContentPropertyModelByQName(contentModel, sImpl); - - // add attribute property model - Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); - - // compute empty/element/mixed - int complexVariety; - if (contentModel == null && baseType != null && - baseType.getContentType() == SchemaType.SIMPLE_CONTENT) - { - complexVariety = SchemaType.SIMPLE_CONTENT; - sImpl.setContentBasedOnTypeRef(baseType.getContentBasedOnType().getRef()); - } - else - complexVariety = ( mixed ? SchemaType.MIXED_CONTENT : - (contentModel == null ? SchemaType.EMPTY_CONTENT : SchemaType.ELEMENT_CONTENT)); - - // now fill in the actual schema type implementation - if (baseType == null) - baseType = XmlObject.type; - sImpl.setBaseTypeRef(baseType.getRef()); - sImpl.setBaseDepth(((SchemaTypeImpl)baseType).getBaseDepth() + 1); - sImpl.setDerivationType(SchemaType.DT_EXTENSION); - sImpl.setComplexTypeVariety(complexVariety); - sImpl.setContentModel(contentModel, attrModel, elementPropertyModel, attributePropertyModel, isAll); - sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); - sImpl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards); - } - - static void resolveScRestriction(SchemaTypeImpl sImpl, SimpleRestrictionType parseTree) - { - SchemaType baseType; - SchemaType contentType = null; - StscState state = StscState.get(); - String targetNamespace = sImpl.getTargetNamespace(); - boolean chameleon = (sImpl.getChameleonNamespace() != null); - List anonymousTypes = new ArrayList(); - if (parseTree.getSimpleType() != null) - { - LocalSimpleType typedef = parseTree.getSimpleType(); - SchemaTypeImpl anonType = StscTranslator. - translateAnonymousSimpleType(typedef, targetNamespace, chameleon, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), - anonymousTypes, sImpl); - contentType = anonType; - } - if (parseTree.getBase() == null) - { - state.error("A simpleContent restriction must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - else - { - if (sImpl.isRedefinition()) - { - baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); - if (baseType != null && !baseType.getName().equals(sImpl.getName())) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, - new Object[] { "", - QNameHelper.pretty(baseType.getName()), - QNameHelper.pretty(sImpl.getName()) - }, - parseTree); - } - } - else - { - baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); - } - if (baseType == null) - { - state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - } - - // Recursion - StscResolver.resolveType((SchemaTypeImpl)baseType); - if (contentType != null) - StscResolver.resolveType((SchemaTypeImpl)contentType); - else - contentType = baseType; - - if (baseType.isSimpleType()) - { - // src-ct.2: complex types with simple content cannot restrict simple types - state.recover(XmlErrorCodes.COMPLEX_TYPE_PROPERTIES$SIMPLE_TYPE_EXTENSION, - new Object[] { QNameHelper.pretty(baseType.getName()) }, - parseTree); - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - else if (baseType.getContentType() != SchemaType.SIMPLE_CONTENT && - contentType == null) - { - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - - if (baseType != null && baseType.finalRestriction()) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$FINAL, - new Object[] { QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName()) }, - parseTree.xgetBase()); - // recovery: just keep going - } - - // build attr model and anonymous types - SchemaAttributeModelImpl attrModel; - if (baseType == null) - attrModel = new SchemaAttributeModelImpl(); - else - attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); - translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), - anonymousTypes, sImpl, null, attrModel, baseType, false, null); - - // summarize wildcard information - WildcardResult wcAttr = summarizeAttrWildcards(attrModel); - - // add attribute property model - Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); - - // now fill in the actual schema type implementation - sImpl.setBaseTypeRef(baseType.getRef()); - sImpl.setBaseDepth(((SchemaTypeImpl)baseType).getBaseDepth() + 1); - sImpl.setContentBasedOnTypeRef(contentType.getRef()); - sImpl.setDerivationType(SchemaType.DT_RESTRICTION); - sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); - sImpl.setWildcardSummary(QNameSet.EMPTY, false, wcAttr.typedWildcards, wcAttr.hasWildcards); - sImpl.setComplexTypeVariety(SchemaType.SIMPLE_CONTENT); - sImpl.setContentModel(null, attrModel, null, attributePropertyModel, false); - sImpl.setSimpleTypeVariety(contentType.getSimpleVariety()); - sImpl.setPrimitiveTypeRef(contentType.getPrimitiveType() == null ? null : contentType.getPrimitiveType().getRef()); - switch (sImpl.getSimpleVariety()) - { - case SchemaType.LIST: - sImpl.setListItemTypeRef(contentType.getListItemType().getRef()); - break; - - case SchemaType.UNION: - sImpl.setUnionMemberTypeRefs(makeRefArray(Arrays.asList(contentType.getUnionMemberTypes()))); - break; - } - - // deal with facets - StscSimpleTypeResolver.resolveFacets(sImpl, parseTree, (SchemaTypeImpl) contentType); - - // now compute our intrinsic properties - StscSimpleTypeResolver.resolveFundamentalFacets(sImpl); - } - - static void resolveScExtension(SchemaTypeImpl sImpl, SimpleExtensionType parseTree) - { - SchemaType baseType; - StscState state = StscState.get(); - String targetNamespace = sImpl.getTargetNamespace(); - boolean chameleon = (sImpl.getChameleonNamespace() != null); - if (parseTree.getBase() == null) - { - state.error("A simpleContent extension must define a base type", XmlErrorCodes.MISSING_BASE, parseTree); - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - else - { - if (sImpl.isRedefinition()) - { - baseType = state.findRedefinedGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), sImpl); - if (baseType != null && !baseType.getName().equals(sImpl.getName())) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, - new Object[] { "", - QNameHelper.pretty(baseType.getName()), - QNameHelper.pretty(sImpl.getName()) - }, - parseTree); - } - } - else - { - baseType = state.findGlobalType(parseTree.getBase(), sImpl.getChameleonNamespace(), targetNamespace); - } - if (baseType == null) - { - state.notFoundError(parseTree.getBase(), SchemaType.TYPE, parseTree.xgetBase(), true); - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - } - - // Recursion - StscResolver.resolveType((SchemaTypeImpl)baseType); - - if (!baseType.isSimpleType() && baseType.getContentType() != SchemaType.SIMPLE_CONTENT) - { - // src-ct.2: complex types with simple content can only extend simple types - state.error(XmlErrorCodes.SCHEMA_COMPLEX_TYPE$SIMPLE_CONTENT, - new Object[] { QNameHelper.pretty(baseType.getName()) } , - parseTree); - // recovery: extends ANY_SIMPLE type - baseType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - - if (baseType != null && baseType.finalExtension()) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_EXTENSION$FINAL, - new Object[] { QNameHelper.pretty(baseType.getName()), QNameHelper.pretty(sImpl.getName()) }, - parseTree.xgetBase()); - // recovery: just keep going - } - - resolveScExtensionPart2(sImpl, baseType, parseTree, targetNamespace, chameleon); - } - - static void resolveScExtensionPart2(SchemaTypeImpl sImpl, SchemaType baseType, ExtensionType parseTree, - String targetNamespace, boolean chameleon) - { - // build attr model and anonymous types - List anonymousTypes = new ArrayList(); - SchemaAttributeModelImpl attrModel; - attrModel = new SchemaAttributeModelImpl(baseType.getAttributeModel()); - translateAttributeModel(parseTree, targetNamespace, chameleon, sImpl.getAttFormDefault(), anonymousTypes, sImpl, null, attrModel, baseType, true, null); - - // summarize wildcard information - WildcardResult wcAttr = summarizeAttrWildcards(attrModel); - - // add attribute property model - Map attributePropertyModel = buildAttributePropertyModelByQName(attrModel, sImpl); - - // now fill in the actual schema type implementation - sImpl.setBaseTypeRef(baseType.getRef()); - sImpl.setBaseDepth(((SchemaTypeImpl)baseType).getBaseDepth() + 1); - sImpl.setContentBasedOnTypeRef(baseType.getRef()); - sImpl.setDerivationType(SchemaType.DT_EXTENSION); - sImpl.setAnonymousTypeRefs(makeRefArray(anonymousTypes)); - sImpl.setWildcardSummary(QNameSet.EMPTY, false, wcAttr.typedWildcards, wcAttr.hasWildcards); - sImpl.setComplexTypeVariety(SchemaType.SIMPLE_CONTENT); - sImpl.setContentModel(null, attrModel, null, attributePropertyModel, false); - sImpl.setSimpleTypeVariety(baseType.getSimpleVariety()); - sImpl.setPrimitiveTypeRef(baseType.getPrimitiveType() == null ? null : baseType.getPrimitiveType().getRef()); - switch (sImpl.getSimpleVariety()) - { - case SchemaType.LIST: - sImpl.setListItemTypeRef(baseType.getListItemType().getRef()); - break; - - case SchemaType.UNION: - sImpl.setUnionMemberTypeRefs(makeRefArray(Arrays.asList(baseType.getUnionMemberTypes()))); - break; - } - - // deal with facets - StscSimpleTypeResolver.resolveFacets(sImpl, null, (SchemaTypeImpl)baseType); - - // now compute our intrinsic properties - StscSimpleTypeResolver.resolveFundamentalFacets(sImpl); - } - - static class WildcardResult - { - WildcardResult(QNameSet typedWildcards, boolean hasWildcards) - { - this.typedWildcards = typedWildcards; - this.hasWildcards = hasWildcards; - } - QNameSet typedWildcards; - boolean hasWildcards; - } - - static WildcardResult summarizeAttrWildcards(SchemaAttributeModel attrModel) - { - if (attrModel.getWildcardProcess() == SchemaAttributeModel.NONE) - return new WildcardResult(QNameSet.EMPTY, false); - if (attrModel.getWildcardProcess() == SchemaAttributeModel.SKIP) - return new WildcardResult(QNameSet.EMPTY, true); - return new WildcardResult(attrModel.getWildcardSet(), true); - } - - static WildcardResult summarizeEltWildcards(SchemaParticle contentModel) - { - if (contentModel == null) - { - return new WildcardResult(QNameSet.EMPTY, false); - } - - switch (contentModel.getParticleType()) - { - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - case SchemaParticle.CHOICE: - QNameSetBuilder set = new QNameSetBuilder(); - boolean hasWildcards = false; - for (int i = 0; i < contentModel.countOfParticleChild(); i++) - { - WildcardResult inner = summarizeEltWildcards(contentModel.getParticleChild(i)); - set.addAll(inner.typedWildcards); - hasWildcards |= inner.hasWildcards; - } - return new WildcardResult(set.toQNameSet(), hasWildcards); - case SchemaParticle.WILDCARD: - return new WildcardResult( - (contentModel.getWildcardProcess() == SchemaParticle.SKIP) ? - QNameSet.EMPTY : contentModel.getWildcardSet(), true); - // otherwise fallthrough - - default: - return new WildcardResult(QNameSet.EMPTY, false); - } - } - - static void translateAttributeModel(XmlObject parseTree, - String targetNamespace, boolean chameleon, String formDefault, - List anonymousTypes, SchemaType outerType, - Set seenAttributes, SchemaAttributeModelImpl result, - SchemaType baseType, boolean extension, - SchemaAttributeGroupImpl redefinitionFor) - { - StscState state = StscState.get(); - if (seenAttributes == null) - seenAttributes = new HashSet(); - boolean seenWildcard = false; - boolean seenRedefinition = false; - SchemaAttributeModel baseModel = null; - if (baseType != null) - baseModel = baseType.getAttributeModel(); - - XmlCursor cur = parseTree.newCursor(); - - for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) - { - switch (translateAttributeCode(cur.getName())) - { - case ATTRIBUTE_CODE: - { - Attribute xsdattr = (Attribute)cur.getObject(); - - SchemaLocalAttribute sAttr = StscTranslator.translateAttribute(xsdattr, targetNamespace, formDefault, chameleon, anonymousTypes, outerType, baseModel, true); - if (sAttr == null) - continue; - - if (seenAttributes.contains(sAttr.getName())) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_PROPERTIES$DUPLICATE_ATTRIBUTE, - new Object[] { QNameHelper.pretty(sAttr.getName()), QNameHelper.pretty(outerType.getName()) }, - xsdattr.xgetName()); - continue; // ignore the duplicate attr - } - - seenAttributes.add(sAttr.getName()); - - if (baseModel != null) - { - SchemaLocalAttribute baseAttr = baseModel.getAttribute(sAttr.getName()); - if (baseAttr == null) - { - if (!extension) - { - if (!baseModel.getWildcardSet().contains(sAttr.getName())) - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ATTR_IN_BASE_WILDCARD_SET, - new Object[] { QNameHelper.pretty(sAttr.getName()), QNameHelper.pretty(outerType.getName()) }, xsdattr); - } - } - else - { - if (extension) - { - // KHK: cos-ct-extends.1.2? - if (sAttr.getUse() == SchemaLocalAttribute.PROHIBITED) - state.error("An extension cannot prohibit an attribute from the base type; use restriction instead.", XmlErrorCodes.DUPLICATE_ATTRIBUTE_NAME, xsdattr.xgetUse()); - } - else - { - if (sAttr.getUse() != SchemaLocalAttribute.REQUIRED) - { - if (baseAttr.getUse() == SchemaLocalAttribute.REQUIRED) - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ATTR_REQUIRED, - new Object[] { QNameHelper.pretty(sAttr.getName()), QNameHelper.pretty(outerType.getName()) }, xsdattr); - - if (sAttr.getUse() == SchemaLocalAttribute.PROHIBITED) - result.removeProhibitedAttribute(sAttr.getName()); - } - } - } - } - - if (sAttr.getUse() != SchemaLocalAttribute.PROHIBITED) - { - result.addAttribute(sAttr); - } - else - { - // attribute is prohibited. If it has an anonymous type remove - // it from the list (this will prevent inclusion of any anonymous - // types defined within the prohibited attribute which would - // otherwise attempt to refer to the prohibited attribute at - // save() time) - SchemaType attrType = sAttr.getType(); - if (anonymousTypes != null && anonymousTypes.contains(attrType)) - { - anonymousTypes.remove(attrType); - } - } - - if (sAttr.getDefaultText() != null && !sAttr.isFixed()) - { - if (sAttr.getUse() != SchemaLocalAttribute.OPTIONAL) - state.error(XmlErrorCodes.SCHEMA_ATTR$DEFAULT_AND_USE_OPTIONAL, - new Object[] { QNameHelper.pretty(sAttr.getName()) }, xsdattr); - } - - - break; - } - case ANY_ATTRIBUTE_CODE: - { - Wildcard xsdwc = (Wildcard)cur.getObject(); - if (seenWildcard) - { - // KHK: ? - state.error("Only one attribute wildcard allowed", XmlErrorCodes.DUPLICATE_ANY_ATTRIBUTE, xsdwc); - continue; // ignore the extra wildcard - } - seenWildcard = true; - NamespaceList nsList = xsdwc.xgetNamespace(); - String nsText; - if (nsList == null) - nsText = "##any"; - else - nsText = nsList.getStringValue(); - QNameSet wcset = QNameSet.forWildcardNamespaceString(nsText, targetNamespace); - - if (baseModel != null && !extension) - { - if (baseModel.getWildcardSet() == null) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$BASE_HAS_ATTR_WILDCARD, null, xsdwc); - continue; // ignore the extra wildcard - } - else if (!baseModel.getWildcardSet().containsAll(wcset)) - { - state.error(XmlErrorCodes.COMPLEX_TYPE_RESTRICTION$ATTR_WILDCARD_SUBSET, - new Object[] { nsText }, xsdwc); - continue; // ignore the restriction - } - } - - int wcprocess = translateWildcardProcess(xsdwc.xgetProcessContents()); - if (result.getWildcardProcess() == SchemaAttributeModel.NONE) - { - result.setWildcardSet(wcset); - result.setWildcardProcess(wcprocess); - } - else - { - if (extension) - { - result.setWildcardSet(wcset.union(result.getWildcardSet())); - result.setWildcardProcess(wcprocess); - } - else - { - result.setWildcardSet(wcset.intersect(result.getWildcardSet())); - // keep old process - } - } - break; - } - case ATTRIBUTE_GROUP_CODE: - { - AttributeGroupRef xsdag = (AttributeGroupRef)cur.getObject(); - QName ref = xsdag.getRef(); - if (ref == null) - { - // KHK: s4s - state.error("Attribute group reference must have a ref attribute", XmlErrorCodes.ATTRIBUTE_GROUP_MISSING_REF, xsdag); - continue; - } - SchemaAttributeGroupImpl group; - if (redefinitionFor != null) - { - group = state.findRedefinedAttributeGroup(ref, chameleon ? targetNamespace : null, redefinitionFor); - if (group != null && - redefinitionFor.getName().equals(group.getName())) - { - if (seenRedefinition) - state.error(XmlErrorCodes.SCHEMA_REDEFINE$ATTR_GROUP_SELF_REF, - new Object[] { QNameHelper.pretty(redefinitionFor.getName()) }, xsdag); - seenRedefinition = true; - } - } - else - { - group = state.findAttributeGroup(ref, chameleon ? targetNamespace : null, targetNamespace); - } - if (group == null) - { - state.notFoundError(ref, SchemaType.ATTRIBUTE_GROUP, xsdag.xgetRef(), true); - continue; - } - if (state.isProcessing(group)) - { - state.error(XmlErrorCodes.SCHEMA_ATTR_GROUP$SELF_REF, - new Object[] { QNameHelper.pretty(group.getName()) },group.getParseObject()); - continue; - } - String subTargetNamespace = targetNamespace; - if (group.getTargetNamespace() != null) - { - subTargetNamespace = group.getTargetNamespace(); - chameleon = group.getChameleonNamespace() != null; - } - - state.startProcessing(group); - SchemaAttributeGroupImpl nestedRedefinitionFor = null; - if (group.isRedefinition()) - nestedRedefinitionFor = group; - translateAttributeModel(group.getParseObject(), subTargetNamespace, chameleon, - group.getFormDefault(), - anonymousTypes, outerType, seenAttributes, result, baseType, - extension, nestedRedefinitionFor); - state.finishProcessing(group); - break; - } - default: - { - continue; // skip things that are not part of the attribute model. - } - } - } - // If this is restriction and no wildcard was present, then - // we have to erase the inherited wildcards - if (!extension && !seenWildcard) - { - result.setWildcardSet(null); - result.setWildcardProcess(SchemaAttributeModel.NONE); - } - } - - static SchemaParticle extendContentModel(SchemaParticle baseContentModel, SchemaParticle extendedContentModel, XmlObject parseTree) - { - // http://www.w3.org/TR/xmlschema-1/#element-complexContent::extension - - // 2.1 If the explicit content is empty, then the {content type} of the type definition resolved to by the �actual value� of the base [attribute] - if (extendedContentModel == null) - return baseContentModel; - - // 2.2 If the type definition resolved to by the actual value of the base [attribute] has a {content type} of empty, then a pair of mixed or elementOnly (determined as per clause 1.2.1 above) and the explicit content itself; - if (baseContentModel == null) - return extendedContentModel; - - // 2.3 otherwise a pair of mixed or elementOnly (determined as per clause 1.2.1 above) and a particle whose properties are as follows: - SchemaParticleImpl sPart = new SchemaParticleImpl(); - sPart.setParticleType(SchemaParticle.SEQUENCE); - - List accumulate = new ArrayList(); - addMinusPointlessParticles(accumulate, baseContentModel, SchemaParticle.SEQUENCE); - addMinusPointlessParticles(accumulate, extendedContentModel, SchemaParticle.SEQUENCE); - sPart.setMinOccurs(BigInteger.ONE); - sPart.setMaxOccurs(BigInteger.ONE); - sPart.setParticleChildren((SchemaParticle[]) - accumulate.toArray(new SchemaParticle[accumulate.size()])); - - return filterPointlessParticlesAndVerifyAllParticles(sPart, parseTree); - } - - static BigInteger extractMinOccurs(XmlNonNegativeInteger nni) - { - if (nni == null) - return BigInteger.ONE; - BigInteger result = nni.getBigIntegerValue(); - if (result == null) - return BigInteger.ONE; - return result; - } - - static BigInteger extractMaxOccurs(AllNNI allNNI) - { - if (allNNI == null) - return BigInteger.ONE; - - if (allNNI.instanceType().getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) - return ((XmlInteger)allNNI).getBigIntegerValue(); - else - return null; - } - - private static class RedefinitionForGroup - { - private SchemaModelGroupImpl group; - private boolean seenRedefinition = false; - - public RedefinitionForGroup(SchemaModelGroupImpl group) - { - this.group = group; - } - - public SchemaModelGroupImpl getGroup() - { - return group; - } - - public boolean isSeenRedefinition() - { - return seenRedefinition; - } - - public void setSeenRedefinition(boolean seenRedefinition) - { - this.seenRedefinition = seenRedefinition; - } - } - - static SchemaParticle translateContentModel( - SchemaType outerType, - XmlObject parseTree, String targetNamespace, boolean chameleon, - String elemFormDefault, String attFormDefault, - int particleCode, List anonymousTypes, Map elementModel, - boolean allowElt, RedefinitionForGroup redefinitionFor) - { - if (parseTree == null || particleCode == 0) - return null; - - StscState state = StscState.get(); - - // emitDBG("Translating content model for " + outerType); - // indentDBG(); - assert(particleCode != 0); - - boolean hasChildren = false; - BigInteger minOccurs; - BigInteger maxOccurs; - SchemaModelGroupImpl group = null; - - SchemaParticleImpl sPart; - - if (particleCode == SchemaParticle.ELEMENT) - { - if (!allowElt) - state.error("Must be a sequence, choice or all here", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, parseTree); - - // TODO: detect substitution group for this element and construct a choice - - LocalElement parseElt = (LocalElement)parseTree; - sPart = StscTranslator.translateElement(parseElt, targetNamespace, chameleon, - elemFormDefault, attFormDefault, anonymousTypes, outerType); - if (sPart == null) - return null; - minOccurs = extractMinOccurs(parseElt.xgetMinOccurs()); - maxOccurs = extractMaxOccurs(parseElt.xgetMaxOccurs()); - - SchemaType oldType = (SchemaType)elementModel.get(sPart.getName()); - if (oldType == null) - { - elementModel.put(sPart.getName(), sPart.getType()); - } - else if (!sPart.getType().equals(oldType)) - { - state.error(XmlErrorCodes.ELEM_CONSISTANT, new Object[] { QNameHelper.pretty(sPart.getName()) }, parseTree); - return null; - } - } - else if (particleCode == SchemaParticle.WILDCARD) - { - if (!allowElt) - state.error("Must be a sequence, choice or all here", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, parseTree); - Any parseAny = (Any)parseTree; - sPart = new SchemaParticleImpl(); - sPart.setParticleType(SchemaParticle.WILDCARD); - QNameSet wcset; - NamespaceList nslist = parseAny.xgetNamespace(); - if (nslist == null) - wcset = QNameSet.ALL; - else - wcset = QNameSet.forWildcardNamespaceString(nslist.getStringValue(), targetNamespace); - sPart.setWildcardSet(wcset); - sPart.setWildcardProcess(translateWildcardProcess(parseAny.xgetProcessContents())); - minOccurs = extractMinOccurs(parseAny.xgetMinOccurs()); - maxOccurs = extractMaxOccurs(parseAny.xgetMaxOccurs()); - } - else - { - Group parseGroup = (Group)parseTree; - sPart = new SchemaParticleImpl(); - - // grab min/maxOccurs before dereferencign group ref - minOccurs = extractMinOccurs(parseGroup.xgetMinOccurs()); - maxOccurs = extractMaxOccurs(parseGroup.xgetMaxOccurs()); - - if (particleCode == MODEL_GROUP_CODE) - { - QName ref = parseGroup.getRef(); - if (ref == null) - { - // KHK: s4s - state.error("Group reference must have a ref attribute", XmlErrorCodes.GROUP_MISSING_REF, parseTree); - return null; - } - - if (redefinitionFor != null) - { - group = state.findRedefinedModelGroup(ref, chameleon ? targetNamespace : null, redefinitionFor.getGroup()); - if (group != null && group.getName().equals(redefinitionFor.getGroup().getName())) - { - if (redefinitionFor.isSeenRedefinition()) - state.error(XmlErrorCodes.SCHEMA_REDEFINE$GROUP_SELF_REF, - new Object[] { QNameHelper.pretty(group.getName()) }, parseTree); - if (!BigInteger.ONE.equals(maxOccurs) || !BigInteger.ONE.equals(minOccurs)) - state.error(XmlErrorCodes.SCHEMA_REDEFINE$GROUP_SELF_REF_MIN_MAX_1, - new Object[] { QNameHelper.pretty(group.getName()) }, parseTree); - redefinitionFor.setSeenRedefinition(true); - } - } - else - { - group = state.findModelGroup(ref, chameleon ? targetNamespace : null, targetNamespace); - } - if (group == null) - { - state.notFoundError(ref, SchemaType.MODEL_GROUP, ((Group)parseTree).xgetRef(), true); - return null; - } - if (state.isProcessing(group)) - { - state.error(XmlErrorCodes.MODEL_GROUP_PROPERTIES$CIRCULAR, - new Object[] { QNameHelper.pretty(group.getName()) }, group.getParseObject()); - return null; - } - - // no go to the child. - XmlCursor cur = group.getParseObject().newCursor(); - for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) - { - particleCode = translateParticleCode(cur.getName()); - if (particleCode != 0) - { - parseTree = parseGroup = (Group)cur.getObject(); - break; - } - } - if (particleCode == 0) - { - // KHK: s4s - state.error("Model group " + QNameHelper.pretty(group.getName()) + " is empty", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, group.getParseObject()); - return null; - } - if (particleCode != SchemaParticle.ALL && particleCode != SchemaParticle.SEQUENCE && particleCode != SchemaParticle.CHOICE) - { - // KHK: s4s - state.error("Model group " + QNameHelper.pretty(group.getName()) + " is not a sequence, all, or choice", XmlErrorCodes.EXPLICIT_GROUP_NEEDED, group.getParseObject()); - } - - String newTargetNamespace = group.getTargetNamespace(); - if (newTargetNamespace != null) - targetNamespace = newTargetNamespace; - elemFormDefault = group.getElemFormDefault(); - attFormDefault = group.getAttFormDefault(); - chameleon = group.getChameleonNamespace() != null; - } - - switch (particleCode) - { - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - case SchemaParticle.CHOICE: - sPart.setParticleType(particleCode); - hasChildren = true; - break; - - default: - assert(false); - throw new IllegalStateException(); - } - } - - if (maxOccurs != null && minOccurs.compareTo(maxOccurs) > 0) - { - state.error(XmlErrorCodes.PARTICLE_PROPERTIES$MIN_LTE_MAX, null, parseTree); - maxOccurs = minOccurs; // remedy: pin max up to min - } - - if (maxOccurs != null && maxOccurs.compareTo(BigInteger.ONE) < 0) - { - state.warning(XmlErrorCodes.PARTICLE_PROPERTIES$MAX_GTE_1, null, parseTree); - - // remove from the list of anonymous types if it was added - anonymousTypes.remove(sPart.getType()); - return null; // maxOccurs == minOccurs == 0, same as no particle at all. - } - - sPart.setMinOccurs(minOccurs); - sPart.setMaxOccurs(maxOccurs); - - if (group != null) - { - state.startProcessing(group); - redefinitionFor = null; - if (group.isRedefinition()) - redefinitionFor = new RedefinitionForGroup(group); - } - - if (hasChildren) - { - XmlCursor cur = parseTree.newCursor(); - List accumulate = new ArrayList(); - for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) - { - int code = translateParticleCode(cur.getName()); - if (code == 0) - continue; - addMinusPointlessParticles(accumulate, - translateContentModel(outerType, - cur.getObject(), targetNamespace, chameleon, - elemFormDefault, attFormDefault, code, - anonymousTypes, elementModel, true, redefinitionFor), - sPart.getParticleType()); - } - sPart.setParticleChildren((SchemaParticle[]) - accumulate.toArray(new SchemaParticle[accumulate.size()])); - cur.dispose(); - } - - - SchemaParticle result = filterPointlessParticlesAndVerifyAllParticles(sPart, parseTree); - - if (group != null) - { - state.finishProcessing(group); - } - // outdentDBG(); - return result; - } - - static int translateWildcardProcess(Any.ProcessContents process) - { - if (process == null) - return SchemaParticle.STRICT; - - String processValue = process.getStringValue(); - - if ("lax".equals(processValue)) - return SchemaParticle.LAX; - - if ("skip".equals(processValue)) - return SchemaParticle.SKIP; - - return SchemaParticle.STRICT; - } - - static SchemaParticle filterPointlessParticlesAndVerifyAllParticles(SchemaParticle part, XmlObject parseTree) - { - if (part.getMaxOccurs() != null && part.getMaxOccurs().signum() == 0) - return null; - - switch (part.getParticleType()) - { - case SchemaParticle.SEQUENCE: - case SchemaParticle.ALL: - if (part.getParticleChildren().length == 0) - return null; - if (part.isSingleton() && part.countOfParticleChild() == 1) - return part.getParticleChild(0); - break; - - case SchemaParticle.CHOICE: - if (part.getParticleChildren().length == 0 && - part.getMinOccurs().compareTo(BigInteger.ZERO) == 0) - return null; - if (part.isSingleton() && part.countOfParticleChild() == 1) - return part.getParticleChild(0); - break; - - case SchemaParticle.ELEMENT: - case SchemaParticle.WILDCARD: - return part; - - default: - assert(false); - throw new IllegalStateException(); - } - - boolean isAll = part.getParticleType() == SchemaParticle.ALL; - - if (isAll) - { - // http://www.w3.org/TR/xmlschema-1/#cos-all-limited - if (part.getMaxOccurs() == null || part.getMaxOccurs().compareTo(BigInteger.ONE) > 0) - { - // An all group must have maxOccurs <= 1 - // KHK: review - StscState.get().error(XmlErrorCodes.ALL_GROUP_LIMITED$IN_MIN_MAX_1_PARTICLE, null, parseTree); - } - } - - for (int i = 0; i < part.countOfParticleChild(); i++) - { - SchemaParticle child = part.getParticleChild(i); - if (child.getParticleType() == SchemaParticle.ALL) - { - // An all group is only allowed at the top level of the content model - // KHK: review - StscState.get().error(XmlErrorCodes.ALL_GROUP_LIMITED$IN_COMPLEX_TYPE_DEF_PARTICLE, null, parseTree); - } - else if (isAll && (child.getParticleType() != SchemaParticle.ELEMENT || child.getMaxOccurs() == null || child.getMaxOccurs().compareTo(BigInteger.ONE) > 0)) - { - // An all group can contain only element particles with maxOccurs <= 1 - // KHK: review - StscState.get().error(XmlErrorCodes.ALL_GROUP_LIMITED$CHILD_PARTICLES_MAX_LTE_1, null, parseTree); - } - } - - return part; - } - - static void addMinusPointlessParticles( - List list, SchemaParticle part, int parentParticleType) - { - if (part == null) - return; - - switch (part.getParticleType()) - { - case SchemaParticle.SEQUENCE: - if (parentParticleType == SchemaParticle.SEQUENCE && part.isSingleton()) - { - // emitDBG("dropping redundant sequence"); - list.addAll(Arrays.asList(part.getParticleChildren())); - return; - } - break; - - case SchemaParticle.CHOICE: - if (parentParticleType == SchemaParticle.CHOICE && part.isSingleton()) - { - // emitDBG("dropping redundant choice"); - list.addAll(Arrays.asList(part.getParticleChildren())); - return; - } - break; - - case SchemaParticle.ALL: - default: - } - list.add(part); - } - - static Map buildAttributePropertyModelByQName(SchemaAttributeModel attrModel, SchemaType owner) - { - Map result = new LinkedHashMap(); - SchemaLocalAttribute[] attruses = attrModel.getAttributes(); - - for (int i = 0; i < attruses.length; i++) - result.put(attruses[i].getName(), buildUseProperty(attruses[i], owner)); - - return result; - } - - static Map buildContentPropertyModelByQName(SchemaParticle part, SchemaType owner) - { - if (part == null) - return Collections.EMPTY_MAP; - - boolean asSequence = false; - Map model = null; - - switch (part.getParticleType()) - { - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - asSequence = true; - break; - case SchemaParticle.CHOICE: - asSequence = false; - break; - case SchemaParticle.ELEMENT: - model = buildElementPropertyModel((SchemaLocalElement)part, owner); - break; - case SchemaParticle.WILDCARD: - model = Collections.EMPTY_MAP; - break; - default: - assert(false); - throw new IllegalStateException(); - } - - if (model == null) - { - // build model for children - model = new LinkedHashMap(); - SchemaParticle[] children = part.getParticleChildren(); - - for (int i = 0; i < children.length; i++) - { - // indentDBG(); - Map childModel = buildContentPropertyModelByQName(children[i], owner); - // outdentDBG(); - for (Iterator j = childModel.values().iterator(); j.hasNext(); ) - { - SchemaProperty iProp = (SchemaProperty)j.next(); - SchemaPropertyImpl oProp = (SchemaPropertyImpl)model.get(iProp.getName()); - if (oProp == null) - { - if (!asSequence) - ((SchemaPropertyImpl)iProp).setMinOccurs(BigInteger.ZERO); - model.put(iProp.getName(), iProp); - continue; - } - // consistency verified in an earlier step - assert(oProp.getType().equals(iProp.getType())); - - mergeProperties(oProp, iProp, asSequence); - } - } - - // finally deal with minOccurs, maxOccurs over whole group - BigInteger min = part.getMinOccurs(); - BigInteger max = part.getMaxOccurs(); - - for (Iterator j = model.values().iterator(); j.hasNext(); ) - { - SchemaProperty oProp = (SchemaProperty)j.next(); - BigInteger minOccurs = oProp.getMinOccurs(); - BigInteger maxOccurs = oProp.getMaxOccurs(); - - minOccurs = minOccurs.multiply(min); - if (max != null && max.equals(BigInteger.ZERO)) - maxOccurs = BigInteger.ZERO; - else if (maxOccurs != null && !maxOccurs.equals(BigInteger.ZERO)) - maxOccurs = max == null ? null : maxOccurs.multiply(max); - - ((SchemaPropertyImpl)oProp).setMinOccurs(minOccurs); - ((SchemaPropertyImpl)oProp).setMaxOccurs(maxOccurs); - } - } - - return model; - } - - static Map buildElementPropertyModel(SchemaLocalElement epart, SchemaType owner) - { - Map result = new HashMap(1); - - SchemaProperty sProp = buildUseProperty(epart, owner); - result.put(sProp.getName(), sProp); - return result; - } - - static SchemaProperty buildUseProperty(SchemaField use, SchemaType owner) - { - SchemaPropertyImpl sPropImpl = new SchemaPropertyImpl(); - sPropImpl.setName(use.getName()); - sPropImpl.setContainerTypeRef(owner.getRef()); - sPropImpl.setTypeRef(use.getType().getRef()); - sPropImpl.setAttribute(use.isAttribute()); - sPropImpl.setDefault(use.isDefault() ? SchemaProperty.CONSISTENTLY : SchemaProperty.NEVER); - sPropImpl.setFixed(use.isFixed() ? SchemaProperty.CONSISTENTLY : SchemaProperty.NEVER); - sPropImpl.setNillable(use.isNillable() ? SchemaProperty.CONSISTENTLY : SchemaProperty.NEVER); - sPropImpl.setDefaultText(use.getDefaultText()); - sPropImpl.setMinOccurs(use.getMinOccurs()); - sPropImpl.setMaxOccurs(use.getMaxOccurs()); - - if (use instanceof SchemaLocalElementImpl) - { - SchemaLocalElementImpl elt = (SchemaLocalElementImpl)use; - sPropImpl.setAcceptedNames(elt.acceptedStartNames()); - } - - return sPropImpl; - } - - static void mergeProperties(SchemaPropertyImpl into, SchemaProperty from, boolean asSequence) - { - // minoccur, maxoccur - BigInteger minOccurs = into.getMinOccurs(); - BigInteger maxOccurs = into.getMaxOccurs(); - if (asSequence) - { - minOccurs = minOccurs.add(from.getMinOccurs()); - if (maxOccurs != null) - maxOccurs = (from.getMaxOccurs() == null ? null : - maxOccurs.add(from.getMaxOccurs())); - } - else - { - minOccurs = minOccurs.min(from.getMinOccurs()); - if (maxOccurs != null) - maxOccurs = (from.getMaxOccurs() == null ? null : - maxOccurs.max(from.getMaxOccurs())); - } - into.setMinOccurs(minOccurs); - into.setMaxOccurs(maxOccurs); - - // nillable, default, fixed - if (from.hasNillable() != into.hasNillable()) - into.setNillable(SchemaProperty.VARIABLE); - if (from.hasDefault() != into.hasDefault()) - into.setDefault(SchemaProperty.VARIABLE); - if (from.hasFixed() != into.hasFixed()) - into.setFixed(SchemaProperty.VARIABLE); - - // default value - if (into.getDefaultText() != null) - { - if (from.getDefaultText() == null || - !into.getDefaultText().equals(from.getDefaultText())) - into.setDefaultText(null); - } - } - - static SchemaParticle[] ensureStateMachine(SchemaParticle[] children) - { - for (int i = 0; i < children.length; i++) - { - buildStateMachine(children[i]); - } - return children; - } - - static void buildStateMachine(SchemaParticle contentModel) - { - if (contentModel == null) - return; - - SchemaParticleImpl partImpl = (SchemaParticleImpl)contentModel; - if (partImpl.hasTransitionNotes()) - return; - - QNameSetBuilder start = new QNameSetBuilder(); - QNameSetBuilder excludenext = new QNameSetBuilder(); - boolean deterministic = true; - SchemaParticle[] children = null; - boolean canskip = (partImpl.getMinOccurs().signum() == 0); - - switch (partImpl.getParticleType()) - { - case SchemaParticle.ELEMENT: - // compute start and excludeNext; canskip is already correct - if (partImpl.hasTransitionRules()) - start.addAll(partImpl.acceptedStartNames()); - else - start.add(partImpl.getName()); - - break; - - case SchemaParticle.WILDCARD: - // compute start and excludeNext; canskip is already correct - start.addAll(partImpl.getWildcardSet()); - break; - - case SchemaParticle.SEQUENCE: - children = ensureStateMachine(partImpl.getParticleChildren()); - - // adjust canskip if all children are skippable - canskip = true; - for (int i = 0; canskip && i < children.length; i++) - { - if (!(children[i]).isSkippable()) - canskip = false; - } - - // bubble up nondeterministic bit - for (int i = 0; deterministic && i < children.length; i++) - { - if (!((SchemaParticleImpl)children[i]).isDeterministic()) - deterministic = false; - } - - // verify deterministic and compute excludeNext set - for (int i = 1; i < children.length; i++) - { - excludenext.addAll(((SchemaParticleImpl)children[i - 1]).getExcludeNextSet()); - if (deterministic && !excludenext.isDisjoint((children[i]).acceptedStartNames())) - deterministic = false; - if ((children[i]).isSkippable()) - excludenext.addAll((children[i]).acceptedStartNames()); - else - excludenext.clear(); - } - - // next, compute start set - for (int i = 0; i < children.length; i++) - { - start.addAll((children[i]).acceptedStartNames()); - if (!(children[i]).isSkippable()) - break; - } - break; - - case SchemaParticle.CHOICE: - children = ensureStateMachine(partImpl.getParticleChildren()); - - // adjust canskip if any children are skippable - canskip = false; - for (int i = 0; !canskip && i < children.length; i++) - { - if ((children[i]).isSkippable()) - canskip = true; - } - - // bubble up nondeterministic bit - for (int i = 0; deterministic && i < children.length; i++) - { - if (!((SchemaParticleImpl)children[i]).isDeterministic()) - deterministic = false; - } - - // compute start and excludeNext sets, verify deterministic - for (int i = 0; i < children.length; i++) - { - if (deterministic && !start.isDisjoint((children[i]).acceptedStartNames())) - deterministic = false; - start.addAll((children[i]).acceptedStartNames()); - excludenext.addAll(((SchemaParticleImpl)children[i]).getExcludeNextSet()); - } - - break; - - case SchemaParticle.ALL: - children = ensureStateMachine(partImpl.getParticleChildren()); - - // adjust canskip if all children are skippable - canskip = true; - for (int i = 0; !canskip && i < children.length; i++) - { - if (!(children[i]).isSkippable()) - canskip = false; - } - - // bubble up nondeterministic bit - for (int i = 0; deterministic && i < children.length; i++) - { - if (!((SchemaParticleImpl)children[i]).isDeterministic()) - deterministic = false; - } - - // compute start and excludeNext sets, verify deterministic - for (int i = 0; i < children.length; i++) - { - if (deterministic && !start.isDisjoint((children[i]).acceptedStartNames())) - deterministic = false; - start.addAll((children[i]).acceptedStartNames()); - excludenext.addAll(((SchemaParticleImpl)children[i]).getExcludeNextSet()); - } - if (canskip) - excludenext.addAll(start); - - break; - - default: - throw new IllegalStateException("Unrecognized schema particle"); - } - - // apply looping logic - - BigInteger minOccurs = partImpl.getMinOccurs(); - BigInteger maxOccurs = partImpl.getMaxOccurs(); - boolean canloop = (maxOccurs == null || maxOccurs.compareTo(BigInteger.ONE) > 0); - boolean varloop = (maxOccurs == null || minOccurs.compareTo(maxOccurs) < 0); - - if (canloop && deterministic && !excludenext.isDisjoint(start)) - { - // we have a possible looping nondeterminism. - // let's take some time now to see if it's actually caused - // by non-unique-particle-attribute or not. - QNameSet suspectSet = excludenext.intersect(start); - - // compute the set of all particles that could start this group - Map startMap = new HashMap(); - particlesMatchingStart(partImpl, suspectSet, startMap, new QNameSetBuilder()); - - // compute the set of all particles that could have been repeated rather than ending this group - Map afterMap = new HashMap(); - particlesMatchingAfter(partImpl, suspectSet, afterMap, new QNameSetBuilder(), true); - - // see if we can find a member of after that is not a member of start - // if we can, then particle attribution is not unique - deterministic = afterMapSubsumedByStartMap(startMap, afterMap); - } - - if (varloop) - excludenext.addAll(start); - - canskip = canskip || minOccurs.signum() == 0; - - partImpl.setTransitionRules(start.toQNameSet(), canskip); - partImpl.setTransitionNotes(excludenext.toQNameSet(), deterministic); - } - - private static boolean afterMapSubsumedByStartMap(Map startMap, Map afterMap) - { - if (afterMap.size() > startMap.size()) - return false; - - if (afterMap.isEmpty()) - return true; - - for (Iterator i = startMap.keySet().iterator(); i.hasNext(); ) - { - SchemaParticle part = (SchemaParticle)i.next(); - if (part.getParticleType() == SchemaParticle.WILDCARD) - { - if (afterMap.containsKey(part)) - { - QNameSet startSet = (QNameSet)startMap.get(part); - QNameSet afterSet = (QNameSet)afterMap.get(part); - if (!startSet.containsAll(afterSet)) - return false; - } - } - afterMap.remove(part); - if (afterMap.isEmpty()) - return true; - } - return (afterMap.isEmpty()); - } - - private static void particlesMatchingStart(SchemaParticle part, QNameSetSpecification suspectSet, Map result, QNameSetBuilder eliminate) - { - switch (part.getParticleType()) - { - case SchemaParticle.ELEMENT: - if (!suspectSet.contains(part.getName())) - return; - result.put(part, null); - eliminate.add(part.getName()); - return; - - case SchemaParticle.WILDCARD: - if (suspectSet.isDisjoint(part.getWildcardSet())) - return; - result.put(part, part.getWildcardSet().intersect(suspectSet)); - eliminate.addAll(part.getWildcardSet()); - return; - - case SchemaParticle.CHOICE: - case SchemaParticle.ALL: - { - SchemaParticle[] children = part.getParticleChildren(); - for (int i = 0; i < children.length; i++) - particlesMatchingStart(children[i], suspectSet, result, eliminate); - return; - } - - case SchemaParticle.SEQUENCE: - { - SchemaParticle[] children = part.getParticleChildren(); - if (children.length == 0) - return; - if (!children[0].isSkippable()) - { - particlesMatchingStart(children[0], suspectSet, result, eliminate); - return; - } - QNameSetBuilder remainingSuspects = new QNameSetBuilder(suspectSet); - QNameSetBuilder suspectsToEliminate = new QNameSetBuilder(); - for (int i = 0; i < children.length; i++) - { - particlesMatchingStart(children[i], remainingSuspects, result, suspectsToEliminate); - eliminate.addAll(suspectsToEliminate); - if (!children[i].isSkippable()) - return; - remainingSuspects.removeAll(suspectsToEliminate); - if (remainingSuspects.isEmpty()) - return; - suspectsToEliminate.clear(); - } - return; - } - } - } - - private static void particlesMatchingAfter(SchemaParticle part, QNameSetSpecification suspectSet, Map result, QNameSetBuilder eliminate, boolean top) - { - recurse: switch (part.getParticleType()) - { - case SchemaParticle.CHOICE: - case SchemaParticle.ALL: - { - SchemaParticle[] children = part.getParticleChildren(); - for (int i = 0; i < children.length; i++) - particlesMatchingAfter(children[i], suspectSet, result, eliminate, false); - break recurse; - } - - case SchemaParticle.SEQUENCE: - { - SchemaParticle[] children = part.getParticleChildren(); - if (children.length == 0) - break recurse; - if (!children[children.length - 1].isSkippable()) - { - particlesMatchingAfter(children[0], suspectSet, result, eliminate, false); - break recurse; - } - QNameSetBuilder remainingSuspects = new QNameSetBuilder(suspectSet); - QNameSetBuilder suspectsToEliminate = new QNameSetBuilder(); - for (int i = children.length - 1; i >= 0; i--) - { - particlesMatchingAfter(children[i], remainingSuspects, result, suspectsToEliminate, false); - eliminate.addAll(suspectsToEliminate); - if (!children[i].isSkippable()) - break recurse; - remainingSuspects.removeAll(suspectsToEliminate); - if (remainingSuspects.isEmpty()) - break recurse; - suspectsToEliminate.clear(); - } - break recurse; - } - } - - if (!top) - { - BigInteger minOccurs = part.getMinOccurs(); - BigInteger maxOccurs = part.getMaxOccurs(); - boolean varloop = (maxOccurs == null || minOccurs.compareTo(maxOccurs) < 0); - if (varloop) - { - particlesMatchingStart(part, suspectSet, result, eliminate); - } - } - } - - private static class CodeForNameEntry - { - CodeForNameEntry(QName name, int code) - { this.name = name; this.code = code; } - public QName name; - public int code; - } - - private static final int MODEL_GROUP_CODE = 100; - - private static CodeForNameEntry[] particleCodes = new CodeForNameEntry[] - { - new CodeForNameEntry(QNameHelper.forLNS("all", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.ALL), - new CodeForNameEntry(QNameHelper.forLNS("sequence", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.SEQUENCE), - new CodeForNameEntry(QNameHelper.forLNS("choice", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.CHOICE), - new CodeForNameEntry(QNameHelper.forLNS("element", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.ELEMENT), - new CodeForNameEntry(QNameHelper.forLNS("any", "http://www.w3.org/2001/XMLSchema"), SchemaParticle.WILDCARD), - new CodeForNameEntry(QNameHelper.forLNS("group", "http://www.w3.org/2001/XMLSchema"), MODEL_GROUP_CODE), - }; - - private static Map particleCodeMap = buildParticleCodeMap(); - - private static Map buildParticleCodeMap() - { - Map result = new HashMap(); - for (int i = 0; i < particleCodes.length; i++) - result.put(particleCodes[i].name, new Integer(particleCodes[i].code)); - return result; - } - - private static int translateParticleCode(Group parseEg) - { - if (parseEg == null) - return 0; - return translateParticleCode(parseEg.newCursor().getName()); - } - - private static int translateParticleCode(QName name) - { - Integer result = (Integer)particleCodeMap.get(name); - if (result == null) - return 0; - return result.intValue(); - } - - private static final int ATTRIBUTE_CODE = 100; - private static final int ATTRIBUTE_GROUP_CODE = 101; - private static final int ANY_ATTRIBUTE_CODE = 102; - - private static CodeForNameEntry[] attributeCodes = new CodeForNameEntry[] - { - new CodeForNameEntry(QNameHelper.forLNS("attribute", "http://www.w3.org/2001/XMLSchema"), ATTRIBUTE_CODE), - new CodeForNameEntry(QNameHelper.forLNS("attributeGroup", "http://www.w3.org/2001/XMLSchema"), ATTRIBUTE_GROUP_CODE), - new CodeForNameEntry(QNameHelper.forLNS("anyAttribute", "http://www.w3.org/2001/XMLSchema"), ANY_ATTRIBUTE_CODE), - }; - - private static Map attributeCodeMap = buildAttributeCodeMap(); - - private static Map buildAttributeCodeMap() - { - Map result = new HashMap(); - for (int i = 0; i < attributeCodes.length; i++) - result.put(attributeCodes[i].name, new Integer(attributeCodes[i].code)); - return result; - } - - static int translateAttributeCode(QName currentName) - { - Integer result = (Integer)attributeCodeMap.get(currentName); - if (result == null) - return 0; - return result.intValue(); - } - - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java deleted file mode 100644 index c47ba67..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java +++ /dev/null @@ -1,1008 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.ImportDocument.Import; -import org.apache.xmlbeans.impl.xb.xsdschema.IncludeDocument.Include; - -import java.util.Map; -import java.util.List; -import java.util.LinkedList; -import java.util.Set; -import java.util.HashMap; -import java.util.HashSet; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Arrays; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.MalformedURLException; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.io.InputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.CharArrayReader; -import java.io.Writer; -import java.io.CharArrayWriter; -import java.io.OutputStreamWriter; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.IOUtil; -import org.apache.xmlbeans.impl.common.XmlEncodingSniffer; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class StscImporter -{ - public static SchemaToProcess[] resolveImportsAndIncludes(Schema[] startWith, boolean forceSrcSave) - { - DownloadTable engine = new DownloadTable(startWith); - return engine.resolveImportsAndIncludes(forceSrcSave); - } - - public static class SchemaToProcess - { - private Schema schema; - private String chameleonNamespace; - private List includes; // list of SchemaToProcess objects directly included by this - private List redefines; // list of SchemaToProcess objects directly redefined by this - private List redefineObjects; // list of Redefine objects associated to each redefinition - private Set indirectIncludes; // set of SchemaToProcess objects directly/indirectly included by this - private Set indirectIncludedBy; // set of SchemaToProcess objects that include this directly/indirectly - - public SchemaToProcess(Schema schema, String chameleonNamespace) - { - this.schema = schema; - this.chameleonNamespace = chameleonNamespace; - } - - /** - * The schema to parse. - */ - public Schema getSchema() - { - return schema; - } - - /** - * The base URI for this stp - */ - public String getSourceName() - { - return schema.documentProperties().getSourceName(); - } - - /** - * The chameleon namespace. Null if this schema is not being treated - * as a chameleon. (The ordinary targetNamespace will just be extracted - * from the syntax of the schema.) - */ - public String getChameleonNamespace() - { - return chameleonNamespace; - } - - /** - * This method and the remaining methods are used to represent a - * directed graph of includes/redefines. This is required in order - * to establish identity component by component, as required in - * xmlschema-1, chapter 4.2.2 - * @return - */ - public List getRedefines() - { - return redefines; - } - - public List getRedefineObjects() - { - return redefineObjects; - } - - private void addInclude(SchemaToProcess include) - { - if (includes == null) - includes = new ArrayList(); - includes.add(include); - } - - private void addRedefine(SchemaToProcess redefine, Redefine object) - { - if (redefines == null || redefineObjects == null) - { - redefines = new ArrayList(); - redefineObjects = new ArrayList(); - } - redefines.add(redefine); - redefineObjects.add(object); - } - - private void buildIndirectReferences() - { - if (includes != null) - for (int i = 0; i < includes.size(); i++) - { - SchemaToProcess schemaToProcess = (SchemaToProcess) includes.get(i); - /* We have a this-schemaToProcess vertex - * This means that all nodes accessible from schemaToProcess are - * also accessible from this and all nodes that have access to - * this also have access to schemaToProcess */ - this.addIndirectIncludes(schemaToProcess); - } - // Repeat the same algorithm for redefines, since redefines are also includes - if (redefines != null) - for (int i = 0; i < redefines.size(); i++) - { - SchemaToProcess schemaToProcess = (SchemaToProcess) redefines.get(i); - this.addIndirectIncludes(schemaToProcess); - } - } - - private void addIndirectIncludes(SchemaToProcess schemaToProcess) - { - if (indirectIncludes == null) - indirectIncludes = new HashSet(); - indirectIncludes.add(schemaToProcess); - if (schemaToProcess.indirectIncludedBy == null) - schemaToProcess.indirectIncludedBy = new HashSet(); - schemaToProcess.indirectIncludedBy.add(this); - addIndirectIncludesHelper(this, schemaToProcess); - if (indirectIncludedBy != null) - for (Iterator it = indirectIncludedBy.iterator(); it.hasNext();) - { - SchemaToProcess stp = (SchemaToProcess) it.next(); - stp.indirectIncludes.add(schemaToProcess); - schemaToProcess.indirectIncludedBy.add(stp); - addIndirectIncludesHelper(stp, schemaToProcess); - } - } - - private static void addIndirectIncludesHelper(SchemaToProcess including, - SchemaToProcess schemaToProcess) - { - if (schemaToProcess.indirectIncludes != null) - for (Iterator it = schemaToProcess.indirectIncludes.iterator(); it.hasNext();) - { - SchemaToProcess stp = (SchemaToProcess) it.next(); - including.indirectIncludes.add(stp); - stp.indirectIncludedBy.add(including); - } - } - - public boolean indirectIncludes(SchemaToProcess schemaToProcess) - { - return indirectIncludes != null && indirectIncludes.contains(schemaToProcess); - } - - public boolean equals(Object o) - { - if (this == o) return true; - if (!(o instanceof SchemaToProcess)) return false; - - final SchemaToProcess schemaToProcess = (SchemaToProcess) o; - - if (chameleonNamespace != null ? !chameleonNamespace.equals(schemaToProcess.chameleonNamespace) : schemaToProcess.chameleonNamespace != null) return false; - if (!(schema == schemaToProcess.schema)) return false; - - return true; - } - - public int hashCode() - { - int result; - result = schema.hashCode(); - result = 29 * result + (chameleonNamespace != null ? chameleonNamespace.hashCode() : 0); - return result; - } - } - - private final static String PROJECT_URL_PREFIX = "project://local"; - - private static String baseURLForDoc(XmlObject obj) - { - String path = obj.documentProperties().getSourceName(); - - if (path == null) - return null; - - if (path.startsWith("/")) - return PROJECT_URL_PREFIX + path.replace('\\', '/'); - - // looks like a URL? - int colon = path.indexOf(':'); - if (colon > 1 && path.substring(0, colon).matches("^\\w+$")) - return path; - - return PROJECT_URL_PREFIX + "/" + path.replace('\\', '/'); - } - - private static URI parseURI(String s) - { - if (s == null) - return null; - - try - { - return new URI(s); - } - catch (URISyntaxException syntax) - { - return null; - } - } - - //workaround for Sun bug # 4723726 - public static URI resolve(URI base, String child) - throws URISyntaxException - { - URI childUri = new URI(child); - URI ruri = base.resolve(childUri); - - // if the child fragment is relative (which we'll assume is the case - // if URI.resolve doesn't do anything useful with it) and the base - // URI is pointing at something nested inside a jar, we seem to have - // to this ourselves to make sure that the nested jar url gets - // resolved correctly - if (childUri.equals(ruri) && !childUri.isAbsolute() && - (base.getScheme().equals("jar") || base.getScheme().equals("zip"))) { - String r = base.toString(); - int lastslash = r.lastIndexOf('/'); - r = r.substring(0,lastslash) + "/" + childUri; - // Sun's implementation of URI doesn't support references to the - // parent directory ("/..") in the part after "!/" so we have to - // remove these ourselves - int exclPointSlashIndex = r.lastIndexOf("!/"); - if (exclPointSlashIndex > 0) - { - int slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex); - while (slashDotDotIndex > 0) - { - int prevSlashIndex = r.lastIndexOf("/", slashDotDotIndex - 1); - if (prevSlashIndex >= exclPointSlashIndex) - { - String temp = r.substring(slashDotDotIndex + 3); - r = r.substring(0, prevSlashIndex).concat(temp); - } - slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex); - } - } - return URI.create(r); - } - - //fix up normalization bug - if ("file".equals(ruri.getScheme()) && ! child.equals(ruri)) - { - if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//")) - { - String path = "///".concat(ruri.getPath()); - try - { - ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment()); - } - catch(URISyntaxException uris) - {} - } - } - return ruri; - } - - public static class DownloadTable - { - /** - * Namespace/schemaLocation pair. - * - * Downloaded schemas are indexed by namespace, schemaLocation, and both. - * - * A perfect match is preferred, but a match-by-namespace is accepted. - * A match-by-schemaLocation is only accepted for includes (not imports). - */ - private static class NsLocPair - { - private String namespaceURI; - private String locationURL; - - public NsLocPair(String namespaceURI, String locationURL) - { - this.namespaceURI = namespaceURI; - this.locationURL = locationURL; - } - - /** - * Empty string for no-namespace, null for namespace-not-part-of-key - */ - public String getNamespaceURI() - { - return namespaceURI; - } - - public String getLocationURL() - { - return locationURL; - } - - public boolean equals(Object o) - { - if (this == o) return true; - if (!(o instanceof NsLocPair)) return false; - - final NsLocPair nsLocPair = (NsLocPair) o; - - if (locationURL != null ? !locationURL.equals(nsLocPair.locationURL) : nsLocPair.locationURL != null) return false; - if (namespaceURI != null ? !namespaceURI.equals(nsLocPair.namespaceURI) : nsLocPair.namespaceURI != null) return false; - - return true; - } - - public int hashCode() - { - int result; - result = (namespaceURI != null ? namespaceURI.hashCode() : 0); - result = 29 * result + (locationURL != null ? locationURL.hashCode() : 0); - return result; - } - } - - private static class DigestKey - { - byte[] _digest; - int _hashCode; - DigestKey(byte[] digest) - { - _digest = digest; - for (int i = 0; i < 4 && i < digest.length; i++) - { - _hashCode = _hashCode << 8; - _hashCode = _hashCode + digest[i]; - } - } - - public boolean equals(Object o) - { - if (this == o) return true; - if (!(o instanceof DigestKey)) return false; - return Arrays.equals(_digest, ((DigestKey)o)._digest); - } - - public int hashCode() - { - return _hashCode; - } - } - - private Map schemaByNsLocPair = new HashMap(); - private Map schemaByDigestKey = new HashMap(); - private LinkedList scanNeeded = new LinkedList(); - private Set emptyNamespaceSchemas = new HashSet(); - private Map scannedAlready = new HashMap(); - private Set failedDownloads = new HashSet(); - - private Schema downloadSchema(XmlObject referencedBy, String targetNamespace, String locationURL) - { - // no location URL provided? Then nothing to do. - if (locationURL == null) - return null; - - StscState state = StscState.get(); - - // First resolve relative URLs with respect to base URL for doc - URI baseURI = parseURI(baseURLForDoc(referencedBy)); - String absoluteURL = null; - try - { - absoluteURL = baseURI == null ? locationURL : resolve(baseURI, locationURL).toString(); - } - catch (URISyntaxException e) - { - state.error("Could not find resource - invalid location URL: " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - return null; - } - - // probe 0: this url is already processed, from a previous compile - if (state.isFileProcessed(absoluteURL)) - return null; - - // probe 1: ns+url - perfect match - if (absoluteURL != null && targetNamespace != null) - { - Schema result = (Schema)schemaByNsLocPair.get(new NsLocPair(targetNamespace, absoluteURL)); - if (result != null) - return result; - } - - // probe 2: we have preexisting knowledge of this namespace, - // either from another schema file or from the linker. - // If we're not downloading the given URL, skip it silently if the - // namespace is already represented by a file we have. - // Also, suppress downloads of URLs to namespaces that are already - // known by the linker. - // (We never assume preexisting knowledge of the no-namespace, - // even if we have some definitions, since it's likely that - // more than one person is playing in the no-namespace at once.) - if (targetNamespace != null && !targetNamespace.equals("")) - { - // the URL is not one to download; should we assume we know about the namespace? - if (!state.shouldDownloadURI(absoluteURL)) - { - // If we already have a schema representing this namespace, - // then skip this URL silently without producing an error. - Schema result = (Schema)schemaByNsLocPair.get(new NsLocPair(targetNamespace, null)); - if (result != null) - return result; - } - - // If the linker already knows about this namespace, skip - // this URL. - if (state.linkerDefinesNamespace(targetNamespace)) - return null; - } - - // probe 3: url only - if (absoluteURL != null) - { - Schema result = (Schema)schemaByNsLocPair.get(new NsLocPair(null, absoluteURL)); - if (result != null) - return result; - } - - // no match: error if we can't or won't download. - if (absoluteURL == null) - { - state.error("Could not find resource - no valid location URL.", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - return null; - } - - if (previouslyFailedToDownload(absoluteURL)) - { - // an error message has already been produced. - return null; - } - - if (!state.shouldDownloadURI(absoluteURL)) - { - state.error("Could not load resource \"" + absoluteURL + "\" (network downloads disabled).", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - addFailedDownload(absoluteURL); - return null; - } - - // try to download - download: try - { - XmlObject xdoc = downloadDocument(state.getS4SLoader(), targetNamespace, absoluteURL); - - Schema result = findMatchByDigest(xdoc); - String shortname = state.relativize(absoluteURL); - if (result != null) - { - // if an exactly-the-same document has already been loaded, use the original and spew - String dupname = state.relativize(result.documentProperties().getSourceName()); - if (dupname != null) - state.info(shortname + " is the same as " + dupname + " (ignoring the duplicate file)"); - else - state.info(shortname + " is the same as another schema"); - } - else - { - // otherwise, it's a new document: validate it and grab the contents - XmlOptions voptions = new XmlOptions(); - voptions.setErrorListener(state.getErrorListener()); - if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) - { - state.error("Referenced document is not a valid schema", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - break download; - } - - SchemaDocument sDoc = (SchemaDocument)xdoc; - - result = sDoc.getSchema(); - state.info("Loading referenced file " + shortname); - } - NsLocPair key = new NsLocPair(emptyStringIfNull(result.getTargetNamespace()), absoluteURL); - addSuccessfulDownload(key, result); - return result; - } - catch (MalformedURLException malformed) - { - state.error("URL \"" + absoluteURL + "\" is not well-formed", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - } - catch (IOException connectionProblem) - { - state.error(connectionProblem.toString(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - } - catch (XmlException e) - { - state.error("Problem parsing referenced XML resource - " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy); - } - - // record failure so that we don't try to download this URL again - addFailedDownload(absoluteURL); - return null; - } - - static XmlObject downloadDocument(SchemaTypeLoader loader, String namespace, String absoluteURL) - throws MalformedURLException, IOException, XmlException - { - StscState state = StscState.get(); - - EntityResolver resolver = state.getEntityResolver(); - if (resolver != null) - { - InputSource source = null; - try - { - source = resolver.resolveEntity(namespace, absoluteURL); - } - catch (SAXException e) - { - throw new XmlException(e); - } - - if (source != null) - { - state.addSourceUri(absoluteURL, null); - - // first preference for InputSource contract: character stream - Reader reader = source.getCharacterStream(); - if (reader != null) - { - reader = copySchemaSource(absoluteURL, reader, state); - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setDocumentSourceName(absoluteURL); - return loader.parse(reader, null, options); - } - - // second preference for InputSource contract: - InputStream bytes = source.getByteStream(); - if (bytes != null) - { - bytes = copySchemaSource(absoluteURL, bytes, state); - String encoding = source.getEncoding(); - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setLoadMessageDigest(); - options.setDocumentSourceName(absoluteURL); - if (encoding != null) - options.setCharacterEncoding(encoding); - return loader.parse(bytes, null, options); - } - - // third preference: use the (possibly redirected) url - String urlToLoad = source.getSystemId(); - if (urlToLoad == null) - throw new IOException("EntityResolver unable to resolve " + absoluteURL + " (for namespace " + namespace + ")"); - - copySchemaSource(absoluteURL, state, false); - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setLoadMessageDigest(); - options.setDocumentSourceName(absoluteURL); - URL urlDownload = new URL(urlToLoad); - return loader.parse(urlDownload, null, options); - } - } - - // no resolver - just use the URL directly, no substitution - state.addSourceUri(absoluteURL, null); - copySchemaSource(absoluteURL, state, false); - - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setLoadMessageDigest(); - URL urlDownload = new URL(absoluteURL); - - return loader.parse(urlDownload, null, options); - } - - private void addSuccessfulDownload(NsLocPair key, Schema schema) - { - byte[] digest = schema.documentProperties().getMessageDigest(); - if (digest == null) - { - StscState.get().addSchemaDigest(null); - } - else - { - DigestKey dk = new DigestKey(digest); - if (!schemaByDigestKey.containsKey(dk)) - { - schemaByDigestKey.put(new DigestKey(digest), schema); - StscState.get().addSchemaDigest(digest); - } - } - - schemaByNsLocPair.put(key, schema); - NsLocPair key1 = new NsLocPair(key.getNamespaceURI(), null); - if (!schemaByNsLocPair.containsKey(key1)) - schemaByNsLocPair.put(key1, schema); - NsLocPair key2 = new NsLocPair(null, key.getLocationURL()); - if (!schemaByNsLocPair.containsKey(key2)) - schemaByNsLocPair.put(key2, schema); - } - - private Schema findMatchByDigest(XmlObject original) - { - byte[] digest = original.documentProperties().getMessageDigest(); - if (digest == null) - return null; - return (Schema)schemaByDigestKey.get(new DigestKey(digest)); - } - - private void addFailedDownload(String locationURL) - { - failedDownloads.add(locationURL); - } - - private boolean previouslyFailedToDownload(String locationURL) - { - return failedDownloads.contains(locationURL); - } - - private static boolean nullableStringsMatch(String s1, String s2) - { - if (s1 == null && s2 == null) - return true; - if (s1 == null || s2 == null) - return false; - return (s1.equals(s2)); - } - - private static String emptyStringIfNull(String s) - { - if (s == null) - return ""; - return s; - } - - private SchemaToProcess addScanNeeded(SchemaToProcess stp) - { - if (!scannedAlready.containsKey(stp)) - { - scannedAlready.put(stp, stp); - scanNeeded.add(stp); - return stp; - } - else - return (SchemaToProcess) scannedAlready.get(stp); - } - - private void addEmptyNamespaceSchema(Schema s) - { - emptyNamespaceSchemas.add(s); - } - - private void usedEmptyNamespaceSchema(Schema s) - { - emptyNamespaceSchemas.remove(s); - } - - private boolean fetchRemainingEmptyNamespaceSchemas() - { - if (emptyNamespaceSchemas.isEmpty()) - return false; - - for (Iterator i = emptyNamespaceSchemas.iterator(); i.hasNext();) - { - Schema schema = (Schema)i.next(); - addScanNeeded(new SchemaToProcess(schema, null)); - } - - emptyNamespaceSchemas.clear(); - return true; - } - - private boolean hasNextToScan() - { - return !scanNeeded.isEmpty(); - } - - private SchemaToProcess nextToScan() - { - SchemaToProcess next = (SchemaToProcess)scanNeeded.removeFirst(); - return next; - } - - public DownloadTable(Schema[] startWith) - { - for (int i = 0; i < startWith.length; i++) - { - String targetNamespace = startWith[i].getTargetNamespace(); - NsLocPair key = new NsLocPair(targetNamespace, baseURLForDoc(startWith[i])); - addSuccessfulDownload(key, startWith[i]); - if (targetNamespace != null) - addScanNeeded(new SchemaToProcess(startWith[i], null)); - else - addEmptyNamespaceSchema(startWith[i]); - } - } - - public SchemaToProcess[] resolveImportsAndIncludes(boolean forceSave) - { - StscState state = StscState.get(); - List result = new ArrayList(); - boolean hasRedefinitions = false; - - // algorithm is to scan through each schema document and - // 1. download each import and include (if not already downloaded) - // 2. queue each imported or included schema to be process (if not already queued) - - // The algorithm is run twice: first we begin with non-empty - // namespace schemas only. Then we repeat starting with any - // empty empty-namespace schemas that have NOT been chameleon- - // included by other schemas and process them. - - for (;;) - { - while (hasNextToScan()) - { - SchemaToProcess stp = nextToScan(); - String uri = stp.getSourceName(); - state.addSourceUri(uri, null); - result.add(stp); - copySchemaSource(uri, state, forceSave); - - { - // handle imports - Import[] imports = stp.getSchema().getImportArray(); - for (int i = 0; i < imports.length; i++) - { - Schema imported = downloadSchema(imports[i], emptyStringIfNull(imports[i].getNamespace()), imports[i].getSchemaLocation()); - - // if download fails, an error has already been reported. - if (imported == null) - continue; - - if (!nullableStringsMatch(imported.getTargetNamespace(), imports[i].getNamespace())) - { - StscState.get().error("Imported schema has a target namespace \"" + imported.getTargetNamespace() + "\" that does not match the specified \"" + imports[i].getNamespace() + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, imports[i]); - } - else - { - addScanNeeded(new SchemaToProcess(imported, null)); - } - } - } - - { - // handle includes - Include[] includes = stp.getSchema().getIncludeArray(); - String sourceNamespace = stp.getChameleonNamespace(); - if (sourceNamespace == null) - sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace()); - - for (int i = 0; i < includes.length; i++) - { - Schema included = downloadSchema(includes[i], null, includes[i].getSchemaLocation()); - // if download fails, an error has already been reported. - if (included == null) - continue; - - if (emptyStringIfNull(included.getTargetNamespace()).equals(sourceNamespace)) - { - // non-chameleon case - just like an import - SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, null)); - stp.addInclude(s); - } - else if (included.getTargetNamespace() != null) - { - // illegal include: included schema in wrong namespace. - StscState.get().error("Included schema has a target namespace \"" + included.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, includes[i]); - } - else - { - // chameleon include - SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, sourceNamespace)); - stp.addInclude(s); - usedEmptyNamespaceSchema(included); - } - } - } - - { - // handle redefines - Redefine[] redefines = stp.getSchema().getRedefineArray(); - String sourceNamespace = stp.getChameleonNamespace(); - if (sourceNamespace == null) - sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace()); - for (int i = 0; i < redefines.length; i++) - { - Schema redefined = downloadSchema(redefines[i], null, redefines[i].getSchemaLocation()); - // if download fails, an error has already been reported. - if (redefined == null) - continue; - - if (emptyStringIfNull(redefined.getTargetNamespace()).equals(sourceNamespace)) - { - // non-chameleon case - SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, null)); - stp.addRedefine(s, redefines[i]); - hasRedefinitions = true; - } - else if (redefined.getTargetNamespace() != null) - { - // illegal include: included schema in wrong namespace. - StscState.get().error("Redefined schema has a target namespace \"" + redefined.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, redefines[i]); - } - else - { - // chameleon redefine - SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, sourceNamespace)); - stp.addRedefine(s, redefines[i]); - usedEmptyNamespaceSchema(redefined); - hasRedefinitions = true; - } - } - } - } - - if (!fetchRemainingEmptyNamespaceSchemas()) - break; - } - - // Build the lists of indirect references - // Make all the effort only if there are redefinitions - if (hasRedefinitions) - for (int i = 0; i < result.size(); i++) - { - SchemaToProcess schemaToProcess = (SchemaToProcess) result.get(i); - schemaToProcess.buildIndirectReferences(); - } - return (SchemaToProcess[])result.toArray(new SchemaToProcess[result.size()]); - } - - private static Reader copySchemaSource(String url, Reader reader, StscState state) - { - //Copy the schema file if it wasn't already copied - if (state.getSchemasDir() == null) - return reader; - - String schemalocation = state.sourceNameForUri(url); - File targetFile = new File(state.getSchemasDir(), schemalocation); - if (targetFile.exists()) - return reader; - - try - { - File parentDir = new File(targetFile.getParent()); - IOUtil.createDir(parentDir, null); - - CharArrayReader car = copy(reader); - XmlEncodingSniffer xes = new XmlEncodingSniffer(car, null); - Writer out = new OutputStreamWriter(new FileOutputStream(targetFile), xes.getXmlEncoding()); - IOUtil.copyCompletely(car, out); - - car.reset(); - return car; - } - catch (IOException e) - { - System.err.println("IO Error " + e); - return reader; - } - } - - private static InputStream copySchemaSource(String url, InputStream bytes, StscState state) - { - //Copy the schema file if it wasn't already copied - if (state.getSchemasDir() == null) - return bytes; - - String schemalocation = state.sourceNameForUri(url); - File targetFile = new File(state.getSchemasDir(), schemalocation); - if (targetFile.exists()) - return bytes; - - try - { - File parentDir = new File(targetFile.getParent()); - IOUtil.createDir(parentDir, null); - - ByteArrayInputStream bais = copy(bytes); - - FileOutputStream out = new FileOutputStream(targetFile); - IOUtil.copyCompletely(bais, out); - - bais.reset(); - return bais; - } - catch (IOException e) - { - System.err.println("IO Error " + e); - return bytes; - } - } - - private static void copySchemaSource(String urlLoc, StscState state, boolean forceCopy) - { - //Copy the schema file if it wasn't already copied - if (state.getSchemasDir()!=null) - { - String schemalocation = state.sourceNameForUri(urlLoc); - - File targetFile = new File(state.getSchemasDir(), schemalocation); - if (forceCopy || !targetFile.exists()) - { - try - { - File parentDir = new File(targetFile.getParent()); - IOUtil.createDir(parentDir, null); - - InputStream in = null; - URL url = new URL(urlLoc); - // Copy the file from filepath to schema[METADATA_PACKAGE_GEN]/src/ - try - { - in = url.openStream(); - } - catch (FileNotFoundException fnfe) - { - if (forceCopy && targetFile.exists()) - targetFile.delete(); - else - throw fnfe; - } - if (in != null) - { - FileOutputStream out = new FileOutputStream(targetFile); - IOUtil.copyCompletely(in, out); - } - } - catch (IOException e) - { - System.err.println("IO Error " + e); - // failure = true; - not cause for failure - } - } - } - } - - private static ByteArrayInputStream copy(InputStream is) throws IOException - { - byte [] buf = new byte[1024]; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - int bytesRead; - while(( bytesRead = is.read(buf, 0, 1024)) > 0) - baos.write(buf, 0, bytesRead); - - return new ByteArrayInputStream(baos.toByteArray()); - } - - private static CharArrayReader copy(Reader is) throws IOException - { - char[] buf = new char[1024]; - CharArrayWriter baos = new CharArrayWriter(); - - int bytesRead; - while(( bytesRead = is.read(buf, 0, 1024)) > 0) - baos.write(buf, 0, bytesRead); - - return new CharArrayReader(baos.toCharArray()); - } - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java deleted file mode 100644 index 365f73e..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java +++ /dev/null @@ -1,943 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.impl.common.NameUtil; -import org.apache.xmlbeans.QNameSetBuilder; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.UserType; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.SchemaStringEnumEntry; -import org.apache.xmlbeans.XmlByte; -import org.apache.xmlbeans.XmlShort; -import org.apache.xmlbeans.InterfaceExtension; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.PrePostExtension; -import org.apache.xmlbeans.BindingConfig; - -import java.util.*; -import java.math.BigInteger; - -import javax.xml.namespace.QName; - -public class StscJavaizer -{ - - /** - * XMLBEANS-307 - * if enumeration count is greater than 3668, - * xmlbeans scomp will fail with a code too large error - */ - private static final int MAX_ENUM_COUNT = 3668; - /** - * Does a topo walk of all the types to resolve them. - */ - public static void javaizeAllTypes(boolean javaize) - { - StscState state = StscState.get(); - - List allSeenTypes = new ArrayList(); - allSeenTypes.addAll(Arrays.asList(state.documentTypes())); - allSeenTypes.addAll(Arrays.asList(state.attributeTypes())); - allSeenTypes.addAll(Arrays.asList(state.globalTypes())); - - // First distribute the global names among the top entities. - if (javaize) - assignGlobalJavaNames(allSeenTypes); - - // now fully javaize everything deeply. - for (int i = 0; i < allSeenTypes.size(); i++) - { - SchemaType gType = (SchemaType)allSeenTypes.get(i); - if (javaize) - { - javaizeType((SchemaTypeImpl)gType); - String className = gType.getFullJavaName(); - if (className != null) - state.addClassname(className.replace('$', '.'), gType); - } - else - skipJavaizingType((SchemaTypeImpl)gType); - allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); - // We need to javaize the anonymous types defined inside redefined types - // since redefined type do not get a Java class of their own. - // The exception is complex types derived by restriction, since in this case - // anonymous types are not inherited - addAnonymousTypesFromRedefinition(gType, allSeenTypes); - } - } - - static void assignGlobalJavaNames(Collection schemaTypes) - { - HashSet usedNames = new HashSet(); - StscState state = StscState.get(); - - for (Iterator i = schemaTypes.iterator(); i.hasNext(); ) - { - SchemaTypeImpl sImpl = (SchemaTypeImpl)i.next(); - QName topName = findTopName(sImpl); - String pickedName = state.getJavaname(topName, sImpl.isDocumentType() ? - BindingConfig.QNAME_DOCUMENT_TYPE : BindingConfig.QNAME_TYPE); - if (sImpl.isUnjavaized()) - { - sImpl.setFullJavaName(pickFullJavaClassName(usedNames, findTopName(sImpl), pickedName, sImpl.isDocumentType(), sImpl.isAttributeType())); - sImpl.setFullJavaImplName(pickFullJavaImplName(usedNames, sImpl.getFullJavaName())); - - setUserTypes(sImpl, state); - - setExtensions(sImpl, state); - } - } - - verifyInterfaceNameCollisions(usedNames, state); - } - - private static void verifyInterfaceNameCollisions(Set usedNames, StscState state) - { - BindingConfig config = state.getBindingConfig(); - if (config == null) - return; - - InterfaceExtension[] exts = config.getInterfaceExtensions(); - for (int i = 0; i < exts.length; i++) - { - if (usedNames.contains(exts[i].getInterface().toLowerCase())) - state.error("InterfaceExtension interface '" + exts[i].getInterface() + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null); - - String handler = exts[i].getStaticHandler(); - if (handler != null && usedNames.contains(handler.toLowerCase())) - state.error("InterfaceExtension handler class '" + handler + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null); - } - - PrePostExtension[] prepost = config.getPrePostExtensions(); - for (int i = 0; i < prepost.length; i++) - { - String handler = prepost[i].getStaticHandler(); - if (handler != null && usedNames.contains(handler.toLowerCase())) - state.error("PrePostExtension handler class '" + handler + "' creates a name collision with one of the generated interfaces or classes.", XmlError.SEVERITY_ERROR, null); - } - } - - private static void setUserTypes(SchemaTypeImpl sImpl, StscState state) - { - BindingConfig config = state.getBindingConfig(); - - if (config != null) - { - UserType utype = config.lookupUserTypeForQName(sImpl.getName()); - if (utype != null) - { - sImpl.setUserTypeName(utype.getJavaName()); - sImpl.setUserTypeHandlerName(utype.getStaticHandler()); - } - } - } - - private static void setExtensions(SchemaTypeImpl sImpl, StscState state) - { - String javaName = sImpl.getFullJavaName(); - BindingConfig config = state.getBindingConfig(); - - if (javaName != null && config != null) - { - sImpl.setInterfaceExtensions(config.getInterfaceExtensions(javaName)); - sImpl.setPrePostExtension(config.getPrePostExtension(javaName)); - } - } - - private static boolean isStringType(SchemaType type) - { - if (type == null || type.getSimpleVariety() != SchemaType.ATOMIC) - return false; - return (type.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_STRING); - } - - static String pickConstantName(Set usedNames, String words) - { - String base = NameUtil.upperCaseUnderbar(words); - - if (base.length() == 0) - { - base = "X"; - } - - if (base.startsWith("INT_")) // reserved for int codes - { - base = "X_" + base; - } - - String uniqName; - int index = 1; - for (uniqName = base; usedNames.contains(uniqName); ) - { - index++; - uniqName = base + "_" + index; - } - - usedNames.add(uniqName); - - return uniqName; - } - - static void skipJavaizingType(SchemaTypeImpl sImpl) - { - if (sImpl.isJavaized()) - return; - - SchemaTypeImpl baseType = (SchemaTypeImpl)sImpl.getBaseType(); - if (baseType != null) - skipJavaizingType(baseType); - - sImpl.startJavaizing(); - secondPassProcessType(sImpl); - sImpl.finishJavaizing(); - } - - static void secondPassProcessType(SchemaTypeImpl sImpl) - { - if (isStringType(sImpl)) - { - XmlAnySimpleType[] enumVals = sImpl.getEnumerationValues(); - - // if this is an enumerated string type, values are to be - // javaized as constants. - if (enumVals != null) - { - //ERROR is found at > 3668 - if (enumVals.length > MAX_ENUM_COUNT) - { - StscState.get().warning("SchemaType Enumeration found with too many enumeration values " + - "to create a Java enumeration. The base SchemaType \"" + - sImpl.getBaseEnumType() + "\" will be used instead", XmlError.SEVERITY_WARNING, null); - - sImpl = (SchemaTypeImpl) sImpl.getBaseEnumType(); - } - else - { - SchemaStringEnumEntry[] entryArray = new SchemaStringEnumEntry[enumVals.length]; - SchemaType basedOn = sImpl.getBaseEnumType(); - if (basedOn == sImpl) - { - Set usedNames = new HashSet(); - for (int i = 0; i < enumVals.length; i++) - { - String val = enumVals[i].getStringValue(); - - entryArray[i] = new SchemaStringEnumEntryImpl(val, i + 1, pickConstantName(usedNames, val)); - } - } - else - { - for (int i = 0; i < enumVals.length; i++) - { - String val = enumVals[i].getStringValue(); - entryArray[i] = basedOn.enumEntryForString(val); - } - } - sImpl.setStringEnumEntries(entryArray); - } - } - } - } - - static void javaizeType(SchemaTypeImpl sImpl) - { - if (sImpl.isJavaized()) - return; - - SchemaTypeImpl baseType = (SchemaTypeImpl)sImpl.getBaseType(); - if (baseType != null) - javaizeType(baseType); - if (sImpl.getContentBasedOnType() != null && sImpl.getContentBasedOnType() != baseType) - javaizeType((SchemaTypeImpl) sImpl.getContentBasedOnType()); - - sImpl.startJavaizing(); - - sImpl.setCompiled(true); - - secondPassProcessType(sImpl); - - if (!sImpl.isSimpleType()) - { - SchemaProperty[] eltProps = sImpl.getElementProperties(); - SchemaProperty[] attrProps = sImpl.getAttributeProperties(); - - // Handing out java names - this permits us to avoid collisions. - Set usedPropNames = new HashSet(); - - // First, copy all used property names from base, since these - // cannnot be changed at this point and they may be arbitrary - // because of derivation by restriction and the "nopvr" switch - SchemaProperty[] baseProps = baseType.getProperties(); - for (int i = 0; i < baseProps.length; i++) - { - String name = baseProps[i].getJavaPropertyName(); - assert !usedPropNames.contains(name); - usedPropNames.add(name); - } - - // count in the methods from extension interfaces - avoidExtensionMethods(usedPropNames, sImpl); - - // Assign names in two passes: first inherited names, then others. - for (boolean doInherited = true; ; doInherited = false) - { - if (eltProps.length > 0) - assignJavaPropertyNames(usedPropNames, eltProps, baseType, doInherited); - - assignJavaPropertyNames(usedPropNames, attrProps, baseType, doInherited); - - if (doInherited == false) - break; - } - - SchemaProperty[] allprops = sImpl.getProperties(); - - // determine whether order insensitive - boolean insensitive = isPropertyModelOrderInsensitive(allprops); - - // Fill in the java type codes now. - // This depends on recursive type information, so it's done in typechecking - assignJavaTypeCodes(allprops); - - sImpl.setOrderSensitive(!insensitive); - } - - // assign java type names to anonymous types - // for redefined types, this step was performed when javaizing the redefinition - if (sImpl.getFullJavaName() != null || sImpl.getOuterType() != null) - assignJavaAnonymousTypeNames(sImpl); - - sImpl.finishJavaizing(); - } - - private static final String[] PREFIXES = new String[]{"get", "xget", "isNil", "isSet", "sizeOf", "set", - "xset", "addNew", "setNil", "unset", "insert", "add", "insertNew", "addNew", "remove"}; - - private static void avoidExtensionMethods(Set usedPropNames, SchemaTypeImpl sImpl) - { - InterfaceExtension[] exts = sImpl.getInterfaceExtensions(); - if (exts != null) for (int i = 0; i < exts.length; i++) - { - InterfaceExtension ext = exts[i]; - InterfaceExtension.MethodSignature[] methods = ext.getMethods(); - for (int j = 0; j < methods.length; j++) - { - String methodName = methods[j].getName(); - for (int k = 0; k < PREFIXES.length; k++) - { - String prefix = PREFIXES[k]; - if (methodName.startsWith(prefix)) - usedPropNames.add(methodName.substring(prefix.length())); - } - } - } - } - - static void assignJavaAnonymousTypeNames(SchemaTypeImpl outerType) - { - Set usedTypeNames = new HashSet(); - SchemaType[] anonymousTypes = outerType.getAnonymousTypes(); - StscState state = StscState.get(); - - int nrOfAnonTypes = anonymousTypes.length; - if (outerType.isRedefinition()) - { - // We have to add the anonymous types for redefinitions to the list - // since they don't have another outer class - ArrayList list = new ArrayList(); - addAnonymousTypesFromRedefinition(outerType, list); - if (list.size() > 0) - { - SchemaType[] temp = new SchemaType[nrOfAnonTypes + list.size()]; - list.toArray(temp); - System.arraycopy(anonymousTypes, 0, temp, list.size(), nrOfAnonTypes); - anonymousTypes = temp; - } - } - - // Because we generate nested java interfaces, and nested - // interface names must not be the same as an ancestor, use up - // the ancestors - - for ( SchemaType scanOuterType = outerType ; - scanOuterType != null ; - scanOuterType = scanOuterType.getOuterType() ) - { - usedTypeNames.add( scanOuterType.getShortJavaName() ); - } - - for ( SchemaType scanOuterType = outerType ; - scanOuterType != null ; - scanOuterType = scanOuterType.getOuterType() ) - { - usedTypeNames.add( scanOuterType.getShortJavaImplName() ); - } - - // and because things are problematic if an inner type name - // is the same as a top-level package name, also get rid of that - // collision - usedTypeNames.add(getOutermostPackage(outerType.getFullJavaName())); - - // assign names - for (int i = 0; i < anonymousTypes.length; i++) - { - SchemaTypeImpl sImpl = (SchemaTypeImpl)anonymousTypes[i]; - if (sImpl == null) // already handled in first pass - continue; - if (sImpl.isSkippedAnonymousType()) - continue; - String localname = null; - String javaname = null; - - SchemaField containerField = sImpl.getContainerField(); - if (containerField != null) - { - QName qname = sImpl.getContainerField().getName(); - localname = qname.getLocalPart(); - javaname = state.getJavaname(sImpl.getContainerField().getName(), BindingConfig.QNAME_TYPE); - } - else - { - // not defined inside an Elt or Attr: must be a nested simple type - switch (sImpl.getOuterType().getSimpleVariety()) - { - case SchemaType.UNION: - javaname = "Member"; break; - case SchemaType.LIST: - javaname = "Item"; break; - case SchemaType.ATOMIC: - default: - assert(false) : "Weird type " + sImpl.toString(); - javaname = "Base"; break; - } - } - - if (i < nrOfAnonTypes) - { - sImpl.setShortJavaName( - pickInnerJavaClassName(usedTypeNames, localname, javaname)); - sImpl.setShortJavaImplName( - pickInnerJavaImplName(usedTypeNames, localname, javaname == null ? null : javaname + "Impl")); - } - else - { - // This comes from redefined types, so we have to compute the - // full name here - sImpl.setFullJavaName(outerType.getFullJavaName() + "$" + - pickInnerJavaClassName(usedTypeNames, localname, javaname)); - sImpl.setFullJavaImplName(outerType.getFullJavaImplName() + "$" + - pickInnerJavaImplName(usedTypeNames, localname, javaname == null ? null : javaname + "Impl")); - } - - // TODO(radup) why is this inside this loop here? - setExtensions(sImpl, state); - } - } - - static void assignJavaPropertyNames(Set usedNames, SchemaProperty[] props, SchemaType baseType, boolean doInherited) - { - StscState state = StscState.get(); - - // two passes: first deal with inherited properties, then with new ones. - // this ensures that we match up with base class definitions cleanly - // BUGBUG(radup) We have to look for particles that have been removed - // in the derivation tree for this type using derivation by restriction, - // because they have not been removed in Java and may collide with - // this type's properties. - - for (int i = 0; i < props.length; i++) - { - SchemaPropertyImpl sImpl = (SchemaPropertyImpl)props[i]; - - SchemaProperty baseProp = - (sImpl.isAttribute() ? - baseType.getAttributeProperty(sImpl.getName()) : - baseType.getElementProperty(sImpl.getName())); - - if ((baseProp != null) != doInherited) - continue; - - QName propQName = sImpl.getName(); - - String theName; - - if (baseProp == null) - theName = pickJavaPropertyName(usedNames, propQName.getLocalPart(), - state.getJavaname(propQName, sImpl.isAttribute() ? BindingConfig.QNAME_ACCESSOR_ATTRIBUTE : - BindingConfig.QNAME_ACCESSOR_ELEMENT)); - else - theName = baseProp.getJavaPropertyName(); - - sImpl.setJavaPropertyName(theName); - - boolean isArray = (sImpl.getMaxOccurs() == null || - sImpl.getMaxOccurs().compareTo(BigInteger.ONE) > 0); - boolean isSingleton = !isArray && (sImpl.getMaxOccurs().signum() > 0); - boolean isOption = isSingleton && (sImpl.getMinOccurs().signum() == 0); - SchemaType javaBasedOnType = sImpl.getType(); - - if (baseProp != null) - { - if (baseProp.extendsJavaArray()) - { - isSingleton = false; - isOption = false; - isArray = true; - } - if (baseProp.extendsJavaSingleton()) - { - isSingleton = true; - } - if (baseProp.extendsJavaOption()) - { - isOption = true; - } - javaBasedOnType = baseProp.javaBasedOnType(); - } - - sImpl.setExtendsJava(javaBasedOnType.getRef(), isSingleton, isOption, isArray); - } - - } - - static void assignJavaTypeCodes(SchemaProperty[] properties) - { - for (int i = 0; i < properties.length; i++) - { - SchemaPropertyImpl sImpl = (SchemaPropertyImpl)properties[i]; - SchemaType sType = sImpl.javaBasedOnType(); - sImpl.setJavaTypeCode(javaTypeCodeForType(sType)); - } - } - - static int javaTypeCodeInCommon(SchemaType[] types) - { - if (types == null || types.length == 0) - return SchemaProperty.XML_OBJECT; - - int code = javaTypeCodeForType(types[0]); - if (code == SchemaProperty.JAVA_OBJECT) - return code; - for (int i = 1; i < types.length; i++) - { - // if any two are different, the answer is java.lang.Object - if (code != javaTypeCodeForType(types[i])) - return SchemaProperty.JAVA_OBJECT; - } - return code; - } - - static int javaTypeCodeForType(SchemaType sType) - { - if (!sType.isSimpleType()) - return SchemaProperty.XML_OBJECT; - - if (((SchemaTypeImpl)sType).getUserTypeHandlerName() != null) - return SchemaProperty.JAVA_USER; - - if (sType.getSimpleVariety() == SchemaType.UNION) - { - // see if we can find an interesting common base type, e.g., for string enums - SchemaType baseType = sType.getUnionCommonBaseType(); - if (baseType != null && !baseType.isURType()) - sType = baseType; - else - return javaTypeCodeInCommon(sType.getUnionConstituentTypes()); - } - - if (sType.getSimpleVariety() == SchemaType.LIST) - return SchemaProperty.JAVA_LIST; - - if (sType.isURType()) - return SchemaProperty.XML_OBJECT; - - switch (sType.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_ANY_SIMPLE: - // return SchemaProperty.XML_OBJECT; - return SchemaProperty.JAVA_STRING; - - case SchemaType.BTC_BOOLEAN: - return SchemaProperty.JAVA_BOOLEAN; - - case SchemaType.BTC_BASE_64_BINARY: - return SchemaProperty.JAVA_BYTE_ARRAY; - - case SchemaType.BTC_HEX_BINARY: - return SchemaProperty.JAVA_BYTE_ARRAY; - - case SchemaType.BTC_ANY_URI: - return SchemaProperty.JAVA_STRING; - - case SchemaType.BTC_QNAME: - return SchemaProperty.JAVA_QNAME; - - case SchemaType.BTC_NOTATION: - return SchemaProperty.XML_OBJECT; - - case SchemaType.BTC_FLOAT: - return SchemaProperty.JAVA_FLOAT; - - case SchemaType.BTC_DOUBLE: - return SchemaProperty.JAVA_DOUBLE; - - case SchemaType.BTC_DECIMAL: - switch (sType.getDecimalSize()) - { - case SchemaType.SIZE_BYTE: - return SchemaProperty.JAVA_BYTE; - case SchemaType.SIZE_SHORT: - return SchemaProperty.JAVA_SHORT; - case SchemaType.SIZE_INT: - return SchemaProperty.JAVA_INT; - case SchemaType.SIZE_LONG: - return SchemaProperty.JAVA_LONG; - case SchemaType.SIZE_BIG_INTEGER: - return SchemaProperty.JAVA_BIG_INTEGER; - case SchemaType.SIZE_BIG_DECIMAL: - default: - return SchemaProperty.JAVA_BIG_DECIMAL; - } - - case SchemaType.BTC_STRING: - if (isStringType(sType.getBaseEnumType())) - { - // This is necessary for local types, etc. - // schema enums with > ~3668 cause a Java Src file to be created - // that cannot be compiled due to JVM restrictions - // FIXFIX: http://issues.apache.org/jira/browse/XMLBEANS-307 - // FIXFIX: XMLBeans scomp throws error "code too large" - if (sType.getEnumerationValues() != null && - sType.getEnumerationValues().length > MAX_ENUM_COUNT) - { - return SchemaProperty.JAVA_STRING; - } - else - { - return SchemaProperty.JAVA_ENUM; - } - } - return SchemaProperty.JAVA_STRING; - - case SchemaType.BTC_DURATION: - return SchemaProperty.JAVA_GDURATION; - - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_DATE: - // return SchemaProperty.JAVA_DATE; // converted to calendar - - case SchemaType.BTC_TIME: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - // return SchemaProperty.JAVA_GDATE; // converted to calendar (JAX-B) - return SchemaProperty.JAVA_CALENDAR; - - default: - assert(false) : "unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode(); - throw new IllegalStateException("unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode() + " of " + sType.getPrimitiveType().getName()); - } - } - - static boolean isPropertyModelOrderInsensitive(SchemaProperty[] properties) - { - for (int i = 0; i < properties.length; i++) - { - SchemaProperty prop = properties[i]; - if (prop.hasNillable() == SchemaProperty.VARIABLE) - return false; - if (prop.hasDefault() == SchemaProperty.VARIABLE) - return false; - if (prop.hasFixed() == SchemaProperty.VARIABLE) - return false; - if (prop.hasDefault() != SchemaProperty.NEVER && - prop.getDefaultText() == null) - return false; - } - return true; - } - - static boolean protectReservedGlobalClassNames(String name) - { - int i = name.lastIndexOf('.'); - String lastSegment = name.substring(i + 1); - if (lastSegment.endsWith("Document") && !lastSegment.equals("Document")) - return true; - return false; - } - - static boolean protectReservedInnerClassNames(String name) - { - return (name.equals("Enum") || name.equals("Factory")); - } - - static String[] PROTECTED_PROPERTIES = { - "StringValue", - "BooleanValue", - "ByteValue", - "ShortValue", - "IntValue", - "LongValue", - "BigIntegerValue", - "BigDecimalValue", - "FloatValue", - "DoubleValue", - "ByteArrayValue", - "EnumValue", - "CalendarValue", - "DateValue", - "GDateValue", - "GDurationValue", - "QNameValue", - "ListValue", - "ObjectValue", - "Class", - }; - static Set PROTECTED_PROPERTIES_SET = new HashSet(Arrays.asList(PROTECTED_PROPERTIES)); - - static boolean protectReservedPropertyNames(String name) - { - return PROTECTED_PROPERTIES_SET.contains(name) || - (name.endsWith("Array") && !name.equals("Array")); - } - - static String pickFullJavaClassName(Set usedNames, QName qName, String configname, boolean isDocument, boolean isAttrType) - { - String base; - boolean protect; - - if (configname != null && configname.indexOf('.') >= 0) - { - // a configname with dots defines the fully qualified java class name - base = configname; - protect = protectReservedGlobalClassNames(base); - } - else - { - StscState state = StscState.get(); - String uri = qName.getNamespaceURI(); - - base = NameUtil.getClassNameFromQName(qName); - - // Check to see if we have a mapping from namespace URI to Java package - // name. If so, apply the mapped package prefix at the beginning of - // the base name - - String pkgPrefix = state.getPackageOverride(uri); - - if (pkgPrefix != null) - { - // Form the new qualified class name from the new package name - // and the old class name - base = pkgPrefix + "." + base.substring(base.lastIndexOf('.') + 1); - } - - // See if there is a prefix... - String javaPrefix = state.getJavaPrefix(uri); - if (javaPrefix != null) - base = base.substring(0, base.lastIndexOf('.') + 1) + javaPrefix + base.substring(base.lastIndexOf('.') + 1); - - // a configname without dots may override the shortname part. - if (configname != null) - { - base = base.substring(0, base.lastIndexOf('.') + 1) + configname; - } - - protect = protectReservedGlobalClassNames(base); - if (configname == null) - { - // add special suffix - if (isDocument) - base = base + "Document"; - else if (isAttrType) - base = base + "Attribute"; - - // add configured suffix - String javaSuffix = state.getJavaSuffix(uri); - if (javaSuffix != null) - base = base + javaSuffix; - } - } - - String outermostPkg = getOutermostPackage(base); - - int index = 1; - String uniqName; - if (protect) - uniqName = base + index; - else - uniqName = base; - while (usedNames.contains(uniqName.toLowerCase()) || uniqName.equals(outermostPkg)) - { - index++; - uniqName = base + index; - } - - usedNames.add(uniqName.toLowerCase()); - - return uniqName; - } - - static String getOutermostPackage(String fqcn) - { - if (fqcn == null) - return ""; - - // remove class name - int lastdot = fqcn.indexOf('.'); - if (lastdot < 0) - return ""; - - // remove outer package names - return fqcn.substring(0, lastdot); - } - - static String pickFullJavaImplName(Set usedNames, String intfName) - { - // Strip off the package from the class name so we can replace it - String className = intfName; - String pkgName = null; - int index = intfName.lastIndexOf('.'); - if (index >= 0) - { - className = intfName.substring(index + 1); - pkgName = intfName.substring(0, index); - } - - // Form the new qualified class name from the new package name - // and the old class name - String base = pkgName + ".impl." + className + "Impl"; - - index = 1; - String uniqName = base; - while (usedNames.contains(uniqName.toLowerCase())) - { - index++; - uniqName = base + index; - } - - usedNames.add(uniqName.toLowerCase()); - - return uniqName; - } - - static String pickJavaPropertyName(Set usedNames, String localName, String javaName) - { - if (javaName == null) - javaName = NameUtil.upperCamelCase(localName); - boolean protect = protectReservedPropertyNames(javaName); - String uniqName; - int index = 1; - if (protect) - uniqName = javaName + index; - else - uniqName = javaName; - while (usedNames.contains(uniqName)) - { - index++; - uniqName = javaName + index; - } - - usedNames.add(uniqName); - - return uniqName; - } - - static String pickInnerJavaClassName(Set usedNames, String localName, String javaName) - { - if (javaName == null) - javaName = NameUtil.upperCamelCase(localName); - boolean protect = protectReservedInnerClassNames(javaName); - String uniqName; - int index = 1; - if (protect) - uniqName = javaName + index; - else - uniqName = javaName; - while (usedNames.contains(uniqName)) - { - index++; - uniqName = javaName + index; - } - - usedNames.add(uniqName); - - return uniqName; - } - - static String pickInnerJavaImplName(Set usedNames, String localName, String javaName) - { - if (javaName == null) - javaName = NameUtil.upperCamelCase(localName) + "Impl"; - String uniqName = javaName; - int index = 1; - while (usedNames.contains(uniqName)) - { - index++; - uniqName = javaName + index; - } - - usedNames.add(uniqName); - - return uniqName; - } - - static QName findTopName(SchemaType sType) - { - if (sType.getName() != null) - return sType.getName(); - - if (sType.isDocumentType()) - { - // A document type must have a content model consisting of a single elt - if (sType.getContentModel() == null || sType.getContentModel().getParticleType() != SchemaParticle.ELEMENT) - throw new IllegalStateException(); - return (sType.getDocumentElementName()); - } - - if (sType.isAttributeType()) - { - if (sType.getAttributeModel() == null || sType.getAttributeModel().getAttributes().length != 1) - throw new IllegalStateException(); - return sType.getAttributeTypeAttributeName(); - } - - SchemaField sElt = sType.getContainerField(); - assert(sElt != null); - assert(sType.getOuterType() == null); - return sElt.getName(); - } - - static void addAnonymousTypesFromRedefinition(SchemaType sType, List result) - { - while (((SchemaTypeImpl)sType).isRedefinition() && - (sType.getDerivationType() == SchemaType.DT_EXTENSION || - sType.isSimpleType())) - { - sType = sType.getBaseType(); - SchemaType[] newAnonTypes = sType.getAnonymousTypes(); - if (newAnonTypes.length > 0) - result.addAll(Arrays.asList(newAnonTypes)); - } - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java deleted file mode 100644 index 0c96d66..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java +++ /dev/null @@ -1,303 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.XmlErrorCodes; - -import java.math.BigInteger; - -import java.util.*; - -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelElement; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelAttribute; -import org.apache.xmlbeans.impl.xb.xsdschema.SimpleType; -import org.apache.xmlbeans.impl.xb.xsdschema.Attribute; -import org.apache.xmlbeans.impl.xb.xsdschema.Element; -import org.apache.xmlbeans.impl.xb.xsdschema.KeyrefDocument.Keyref; -import javax.xml.namespace.QName; - -public class StscResolver -{ - /** - * Does a topo walk of all the types to resolve them. - */ - public static void resolveAll() - { - // resolve tree of types - StscState state = StscState.get(); - - SchemaType[] documentTypes = state.documentTypes(); - for (int i = 0 ; i < documentTypes.length ; i++) - resolveSubstitutionGroup((SchemaTypeImpl)documentTypes[i]); - - List allSeenTypes = new ArrayList(); - allSeenTypes.addAll(Arrays.asList(state.documentTypes())); - allSeenTypes.addAll(Arrays.asList(state.attributeTypes())); - allSeenTypes.addAll(Arrays.asList(state.redefinedGlobalTypes())); - allSeenTypes.addAll(Arrays.asList(state.globalTypes())); - - for (int i = 0; i < allSeenTypes.size(); i++) - { - SchemaType gType = (SchemaType)allSeenTypes.get(i); - resolveType((SchemaTypeImpl)gType); - allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes())); - } - - // Resolve all keyref refs - resolveIdentityConstraints(); - } - - public static boolean resolveType(SchemaTypeImpl sImpl) - { - if (sImpl.isResolved()) - return true; - if (sImpl.isResolving()) - { - StscState.get().error("Cyclic dependency error", XmlErrorCodes.CYCLIC_DEPENDENCY, sImpl.getParseObject()); - return false; // cyclic dependency error - } - // System.out.println("Resolving " + sImpl); - - sImpl.startResolving(); - - if (sImpl.isDocumentType()) - resolveDocumentType(sImpl); - else if (sImpl.isAttributeType()) - resolveAttributeType(sImpl); - else if (sImpl.isSimpleType()) - StscSimpleTypeResolver.resolveSimpleType(sImpl); - else - StscComplexTypeResolver.resolveComplexType(sImpl); - - sImpl.finishResolving(); - // System.out.println("Finished resolving " + sImpl); - return true; - } - - public static boolean resolveSubstitutionGroup(SchemaTypeImpl sImpl) - { - assert sImpl.isDocumentType(); - - if (sImpl.isSGResolved()) - return true; - if (sImpl.isSGResolving()) - { - StscState.get().error("Cyclic dependency error", XmlErrorCodes.CYCLIC_DEPENDENCY, sImpl.getParseObject()); - return false; // cyclic dependency error - } - - sImpl.startResolvingSGs(); - - // Resolve substitution group - - TopLevelElement elt = (TopLevelElement)sImpl.getParseObject(); - SchemaTypeImpl substitutionGroup = null; - QName eltName = new QName(sImpl.getTargetNamespace(), elt.getName()); - - // BUG: How do I tell if the type is in this compilation unit? - if (elt.isSetSubstitutionGroup()) - { - substitutionGroup = StscState.get().findDocumentType(elt.getSubstitutionGroup(), - sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); - - if (substitutionGroup == null) - StscState.get().notFoundError(elt.getSubstitutionGroup(), SchemaType.ELEMENT, elt.xgetSubstitutionGroup(), true); - // recovery - ignore substitution group - else if (! resolveSubstitutionGroup(substitutionGroup) ) - substitutionGroup = null; - else - sImpl.setSubstitutionGroup(elt.getSubstitutionGroup()); - } - - // Walk up the chain of subtitution groups adding this schematype to each head's - // member list - while (substitutionGroup != null) - { - - substitutionGroup.addSubstitutionGroupMember(eltName); - - if (substitutionGroup.getSubstitutionGroup() == null) - break; - - substitutionGroup = StscState.get().findDocumentType( - substitutionGroup.getSubstitutionGroup(), substitutionGroup.getChameleonNamespace(), null/*no dependency added*/); - - assert substitutionGroup != null : "Could not find document type for: " + substitutionGroup.getSubstitutionGroup(); - - if (! resolveSubstitutionGroup(substitutionGroup) ) - substitutionGroup = null; // cyclic dependency - no subst group - - } - - sImpl.finishResolvingSGs(); - return true; - - } - - public static void resolveDocumentType ( SchemaTypeImpl sImpl ) - { - assert sImpl.isResolving(); - - assert sImpl.isDocumentType(); - - - // translate the global element associated with this document type - // and construct a content model which allows just that element - - List anonTypes = new ArrayList(); - - SchemaGlobalElementImpl element = - (SchemaGlobalElementImpl) - StscTranslator.translateElement( - (Element) sImpl.getParseObject(), - sImpl.getTargetNamespace(), sImpl.isChameleon(), null, null, - anonTypes, sImpl ); - - SchemaLocalElementImpl contentModel = null; - - if (element != null) - { - StscState.get().addGlobalElement( element ); - - contentModel = new SchemaLocalElementImpl(); - - contentModel.setParticleType( SchemaParticle.ELEMENT ); - StscTranslator.copyGlobalElementToLocalElement( element, contentModel ); - contentModel.setMinOccurs( BigInteger.ONE ); - contentModel.setMaxOccurs( BigInteger.ONE ); - - contentModel.setTransitionNotes(QNameSet.EMPTY, true); - } - - Map elementPropertyModel = - StscComplexTypeResolver.buildContentPropertyModelByQName( - contentModel, sImpl ); - - SchemaTypeImpl baseType = sImpl.getSubstitutionGroup() == null ? - BuiltinSchemaTypeSystem.ST_ANY_TYPE : - StscState.get().findDocumentType(sImpl.getSubstitutionGroup(), - sImpl.isChameleon() ? sImpl.getTargetNamespace() : null, null/*already added*/) - ; - - sImpl.setBaseTypeRef( baseType.getRef() ); - sImpl.setBaseDepth( baseType.getBaseDepth() + 1 ); - sImpl.setDerivationType( SchemaType.DT_RESTRICTION ); - sImpl.setComplexTypeVariety( SchemaType.ELEMENT_CONTENT ); - - sImpl.setContentModel( - contentModel, new SchemaAttributeModelImpl(), - elementPropertyModel, Collections.EMPTY_MAP, false ); - - sImpl.setWildcardSummary( - QNameSet.EMPTY, false, QNameSet.EMPTY, false ); - - sImpl.setAnonymousTypeRefs( makeRefArray( anonTypes ) ); - - - - } - - public static void resolveAttributeType ( SchemaTypeImpl sImpl ) - { - assert sImpl.isResolving(); - - assert sImpl.isAttributeType(); - - List anonTypes = new ArrayList(); - - SchemaGlobalAttributeImpl attribute = - (SchemaGlobalAttributeImpl) StscTranslator.translateAttribute( - (Attribute) sImpl.getParseObject(), sImpl.getTargetNamespace(), null, - sImpl.isChameleon(), anonTypes, sImpl, null, false ); - - SchemaAttributeModelImpl attributeModel = new SchemaAttributeModelImpl(); - - if (attribute != null) - { - StscState.get().addGlobalAttribute( attribute ); - - SchemaLocalAttributeImpl attributeCopy = new SchemaLocalAttributeImpl(); - StscTranslator.copyGlobalAttributeToLocalAttribute( attribute, attributeCopy ); - attributeModel.addAttribute( attributeCopy ); - } - - sImpl.setBaseTypeRef( BuiltinSchemaTypeSystem.ST_ANY_TYPE.getRef() ); - sImpl.setBaseDepth( sImpl.getBaseDepth() + 1 ); - sImpl.setDerivationType( SchemaType.DT_RESTRICTION ); - sImpl.setComplexTypeVariety( SchemaType.EMPTY_CONTENT ); - - Map attributePropertyModel = - StscComplexTypeResolver.buildAttributePropertyModelByQName( - attributeModel, sImpl ); - - sImpl.setContentModel( - null, attributeModel, Collections.EMPTY_MAP, attributePropertyModel, false ); - - sImpl.setWildcardSummary( - QNameSet.EMPTY, false, QNameSet.EMPTY, false ); - - sImpl.setAnonymousTypeRefs( makeRefArray( anonTypes ) ); - } - - private static SchemaType.Ref[] makeRefArray(Collection typeList) - { - SchemaType.Ref[] result = new SchemaType.Ref[typeList.size()]; - int j = 0; - for (Iterator i = typeList.iterator(); i.hasNext(); j++) - result[j] = ((SchemaType)i.next()).getRef(); - return result; - } - - - public static void resolveIdentityConstraints() - { - StscState state = StscState.get(); - SchemaIdentityConstraintImpl[] idcs = state.idConstraints(); - - for (int i = 0 ; i < idcs.length ; i++) - { - if (!idcs[i].isResolved()) - { - Keyref xsdkr = (Keyref)idcs[i].getParseObject(); - QName keyName = xsdkr.getRefer(); - SchemaIdentityConstraintImpl key = null; - - key = state.findIdConstraint(keyName, idcs[i].getChameleonNamespace(), idcs[i].getTargetNamespace()); - if (key == null) - { - state.notFoundError(keyName, SchemaType.IDENTITY_CONSTRAINT, xsdkr, true); - } - else - { - if (key.getConstraintCategory() == SchemaIdentityConstraintImpl.CC_KEYREF) - state.error(XmlErrorCodes.IDENTITY_CONSTRAINT_PROPERTIES$KEYREF_REFERS_TO_KEYREF, - null, idcs[i].getParseObject()); - - if (key.getFields().length != idcs[i].getFields().length) - state.error(XmlErrorCodes.IDENTITY_CONSTRAINT_PROPERTIES$KEY_KEYREF_FIELD_COUNT_EQ, - null, idcs[i].getParseObject()); - - idcs[i].setReferencedKey(key.getRef()); - } - } - } - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java deleted file mode 100644 index a3b51b8..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java +++ /dev/null @@ -1,1247 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import java.util.*; -import java.util.List; -import java.math.BigInteger; - -import javax.xml.namespace.QName; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.apache.xmlbeans.impl.regex.RegularExpression; -import org.apache.xmlbeans.impl.regex.ParseException; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlByte; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlInteger; -import org.apache.xmlbeans.XmlNonNegativeInteger; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlPositiveInteger; -import org.apache.xmlbeans.XmlShort; -import org.apache.xmlbeans.XmlUnsignedByte; -import org.apache.xmlbeans.impl.xb.xsdschema.*; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; - -public class StscSimpleTypeResolver -{ - - /************************************************************************** - * SIMPLE TYPE RESOLUTION HERE - * - * Simple types can be declared as lists, unions, or restrictions. - * These three cases are treated separately in resolveListType, - * resolveUnionType, and resolveSimpleRestrictionType. - * - * The intricate work with facets is done in the restriction case, - * using method called resolveFacets (the union and list cases have - * trivial facet rules). Then all simple types call resolveProperties - * in the end to have their "fundamental facets" resolved. - */ - - public static void resolveSimpleType(SchemaTypeImpl sImpl) - { - SimpleType parseSt = (SimpleType)sImpl.getParseObject(); - - assert sImpl.isSimpleType(); - - Schema schema = StscComplexTypeResolver.getSchema(parseSt); - - // Verify: have list, union, or restriction, but not more than one - int count = - (parseSt.isSetList() ? 1 : 0) + - (parseSt.isSetUnion() ? 1 : 0) + - (parseSt.isSetRestriction() ? 1 : 0); - if (count > 1) - { - StscState.get().error( - "A simple type must define either a list, a union, or a restriction: more than one found.", - XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN, - parseSt); - // recovery: treat it as the first of list, union, restr - } - else if (count < 1) - { - StscState.get().error("A simple type must define either a list, a union, or a restriction: none was found.", - XmlErrorCodes.MALFORMED_SIMPLE_TYPE_DEFN, - parseSt); - // recovery: treat it as restriction of anySimpleType - resolveErrorSimpleType(sImpl); - return; - } - - // Set final flags - boolean finalRest = false; - boolean finalList = false; - boolean finalUnion = false; - - Object finalValue = null; - if (parseSt.isSetFinal()) - { - finalValue = parseSt.getFinal(); - } - // Inspect the finalDefault attribute on the schema - else if (schema != null && schema.isSetFinalDefault()) - { - finalValue = schema.getFinalDefault(); - } - - if (finalValue != null) - { - if (finalValue instanceof String) - { - if ("#all".equals((String)finalValue)) - { - finalRest = finalList = finalUnion = true; - } - } - else if (finalValue instanceof List) - { - List lFinalValue = (List) finalValue; - if (lFinalValue.contains("restriction")) - finalRest = true; - - if (lFinalValue.contains("list")) - finalList = true; - - if (lFinalValue.contains("union")) - finalUnion= true; - } - } - - sImpl.setSimpleFinal(finalRest, finalList, finalUnion); - - List anonTypes = new ArrayList(); - - if (parseSt.getList() != null) - resolveListType(sImpl, parseSt.getList(), anonTypes); - else if (parseSt.getUnion() != null) - resolveUnionType(sImpl, parseSt.getUnion(), anonTypes); - else if (parseSt.getRestriction() != null) - resolveSimpleRestrictionType(sImpl, parseSt.getRestriction(), anonTypes); - - sImpl.setAnonymousTypeRefs(makeRefArray(anonTypes)); - } - - private static SchemaType.Ref[] makeRefArray(Collection typeList) - { - SchemaType.Ref[] result = new SchemaType.Ref[typeList.size()]; - int j = 0; - for (Iterator i = typeList.iterator(); i.hasNext(); j++) - result[j] = ((SchemaType)i.next()).getRef(); - return result; - } - - static void resolveErrorSimpleType(SchemaTypeImpl sImpl) - { - sImpl.setSimpleTypeVariety(SchemaType.ATOMIC); - sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1); - sImpl.setPrimitiveTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - } - - static void resolveListType(SchemaTypeImpl sImpl, org.apache.xmlbeans.impl.xb.xsdschema.ListDocument.List parseList, List anonTypes) - { - StscState state = StscState.get(); - - sImpl.setSimpleTypeVariety(SchemaType.LIST); - sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1); - sImpl.setDerivationType(SchemaType.DT_RESTRICTION); - - if (sImpl.isRedefinition()) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, - new Object[] { "list" }, parseList); - // recovery: oh well. - } - - QName itemName = parseList.getItemType(); - LocalSimpleType parseInner = parseList.getSimpleType(); - - if (itemName != null && parseInner != null) - { - state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$LIST_HAS_BOTH_ITEM_OR_SIMPLE_TYPE, null, parseList); - // recovery: ignore the inner simple type. - parseInner = null; - } - - SchemaTypeImpl itemImpl; - XmlObject errorLoc; - - if (itemName != null) - { - itemImpl = state.findGlobalType(itemName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); - errorLoc = parseList.xgetItemType(); - if (itemImpl == null) - { - state.notFoundError(itemName, SchemaType.TYPE, parseList.xgetItemType(), true); - // recovery: treat it as a list of anySimpleType - itemImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - } - else if (parseInner != null) - { - itemImpl = StscTranslator.translateAnonymousSimpleType(parseInner, - sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl); - errorLoc = parseInner; - } - else - { - state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$LIST_HAS_NEITHER_ITEM_OR_SIMPLE_TYPE, null, parseList); - // recovery: treat it as an extension of anySimpleType - resolveErrorSimpleType(sImpl); - return; - } - - // Verify final restrictions - if (itemImpl.finalList()) - state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$LIST_FINAL, null, parseList); - - // Recursion... - StscResolver.resolveType(itemImpl); - - if (!itemImpl.isSimpleType()) - { - state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_NOT_SIMPLE, null, errorLoc); - // recovery: treat the item type as anySimpleType - sImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - - switch (itemImpl.getSimpleVariety()) - { - case SchemaType.LIST: - state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_LIST, null, errorLoc); - // recovery: treat the list as an anySimpleType - resolveErrorSimpleType(sImpl); - return; - case SchemaType.UNION: - if (itemImpl.isUnionOfLists()) - { - state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$LIST_ITEM_IS_UNION_OF_LIST, null, errorLoc); - resolveErrorSimpleType(sImpl); - return; - } - // fallthrough: nonlist unions are just like atomic items - case SchemaType.ATOMIC: - sImpl.setListItemTypeRef(itemImpl.getRef()); - // Check that the item type is not a plan NOTATION - if (sImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) - state.recover(XmlErrorCodes.DATATYPE_ENUM_NOTATION, null, errorLoc); - break; - default: - assert(false); - sImpl.setListItemTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - } - - // now deal with facets - sImpl.setBasicFacets(StscState.FACETS_LIST, StscState.FIXED_FACETS_LIST); - sImpl.setWhiteSpaceRule( SchemaType.WS_COLLAPSE ); - - // now compute our intrinsic properties - resolveFundamentalFacets(sImpl); - } - - - - - static void resolveUnionType(SchemaTypeImpl sImpl, UnionDocument.Union parseUnion, List anonTypes) - { - sImpl.setSimpleTypeVariety(SchemaType.UNION); - sImpl.setBaseTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef()); - sImpl.setBaseDepth(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getBaseDepth() + 1); - sImpl.setDerivationType(SchemaType.DT_RESTRICTION); - - StscState state = StscState.get(); - - if (sImpl.isRedefinition()) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, - new Object[] { "union" }, parseUnion); - // recovery: oh well. - } - - List memberTypes = parseUnion.getMemberTypes(); - SimpleType[] simpleTypes = parseUnion.getSimpleTypeArray(); - - List memberImplList = new ArrayList(); - - if (simpleTypes.length == 0 && (memberTypes == null || memberTypes.size() == 0)) - { - state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$UNION_HAS_MEMBER_TYPES_OR_SIMPLE_TYPES, null, parseUnion); - // recovery: oh well, zero member types is fine. - } - - if (memberTypes != null) - { - for (Iterator mNames = memberTypes.iterator(); mNames.hasNext(); ) - { - QName mName = (QName)mNames.next(); - SchemaTypeImpl memberImpl = state.findGlobalType(mName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); - if (memberImpl == null) - // recovery: skip member - state.notFoundError(mName, SchemaType.TYPE, parseUnion.xgetMemberTypes(), true); - else - memberImplList.add(memberImpl); - } - } - - for (int i = 0; i < simpleTypes.length; i++) - { - // BUGBUG: see if non children can leak through - SchemaTypeImpl mImpl = StscTranslator.translateAnonymousSimpleType(simpleTypes[i], - sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl); - memberImplList.add(mImpl); - mImpl.setAnonymousUnionMemberOrdinal(i + 1); - } - - // Recurse and resolve all member types - for (Iterator mImpls = memberImplList.iterator(); mImpls.hasNext(); ) - { - SchemaTypeImpl mImpl = (SchemaTypeImpl)mImpls.next(); - if (!StscResolver.resolveType(mImpl)) - { - // KHK: review - String memberName = ""; - XmlObject errorLoc; - if (mImpl.getOuterType().equals(sImpl)) - { - errorLoc = mImpl.getParseObject(); - } - else - { - memberName = QNameHelper.pretty(mImpl.getName()) + " "; - errorLoc = parseUnion.xgetMemberTypes(); - } - - state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$CYCLIC_UNION, new Object[] { memberName }, errorLoc); - - // recovery: ignore the errant union member - mImpls.remove(); - continue; - } - } - - // Now verify members - boolean isUnionOfLists = false; - - for (Iterator mImpls = memberImplList.iterator(); mImpls.hasNext(); ) - { - SchemaTypeImpl mImpl = (SchemaTypeImpl)mImpls.next(); - - if (!mImpl.isSimpleType()) - { - // KHK: review - String memberName = ""; - XmlObject errorLoc; - if (mImpl.getOuterType() != null && mImpl.getOuterType().equals(sImpl)) - { - errorLoc = mImpl.getParseObject(); - } - else - { - memberName = QNameHelper.pretty(mImpl.getName()) + " "; - errorLoc = parseUnion.xgetMemberTypes(); - } - - state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$UNION_MEMBER_NOT_SIMPLE, new Object[] { memberName }, errorLoc); - - // recovery: ignore the errant union member - mImpls.remove(); - continue; - } - - if (mImpl.getSimpleVariety() == SchemaType.LIST || - mImpl.getSimpleVariety() == SchemaType.UNION && mImpl.isUnionOfLists()) - isUnionOfLists = true; - } - - // Verify any final restrictions - for (int i = 0 ; i < memberImplList.size() ; i++) - { - SchemaTypeImpl mImpl = (SchemaTypeImpl)memberImplList.get(i); - if (mImpl.finalUnion()) - state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$UNION_FINAL, null, parseUnion); - } - - sImpl.setUnionOfLists(isUnionOfLists); - - sImpl.setUnionMemberTypeRefs(makeRefArray(memberImplList)); - - // now deal with facets - sImpl.setBasicFacets(StscState.FACETS_UNION, StscState.FIXED_FACETS_UNION); - - // now compute our intrinsic properties - resolveFundamentalFacets(sImpl); - } - - static void resolveSimpleRestrictionType(SchemaTypeImpl sImpl, RestrictionDocument.Restriction parseRestr, List anonTypes) - { - QName baseName = parseRestr.getBase(); - SimpleType parseInner = parseRestr.getSimpleType(); - StscState state = StscState.get(); - - if (baseName != null && parseInner != null) - { - state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_BOTH_BASE_OR_SIMPLE_TYPE, null, parseRestr); - // recovery: ignore the inner simple type. - parseInner = null; - } - - SchemaTypeImpl baseImpl; - - if (baseName != null) - { - if (sImpl.isRedefinition()) - { - baseImpl = state.findRedefinedGlobalType(parseRestr.getBase(), sImpl.getChameleonNamespace(), sImpl); - if (baseImpl != null && !baseImpl.getName().equals(sImpl.getName())) - { - state.error(XmlErrorCodes.SCHEMA_REDEFINE$SAME_TYPE, - new Object[] { "", - QNameHelper.pretty(baseName), - QNameHelper.pretty(sImpl.getName()) - }, - parseRestr); - } - } - else - { - baseImpl = state.findGlobalType(baseName, sImpl.getChameleonNamespace(), sImpl.getTargetNamespace()); - } - if (baseImpl == null) - { - state.notFoundError(baseName, SchemaType.TYPE, parseRestr.xgetBase(), true); - // recovery: treat it as an extension of anySimpleType - baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - } - else if (parseInner != null) - { - if (sImpl.isRedefinition()) - { - StscState.get().error(XmlErrorCodes.SCHEMA_REDEFINE$EXTEND_OR_RESTRICT, - new Object[] { "" }, parseInner); - // recovery: oh well. - } - - baseImpl = StscTranslator.translateAnonymousSimpleType(parseInner, - sImpl.getTargetNamespace(), sImpl.getChameleonNamespace() != null, - sImpl.getElemFormDefault(), sImpl.getAttFormDefault(), anonTypes, sImpl); - } - else - { - state.error(XmlErrorCodes.SCHEMA_SIMPLE_TYPE$RESTRICTION_HAS_NEITHER_BASE_OR_SIMPLE_TYPE, null, parseRestr); - // recovery: treat it as an extension of anySimpleType - baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - - // Recursion! - if (!StscResolver.resolveType(baseImpl)) - { - // cyclic dependency recovery: treat it as an extension of anySimpleType - baseImpl = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - - if (baseImpl.finalRestriction()) - state.error(XmlErrorCodes.SIMPLE_TYPE_PROPERTIES$RESTRICTION_FINAL, null, parseRestr); - - sImpl.setBaseTypeRef(baseImpl.getRef()); - sImpl.setBaseDepth(baseImpl.getBaseDepth() + 1); - sImpl.setDerivationType(SchemaType.DT_RESTRICTION); - - if (!baseImpl.isSimpleType()) - { - state.error(XmlErrorCodes.SIMPLE_TYPE_RESTRICTION$ATOMIC_NOT_SIMPLE, null, parseRestr.xgetBase()); - // recovery: treat it as a restriction of anySimpleType - resolveErrorSimpleType(sImpl); - return; - } - - sImpl.setSimpleTypeVariety(baseImpl.getSimpleVariety()); - - // copy variety-specific properties - switch (baseImpl.getSimpleVariety()) - { - case SchemaType.ATOMIC: - sImpl.setPrimitiveTypeRef(baseImpl.getPrimitiveType().getRef()); - break; - case SchemaType.UNION: - sImpl.setUnionOfLists(baseImpl.isUnionOfLists()); - sImpl.setUnionMemberTypeRefs(makeRefArray(Arrays.asList(baseImpl.getUnionMemberTypes()))); - break; - case SchemaType.LIST: - sImpl.setListItemTypeRef(baseImpl.getListItemType().getRef()); - break; - } - - // deal with facets - resolveFacets(sImpl, parseRestr, baseImpl); - - // now compute our intrinsic properties - resolveFundamentalFacets(sImpl); - } - - static int translateWhitespaceCode(XmlAnySimpleType value) - { - // BUGBUG: add whitespace rule to textvalue. - String textval = value.getStringValue(); - - if (textval.equals("collapse")) - return SchemaType.WS_COLLAPSE; - - if (textval.equals("preserve")) - return SchemaType.WS_PRESERVE; - - if (textval.equals("replace")) - return SchemaType.WS_REPLACE; - - // KHK: s4s - StscState.get().error("Unrecognized whitespace value \"" + textval + "\"", XmlErrorCodes.FACET_VALUE_MALFORMED, value); - return SchemaType.WS_UNSPECIFIED; - } - - static boolean isMultipleFacet(int facetcode) - { - return (facetcode == SchemaType.FACET_ENUMERATION || - facetcode == SchemaType.FACET_PATTERN); - } - - static boolean facetAppliesToType(int facetCode, SchemaTypeImpl baseImpl) - { - switch (baseImpl.getSimpleVariety()) - { - case SchemaType.LIST: - switch (facetCode) - { - case SchemaType.FACET_LENGTH: - case SchemaType.FACET_MIN_LENGTH: - case SchemaType.FACET_MAX_LENGTH: - case SchemaType.FACET_ENUMERATION: - case SchemaType.FACET_PATTERN: - case SchemaType.FACET_WHITE_SPACE: - return true; - } - return false; - - case SchemaType.UNION: - switch (facetCode) - { - case SchemaType.FACET_ENUMERATION: - case SchemaType.FACET_PATTERN: - return true; - } - return false; - } - - // the atomic case - - switch (baseImpl.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_ANY_SIMPLE: - return false; - - case SchemaType.BTC_BOOLEAN: - switch (facetCode) - { - case SchemaType.FACET_PATTERN: - case SchemaType.FACET_WHITE_SPACE: - return true; - } - return false; - - case SchemaType.BTC_FLOAT: - case SchemaType.BTC_DOUBLE: - case SchemaType.BTC_DURATION: - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - switch (facetCode) - { - case SchemaType.FACET_MIN_EXCLUSIVE: - case SchemaType.FACET_MIN_INCLUSIVE: - case SchemaType.FACET_MAX_INCLUSIVE: - case SchemaType.FACET_MAX_EXCLUSIVE: - case SchemaType.FACET_ENUMERATION: - case SchemaType.FACET_PATTERN: - case SchemaType.FACET_WHITE_SPACE: - return true; - } - return false; - - case SchemaType.BTC_DECIMAL: - switch (facetCode) - { - case SchemaType.FACET_MIN_EXCLUSIVE: - case SchemaType.FACET_MIN_INCLUSIVE: - case SchemaType.FACET_MAX_INCLUSIVE: - case SchemaType.FACET_MAX_EXCLUSIVE: - case SchemaType.FACET_TOTAL_DIGITS: - case SchemaType.FACET_FRACTION_DIGITS: - case SchemaType.FACET_ENUMERATION: - case SchemaType.FACET_PATTERN: - case SchemaType.FACET_WHITE_SPACE: - return true; - } - return false; - - case SchemaType.BTC_BASE_64_BINARY: - case SchemaType.BTC_HEX_BINARY: - case SchemaType.BTC_ANY_URI: - case SchemaType.BTC_QNAME: - case SchemaType.BTC_NOTATION: - case SchemaType.BTC_STRING: - switch (facetCode) - { - case SchemaType.FACET_LENGTH: - case SchemaType.FACET_MIN_LENGTH: - case SchemaType.FACET_MAX_LENGTH: - case SchemaType.FACET_ENUMERATION: - case SchemaType.FACET_PATTERN: - case SchemaType.FACET_WHITE_SPACE: - return true; - } - return false; - - default: - assert(false); - return false; - } - } - - private static int other_similar_limit(int facetcode) - { - switch (facetcode) - { - case SchemaType.FACET_MIN_EXCLUSIVE: - return SchemaType.FACET_MIN_INCLUSIVE; - case SchemaType.FACET_MIN_INCLUSIVE: - return SchemaType.FACET_MIN_EXCLUSIVE; - case SchemaType.FACET_MAX_INCLUSIVE: - return SchemaType.FACET_MAX_EXCLUSIVE; - case SchemaType.FACET_MAX_EXCLUSIVE: - return SchemaType.FACET_MAX_INCLUSIVE; - default: - assert(false); - throw new IllegalStateException(); - } - } - - static void resolveFacets(SchemaTypeImpl sImpl, XmlObject restriction, SchemaTypeImpl baseImpl) - { - StscState state = StscState.get(); - - boolean[] seenFacet = new boolean[SchemaType.LAST_FACET + 1]; - XmlAnySimpleType[] myFacets = baseImpl.getBasicFacets(); // makes a copy - boolean[] fixedFacets = baseImpl.getFixedFacets(); - int wsr = SchemaType.WS_UNSPECIFIED; - List enumeratedValues = null; - List patterns = null; - - if (restriction != null) - { - XmlCursor cur = restriction.newCursor(); - for (boolean more = cur.toFirstChild(); more; more = cur.toNextSibling()) - { - QName facetQName = cur.getName(); - String facetName = facetQName.getLocalPart(); - int code = translateFacetCode(facetQName); - if (code == -1) - continue; - - Facet facet = (Facet)cur.getObject(); - - if (!facetAppliesToType(code, baseImpl)) - { - state.error(XmlErrorCodes.FACETS_APPLICABLE, - new Object[] { facetName, QNameHelper.pretty(baseImpl.getName()) }, facet); - continue; - } - else if (baseImpl.getSimpleVariety() == SchemaType.ATOMIC && - baseImpl.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION - && (code == SchemaType.FACET_LENGTH || code == SchemaType.FACET_MIN_LENGTH || - code == SchemaType.FACET_MAX_LENGTH)) - { - state.warning(XmlErrorCodes.FACETS_DEPRECATED_NOTATION, - new Object[] {facetName, QNameHelper.pretty(baseImpl.getName()) }, facet); - } - if (seenFacet[code] && !isMultipleFacet(code)) - { - state.error(XmlErrorCodes.DATATYPE_SINGLE_FACET_VALUE, null, facet); - continue; - } - seenFacet[code] = true; - - switch (code) - { - case SchemaType.FACET_LENGTH: -// if (myFacets[SchemaType.FACET_MIN_LENGTH] != null || -// myFacets[SchemaType.FACET_MAX_LENGTH] != null) -// { -// state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); -// continue; -// } - XmlInteger len = StscTranslator.buildNnInteger(facet.getValue()); - if (len == null) - { - state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); - continue; - } - if (fixedFacets[code] && !myFacets[code].valueEquals(len)) - { - state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet); - continue; - } - if (myFacets[SchemaType.FACET_MIN_LENGTH] != null) - { - // An error for 'length' and 'minLength' to be specified at the same time - // except if the base type had the same value for 'minLength' also - XmlAnySimpleType baseMinLength = baseImpl.getFacet(SchemaType.FACET_MIN_LENGTH); - if (!(baseMinLength != null && - baseMinLength.valueEquals(myFacets[SchemaType.FACET_MIN_LENGTH]) && - baseMinLength.compareValue(len) <= 0)) - { - state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); - continue; - } - } - if (myFacets[SchemaType.FACET_MAX_LENGTH] != null) - { - // An error for 'length' and 'maxLength' to be specified at the same time - // except if the base type had the same value for 'maxLength' also - XmlAnySimpleType baseMaxLength = baseImpl.getFacet(SchemaType.FACET_MAX_LENGTH); - if (!(baseMaxLength != null && - baseMaxLength.valueEquals(myFacets[SchemaType.FACET_MAX_LENGTH]) && - baseMaxLength.compareValue(len) >= 0)) - { - state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); - continue; - } - } - myFacets[code] = len; - break; - - case SchemaType.FACET_MIN_LENGTH: - case SchemaType.FACET_MAX_LENGTH: - XmlInteger mlen = StscTranslator.buildNnInteger(facet.getValue()); - if (mlen == null) - { - state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); - continue; - } - if (fixedFacets[code] && !myFacets[code].valueEquals(mlen)) - { - state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet); - continue; - } - if (myFacets[SchemaType.FACET_LENGTH] != null) - { - // It's an error for 'length' and 'minLength'/'maxLength' to be - // specified at the same time, except for the case when - // the base type had the same value for 'minLength'/'maxLength' - // and the two values are consistent - XmlAnySimpleType baseMinMaxLength = baseImpl.getFacet(code); - if (!(baseMinMaxLength != null && - baseMinMaxLength.valueEquals(mlen) && - (code == SchemaType.FACET_MIN_LENGTH ? - baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) <= 0 : - baseMinMaxLength.compareTo(myFacets[SchemaType.FACET_LENGTH]) >= 0))) - { - state.error(XmlErrorCodes.DATATYPE_LENGTH, null, facet); - continue; - } - } - if (myFacets[SchemaType.FACET_MAX_LENGTH] != null) - { - if (mlen.compareValue(myFacets[SchemaType.FACET_MAX_LENGTH]) > 0) - { - state.error(XmlErrorCodes.DATATYPE_MAX_LENGTH_RESTRICTION, null, facet); - continue; - } - } - if (myFacets[SchemaType.FACET_MIN_LENGTH] != null) - { - if (mlen.compareValue(myFacets[SchemaType.FACET_MIN_LENGTH]) < 0) - { - state.error(XmlErrorCodes.DATATYPE_MIN_LENGTH_RESTRICTION, null, facet); - continue; - } - } - myFacets[code] = mlen; - break; - - case SchemaType.FACET_TOTAL_DIGITS: - XmlPositiveInteger dig = StscTranslator.buildPosInteger(facet.getValue()); - if (dig == null) - { - state.error("Must be a positive integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); - break; - } - if (fixedFacets[code] && !myFacets[code].valueEquals(dig)) - { - state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet); - continue; - } - if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null) - { - if (dig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0) - state.error(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_RESTRICTION, null, facet); - } - myFacets[code] = dig; - break; - - case SchemaType.FACET_FRACTION_DIGITS: - XmlNonNegativeInteger fdig = StscTranslator.buildNnInteger(facet.getValue()); - if (fdig == null) - { - state.error("Must be a nonnegative integer", XmlErrorCodes.FACET_VALUE_MALFORMED, facet); - break; - } - if (fixedFacets[code] && !myFacets[code].valueEquals(fdig)) - { - state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet); - continue; - } - if (myFacets[SchemaType.FACET_FRACTION_DIGITS] != null) - { - if (fdig.compareValue(myFacets[SchemaType.FACET_FRACTION_DIGITS]) > 0) - state.error(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_RESTRICTION, null, facet); - } - if (myFacets[SchemaType.FACET_TOTAL_DIGITS] != null) - { - if (fdig.compareValue(myFacets[SchemaType.FACET_TOTAL_DIGITS]) > 0) - state.error(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_LE_TOTAL_DIGITS, null, facet); - } - myFacets[code] = fdig; - break; - - case SchemaType.FACET_MIN_EXCLUSIVE: - case SchemaType.FACET_MIN_INCLUSIVE: - case SchemaType.FACET_MAX_INCLUSIVE: - case SchemaType.FACET_MAX_EXCLUSIVE: - - if (seenFacet[other_similar_limit(code)]) - { - state.error("Cannot define both inclusive and exclusive limit in the same restriciton", XmlErrorCodes.FACET_DUPLICATED, facet); - continue; - } - boolean ismin = (code == SchemaType.FACET_MIN_EXCLUSIVE || code == SchemaType.FACET_MIN_INCLUSIVE); - boolean isexclusive = (code == SchemaType.FACET_MIN_EXCLUSIVE || code == SchemaType.FACET_MAX_EXCLUSIVE); - - XmlAnySimpleType limit; - try - { - limit = baseImpl.newValue(facet.getValue(), true); - } - catch (XmlValueOutOfRangeException e) - { - // note: this guarantees that the limit is a valid number in the - // base data type!! - switch (code) - { - case SchemaType.FACET_MIN_EXCLUSIVE: - state.error(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_RESTRICTION, - new Object[] {e.getMessage()}, facet); - break; - case SchemaType.FACET_MIN_INCLUSIVE: - state.error(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_RESTRICTION, - new Object[] {e.getMessage()}, facet); - break; - case SchemaType.FACET_MAX_INCLUSIVE: - state.error(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_RESTRICTION, - new Object[] {e.getMessage()}, facet); - break; - case SchemaType.FACET_MAX_EXCLUSIVE: - state.error(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_RESTRICTION, - new Object[] {e.getMessage()}, facet); - break; - } - - // BUGBUG: if there are actual schemas that redefine min/maxExclusive, - // they will need this rule relaxed for them!! - continue; - } - if (fixedFacets[code] && !myFacets[code].valueEquals(limit)) - { - state.error(XmlErrorCodes.FACET_FIXED, new Object[] { facetName }, facet); - continue; - } - if (myFacets[code] != null) - { - SchemaType limitSType = limit.schemaType(); - if ( limitSType!=null && !limitSType.isSimpleType() && - limitSType.getContentType()==SchemaType.SIMPLE_CONTENT) - { - // in the case of complex types with simple content that has facets - // we need to compare values based on the content type - limit = baseImpl.getContentBasedOnType().newValue(facet.getValue()); - } - - int comparison = limit.compareValue(myFacets[code]); - if (comparison == 2 || comparison == (ismin ? -1 : 1)) - { - state.error(ismin ? - (isexclusive ? - "Must be greater than or equal to previous minExclusive" : - "Must be greater than or equal to previous minInclusive") : - (isexclusive ? - "Must be less than or equal to previous maxExclusive" : - "Must be less than or equal to previous maxInclusive"), - XmlErrorCodes.FACET_VALUE_MALFORMED, facet); - continue; - } - } - myFacets[code] = limit; - myFacets[other_similar_limit(code)] = null; - break; - - case SchemaType.FACET_WHITE_SPACE: - wsr = translateWhitespaceCode(facet.getValue()); - if (baseImpl.getWhiteSpaceRule() > wsr) - { - wsr = SchemaType.WS_UNSPECIFIED; - state.error(XmlErrorCodes.DATATYPE_WHITESPACE_RESTRICTION, null, facet); - continue; - } - myFacets[code] = StscState.build_wsstring(wsr).get(); - break; - - case SchemaType.FACET_ENUMERATION: - XmlObject enumval; - try - { - enumval = baseImpl.newValue(facet.getValue(), true); - // enumval.set(facet.getValue()); - // ((XmlObjectBase)enumval).setImmutable(); - } - catch (XmlValueOutOfRangeException e) - { - state.error(XmlErrorCodes.DATATYPE_ENUM_RESTRICTION, new Object[] { facet.getValue().getStringValue(), e.getMessage() }, facet); - continue; - } - if (enumeratedValues == null) - enumeratedValues = new ArrayList(); - enumeratedValues.add(enumval); - break; - - case SchemaType.FACET_PATTERN: - RegularExpression p; - try { p = new RegularExpression(facet.getValue().getStringValue(), "X"); } - catch (ParseException e) - { - state.error(XmlErrorCodes.PATTERN_REGEX, new Object[] { facet.getValue().getStringValue(), e.getMessage() }, facet); - continue; - } - if (patterns == null) - patterns = new ArrayList(); - patterns.add(p); - break; - } - - if (facet.getFixed()) - fixedFacets[code] = true; - } - } - - // Store the array of basic facets - - sImpl.setBasicFacets(makeValueRefArray(myFacets), fixedFacets); - - // Update the numeric whitespace rule - if (wsr == SchemaType.WS_UNSPECIFIED) - wsr = baseImpl.getWhiteSpaceRule(); - sImpl.setWhiteSpaceRule(wsr); - - // store away the enumerated values - if (enumeratedValues != null) - { - sImpl.setEnumerationValues(makeValueRefArray((XmlAnySimpleType[]) - enumeratedValues.toArray(new XmlAnySimpleType[enumeratedValues.size()]))); - - SchemaType beType = sImpl; - if ( ((SchemaTypeImpl)sImpl).isRedefinition() ){ - beType = sImpl.getBaseType().getBaseEnumType(); - if( beType == null || sImpl.getBaseType() == beType ){ - beType = sImpl; - } - } - else if (sImpl.getBaseType().getBaseEnumType() != null) - beType = sImpl.getBaseType().getBaseEnumType(); - sImpl.setBaseEnumTypeRef(beType.getRef()); - } - else - { - sImpl.copyEnumerationValues(baseImpl); - } - - // store the pattern list - org.apache.xmlbeans.impl.regex.RegularExpression[] patternArray; - if (patterns != null) - patternArray = (org.apache.xmlbeans.impl.regex.RegularExpression[])patterns.toArray(EMPTY_REGEX_ARRAY); - else - patternArray = EMPTY_REGEX_ARRAY; - sImpl.setPatternFacet((patternArray.length > 0 || baseImpl.hasPatternFacet())); - sImpl.setPatterns(patternArray); - - // Check that, if the base type is NOTATION, there is an enumeration facet - // http://www.w3.org/TR/xmlschema-2/#NOTATION - if (baseImpl.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) - if (sImpl.getEnumerationValues() == null) - state.recover(XmlErrorCodes.DATATYPE_ENUM_NOTATION, null, restriction); - } - - private static XmlValueRef[] makeValueRefArray(XmlAnySimpleType[] source) - { - XmlValueRef[] result = new XmlValueRef[source.length]; - for (int i = 0; i < result.length; i++) - result[i] = (source[i] == null ? null : new XmlValueRef(source[i])); - return result; - } - - private static final org.apache.xmlbeans.impl.regex.RegularExpression[] EMPTY_REGEX_ARRAY = new org.apache.xmlbeans.impl.regex.RegularExpression[0]; - - private static boolean isDiscreteType(SchemaTypeImpl sImpl) - { - if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) != null) - return true; - // BUGBUG: spec is silent on enumerations; they're finite too. - switch (sImpl.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - case SchemaType.BTC_BOOLEAN: - return true; - } - return false; - } - - private static boolean isNumericPrimitive(SchemaType sImpl) - { - switch (sImpl.getBuiltinTypeCode()) - { - case SchemaType.BTC_DECIMAL: - case SchemaType.BTC_FLOAT: - case SchemaType.BTC_DOUBLE: - return true; - } - return false; - } - - private static int decimalSizeOfType(SchemaTypeImpl sImpl) - { - int size = mathematicalSizeOfType(sImpl); - - // byte and short are inconvenient, because setByte((byte)4) requires a cast. - // So use "int" unless you're really a xs:byte, xs:short, or an xs:unsignedByte - // (the last case is included for alignment with JAXB) - - if (size == SchemaType.SIZE_BYTE && !XmlByte.type.isAssignableFrom(sImpl)) - size = SchemaType.SIZE_SHORT; - if (size == SchemaType.SIZE_SHORT && !XmlShort.type.isAssignableFrom(sImpl) && !XmlUnsignedByte.type.isAssignableFrom(sImpl)) - size = SchemaType.SIZE_INT; - - return size; - } - - private static int mathematicalSizeOfType(SchemaTypeImpl sImpl) - { - if (sImpl.getPrimitiveType().getBuiltinTypeCode() != SchemaType.BTC_DECIMAL) - return SchemaType.NOT_DECIMAL; - - if (sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS) == null || - ((SimpleValue)sImpl.getFacet(SchemaType.FACET_FRACTION_DIGITS)).getBigIntegerValue().signum() != 0) - return SchemaType.SIZE_BIG_DECIMAL; - - BigInteger min = null; - BigInteger max = null; - - if (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null) - min = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)).getBigIntegerValue(); // .add(BigInteger.ONE); - if (sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE) != null) - min = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE)).getBigIntegerValue(); - if (sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE) != null) - max = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE)).getBigIntegerValue(); - if (sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE) != null) - max = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)).getBigIntegerValue(); // .subtract(BigInteger.ONE); - - if (sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS) != null) - { - BigInteger peg = null; - try - { - BigInteger totalDigits = ((SimpleValue)sImpl.getFacet(SchemaType.FACET_TOTAL_DIGITS)).getBigIntegerValue(); - - switch (totalDigits.intValue()) - { - case 0: case 1: case 2: - peg = BigInteger.valueOf(99L); // BYTE size - break; - case 3: case 4: - peg = BigInteger.valueOf(9999L); // SHORT size - break; - case 5: case 6: case 7: case 8: case 9: - peg = BigInteger.valueOf(999999999L); // INT size - break; - case 10: case 11: case 12: case 13: case 14: - case 15: case 16: case 17: case 18: - peg = BigInteger.valueOf(999999999999999999L); // LONG size - break; - } - } - catch (XmlValueOutOfRangeException e) {} - if (peg != null) - { - min = (min == null ? peg.negate() : min.max(peg.negate())); - max = (max == null ? peg : max.min(peg)); - } - } - - if (min != null && max != null) - { - // find the largest "absolute value" number that must be dealt with - if (min.signum() < 0) - min = min.negate().subtract(BigInteger.ONE); - if (max.signum() < 0) - max = max.negate().subtract(BigInteger.ONE); - - max = max.max(min); - if (max.compareTo(BigInteger.valueOf(Byte.MAX_VALUE)) <= 0) - return SchemaType.SIZE_BYTE; - if (max.compareTo(BigInteger.valueOf(Short.MAX_VALUE)) <= 0) - return SchemaType.SIZE_SHORT; - if (max.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) <= 0) - return SchemaType.SIZE_INT; - if (max.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) <= 0) - return SchemaType.SIZE_LONG; - } - - return SchemaType.SIZE_BIG_INTEGER; - } - - - static void resolveFundamentalFacets(SchemaTypeImpl sImpl) - { - // deal with, isOrdered, isBounded, isFinite, isNumeric - // also deal with - switch (sImpl.getSimpleVariety()) - { - case SchemaType.ATOMIC: - SchemaTypeImpl baseImpl = (SchemaTypeImpl)sImpl.getBaseType(); - sImpl.setOrdered(baseImpl.ordered()); - sImpl.setBounded( - (sImpl.getFacet(SchemaType.FACET_MIN_EXCLUSIVE) != null || - sImpl.getFacet(SchemaType.FACET_MIN_INCLUSIVE) != null) && - (sImpl.getFacet(SchemaType.FACET_MAX_INCLUSIVE) != null || - sImpl.getFacet(SchemaType.FACET_MAX_EXCLUSIVE) != null)); - sImpl.setFinite(baseImpl.isFinite() || - sImpl.isBounded() && isDiscreteType(sImpl)); - sImpl.setNumeric(baseImpl.isNumeric() || - isNumericPrimitive(sImpl.getPrimitiveType())); - sImpl.setDecimalSize(decimalSizeOfType(sImpl)); - break; - case SchemaType.UNION: - SchemaType[] mTypes = sImpl.getUnionMemberTypes(); - int ordered = SchemaType.UNORDERED; - boolean isBounded = true; - boolean isFinite = true; - boolean isNumeric = true; - // ordered if any is ordered, bounded if all are bounded. - for (int i = 0; i < mTypes.length; i++) - { - if (mTypes[i].ordered() != SchemaType.UNORDERED) - ordered = SchemaType.PARTIAL_ORDER; - if (!mTypes[i].isBounded()) - isBounded = false; - if (!mTypes[i].isFinite()) - isFinite = false; - if (!mTypes[i].isNumeric()) - isNumeric = false; - } - sImpl.setOrdered(ordered); - sImpl.setBounded(isBounded); - sImpl.setFinite(isFinite); - sImpl.setNumeric(isNumeric); - sImpl.setDecimalSize(SchemaType.NOT_DECIMAL); - break; - case SchemaType.LIST: - sImpl.setOrdered(SchemaType.UNORDERED); - // BUGBUG: the schema spec is wrong here: MIN_LENGTH is not needed, beause len >=0 - sImpl.setBounded(sImpl.getFacet(SchemaType.FACET_LENGTH) != null || - sImpl.getFacet(SchemaType.FACET_MAX_LENGTH) != null); - // BUGBUG: the schema spec is wrong here: finite cardinality requires item type is finite - sImpl.setFinite(sImpl.getListItemType().isFinite() && sImpl.isBounded()); - sImpl.setNumeric(false); - sImpl.setDecimalSize(SchemaType.NOT_DECIMAL); - break; - } - } - - private static class CodeForNameEntry - { - CodeForNameEntry(QName name, int code) - { this.name = name; this.code = code; } - public QName name; - public int code; - } - - private static CodeForNameEntry[] facetCodes = new CodeForNameEntry[] - { - new CodeForNameEntry(QNameHelper.forLNS("length", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_LENGTH), - new CodeForNameEntry(QNameHelper.forLNS("minLength", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_LENGTH), - new CodeForNameEntry(QNameHelper.forLNS("maxLength", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_LENGTH), - new CodeForNameEntry(QNameHelper.forLNS("pattern", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_PATTERN), - new CodeForNameEntry(QNameHelper.forLNS("enumeration", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_ENUMERATION), - new CodeForNameEntry(QNameHelper.forLNS("whiteSpace", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_WHITE_SPACE), - new CodeForNameEntry(QNameHelper.forLNS("maxInclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_INCLUSIVE), - new CodeForNameEntry(QNameHelper.forLNS("maxExclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MAX_EXCLUSIVE), - new CodeForNameEntry(QNameHelper.forLNS("minInclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_INCLUSIVE), - new CodeForNameEntry(QNameHelper.forLNS("minExclusive", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_MIN_EXCLUSIVE), - new CodeForNameEntry(QNameHelper.forLNS("totalDigits", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_TOTAL_DIGITS), - new CodeForNameEntry(QNameHelper.forLNS("fractionDigits", "http://www.w3.org/2001/XMLSchema"), SchemaType.FACET_FRACTION_DIGITS), - }; - - private static final Map facetCodeMap = buildFacetCodeMap(); - - private static Map buildFacetCodeMap() - { - Map result = new HashMap(); - for (int i = 0; i < facetCodes.length; i++) - result.put(facetCodes[i].name, new Integer(facetCodes[i].code)); - return result; - } - - private static int translateFacetCode(QName name) - { - Integer result = ((Integer)facetCodeMap.get(name)); - if (result == null) - return -1; - return result.intValue(); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java deleted file mode 100644 index c03a094..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java +++ /dev/null @@ -1,1595 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.ResolverUtil; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaComponent; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaAttributeGroup; -import org.apache.xmlbeans.SchemaModelGroup; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.BindingConfig; -import org.apache.xmlbeans.impl.values.XmlStringImpl; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.apache.xmlbeans.impl.util.HexBin; - -import java.util.*; -import java.net.URISyntaxException; -import java.net.URI; -import java.net.URL; -import java.io.File; - - -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.xml.sax.EntityResolver; - -/** - * This class represents the state of the SchemaTypeSystemCompiler as it's - * going. - */ -public class StscState -{ - private String _givenStsName; - private Collection _errorListener; - private SchemaTypeSystemImpl _target; - private BindingConfig _config; - private Map _compatMap; - private boolean _doingDownloads; - private byte[] _digest = null; - private boolean _noDigest = false; - - // EXPERIMENTAL: recovery from compilation errors and partial type systems - private boolean _allowPartial = false; - private int _recoveredErrors = 0; - - private SchemaTypeLoader _importingLoader; - - private Map _containers = new LinkedHashMap(); - private SchemaDependencies _dependencies; - - private Map _redefinedGlobalTypes = new LinkedHashMap(); - private Map _redefinedModelGroups = new LinkedHashMap(); - private Map _redefinedAttributeGroups = new LinkedHashMap(); - - private Map _globalTypes = new LinkedHashMap(); - private Map _globalElements = new LinkedHashMap(); - private Map _globalAttributes = new LinkedHashMap(); - private Map _modelGroups = new LinkedHashMap(); - private Map _attributeGroups = new LinkedHashMap(); - private Map _documentTypes = new LinkedHashMap(); - private Map _attributeTypes = new LinkedHashMap(); - private Map _typesByClassname = new LinkedHashMap(); - private Map _misspelledNames = new HashMap(); - private Set _processingGroups = new LinkedHashSet(); - private Map _idConstraints = new LinkedHashMap(); - private Set _namespaces = new HashSet(); - private List _annotations = new ArrayList(); - private boolean _noUpa; - private boolean _noPvr; - private boolean _noAnn; - private boolean _mdefAll; - private Set _mdefNamespaces = buildDefaultMdefNamespaces(); - private EntityResolver _entityResolver; - private File _schemasDir; - - private static Set buildDefaultMdefNamespaces() - { - // namespaces which are known to appear in WSDLs redundantly - return new HashSet( - Arrays.asList( new String[] { - "http://www.openuri.org/2002/04/soap/conversation/", - })); - } - - /** - * Used to store the new target namespace for a chameleon - * included schema. - */ - public static final Object CHAMELEON_INCLUDE_URI = new Object(); - - /** - * Only constructed via StscState.start(). - */ - private StscState() - { - } - - /** - * Initializer for incremental compilation - */ - public void initFromTypeSystem(SchemaTypeSystemImpl system, Set newNamespaces) - { -// setGivenTypeSystemName(system.getName().substring(14)); - - SchemaContainer[] containers = system.containers(); - for (int i = 0; i < containers.length; i++) - { - if (!newNamespaces.contains(containers[i].getNamespace())) - { - // Copy data from the given container - addContainer(containers[i]); - } - } - } - - - /* CONTAINERS ================================================================*/ - - void addNewContainer(String namespace) - { - if (_containers.containsKey(namespace)) - return; - - SchemaContainer container = new SchemaContainer(namespace); - container.setTypeSystem(sts()); - addNamespace(namespace); - _containers.put(namespace, container); - } - - private void addContainer(SchemaContainer container) - { - _containers.put(container.getNamespace(), container); - List redefModelGroups = container.redefinedModelGroups(); - for (int i = 0; i < redefModelGroups.size(); i++) - { - QName name = ((SchemaModelGroup) redefModelGroups.get(i)).getName(); - _redefinedModelGroups.put(name, redefModelGroups.get(i)); - } - - List redefAttrGroups = container.redefinedAttributeGroups(); - for (int i = 0; i < redefAttrGroups.size(); i++) - { - QName name = ((SchemaAttributeGroup) redefAttrGroups.get(i)).getName(); - _redefinedAttributeGroups.put(name, redefAttrGroups.get(i)); - } - - List redefTypes = container.redefinedGlobalTypes(); - for (int i = 0; i < redefTypes.size(); i++) - { - QName name = ((SchemaType) redefTypes.get(i)).getName(); - _redefinedGlobalTypes.put(name, redefTypes.get(i)); - } - - List globalElems = container.globalElements(); - for (int i = 0; i < globalElems.size(); i++) - { - QName name = ((SchemaGlobalElement) globalElems.get(i)).getName(); - _globalElements.put(name, globalElems.get(i)); - } - - List globalAtts = container.globalAttributes(); - for (int i = 0; i < globalAtts.size(); i++) - { - QName name = ((SchemaGlobalAttribute) globalAtts.get(i)).getName(); - _globalAttributes.put(name, globalAtts.get(i)); - } - - List modelGroups = container.modelGroups(); - for (int i = 0; i < modelGroups.size(); i++) - { - QName name = ((SchemaModelGroup) modelGroups.get(i)).getName(); - _modelGroups.put(name, modelGroups.get(i)); - } - - List attrGroups = container.attributeGroups(); - for (int i = 0; i < attrGroups.size(); i++) - { - QName name = ((SchemaAttributeGroup) attrGroups.get(i)).getName(); - _attributeGroups.put(name, attrGroups.get(i)); - } - - List globalTypes = container.globalTypes(); - for (int i = 0; i < globalTypes.size(); i++) - { - SchemaType t = (SchemaType) globalTypes.get(i); - QName name = t.getName(); - _globalTypes.put(name, t); - if (t.getFullJavaName() != null) - addClassname(t.getFullJavaName(), t); - } - - List documentTypes = container.documentTypes(); - for (int i = 0; i < documentTypes.size(); i++) - { - SchemaType t = (SchemaType) documentTypes.get(i); - QName name = t.getProperties()[0].getName(); - _documentTypes.put(name, t); - if (t.getFullJavaName() != null) - addClassname(t.getFullJavaName(), t); - } - - List attributeTypes = container.attributeTypes(); - for (int i = 0; i < attributeTypes.size(); i++) - { - SchemaType t = (SchemaType) attributeTypes.get(i); - QName name = t.getProperties()[0].getName(); - _attributeTypes.put(name, t); - if (t.getFullJavaName() != null) - addClassname(t.getFullJavaName(), t); - } - - List identityConstraints = container.identityConstraints(); - for (int i = 0; i < identityConstraints.size(); i++) - { - QName name = ((SchemaIdentityConstraint) identityConstraints.get(i)).getName(); - _idConstraints.put(name, identityConstraints.get(i)); - } - - _annotations.addAll(container.annotations()); - _namespaces.add(container.getNamespace()); - container.unsetImmutable(); - } - - SchemaContainer getContainer(String namespace) - { - return (SchemaContainer) _containers.get(namespace); - } - - Map getContainerMap() - { - return Collections.unmodifiableMap(_containers); - } - - /* DEPENDENCIES ================================================================*/ - - void registerDependency(String sourceNs, String targetNs) - { - _dependencies.registerDependency(sourceNs, targetNs); - } - - void registerContribution(String ns, String fileUrl) - { - _dependencies.registerContribution(ns, fileUrl); - } - - SchemaDependencies getDependencies() - { - return _dependencies; - } - - void setDependencies(SchemaDependencies deps) - { - _dependencies = deps; - } - - boolean isFileProcessed(String url) - { - return _dependencies.isFileRepresented(url); - } - - - /** - * Initializer for schematypepath - */ - public void setImportingTypeLoader(SchemaTypeLoader loader) - { - _importingLoader = loader; - } - - /** - * Initializer for error handling. - */ - public void setErrorListener(Collection errorListener) - { _errorListener = errorListener; } - - /** - * Passes an error on to the current error listener. - * KHK: remove this - */ - public void error(String message, int code, XmlObject loc) - { addError(_errorListener, message, code, loc); } - - /** - * Passes an error on to the current error listener. - */ - public void error(String code, Object[] args, XmlObject loc) - { addError(_errorListener, code, args, loc); } - - /** - * Passes a recovered error on to the current error listener. - */ - public void recover(String code, Object[] args, XmlObject loc) - { addError(_errorListener, code, args, loc); _recoveredErrors++; } - - /** - * Passes an error on to the current error listener. - */ - public void warning(String message, int code, XmlObject loc) - { - addWarning(_errorListener, message, code, loc); - } - - /** - * Passes an error on to the current error listener. - */ - public void warning(String code, Object[] args, XmlObject loc) - { - // it's OK for XMLSchema.xsd itself to have reserved type names - if (code == XmlErrorCodes.RESERVED_TYPE_NAME && - loc.documentProperties().getSourceName() != null && - loc.documentProperties().getSourceName().indexOf("XMLSchema.xsd") > 0) - return; - - addWarning(_errorListener, code, args, loc); - } - - /** - * Passes a warning on to the current error listener. - */ - public void info(String message) - { addInfo(_errorListener, message); } - - /** - * Passes a warning on to the current error listener. - */ - public void info(String code, Object[] args) - { addInfo(_errorListener, code, args); } - - // KHK: remove this - public static void addError(Collection errorListener, String message, int code, XmlObject location) - { - XmlError err = - XmlError.forObject( - message, - XmlError.SEVERITY_ERROR, - location); - errorListener.add(err); - } - - public static void addError(Collection errorListener, String code, Object[] args, XmlObject location) - { - XmlError err = - XmlError.forObject( - code, - args, - XmlError.SEVERITY_ERROR, - location); - errorListener.add(err); - } - - public static void addError(Collection errorListener, String code, Object[] args, File location) - { - XmlError err = - XmlError.forLocation( - code, - args, - XmlError.SEVERITY_ERROR, - location.toURI().toString(), 0, 0, 0); - errorListener.add(err); - } - - public static void addError(Collection errorListener, String code, Object[] args, URL location) - { - XmlError err = - XmlError.forLocation( - code, - args, - XmlError.SEVERITY_ERROR, - location.toString(), 0, 0, 0); - errorListener.add(err); - } - - // KHK: remove this - public static void addWarning(Collection errorListener, String message, int code, XmlObject location) - { - XmlError err = - XmlError.forObject( - message, - XmlError.SEVERITY_WARNING, - location); - errorListener.add(err); - } - - public static void addWarning(Collection errorListener, String code, Object[] args, XmlObject location) - { - XmlError err = - XmlError.forObject( - code, - args, - XmlError.SEVERITY_WARNING, - location); - errorListener.add(err); - } - - public static void addInfo(Collection errorListener, String message) - { - XmlError err = XmlError.forMessage(message, XmlError.SEVERITY_INFO); - errorListener.add(err); - } - - public static void addInfo(Collection errorListener, String code, Object[] args) - { - XmlError err = XmlError.forMessage(code, args, XmlError.SEVERITY_INFO); - errorListener.add(err); - } - - public void setGivenTypeSystemName(String name) - { _givenStsName = name; } - - /** - * Initializer for references to the SchemaTypeLoader - */ - public void setTargetSchemaTypeSystem(SchemaTypeSystemImpl target) - { _target = target; } - - /** - * Accumulates a schema digest... - */ - public void addSchemaDigest(byte[] digest) - { - if (_noDigest) - return; - - if (digest == null) - { - _noDigest = true; - _digest = null; - return; - } - - if (_digest == null) - _digest = new byte[128/8]; // 128 bits. - int len = _digest.length; - if (digest.length < len) - len = digest.length; - for (int i = 0; i < len; i++) - _digest[i] ^= digest[i]; - } - - /** - * The SchemaTypeSystem which we're building types on behalf of. - */ - public SchemaTypeSystemImpl sts() - { - if (_target != null) - return _target; - - String name = _givenStsName; - if (name == null && _digest != null) - name = "s" + new String(HexBin.encode(_digest)); - - _target = new SchemaTypeSystemImpl(name); - return _target; - } - - /** - * True if the given URI is a local file - */ - public boolean shouldDownloadURI(String uriString) - { - if (_doingDownloads) - return true; - - if (uriString == null) - return false; - - try - { - URI uri = new URI(uriString); - if (uri.getScheme().equalsIgnoreCase("jar") || - uri.getScheme().equalsIgnoreCase("zip")) - { - // It may be local or not, depending on the embedded URI - String s = uri.getSchemeSpecificPart(); - int i = s.lastIndexOf('!'); - return shouldDownloadURI(i > 0 ? s.substring(0, i) : s); - } - return uri.getScheme().equalsIgnoreCase("file"); - } - catch (Exception e) - { - return false; - } - } - - /** - * Initializer for compatMap. - */ - public void setOptions(XmlOptions options) - { - if (options == null) - { - return; // defaults are all false. - } - - _allowPartial = options.hasOption("COMPILE_PARTIAL_TYPESYSTEM"); - - _compatMap = (Map)options.get(XmlOptions.COMPILE_SUBSTITUTE_NAMES); - _noUpa = options.hasOption(XmlOptions.COMPILE_NO_UPA_RULE) ? true : - !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true")); - _noPvr = options.hasOption(XmlOptions.COMPILE_NO_PVR_RULE) ? true : - !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true")); - _noAnn = options.hasOption(XmlOptions.COMPILE_NO_ANNOTATIONS) ? true : - !"true".equals(SystemProperties.getProperty("xmlbean.schemaannotations", "true")); - _doingDownloads = options.hasOption(XmlOptions.COMPILE_DOWNLOAD_URLS) ? true : - "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false")); - _entityResolver = (EntityResolver)options.get(XmlOptions.ENTITY_RESOLVER); - - if (_entityResolver == null) - _entityResolver = ResolverUtil.getGlobalEntityResolver(); - - if (_entityResolver != null) - _doingDownloads = true; - - if (options.hasOption(XmlOptions.COMPILE_MDEF_NAMESPACES)) - { - _mdefNamespaces.addAll((Collection)options.get(XmlOptions.COMPILE_MDEF_NAMESPACES)); - - String local = "##local"; - String any = "##any"; - - if (_mdefNamespaces.contains(local)) - { - _mdefNamespaces.remove(local); - _mdefNamespaces.add(""); - } - if (_mdefNamespaces.contains(any)) - { - _mdefNamespaces.remove(any); - _mdefAll = true; - } - } - } - - /** - * May return null if there is no custom entity resolver. - */ - public EntityResolver getEntityResolver() - { - return _entityResolver; - } - - /** - * True if no unique particle attribution option is set - */ - public boolean noUpa() - { - return _noUpa; - } - - /** - * True if no particle valid (restriciton) option is set - */ - public boolean noPvr() - { - return _noPvr; - } - - /** - * True if annotations should be skipped - */ - public boolean noAnn() - { - return _noAnn; - } - - /** - * True if a partial SchemaTypeSystem should be produced - */ - // EXPERIMENTAL - public boolean allowPartial() - { - return _allowPartial; - } - - /** - * Get count of recovered errors. Not for public. - */ - // EXPERIMENTAL - public int getRecovered() - { - return _recoveredErrors; - } - - /** - * Intercepts XML names and translates them - * through the compat map, if any. - * - * Also looks for a default namespace for global definitions. - */ - private QName compatName(QName name, String chameleonNamespace) - { - // first check for a chameleonNamespace namespace - if (name.getNamespaceURI().length() == 0 && chameleonNamespace != null && chameleonNamespace.length() > 0) - name = new QName(chameleonNamespace, name.getLocalPart()); - - if (_compatMap == null) - return name; - - QName subst = (QName)_compatMap.get(name); - if (subst == null) - return name; - return subst; - } - - /** - * Initializer for the schema config object. - */ - public void setBindingConfig(BindingConfig config) - throws IllegalArgumentException - { - _config = config; - } - - public BindingConfig getBindingConfig() - throws IllegalArgumentException - { - return _config; - } - - /** - * Looks up package override for a namespace URI - */ - public String getPackageOverride(String namespace) - { - if (_config == null) - return null; - return _config.lookupPackageForNamespace(namespace); - } - - /** - * Looks up package override for a namespace URI - */ - public String getJavaPrefix(String namespace) - { - if (_config == null) - return null; - return _config.lookupPrefixForNamespace(namespace); - } - - /** - * Looks up package override for a namespace URI - */ - public String getJavaSuffix(String namespace) - { - if (_config == null) - return null; - return _config.lookupSuffixForNamespace(namespace); - } - - /** - * Looks up configured java name for the given qname. - */ - public String getJavaname(QName qname, int kind) - { - if (_config == null) - return null; - return _config.lookupJavanameForQName(qname, kind); - } - - /* SPELLINGS ======================================================*/ - - private static String crunchName(QName name) - { - // lowercase, and drop namespace. - return name.getLocalPart().toLowerCase(); - } - - void addSpelling(QName name, SchemaComponent comp) - { - _misspelledNames.put(crunchName(name), comp); - } - - SchemaComponent findSpelling(QName name) - { - return (SchemaComponent)_misspelledNames.get(crunchName(name)); - } - - /* NAMESPACES ======================================================*/ - - void addNamespace(String targetNamespace) - { - _namespaces.add(targetNamespace); - } - - String[] getNamespaces() - { - return (String[])_namespaces.toArray(new String[_namespaces.size()]); - } - - boolean linkerDefinesNamespace(String namespace) - { - return _importingLoader.isNamespaceDefined(namespace); - } - - /* TYPES ==========================================================*/ - - SchemaTypeImpl findGlobalType(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaTypeImpl result = (SchemaTypeImpl)_globalTypes.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaTypeImpl)_importingLoader.findType(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - SchemaTypeImpl findRedefinedGlobalType(QName name, String chameleonNamespace, SchemaTypeImpl redefinedBy) - { - QName redefinedName = redefinedBy.getName(); - name = compatName(name, chameleonNamespace); - if (name.equals(redefinedName)) - { - return (SchemaTypeImpl)_redefinedGlobalTypes.get(redefinedBy); - // BUGBUG: should also link against _importingLoader.findRedefinedType - } - SchemaTypeImpl result = (SchemaTypeImpl)_globalTypes.get(name); - if (result == null) - result = (SchemaTypeImpl)_importingLoader.findType(name); - // no dependency is needed here, necause it's intra-namespace - return result; - } - - void addGlobalType(SchemaTypeImpl type, SchemaTypeImpl redefined) - { - if (type != null) - { - QName name = type.getName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == type.getContainer(); - - if (redefined != null) - { - if (_redefinedGlobalTypes.containsKey(redefined)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _redefinedGlobalTypes.get(redefined)).getSourceName() } , - type.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _redefinedGlobalTypes.get(redefined)).getSourceName() } , - type.getParseObject()); - } - } - } - else - { - _redefinedGlobalTypes.put(redefined, type); - container.addRedefinedType(type.getRef()); - } - } - else - { - if (_globalTypes.containsKey(name)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _globalTypes.get(name)).getSourceName() }, - type.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global type", QNameHelper.pretty(name), ((SchemaType) _globalTypes.get(name)).getSourceName() }, - type.getParseObject()); - } - } - } - else - { - _globalTypes.put(name, type); - container.addGlobalType(type.getRef()); - addSpelling(name, type); - } - } - } - } - - private boolean ignoreMdef(QName name) - { - return _mdefNamespaces.contains(name.getNamespaceURI()); - } - - SchemaType[] globalTypes() - { return (SchemaType[])_globalTypes.values().toArray(new SchemaType[_globalTypes.size()]); } - - SchemaType[] redefinedGlobalTypes() - { return (SchemaType[])_redefinedGlobalTypes.values().toArray(new SchemaType[_redefinedGlobalTypes.size()]); } - - /* DOCUMENT TYPES =================================================*/ - - SchemaTypeImpl findDocumentType(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaTypeImpl result = (SchemaTypeImpl)_documentTypes.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaTypeImpl)_importingLoader.findDocumentType(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - void addDocumentType(SchemaTypeImpl type, QName name) - { - if (_documentTypes.containsKey(name)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global element", QNameHelper.pretty(name), ((SchemaComponent) _documentTypes.get(name)).getSourceName() }, - type.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global element", QNameHelper.pretty(name), ((SchemaComponent) _documentTypes.get(name)).getSourceName() }, - type.getParseObject()); - } - } - } - else - { - _documentTypes.put(name, type); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == type.getContainer(); - container.addDocumentType(type.getRef()); - } - } - - SchemaType[] documentTypes() - { return (SchemaType[])_documentTypes.values().toArray(new SchemaType[_documentTypes.size()]); } - - /* ATTRIBUTE TYPES =================================================*/ - - SchemaTypeImpl findAttributeType(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaTypeImpl result = (SchemaTypeImpl)_attributeTypes.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaTypeImpl)_importingLoader.findAttributeType(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - void addAttributeType(SchemaTypeImpl type, QName name) - { - if (_attributeTypes.containsKey(name)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global attribute", QNameHelper.pretty(name), ((SchemaComponent) _attributeTypes.get(name)).getSourceName() }, - type.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "global attribute", QNameHelper.pretty(name), ((SchemaComponent) _attributeTypes.get(name)).getSourceName() }, - type.getParseObject()); - } - } - } - else - { - _attributeTypes.put(name, type); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == type.getContainer(); - container.addAttributeType(type.getRef()); - } - } - - SchemaType[] attributeTypes() - { return (SchemaType[])_attributeTypes.values().toArray(new SchemaType[_attributeTypes.size()]); } - - /* ATTRIBUTES =====================================================*/ - - SchemaGlobalAttributeImpl findGlobalAttribute(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaGlobalAttributeImpl result = (SchemaGlobalAttributeImpl)_globalAttributes.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaGlobalAttributeImpl)_importingLoader.findAttribute(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - void addGlobalAttribute(SchemaGlobalAttributeImpl attribute) - { - if (attribute != null) - { - QName name = attribute.getName(); - _globalAttributes.put(name, attribute); - addSpelling(name, attribute); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == attribute.getContainer(); - container.addGlobalAttribute(attribute.getRef()); - } - } - - SchemaGlobalAttribute[] globalAttributes() - { return (SchemaGlobalAttribute[])_globalAttributes.values().toArray(new SchemaGlobalAttribute[_globalAttributes.size()]); } - - /* ELEMENTS =======================================================*/ - - SchemaGlobalElementImpl findGlobalElement(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaGlobalElementImpl result = (SchemaGlobalElementImpl)_globalElements.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaGlobalElementImpl)_importingLoader.findElement(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - void addGlobalElement(SchemaGlobalElementImpl element) - { - if (element != null) - { - QName name = element.getName(); - _globalElements.put(name, element); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == element.getContainer(); - container.addGlobalElement(element.getRef()); - addSpelling(name, element); - } - } - - SchemaGlobalElement[] globalElements() - { return (SchemaGlobalElement[])_globalElements.values().toArray(new SchemaGlobalElement[_globalElements.size()]); } - - /* ATTRIBUTE GROUPS ===============================================*/ - - SchemaAttributeGroupImpl findAttributeGroup(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl)_attributeGroups.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaAttributeGroupImpl)_importingLoader.findAttributeGroup(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - SchemaAttributeGroupImpl findRedefinedAttributeGroup(QName name, String chameleonNamespace, SchemaAttributeGroupImpl redefinedBy) - { - QName redefinitionFor = redefinedBy.getName(); - name = compatName(name, chameleonNamespace); - if (name.equals(redefinitionFor)) - { - return (SchemaAttributeGroupImpl)_redefinedAttributeGroups.get(redefinedBy); - // BUGBUG: should also link against _importingLoader.findRedefinedAttributeGroup - } - SchemaAttributeGroupImpl result = (SchemaAttributeGroupImpl)_attributeGroups.get(name); - if (result == null) - result = (SchemaAttributeGroupImpl)_importingLoader.findAttributeGroup(name); - return result; - } - - void addAttributeGroup(SchemaAttributeGroupImpl attributeGroup, SchemaAttributeGroupImpl redefined) - { - if (attributeGroup != null) - { - QName name = attributeGroup.getName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == attributeGroup.getContainer(); - if (redefined != null) - { - if (_redefinedAttributeGroups.containsKey(redefined)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedAttributeGroups.get(redefined)).getSourceName() }, - attributeGroup.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedAttributeGroups.get(redefined)).getSourceName() }, - attributeGroup.getParseObject()); - } - } - } - else - { - _redefinedAttributeGroups.put(redefined, attributeGroup); - container.addRedefinedAttributeGroup(attributeGroup.getRef()); - } - } - else - { - if (_attributeGroups.containsKey( name )) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _attributeGroups.get(name)).getSourceName() }, - attributeGroup.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "attribute group", QNameHelper.pretty(name), ((SchemaComponent) _attributeGroups.get(name)).getSourceName() }, - attributeGroup.getParseObject()); - } - } - } - else - { - _attributeGroups.put(attributeGroup.getName(), attributeGroup); - addSpelling(attributeGroup.getName(), attributeGroup); - container.addAttributeGroup(attributeGroup.getRef()); - } - } - } - } - - SchemaAttributeGroup[] attributeGroups() - { return (SchemaAttributeGroup[])_attributeGroups.values().toArray(new SchemaAttributeGroup[_attributeGroups.size()]); } - - SchemaAttributeGroup[] redefinedAttributeGroups() - { return (SchemaAttributeGroup[])_redefinedAttributeGroups.values().toArray(new SchemaAttributeGroup[_redefinedAttributeGroups.size()]); } - - /* MODEL GROUPS ===================================================*/ - - SchemaModelGroupImpl findModelGroup(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - SchemaModelGroupImpl result = (SchemaModelGroupImpl)_modelGroups.get(name); - boolean foundOnLoader = false; - if (result == null) - { - result = (SchemaModelGroupImpl)_importingLoader.findModelGroup(name); - foundOnLoader = result != null; - } - if (!foundOnLoader && sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return result; - } - - SchemaModelGroupImpl findRedefinedModelGroup(QName name, String chameleonNamespace, SchemaModelGroupImpl redefinedBy) - { - QName redefinitionFor = redefinedBy.getName(); - name = compatName(name, chameleonNamespace); - if (name.equals(redefinitionFor)) - { - return (SchemaModelGroupImpl)_redefinedModelGroups.get(redefinedBy); - // BUGBUG: should also link against _importingLoader.findRedefinedModelGroup - } - SchemaModelGroupImpl result = (SchemaModelGroupImpl)_modelGroups.get(name); - if (result == null) - result = (SchemaModelGroupImpl)_importingLoader.findModelGroup(name); - return result; - } - - void addModelGroup(SchemaModelGroupImpl modelGroup, SchemaModelGroupImpl redefined) - { - if (modelGroup != null) - { - QName name = modelGroup.getName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == modelGroup.getContainer(); - if (redefined != null) - { - if (_redefinedModelGroups.containsKey(redefined)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName() }, - modelGroup.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _redefinedModelGroups.get(redefined)).getSourceName() }, - modelGroup.getParseObject()); - } - } - } - else - { - _redefinedModelGroups.put(redefined, modelGroup); - container.addRedefinedModelGroup(modelGroup.getRef()); - } - } - else - { - if (_modelGroups.containsKey(name)) - { - if (!ignoreMdef(name)) { - if (_mdefAll) { - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _modelGroups.get(name)).getSourceName() }, - modelGroup.getParseObject()); - } else { - error(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "model group", QNameHelper.pretty(name), ((SchemaComponent) _modelGroups.get(name)).getSourceName() }, - modelGroup.getParseObject()); - } - } - } - else - { - _modelGroups.put(modelGroup.getName(), modelGroup); - addSpelling(modelGroup.getName(), modelGroup); - container.addModelGroup(modelGroup.getRef()); - } - } - } - } - - SchemaModelGroup[] modelGroups() - { return (SchemaModelGroup[])_modelGroups.values().toArray(new SchemaModelGroup[_modelGroups.size()]); } - - SchemaModelGroup[] redefinedModelGroups() - { return (SchemaModelGroup[])_redefinedModelGroups.values().toArray(new SchemaModelGroup[_redefinedModelGroups.size()]); } - - /* IDENTITY CONSTRAINTS ===========================================*/ - - SchemaIdentityConstraintImpl findIdConstraint(QName name, String chameleonNamespace, String sourceNamespace) - { - name = compatName(name, chameleonNamespace); - if (sourceNamespace != null) - registerDependency(sourceNamespace, name.getNamespaceURI()); - return (SchemaIdentityConstraintImpl)_idConstraints.get(name); - } - - void addIdConstraint(SchemaIdentityConstraintImpl idc) - { - if (idc != null) - { - QName name = idc.getName(); - SchemaContainer container = getContainer(name.getNamespaceURI()); - assert container != null && container == idc.getContainer(); - if (_idConstraints.containsKey(name)) - { - if (!ignoreMdef(name)) - warning(XmlErrorCodes.SCHEMA_PROPERTIES$DUPLICATE, - new Object[] { "identity constraint", QNameHelper.pretty(name), ((SchemaComponent) _idConstraints.get(name)).getSourceName() }, - idc.getParseObject()); - } - else - { - _idConstraints.put(name, idc); - addSpelling(idc.getName(), idc); - container.addIdentityConstraint(idc.getRef()); - } - } - } - - SchemaIdentityConstraintImpl[] idConstraints() - { return (SchemaIdentityConstraintImpl[])_idConstraints.values().toArray(new SchemaIdentityConstraintImpl[_idConstraints.size()]); } - - /* ANNOTATIONS ===========================================*/ - - void addAnnotation(SchemaAnnotationImpl ann, String targetNamespace) - { - if (ann != null) - { - SchemaContainer container = getContainer(targetNamespace); - assert container != null && container == ann.getContainer(); - _annotations.add(ann); - container.addAnnotation(ann); - } - } - - List annotations() - { return _annotations; } - - /* RECURSION AVOIDANCE ============================================*/ - boolean isProcessing(Object obj) - { - return _processingGroups.contains(obj); - } - - void startProcessing(Object obj) - { - assert(!_processingGroups.contains(obj)); - _processingGroups.add(obj); - } - - void finishProcessing(Object obj) - { - assert(_processingGroups.contains(obj)); - _processingGroups.remove(obj); - } - - Object[] getCurrentProcessing() - { - return _processingGroups.toArray(); - } - - /* JAVAIZATION ====================================================*/ - - Map typesByClassname() - { return Collections.unmodifiableMap(_typesByClassname); } - - void addClassname(String classname, SchemaType type) - { _typesByClassname.put(classname, type); } - - - - /** - * Stack management if (heaven help us) we ever need to do - * nested compilation of schema type system. - */ - private static final class StscStack - { - StscState current; - ArrayList stack = new ArrayList(); - final StscState push() - { - stack.add(current); - current = new StscState(); - return current; - } - final void pop() - { - current = (StscState)stack.get(stack.size() - 1); - stack.remove(stack.size() - 1); - } - } - - private static ThreadLocal tl_stscStack = new ThreadLocal(); - - public static StscState start() - { - StscStack stscStack = (StscStack) tl_stscStack.get(); - - if (stscStack==null) - { - stscStack = new StscStack(); - tl_stscStack.set(stscStack); - } - return stscStack.push(); - } - - public static StscState get() - { - return ((StscStack) tl_stscStack.get()).current; - } - - public static void end() - { - StscStack stscStack = (StscStack) tl_stscStack.get(); - stscStack.pop(); - if (stscStack.stack.size()==0) - tl_stscStack.set(null); // this is required to release all the references in this classloader - // which will enable class unloading and avoid OOM in PermGen - } - - private final static XmlValueRef XMLSTR_PRESERVE = buildString("preserve"); - private final static XmlValueRef XMLSTR_REPLACE = buildString("preserve"); - private final static XmlValueRef XMLSTR_COLLAPSE = buildString("preserve"); - - static final SchemaType[] EMPTY_ST_ARRAY = new SchemaType[0]; - static final SchemaType.Ref[] EMPTY_STREF_ARRAY = new SchemaType.Ref[0]; - - private final static XmlValueRef[] FACETS_NONE = new XmlValueRef[] - { null, null, null, null, null, null, null, null, null, - null, null, null }; - - private final static boolean[] FIXED_FACETS_NONE = new boolean[] - { false, false, false, false, false, false, false, false, false, - false, false, false }; - - private final static XmlValueRef[] FACETS_WS_COLLAPSE = new XmlValueRef[] - { null, null, null, null, null, null, null, null, null, - build_wsstring(SchemaType.WS_COLLAPSE), null, null }; - - private final static boolean[] FIXED_FACETS_WS = new boolean[] - { false, false, false, false, false, false, false, false, false, - true, false, false }; - - final static XmlValueRef[] FACETS_UNION = FACETS_NONE; - final static boolean[] FIXED_FACETS_UNION = FIXED_FACETS_NONE; - final static XmlValueRef[] FACETS_LIST = FACETS_WS_COLLAPSE; - final static boolean[] FIXED_FACETS_LIST = FIXED_FACETS_WS; - - static XmlValueRef build_wsstring(int wsr) - { - switch (wsr) - { - case SchemaType.WS_PRESERVE: - return XMLSTR_PRESERVE; - case SchemaType.WS_REPLACE: - return XMLSTR_REPLACE; - case SchemaType.WS_COLLAPSE: - return XMLSTR_COLLAPSE; - } - return null; - } - - static XmlValueRef buildString(String str) - { - if (str == null) - return null; - - try - { - XmlStringImpl i = new XmlStringImpl(); - i.set(str); - i.setImmutable(); - return new XmlValueRef(i); - } - catch (XmlValueOutOfRangeException e) - { - return null; - } - } - - public void notFoundError(QName itemName, int code, XmlObject loc, boolean recovered) - { - String expected; - String expectedName = QNameHelper.pretty(itemName); - String found = null; - String foundName = null; - String sourceName = null; - - if (recovered) - _recoveredErrors++; - - switch (code) - { - case SchemaType.TYPE: - expected = "type"; - break; - case SchemaType.ELEMENT: - expected = "element"; - break; - case SchemaType.ATTRIBUTE: - expected = "attribute"; - break; - case SchemaType.MODEL_GROUP: - expected = "model group"; - break; - case SchemaType.ATTRIBUTE_GROUP: - expected = "attribute group"; - break; - case SchemaType.IDENTITY_CONSTRAINT: - expected = "identity constraint"; - break; - default: - assert(false); - expected = "definition"; - break; - } - - SchemaComponent foundComponent = findSpelling(itemName); - QName name; - if (foundComponent != null) - { - name = foundComponent.getName(); - if (name != null) - { - switch (foundComponent.getComponentType()) - { - case SchemaComponent.TYPE: - found = "type"; - sourceName = ((SchemaType)foundComponent).getSourceName(); - break; - case SchemaComponent.ELEMENT: - found = "element"; - sourceName = ((SchemaGlobalElement)foundComponent).getSourceName(); - break; - case SchemaComponent.ATTRIBUTE: - found = "attribute"; - sourceName = ((SchemaGlobalAttribute)foundComponent).getSourceName(); - break; - case SchemaComponent.ATTRIBUTE_GROUP: - found = "attribute group"; - break; - case SchemaComponent.MODEL_GROUP: - found = "model group"; - break; - } - - if (sourceName != null) - { - sourceName = sourceName.substring(sourceName.lastIndexOf('/') + 1); - } - - if (!name.equals(itemName)) - { - foundName = QNameHelper.pretty(name); - } - } - } - - if (found == null) - { - // error with no help - error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE, - new Object[] { expected, expectedName }, loc); - } - else { - // error with help - error(XmlErrorCodes.SCHEMA_QNAME_RESOLVE$HELP, - new Object[] { - expected, - expectedName, - found, - (foundName == null ? new Integer(0) : new Integer(1)), - foundName, - (sourceName == null ? new Integer(0) : new Integer(1)), - sourceName - }, - loc); - } - } - - - /** - * Produces the "sourceName" (to be used within the schema project - * source file copies) from the URI of the original source. - * - * Returns null if none. - */ - public String sourceNameForUri(String uri) - { - return (String)_sourceForUri.get(uri); - } - - /** - * Returns the whole sourceCopyMap, mapping URI's that have - * been read to "sourceName" local names that have been used - * to tag the types. - */ - public Map sourceCopyMap() - { - return Collections.unmodifiableMap(_sourceForUri); - } - - /** - * The base URI to use for nice filenames when saving sources. - */ - public void setBaseUri(URI uri) - { - _baseURI = uri; - } - - private final static String PROJECT_URL_PREFIX = "project://local"; - - public String relativize(String uri) - { - return relativize(uri, false); - } - - public String computeSavedFilename(String uri) - { - return relativize(uri, true); - } - - private String relativize(String uri, boolean forSavedFilename) - { - if (uri == null) - return null; - - // deal with things that do not look like absolute uris - if (uri.startsWith("/")) - { - uri = PROJECT_URL_PREFIX + uri.replace('\\', '/'); - } - else - { - // looks like a URL? - int colon = uri.indexOf(':'); - if (colon <= 1 || !uri.substring(0, colon).matches("^\\w+$")) - uri = PROJECT_URL_PREFIX + "/" + uri.replace('\\', '/'); - } - - // now relativize against that... - if (_baseURI != null) - { - try - { - URI relative = _baseURI.relativize(new URI(uri)); - if (!relative.isAbsolute()) - return relative.toString(); - else - uri = relative.toString(); - } - catch (URISyntaxException e) - { - } - } - - if (!forSavedFilename) - return uri; - - int lastslash = uri.lastIndexOf('/'); - String dir = QNameHelper.hexsafe(lastslash == -1 ? "" : uri.substring(0, lastslash)); - - int question = uri.indexOf('?', lastslash + 1); - if (question == -1) - return dir + "/" + uri.substring(lastslash + 1); - - String query = QNameHelper.hexsafe(question == -1 ? "" : uri.substring(question)); - - // if encoded query part is longer than 64 characters, just drop it - if (query.startsWith(QNameHelper.URI_SHA1_PREFIX)) - return dir + "/" + uri.substring(lastslash + 1, question); - else - return dir + "/" + uri.substring(lastslash + 1, question) + query; - } - - /** - * Notes another URI that has been consumed during compilation - * (this is the URI that is in the document .NAME property) - */ - public void addSourceUri(String uri, String nameToUse) - { - if (uri == null) - return; - - if (nameToUse == null) - nameToUse = computeSavedFilename(uri); - - _sourceForUri.put(uri, nameToUse); - } - - /** - * Returns the error listener being filled in during this compilation - */ - public Collection getErrorListener() - { - return _errorListener; - } - - /** - * Returns the schema type loader to use for processing s4s - */ - public SchemaTypeLoader getS4SLoader() - { - return _s4sloader; - } - - Map _sourceForUri = new HashMap(); - URI _baseURI = URI.create(PROJECT_URL_PREFIX + "/"); - SchemaTypeLoader _s4sloader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader()); - - public File getSchemasDir() - { - return _schemasDir; - } - - public void setSchemasDir(File _schemasDir) - { - this._schemasDir = _schemasDir; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java b/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java deleted file mode 100644 index 2e3fa3a..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java +++ /dev/null @@ -1,1781 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.schema; - -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.QNameSetBuilder; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaBookmark; -import org.apache.xmlbeans.SchemaGlobalAttribute; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaIdentityConstraint; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlNonNegativeInteger; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlPositiveInteger; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.XMLChar; -import org.apache.xmlbeans.impl.common.XPath; -import org.apache.xmlbeans.impl.values.NamespaceContext; -import org.apache.xmlbeans.impl.values.XmlNonNegativeIntegerImpl; -import org.apache.xmlbeans.impl.values.XmlPositiveIntegerImpl; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.apache.xmlbeans.impl.xb.xsdschema.Annotated; -import org.apache.xmlbeans.impl.xb.xsdschema.AnnotationDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.Attribute; -import org.apache.xmlbeans.impl.xb.xsdschema.AttributeGroup; -import org.apache.xmlbeans.impl.xb.xsdschema.Element; -import org.apache.xmlbeans.impl.xb.xsdschema.FieldDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.FormChoice; -import org.apache.xmlbeans.impl.xb.xsdschema.Keybase; -import org.apache.xmlbeans.impl.xb.xsdschema.KeyrefDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.LocalElement; -import org.apache.xmlbeans.impl.xb.xsdschema.LocalSimpleType; -import org.apache.xmlbeans.impl.xb.xsdschema.NamedAttributeGroup; -import org.apache.xmlbeans.impl.xb.xsdschema.NamedGroup; -import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; -import org.apache.xmlbeans.impl.xb.xsdschema.SimpleType; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelAttribute; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelElement; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelSimpleType; -import org.apache.xmlbeans.soap.SOAPArrayType; - -import javax.xml.namespace.QName; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class StscTranslator -{ - private static final QName WSDL_ARRAYTYPE_NAME = - QNameHelper.forLNS("arrayType", "http://schemas.xmlsoap.org/wsdl/"); - private static final String FORM_QUALIFIED = "qualified"; - - public static void addAllDefinitions(StscImporter.SchemaToProcess[] schemasAndChameleons) - { - // Build all redefine objects - List redefinitions = new ArrayList(); - for (int i = 0; i < schemasAndChameleons.length; i++) - { - List redefines = schemasAndChameleons[i].getRedefines(); - if (redefines != null) - { - List redefineObjects = schemasAndChameleons[i].getRedefineObjects(); - Iterator it = redefines.iterator(); - Iterator ito = redefineObjects.iterator(); - for (; it.hasNext(); ) - { - assert ito.hasNext() : - "The array of redefines and redefine objects have to have the same length"; - redefinitions.add(new RedefinitionHolder( - (StscImporter.SchemaToProcess) it.next(), - (Redefine) ito.next())); - } - } - } - RedefinitionMaster globalRedefinitions = new RedefinitionMaster((RedefinitionHolder[]) - redefinitions.toArray(new RedefinitionHolder[redefinitions.size()])); - - StscState state = StscState.get(); - for (int j = 0; j < schemasAndChameleons.length; j++) - { - Schema schema = schemasAndChameleons[j].getSchema(); - String givenTargetNamespace = schemasAndChameleons[j].getChameleonNamespace(); - - // quick check for a few unsupported features - - if (schema.sizeOfNotationArray() > 0) - { - state.warning("Schema is not yet supported for this release.", XmlErrorCodes.UNSUPPORTED_FEATURE, schema.getNotationArray(0)); - } - - // figure namespace (taking into account chameleons) - String targetNamespace = schema.getTargetNamespace(); - boolean chameleon = false; - if (givenTargetNamespace != null && targetNamespace == null) - { - targetNamespace = givenTargetNamespace; - chameleon = true; - } - if (targetNamespace == null) - targetNamespace = ""; - - //SchemaContainer container = null; - if (targetNamespace.length() > 0 || !isEmptySchema(schema)) - { - state.registerContribution(targetNamespace, schema.documentProperties().getSourceName()); - state.addNewContainer(targetNamespace); - //container = state.getContainer(targetNamespace); - } - - List redefChain = new ArrayList(); - TopLevelComplexType[] complexTypes = schema.getComplexTypeArray(); - for (int i = 0; i < complexTypes.length; i++) - { - TopLevelComplexType type = complexTypes[i]; - TopLevelComplexType redef; - // 1. Traverse the list of redefining Schemas putting all redefinitions - // of this type in a List - RedefinitionHolder[] rhArray = globalRedefinitions.getComplexTypeRedefinitions( - type.getName(), schemasAndChameleons[j]); - for (int k = 0; k < rhArray.length; k++) - { - // In error cases, some redefinitions were nulled out in the list - // which is why we need to perform this check - if (rhArray[k] != null) - { - redef = rhArray[k].redefineComplexType(type.getName()); - assert redef != null; // This was already checked - redefChain.add(type); - type = redef; - } - } - - SchemaTypeImpl t = translateGlobalComplexType(type, targetNamespace, chameleon, redefChain.size() > 0); - state.addGlobalType(t, null); - SchemaTypeImpl r; - // 2. Traverse the List built in step 1 in reverse and add all the - // types in it to the list of redefined types - for (int k = redefChain.size() - 1; k >= 0; k--) - { - redef = (TopLevelComplexType) redefChain.remove(k); - r = translateGlobalComplexType(redef, targetNamespace, chameleon, k > 0); - state.addGlobalType(r, t); - t = r; - } - } - - TopLevelSimpleType[] simpleTypes = schema.getSimpleTypeArray(); - for (int i = 0; i < simpleTypes.length; i++) - { - TopLevelSimpleType type = simpleTypes[i]; - TopLevelSimpleType redef; - RedefinitionHolder[] rhArray = globalRedefinitions.getSimpleTypeRedefinitions( - type.getName(), schemasAndChameleons[j]); - for (int k = 0; k < rhArray.length; k++) - { - // In error cases, some redefinitions were nulled out in the list - // which is why we need to perform this check - if (rhArray[k] != null) - { - redef = rhArray[k].redefineSimpleType(type.getName()); - assert redef != null; // This was already checked - redefChain.add(type); - type = redef; - } - } - - SchemaTypeImpl t = translateGlobalSimpleType(type, targetNamespace, chameleon,redefChain.size() > 0); - state.addGlobalType(t, null); - SchemaTypeImpl r; - for (int k = redefChain.size()-1; k >= 0; k--) - { - redef = (TopLevelSimpleType) redefChain.remove(k); - r = translateGlobalSimpleType(redef, targetNamespace, chameleon, k > 0); - state.addGlobalType(r, t); - t = r; - } - } - - TopLevelElement[] elements = schema.getElementArray(); - for (int i = 0; i < elements.length; i++) - { - TopLevelElement element = elements[i]; - state.addDocumentType(translateDocumentType(element, targetNamespace, chameleon), QNameHelper.forLNS(element.getName(), targetNamespace)); - } - - TopLevelAttribute[] attributes = schema.getAttributeArray(); - for (int i = 0; i < attributes.length ; i++) - { - TopLevelAttribute attribute = attributes[i]; - state.addAttributeType(translateAttributeType(attribute, targetNamespace, chameleon), QNameHelper.forLNS(attribute.getName(), targetNamespace)); - } - - NamedGroup[] modelgroups = schema.getGroupArray(); - for (int i = 0; i < modelgroups.length; i++) - { - NamedGroup group = modelgroups[i]; - NamedGroup redef; - RedefinitionHolder[] rhArray = globalRedefinitions.getModelGroupRedefinitions( - group.getName(), schemasAndChameleons[j]); - for (int k = 0; k < rhArray.length; k++) - { - // In error cases, some redefinitions were nulled out in the list - // which is why we need to perform this check - if (rhArray[k] != null) - { - redef = rhArray[k].redefineModelGroup(group.getName()); - assert redef != null; // This was already checked - redefChain.add(group); - group = redef; - } - } - - SchemaModelGroupImpl g = translateModelGroup(group, targetNamespace, chameleon, redefChain.size() > 0); - state.addModelGroup(g, null); - SchemaModelGroupImpl r; - for (int k = redefChain.size()-1; k >= 0; k--) - { - redef = (NamedGroup) redefChain.remove(k); - r = translateModelGroup(redef, targetNamespace, chameleon, k > 0); - state.addModelGroup(r, g); - g = r; - } - } - - NamedAttributeGroup[] attrgroups = schema.getAttributeGroupArray(); - for (int i = 0; i < attrgroups.length; i++) - { - NamedAttributeGroup group = attrgroups[i]; - NamedAttributeGroup redef; - RedefinitionHolder[] rhArray = globalRedefinitions.getAttributeGroupRedefinitions( - group.getName(), schemasAndChameleons[j]); - for (int k = 0; k < rhArray.length; k++) - { - // In error cases, some redefinitions were nulled out in the list - // which is why we need to perform this check - if (rhArray[k] != null) - { - redef = rhArray[k].redefineAttributeGroup(group.getName()); - assert redef != null; // This was already checked - redefChain.add(group); - group = redef; - } - } - - SchemaAttributeGroupImpl g = translateAttributeGroup(group, targetNamespace, chameleon, redefChain.size() > 0); - state.addAttributeGroup(g, null); - SchemaAttributeGroupImpl r; - for (int k = redefChain.size()-1; k >= 0; k--) - { - redef = (NamedAttributeGroup) redefChain.remove(k); - r = translateAttributeGroup(redef, targetNamespace, chameleon, k > 0); - state.addAttributeGroup(r, g); - g = r; - } - } - - AnnotationDocument.Annotation[] annotations = schema.getAnnotationArray(); - for (int i = 0; i < annotations.length; i++) - state.addAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), schema, annotations[i]), targetNamespace); - } - - for (int i = 0; i < redefinitions.size(); i++) - ((RedefinitionHolder) redefinitions.get(i)).complainAboutMissingDefinitions(); - } - - private static class RedefinitionHolder - { - // record redefinitions - private Map stRedefinitions = Collections.EMPTY_MAP; - private Map ctRedefinitions = Collections.EMPTY_MAP; - private Map agRedefinitions = Collections.EMPTY_MAP; - private Map mgRedefinitions = Collections.EMPTY_MAP; - private String schemaLocation = ""; - private StscImporter.SchemaToProcess schemaRedefined; - - // first build set of redefined components - RedefinitionHolder(StscImporter.SchemaToProcess schemaToProcess, Redefine redefine) - { - schemaRedefined = schemaToProcess; - if (redefine != null) - { - StscState state = StscState.get(); - - stRedefinitions = new HashMap(); - ctRedefinitions = new HashMap(); - agRedefinitions = new HashMap(); - mgRedefinitions = new HashMap(); - if (redefine.getSchemaLocation() != null) - schemaLocation = redefine.getSchemaLocation(); - - TopLevelComplexType[] complexTypes = redefine.getComplexTypeArray(); - for (int i = 0; i < complexTypes.length; i++) - { - if (complexTypes[i].getName() != null) - { - // KHK: which rule? sch-props-correct.2? - if (ctRedefinitions.containsKey(complexTypes[i].getName())) - state.error("Duplicate type redefinition: " + complexTypes[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); - else - ctRedefinitions.put(complexTypes[i].getName(), complexTypes[i]); - } - } - - TopLevelSimpleType[] simpleTypes = redefine.getSimpleTypeArray(); - for (int i = 0; i < simpleTypes.length; i++) - { - if (simpleTypes[i].getName() != null) - { - if (stRedefinitions.containsKey(simpleTypes[i].getName())) - state.error("Duplicate type redefinition: " + simpleTypes[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); - else - stRedefinitions.put(simpleTypes[i].getName(), simpleTypes[i]); - } - } - - NamedGroup[] modelgroups = redefine.getGroupArray(); - for (int i = 0; i < modelgroups.length; i++) - { - if (modelgroups[i].getName() != null) - { - if (mgRedefinitions.containsKey(modelgroups[i].getName())) - state.error("Duplicate type redefinition: " + modelgroups[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); - else - mgRedefinitions.put(modelgroups[i].getName(), modelgroups[i]); - } - } - - NamedAttributeGroup[] attrgroups = redefine.getAttributeGroupArray(); - for (int i = 0; i < attrgroups.length; i++) - { - if (attrgroups[i].getName() != null) - { - if (agRedefinitions.containsKey(attrgroups[i].getName())) - state.error("Duplicate type redefinition: " + attrgroups[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null); - else - agRedefinitions.put(attrgroups[i].getName(), attrgroups[i]); - } - } - } - } - - public TopLevelSimpleType redefineSimpleType(String name) - { - if (name == null || !stRedefinitions.containsKey(name)) - return null; - return (TopLevelSimpleType)stRedefinitions.remove(name); - } - - public TopLevelComplexType redefineComplexType(String name) - { - if (name == null || !ctRedefinitions.containsKey(name)) - return null; - return (TopLevelComplexType)ctRedefinitions.remove(name); - } - - public NamedGroup redefineModelGroup(String name) - { - if (name == null || !mgRedefinitions.containsKey(name)) - return null; - return (NamedGroup)mgRedefinitions.remove(name); - } - - public NamedAttributeGroup redefineAttributeGroup(String name) - { - if (name == null || !agRedefinitions.containsKey(name)) - return null; - return (NamedAttributeGroup)agRedefinitions.remove(name); - } - - public void complainAboutMissingDefinitions() - { - if (stRedefinitions.isEmpty() && ctRedefinitions.isEmpty() && - agRedefinitions.isEmpty() && mgRedefinitions.isEmpty()) - return; - - StscState state = StscState.get(); - - for (Iterator i = stRedefinitions.keySet().iterator(); i.hasNext(); ) - { - String name = (String)i.next(); - state.error("Redefined simple type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)stRedefinitions.get(name)); - } - - for (Iterator i = ctRedefinitions.keySet().iterator(); i.hasNext(); ) - { - String name = (String)i.next(); - state.error("Redefined complex type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)ctRedefinitions.get(name)); - } - - for (Iterator i = agRedefinitions.keySet().iterator(); i.hasNext(); ) - { - String name = (String)i.next(); - state.error("Redefined attribute group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)agRedefinitions.get(name)); - } - - for (Iterator i = mgRedefinitions.keySet().iterator(); i.hasNext(); ) - { - String name = (String)i.next(); - state.error("Redefined model group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)mgRedefinitions.get(name)); - } - } - } - - /** - * This is used to aggregate all redefinitions for a specific component name. - * The idea is to record the list of <redefine%gt; sections that could - * potentially redefine this component. When the list of actual redefinitions - * is requested, the potential redefinitions are first filtered based on - * accessibilty of the schema currently being processed from the redefining Schemas - * and then topologically sorted based on the inclusion relationship to - * ensure that redefinitions are applied in the right order. - */ - private static class RedefinitionMaster - { - // record redefinitions - private Map stRedefinitions = Collections.EMPTY_MAP; - private Map ctRedefinitions = Collections.EMPTY_MAP; - private Map agRedefinitions = Collections.EMPTY_MAP; - private Map mgRedefinitions = Collections.EMPTY_MAP; - private static final RedefinitionHolder[] EMPTY_REDEFINTION_HOLDER_ARRAY = - new RedefinitionHolder[0]; - - RedefinitionMaster(RedefinitionHolder[] redefHolders) - { - if (redefHolders.length > 0) - { - stRedefinitions = new HashMap(); - ctRedefinitions = new HashMap(); - agRedefinitions = new HashMap(); - mgRedefinitions = new HashMap(); - - for (int i = 0; i < redefHolders.length; i++) - { - RedefinitionHolder redefHolder = redefHolders[i]; - for (Iterator it = redefHolder.stRedefinitions.keySet().iterator(); it.hasNext();) - { - Object key = it.next(); - List redefinedIn = (List) stRedefinitions.get(key); - if (redefinedIn == null) - { - redefinedIn = new ArrayList(); - stRedefinitions.put(key, redefinedIn); - } - redefinedIn.add(redefHolders[i]); - } - for (Iterator it = redefHolder.ctRedefinitions.keySet().iterator(); it.hasNext();) - { - Object key = it.next(); - List redefinedIn = (List) ctRedefinitions.get(key); - if (redefinedIn == null) - { - redefinedIn = new ArrayList(); - ctRedefinitions.put(key, redefinedIn); - } - redefinedIn.add(redefHolders[i]); - } - for (Iterator it = redefHolder.agRedefinitions.keySet().iterator(); it.hasNext();) - { - Object key = it.next(); - List redefinedIn = (List) agRedefinitions.get(key); - if (redefinedIn == null) - { - redefinedIn = new ArrayList(); - agRedefinitions.put(key, redefinedIn); - } - redefinedIn.add(redefHolders[i]); - } - for (Iterator it = redefHolder.mgRedefinitions.keySet().iterator(); it.hasNext();) - { - Object key = it.next(); - List redefinedIn = (List) mgRedefinitions.get(key); - if (redefinedIn == null) - { - redefinedIn = new ArrayList(); - mgRedefinitions.put(key, redefinedIn); - } - redefinedIn.add(redefHolders[i]); - } - } - } - } - - RedefinitionHolder[] getSimpleTypeRedefinitions(String name, - StscImporter.SchemaToProcess schema) - { - List redefines = (List) stRedefinitions.get(name); - if (redefines == null) - return EMPTY_REDEFINTION_HOLDER_ARRAY; - return doTopologicalSort(redefines, schema, name, SIMPLE_TYPE); - } - - RedefinitionHolder[] getComplexTypeRedefinitions(String name, - StscImporter.SchemaToProcess schema) - { - List redefines = (List) ctRedefinitions.get(name); - if (redefines == null) - return EMPTY_REDEFINTION_HOLDER_ARRAY; - return doTopologicalSort(redefines, schema, name, COMPLEX_TYPE); - } - - RedefinitionHolder[] getAttributeGroupRedefinitions(String name, - StscImporter.SchemaToProcess schema) - { - List redefines = (List) agRedefinitions.get(name); - if (redefines == null) - return EMPTY_REDEFINTION_HOLDER_ARRAY; - return doTopologicalSort(redefines, schema, name, ATTRIBUTE_GROUP); - } - - RedefinitionHolder[] getModelGroupRedefinitions(String name, - StscImporter.SchemaToProcess schema) - { - List redefines = (List) mgRedefinitions.get(name); - if (redefines == null) - return EMPTY_REDEFINTION_HOLDER_ARRAY; - return doTopologicalSort(redefines, schema, name, MODEL_GROUP); - } - - private final static short SIMPLE_TYPE = 1; - private final static short COMPLEX_TYPE = 2; - private final static short MODEL_GROUP = 3; - private final static short ATTRIBUTE_GROUP = 4; - - private RedefinitionHolder[] doTopologicalSort(List genericRedefines, - StscImporter.SchemaToProcess schema, String name, short componentType) - { - // We have a list of files that redefine this name - // Filter out the ones that don't redefine this file in particular - RedefinitionHolder[] specificRedefines = new RedefinitionHolder[genericRedefines.size()]; - int n = 0; - for (int i = 0; i < genericRedefines.size(); i++) - { - RedefinitionHolder h = (RedefinitionHolder) genericRedefines.get(i); - if (h.schemaRedefined == schema || - h.schemaRedefined.indirectIncludes(schema)) - specificRedefines[n++] = h; - } - // Now we have the list of files that specifically redefine the - // name in the file that we are looking for - // Sort this list into topological order to get the right order - // and figure out if there are multiple redefinitions involved - RedefinitionHolder[] sortedRedefines = new RedefinitionHolder[n]; - int[] numberOfIncludes = new int[n]; - // Just count the number of inclusions for each redefinition - for (int i = 0; i < n-1; i++) - { - RedefinitionHolder current = specificRedefines[i]; - for (int j = i + 1; j < n; j++) - { - if (current.schemaRedefined.indirectIncludes(specificRedefines[j].schemaRedefined)) - numberOfIncludes[i]++; - if (specificRedefines[j].schemaRedefined.indirectIncludes(current.schemaRedefined)) - numberOfIncludes[j]++; - } - } - // Eliminate members one by one, according to the number of schemas - // that they include, to complete the sort - int position = 0; - boolean errorReported = false; - while (position < n) - { - int index = -1; - for (int i = 0; i < numberOfIncludes.length; i++) - if (numberOfIncludes[i] == 0) - { - if (index < 0) - index = i; - } - if (index < 0) - { - // Error! Circular redefinition - if (!errorReported) - { - StringBuffer fileNameList = new StringBuffer(); - XmlObject location = null; - for (int i = 0; i < n; i++) - if (specificRedefines[i] != null) - { - fileNameList.append(specificRedefines[i].schemaLocation). - append(',').append(' '); - if (location == null) - location = locationFromRedefinitionAndCode( - specificRedefines[i], name, componentType); - } - StscState.get().error("Detected circular redefinition of " + - componentNameFromCode(componentType) + " \"" + name + - "\"; Files involved: " + fileNameList.toString(), - XmlErrorCodes.GENERIC_ERROR, location); - errorReported = true; - } - int min = n; - for (int i = 0; i < n; i++) - if (numberOfIncludes[i] > 0 && numberOfIncludes[i] < min) - { - min = numberOfIncludes[i]; - index = i; - } - numberOfIncludes[index]--; - } - else - { - assert specificRedefines[index] != null; - sortedRedefines[position++] = specificRedefines[index]; - for (int i = 0; i < n; i++) - if (specificRedefines[i] != null && - specificRedefines[i].schemaRedefined. - indirectIncludes(specificRedefines[index]. - schemaRedefined)) - numberOfIncludes[i]--; - specificRedefines[index] = null; - numberOfIncludes[index]--; - } - } - // Nice. We now have all the redefinitions of this name in the list - // Each one has to transitively redefine the one before, otherwise - // it means we are attepting two different redefinitions for the same - // component - for (int i = 1; i < n; i++) - { - // Find the previous index with non-null Schema - // Since i is never 0, such index always exists - int j; - for (j = i-1; j >= 0; j--) - if (sortedRedefines[j] != null) - break; - - if (!sortedRedefines[i].schemaRedefined.indirectIncludes( - sortedRedefines[j].schemaRedefined)) - { - StscState.get().error("Detected multiple redefinitions of " + - componentNameFromCode(componentType) + - " \"" + name + "\"; Files involved: " + - sortedRedefines[j].schemaRedefined.getSourceName() + ", " + - sortedRedefines[i].schemaRedefined.getSourceName(), - XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, - locationFromRedefinitionAndCode(sortedRedefines[i], name, componentType)); - // Ignore this redefinition - switch (componentType) - { - case SIMPLE_TYPE: - sortedRedefines[i].redefineSimpleType(name); break; - case COMPLEX_TYPE: - sortedRedefines[i].redefineComplexType(name); break; - case ATTRIBUTE_GROUP: - sortedRedefines[i].redefineAttributeGroup(name); break; - case MODEL_GROUP: - sortedRedefines[i].redefineModelGroup(name); break; - } - sortedRedefines[i] = null; - } - } - - return sortedRedefines; - } - - private String componentNameFromCode(short code) - { - String componentName; - switch (code) - { - case SIMPLE_TYPE: componentName = "simple type"; break; - case COMPLEX_TYPE: componentName = "complex type"; break; - case MODEL_GROUP: componentName = "model group"; break; - case ATTRIBUTE_GROUP: componentName = "attribute group"; break; - default: componentName = ""; - } - return componentName; - } - - private XmlObject locationFromRedefinitionAndCode(RedefinitionHolder redefinition, - String name, short code) - { - XmlObject location; - switch (code) - { - case SIMPLE_TYPE: - location = (XmlObject) redefinition.stRedefinitions.get(name); - break; - case COMPLEX_TYPE: - location = (XmlObject) redefinition.ctRedefinitions.get(name); - break; - case MODEL_GROUP: - location = (XmlObject) redefinition.mgRedefinitions.get(name); - break; - case ATTRIBUTE_GROUP: - location = (XmlObject) redefinition.agRedefinitions.get(name); - break; - default: - location = null; - } - return location; - } - } - - private static String findFilename(XmlObject xobj) - { - return StscState.get().sourceNameForUri(xobj.documentProperties().getSourceName()); - } - - private static SchemaTypeImpl translateDocumentType ( TopLevelElement xsdType, String targetNamespace, boolean chameleon ) - { - SchemaTypeImpl sType = new SchemaTypeImpl( StscState.get().getContainer(targetNamespace) ); - - sType.setDocumentType(true); - sType.setParseContext( xsdType, targetNamespace, chameleon, null, null, false); - sType.setFilename( findFilename( xsdType ) ); - - return sType; - } - - private static SchemaTypeImpl translateAttributeType ( TopLevelAttribute xsdType, String targetNamespace, boolean chameleon ) - { - SchemaTypeImpl sType = new SchemaTypeImpl( StscState.get().getContainer(targetNamespace) ); - - sType.setAttributeType(true); - sType.setParseContext( xsdType, targetNamespace, chameleon, null, null, false); - sType.setFilename( findFilename( xsdType ) ); - - return sType; - } - - private static SchemaTypeImpl translateGlobalComplexType(TopLevelComplexType xsdType, String targetNamespace, boolean chameleon, boolean redefinition) - { - StscState state = StscState.get(); - - String localname = xsdType.getName(); - if (localname == null) - { - state.error(XmlErrorCodes.MISSING_NAME, new Object[] { "global type" }, xsdType); - // recovery: ignore unnamed types. - return null; - } - if (!XMLChar.isValidNCName(localname)) - { - state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { localname, "name" }, xsdType.xgetName()); - // recovery: let the name go through anyway. - } - - QName name = QNameHelper.forLNS(localname, targetNamespace); - - if (isReservedTypeName(name)) - { - state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[] { QNameHelper.pretty(name) }, xsdType); - return null; - } - // System.err.println("Recording type " + QNameHelper.pretty(name)); - - SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace)); - sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, redefinition); - sType.setFilename(findFilename(xsdType)); - sType.setName(QNameHelper.forLNS(localname, targetNamespace)); - sType.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdType)); - sType.setUserData(getUserData(xsdType)); - return sType; - } - - private static SchemaTypeImpl translateGlobalSimpleType(TopLevelSimpleType xsdType, String targetNamespace, boolean chameleon, boolean redefinition) - { - StscState state = StscState.get(); - - String localname = xsdType.getName(); - if (localname == null) - { - state.error(XmlErrorCodes.MISSING_NAME, new Object[] { "global type" }, xsdType); - // recovery: ignore unnamed types. - return null; - } - if (!XMLChar.isValidNCName(localname)) - { - state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { localname, "name" }, xsdType.xgetName()); - // recovery: let the name go through anyway. - } - - QName name = QNameHelper.forLNS(localname, targetNamespace); - - if (isReservedTypeName(name)) - { - state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[] { QNameHelper.pretty(name) }, xsdType); - return null; - } - // System.err.println("Recording type " + QNameHelper.pretty(name)); - - SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace)); - sType.setSimpleType(true); - sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, redefinition); - sType.setFilename(findFilename(xsdType)); - sType.setName(name); - sType.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdType)); - sType.setUserData(getUserData(xsdType)); - return sType; - } - - /*package*/ static SchemaTypeImpl translateAnonymousSimpleType(SimpleType typedef, - String targetNamespace, boolean chameleon, String elemFormDefault, - String attFormDefault, List anonymousTypes, SchemaType outerType) - { - StscState state = StscState.get(); - SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace)); - sType.setSimpleType(true); - sType.setParseContext(typedef, targetNamespace, chameleon, - elemFormDefault, attFormDefault, false); - sType.setOuterSchemaTypeRef(outerType.getRef()); - sType.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef)); - sType.setUserData(getUserData(typedef)); - anonymousTypes.add(sType); - return sType; - } - - static FormChoice findElementFormDefault(XmlObject obj) - { - XmlCursor cur = obj.newCursor(); - while (cur.getObject().schemaType() != Schema.type) - if (!cur.toParent()) - return null; - return ((Schema)cur.getObject()).xgetElementFormDefault(); - } - - public static boolean uriMatch(String s1, String s2) - { - if (s1 == null) - return s2 == null || s2.equals(""); - if (s2 == null) - return s1.equals(""); - return s1.equals(s2); - } - - public static void copyGlobalElementToLocalElement(SchemaGlobalElement referenced, SchemaLocalElementImpl target ) - { - - target.setNameAndTypeRef(referenced.getName(), referenced.getType().getRef()); - target.setNillable(referenced.isNillable()); - target.setDefault(referenced.getDefaultText(), referenced.isFixed(), ((SchemaGlobalElementImpl)referenced).getParseObject()); - target.setIdentityConstraints(((SchemaLocalElementImpl)referenced).getIdentityConstraintRefs()); - target.setBlock(referenced.blockExtension(), referenced.blockRestriction(), referenced.blockSubstitution()); - target.setAbstract(referenced.isAbstract()); - target.setTransitionRules(((SchemaParticle)referenced).acceptedStartNames(), - ((SchemaParticle)referenced).isSkippable()); - target.setAnnotation(referenced.getAnnotation()); - } - - public static void copyGlobalAttributeToLocalAttribute(SchemaGlobalAttributeImpl referenced, SchemaLocalAttributeImpl target ) - { - target.init( - referenced.getName(), referenced.getTypeRef(), referenced.getUse(), - referenced.getDefaultText(), - referenced.getParseObject(), referenced._defaultValue, - referenced.isFixed(), - referenced.getWSDLArrayType(), - referenced.getAnnotation(), null); - } - - /** - * Translates a local or global schema element. - */ - // check rule 3.3.3 - // http://www.w3c.org/TR/#section-Constraints-on-XML-Representations-of-Element-Declarations - public static SchemaLocalElementImpl translateElement( - Element xsdElt, String targetNamespace, boolean chameleon, - String elemFormDefault, String attFormDefault, - List anonymousTypes, SchemaType outerType) - { - StscState state = StscState.get(); - - SchemaTypeImpl sgHead = null; - - // translate sg head - if (xsdElt.isSetSubstitutionGroup()) - { - sgHead = state.findDocumentType(xsdElt.getSubstitutionGroup(), - ((SchemaTypeImpl)outerType).getChameleonNamespace(), targetNamespace); - - if (sgHead != null) - StscResolver.resolveType(sgHead); - } - - String name = xsdElt.getName(); - QName ref = xsdElt.getRef(); - - - if (ref != null && name != null) - { - // if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI())) - // state.warning("Element " + name + " specifies both a ref and a name", XmlErrorCodes.ELEMENT_EXTRA_REF, xsdElt.xgetRef()); - // else - state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_BOTH, new Object[] { name }, xsdElt.xgetRef()); - // ignore name - name = null; - } - if (ref == null && name == null) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_NEITHER, null, xsdElt); - // recovery: ignore this element - return null; - } - if (name != null && !XMLChar.isValidNCName(name)) - { - state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { name, "name" }, xsdElt.xgetName()); - // recovery: let the name go through anyway. - } - - if (ref != null) - { - if (xsdElt.getType() != null) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "type" }, xsdElt.xgetType()); - // recovery: let the name go through anyway. - } - - if (xsdElt.getSimpleType() != null) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "" }, xsdElt.getSimpleType()); - // recovery: let the name go through anyway. - } - - if (xsdElt.getComplexType() != null) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "" }, xsdElt.getComplexType()); - // recovery: let the name go through anyway. - } - - if (xsdElt.getForm() != null) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "form" }, xsdElt.xgetForm()); - // recovery: let the name go through anyway. - } - - if (xsdElt.sizeOfKeyArray() > 0) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "" }, xsdElt); - // recovery: ignore - } - - if (xsdElt.sizeOfKeyrefArray() > 0) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "" }, xsdElt); - // recovery: ignore - } - - if (xsdElt.sizeOfUniqueArray() > 0) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "" }, xsdElt); - // recovery: ignore - } - - if (xsdElt.isSetDefault()) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "default" }, xsdElt.xgetDefault()); - // recovery: ignore - } - - if (xsdElt.isSetFixed()) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "fixed" }, xsdElt.xgetFixed()); - // recovery: ignore - } - - if (xsdElt.isSetBlock()) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "block" }, xsdElt.xgetBlock()); - // recovery: ignore - } - - if (xsdElt.isSetNillable()) - { - state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "nillable" }, xsdElt.xgetNillable()); - // recovery: ignore - } - - assert(xsdElt instanceof LocalElement); - SchemaGlobalElement referenced = state.findGlobalElement(ref, chameleon ? targetNamespace : null, targetNamespace); - if (referenced == null) - { - state.notFoundError(ref, SchemaType.ELEMENT, xsdElt.xgetRef(), true); - // recovery: ignore this element - return null; - } - SchemaLocalElementImpl target = new SchemaLocalElementImpl(); - target.setParticleType(SchemaParticle.ELEMENT); - target.setUserData(getUserData(xsdElt)); - copyGlobalElementToLocalElement( referenced, target ); - return target; - } - - QName qname; - SchemaLocalElementImpl impl; - SchemaType sType = null; - - if (xsdElt instanceof LocalElement) - { - impl = new SchemaLocalElementImpl(); - boolean qualified = false; // default - FormChoice form = xsdElt.xgetForm(); - if (form != null) - qualified = form.getStringValue().equals(FORM_QUALIFIED); - else if (elemFormDefault != null) - qualified = elemFormDefault.equals(FORM_QUALIFIED); - else - { - form = findElementFormDefault(xsdElt); - qualified = form != null && form.getStringValue().equals(FORM_QUALIFIED); - } - - qname = qualified ? QNameHelper.forLNS(name, targetNamespace) : QNameHelper.forLN(name); - } - else - { - SchemaGlobalElementImpl gelt = new SchemaGlobalElementImpl(state.getContainer(targetNamespace)); - impl = gelt; - - // Set subst group head - if (sgHead != null) - { - SchemaGlobalElementImpl head = state.findGlobalElement(xsdElt.getSubstitutionGroup(), chameleon ? targetNamespace : null, targetNamespace); - if (head != null) - gelt.setSubstitutionGroup(head.getRef()); - } - - // Set subst group members - qname = QNameHelper.forLNS(name, targetNamespace); - SchemaTypeImpl docType = (SchemaTypeImpl)outerType; - - QName[] sgMembers = docType.getSubstitutionGroupMembers(); - QNameSetBuilder transitionRules = new QNameSetBuilder(); - transitionRules.add(qname); - - for (int i = 0 ; i < sgMembers.length ; i++) - { - gelt.addSubstitutionGroupMember(sgMembers[i]); - transitionRules.add(sgMembers[i]); - } - - impl.setTransitionRules(QNameSet.forSpecification(transitionRules), false); - impl.setTransitionNotes(QNameSet.EMPTY, true); - - boolean finalExt = false; - boolean finalRest = false; - Object ds = xsdElt.getFinal(); - if (ds != null) - { - if (ds instanceof String && ds.equals("#all")) - { - // #ALL value - finalExt = finalRest = true; - } - else if (ds instanceof List) - { - if (((List)ds).contains("extension")) - finalExt = true; - if (((List)ds).contains("restriction")) - finalRest = true; - } - } - - gelt.setFinal(finalExt, finalRest); - gelt.setAbstract(xsdElt.getAbstract()); - gelt.setFilename(findFilename(xsdElt)); - gelt.setParseContext(xsdElt, targetNamespace, chameleon); - } - - SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdElt); - impl.setAnnotation(ann); - impl.setUserData(getUserData(xsdElt)); - if (xsdElt.getType() != null) - { - sType = state.findGlobalType(xsdElt.getType(), chameleon ? targetNamespace : null, targetNamespace ); - if (sType == null) - state.notFoundError(xsdElt.getType(), SchemaType.TYPE, xsdElt.xgetType(), true); - } - - boolean simpleTypedef = false; - Annotated typedef = xsdElt.getComplexType(); - if (typedef == null) - { - typedef = xsdElt.getSimpleType(); - simpleTypedef = true; - } - - if ((sType != null) && typedef != null) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$TYPE_ATTR_OR_NESTED_TYPE, null, typedef); - typedef = null; - } - - if (typedef != null) - { - Object[] grps = state.getCurrentProcessing(); - QName[] context = new QName[grps.length]; - for (int i = 0; i < context.length; i++) - if (grps[i] instanceof SchemaModelGroupImpl) - context[i] = ((SchemaModelGroupImpl ) grps[i]).getName(); - SchemaType repeat = checkRecursiveGroupReference(context, qname, (SchemaTypeImpl)outerType); - if (repeat != null) - sType = repeat; - else - { - SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace)); - sType = sTypeImpl; - sTypeImpl.setContainerField(impl); - sTypeImpl.setOuterSchemaTypeRef(outerType == null ? null : outerType.getRef()); - sTypeImpl.setGroupReferenceContext(context); - // leave the anonymous type unresolved: it will be resolved later. - anonymousTypes.add(sType); - sTypeImpl.setSimpleType(simpleTypedef); - sTypeImpl.setParseContext(typedef, targetNamespace, chameleon, - elemFormDefault, attFormDefault, false); - sTypeImpl.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef)); - sTypeImpl.setUserData(getUserData(typedef)); - } - } - - if (sType == null) - { - // type may inherit from substitution group head - if (sgHead != null) - { - SchemaGlobalElement head = state.findGlobalElement(xsdElt.getSubstitutionGroup(), chameleon ? targetNamespace : null, targetNamespace); - - // Bug - Do I need to copy the type if it's anonymous? - // If element does not exist, error has already been reported - if (head != null) - sType = head.getType(); - } - - } - - - - if (sType == null) - sType = BuiltinSchemaTypeSystem.ST_ANY_TYPE; - - SOAPArrayType wat = null; - XmlCursor c = xsdElt.newCursor(); - String arrayType = c.getAttributeText(WSDL_ARRAYTYPE_NAME); - c.dispose(); - if (arrayType != null) - { - try - { - wat = new SOAPArrayType(arrayType, new NamespaceContext(xsdElt)); - } - catch (XmlValueOutOfRangeException e) - { - state.error(XmlErrorCodes.SOAPARRAY, new Object[] {arrayType}, xsdElt); - } - } - impl.setWsdlArrayType(wat); - - boolean isFixed = xsdElt.isSetFixed(); - if (xsdElt.isSetDefault() && isFixed) - { - state.error(XmlErrorCodes.SCHEMA_ELEM$DEFAULT_OR_FIXED, null, xsdElt.xgetFixed()); - // recovery: ignore fixed - isFixed = false; - } - impl.setParticleType(SchemaParticle.ELEMENT); - impl.setNameAndTypeRef(qname, sType.getRef()); - impl.setNillable(xsdElt.getNillable()); - impl.setDefault(isFixed ? xsdElt.getFixed() : xsdElt.getDefault(), isFixed, xsdElt); - - Object block = xsdElt.getBlock(); - boolean blockExt = false; - boolean blockRest = false; - boolean blockSubst = false; - - if (block != null) - { - if (block instanceof String && block.equals("#all")) - { - // #ALL value - blockExt = blockRest = blockSubst = true; - } - else if (block instanceof List) - { - if (((List)block).contains("extension")) - blockExt = true; - if (((List)block).contains("restriction")) - blockRest = true; - if (((List)block).contains("substitution")) - blockSubst = true; - } - } - - impl.setBlock(blockExt, blockRest, blockSubst); - - boolean constraintFailed = false; - - // Translate Identity constraints - - int length = xsdElt.sizeOfKeyArray() + xsdElt.sizeOfKeyrefArray() + xsdElt.sizeOfUniqueArray(); - SchemaIdentityConstraintImpl[] constraints = new SchemaIdentityConstraintImpl[length]; - int cur = 0; - - // Handle key constraints - Keybase[] keys = xsdElt.getKeyArray(); - for (int i = 0 ; i < keys.length ; i++, cur++) { - constraints[cur] = translateIdentityConstraint(keys[i], targetNamespace, chameleon); - if (constraints[cur] != null) - constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_KEY); - else - constraintFailed = true; - } - - // Handle unique constraints - Keybase[] uc = xsdElt.getUniqueArray(); - for (int i = 0 ; i < uc.length ; i++, cur++) { - constraints[cur] = translateIdentityConstraint(uc[i], targetNamespace, chameleon); - if (constraints[cur] != null) - constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_UNIQUE); - else - constraintFailed = true; - } - - // Handle keyref constraints - KeyrefDocument.Keyref[] krs = xsdElt.getKeyrefArray(); - for (int i = 0 ; i < krs.length ; i++, cur++) { - constraints[cur] = translateIdentityConstraint(krs[i], targetNamespace, chameleon); - if (constraints[cur] != null) - constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_KEYREF); - else - constraintFailed = true; - } - - if (!constraintFailed) - { - SchemaIdentityConstraint.Ref[] refs = new SchemaIdentityConstraint.Ref[length]; - for (int i = 0 ; i < refs.length ; i++) - refs[i] = constraints[i].getRef(); - - impl.setIdentityConstraints(refs); - } - - return impl; - } - - /** - * We need to do this because of the following kind of Schemas: - * - * - * - * - * - * - * - * - * - * (see JIRA bug XMLBEANS-35) - * Even though this should not be allowed because it produces an infinite - * number of anonymous types and local elements nested within each other, - * the de facto consensus among Schema processors is that this should be - * valid, therefore we have to detect this situation and "patch up" the - * Schema object model so that instead of creating a new anonymous type, - * we refer to the one that was already created earlier. - * In order to accomplish that, we store inside every anonymous type the - * list of groups that were dereferenced at the moment the type was created - * and if the same pattern is about to repeat, it means that we are in a - * case similar to the above. - */ - private static SchemaType checkRecursiveGroupReference(QName[] context, QName containingElement, SchemaTypeImpl outerType) - { - if (context.length < 1) - return null; - SchemaTypeImpl type = outerType; - - while (type != null) - { - if (type.getName() != null || type.isDocumentType()) - return null; // not anonymous - if (containingElement.equals(type.getContainerField().getName())) - { - QName[] outerContext = type.getGroupReferenceContext(); - if (outerContext != null && outerContext.length == context.length) - { - // Smells like trouble - boolean equal = true; - for (int i = 0; i < context.length; i++) - if (!(context[i] == null && outerContext[i] == null || - context[i] != null && context[i].equals(outerContext[i]))) - { - equal = false; - break; - } - if (equal) - return type; - } - } - type = (SchemaTypeImpl) type.getOuterType(); - } - return null; - } - - private static String removeWhitespace(String xpath) - { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < xpath.length(); i++) - { - char ch = xpath.charAt(i); - if (XMLChar.isSpace(ch)) - continue; - sb.append(ch); - } - return sb.toString(); - } - - public static final org.apache.xmlbeans.impl.regex.RegularExpression XPATH_REGEXP = new org.apache.xmlbeans.impl.regex.RegularExpression("(\\.//)?((((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*|\\*)))))*", "X"); - - private static boolean checkXPathSyntax(String xpath) - { - if (xpath == null) - return false; - - // strip whitespace from xpath - xpath = removeWhitespace(xpath); - - // apply regexp - synchronized (XPATH_REGEXP) - { - return (XPATH_REGEXP.matches(xpath)); - } - } - - private static SchemaIdentityConstraintImpl translateIdentityConstraint(Keybase parseIC, - String targetNamespace, boolean chameleon) - { - StscState state = StscState.get(); - - // first do some checking - String selector = parseIC.getSelector() == null ? null : parseIC.getSelector().getXpath(); - if (!checkXPathSyntax(selector)) - { - state.error(XmlErrorCodes.SELECTOR_XPATH, new Object[] { selector }, parseIC.getSelector().xgetXpath()); - return null; - } - - FieldDocument.Field[] fieldElts = parseIC.getFieldArray(); - for (int j = 0; j < fieldElts.length; j++) - { - if (!checkXPathSyntax(fieldElts[j].getXpath())) - { - state.error(XmlErrorCodes.FIELDS_XPATH, new Object[] { fieldElts[j].getXpath() }, fieldElts[j].xgetXpath()); - return null; - } - } - - // then translate. - SchemaIdentityConstraintImpl ic = new SchemaIdentityConstraintImpl(state.getContainer(targetNamespace)); - ic.setName(QNameHelper.forLNS(parseIC.getName(), targetNamespace)); - ic.setSelector(parseIC.getSelector().getXpath()); - ic.setParseContext(parseIC, targetNamespace, chameleon); - SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), parseIC); - ic.setAnnotation(ann); - ic.setUserData(getUserData(parseIC)); - - // Set the ns map - XmlCursor c = parseIC.newCursor(); - Map nsMap = new HashMap(); - - c.getAllNamespaces(nsMap); - nsMap.remove(""); // Remove the default mapping. This cannot be used by the xpath expressions. - ic.setNSMap(nsMap); - c.dispose(); - - String[] fields = new String[fieldElts.length]; - for (int j = 0 ; j < fields.length ; j++) - fields[j] = fieldElts[j].getXpath(); - ic.setFields(fields); - - try { - ic.buildPaths(); - } - catch (XPath.XPathCompileException e) { - state.error(XmlErrorCodes.INVALID_XPATH, new Object[] { e.getMessage() }, parseIC); - return null; - } - - state.addIdConstraint(ic); - ic.setFilename(findFilename(parseIC)); - - return state.findIdConstraint(ic.getName(), targetNamespace, null); - - } - - public static SchemaModelGroupImpl translateModelGroup(NamedGroup namedGroup, String targetNamespace, boolean chameleon, boolean redefinition) - { - String name = namedGroup.getName(); - if (name == null) - { - StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[] { "model group" }, namedGroup); - return null; - } - SchemaContainer c = StscState.get().getContainer(targetNamespace); - SchemaModelGroupImpl result = new SchemaModelGroupImpl(c); - SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(c, namedGroup); - FormChoice elemFormDefault = findElementFormDefault(namedGroup); - FormChoice attFormDefault = findAttributeFormDefault(namedGroup); - result.init(QNameHelper.forLNS(name, targetNamespace), targetNamespace, chameleon, - elemFormDefault == null ? null : elemFormDefault.getStringValue(), - attFormDefault == null ? null : attFormDefault.getStringValue(), - redefinition, namedGroup, ann, getUserData(namedGroup)); - result.setFilename(findFilename(namedGroup)); - return result; - } - - public static SchemaAttributeGroupImpl translateAttributeGroup(AttributeGroup attrGroup, String targetNamespace, boolean chameleon, boolean redefinition) - { - String name = attrGroup.getName(); - if (name == null) - { - StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[] { "attribute group" }, attrGroup); - return null; - } - SchemaContainer c = StscState.get().getContainer(targetNamespace); - SchemaAttributeGroupImpl result = new SchemaAttributeGroupImpl(c); - SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(c, attrGroup); - FormChoice formDefault = findAttributeFormDefault(attrGroup); - result.init(QNameHelper.forLNS(name, targetNamespace), targetNamespace, chameleon, - formDefault == null ? null : formDefault.getStringValue(), - redefinition, attrGroup, ann, getUserData(attrGroup)); - result.setFilename(findFilename(attrGroup)); - return result; - } - - static FormChoice findAttributeFormDefault(XmlObject obj) - { - XmlCursor cur = obj.newCursor(); - while (cur.getObject().schemaType() != Schema.type) - if (!cur.toParent()) - return null; - return ((Schema)cur.getObject()).xgetAttributeFormDefault(); - } - - static SchemaLocalAttributeImpl translateAttribute( - Attribute xsdAttr, String targetNamespace, String formDefault, boolean chameleon, - List anonymousTypes, SchemaType outerType, SchemaAttributeModel baseModel, - boolean local) - { - StscState state = StscState.get(); - - String name = xsdAttr.getName(); - QName ref = xsdAttr.getRef(); - - if (ref != null && name != null) - { - if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI())) - state.warning(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[] { name }, xsdAttr.xgetRef()); - else - state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[] { name }, xsdAttr.xgetRef()); - // ignore name - name = null; - } - if (ref == null && name == null) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_NEITHER, null, xsdAttr); - // recovery: ignore this element - return null; - } - if (name != null && !XMLChar.isValidNCName(name)) - { - state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { name, "name" }, xsdAttr.xgetName()); - // recovery: let the name go through anyway. - } - - boolean isFixed = false; - String deftext = null; - String fmrfixedtext = null; - QName qname; - SchemaLocalAttributeImpl sAttr; - SchemaType sType = null; - int use = SchemaLocalAttribute.OPTIONAL; - - if (local) - sAttr = new SchemaLocalAttributeImpl(); - else - { - sAttr = new SchemaGlobalAttributeImpl(state.get().getContainer(targetNamespace)); - ((SchemaGlobalAttributeImpl)sAttr).setParseContext(xsdAttr, targetNamespace, chameleon); - } - - if (ref != null) - { - if (xsdAttr.getType() != null) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[] { "type" }, xsdAttr.xgetType()); - // recovery: ignore type, simpleType - } - - if (xsdAttr.getSimpleType() != null) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[] { "" }, xsdAttr.getSimpleType()); - // recovery: ignore type, simpleType - } - - if (xsdAttr.getForm() != null) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[] { "form" }, xsdAttr.xgetForm()); - // recovery: ignore form - } - - SchemaGlobalAttribute referenced = state.findGlobalAttribute(ref, chameleon ? targetNamespace : null, targetNamespace); - if (referenced == null) - { - state.notFoundError(ref, SchemaType.ATTRIBUTE, xsdAttr.xgetRef(), true); - // recovery: ignore this element - return null; - } - - qname = ref; - use = referenced.getUse(); - sType = referenced.getType(); - deftext = referenced.getDefaultText(); - if (deftext != null) - { - isFixed = referenced.isFixed(); - if (isFixed) - fmrfixedtext = deftext; - } - } - else - { - if (local) - { - boolean qualified = false; // default - FormChoice form = xsdAttr.xgetForm(); - if (form != null) - qualified = form.getStringValue().equals(FORM_QUALIFIED); - else if (formDefault != null) - qualified = formDefault.equals(FORM_QUALIFIED); - else - { - form = findAttributeFormDefault(xsdAttr); - qualified = form != null && form.getStringValue().equals(FORM_QUALIFIED); - } - - qname = qualified ? QNameHelper.forLNS(name, targetNamespace) : QNameHelper.forLN(name); - } - else - { - qname = QNameHelper.forLNS(name, targetNamespace); - } - - if (xsdAttr.getType() != null) - { - sType = state.findGlobalType(xsdAttr.getType(), chameleon ? targetNamespace : null, targetNamespace ); - if (sType == null) - state.notFoundError(xsdAttr.getType(), SchemaType.TYPE, xsdAttr.xgetType(), true); - } - - if (qname.getNamespaceURI().equals("http://www.w3.org/2001/XMLSchema-instance")) - { - state.error(XmlErrorCodes.NO_XSI, new Object[] { "http://www.w3.org/2001/XMLSchema-instance" }, xsdAttr.xgetName()); - } - - if (qname.getNamespaceURI().length() == 0 && qname.getLocalPart().equals("xmlns")) - { - state.error(XmlErrorCodes.NO_XMLNS, null, xsdAttr.xgetName()); - } - - LocalSimpleType typedef = xsdAttr.getSimpleType(); - - if ((sType != null) && typedef != null) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$TYPE_ATTR_OR_NESTED_TYPE, null, typedef); - typedef = null; - } - - if (typedef != null) - { - SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace)); - sType = sTypeImpl; - sTypeImpl.setContainerField(sAttr); - sTypeImpl.setOuterSchemaTypeRef(outerType == null ? null : outerType.getRef()); - // leave the anonymous type unresolved: it will be resolved later. - anonymousTypes.add(sType); - sTypeImpl.setSimpleType(true); - sTypeImpl.setParseContext(typedef, targetNamespace, chameleon, null, null, false); - sTypeImpl.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef)); - sTypeImpl.setUserData(getUserData(typedef)); - } - - if (sType == null && baseModel != null && baseModel.getAttribute(qname) != null) - sType = baseModel.getAttribute(qname).getType(); - } - - if (sType == null) - sType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - - if (!sType.isSimpleType()) - { - // KHK: which rule? could use #a-simple_type_definition - state.error("Attributes must have a simple type (not complex).", XmlErrorCodes.INVALID_SCHEMA, xsdAttr); - // recovery: switch to the any-type - sType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; - } - - if (xsdAttr.isSetUse()) - { - use = translateUseCode(xsdAttr.xgetUse()); - - // ignore referenced default if no longer optional - if (use != SchemaLocalAttribute.OPTIONAL && !isFixed) - deftext = null; - } - - if (xsdAttr.isSetDefault() || xsdAttr.isSetFixed()) - { - if (isFixed && !xsdAttr.isSetFixed()) - state.error("A use of a fixed attribute definition must also be fixed", XmlErrorCodes.REDUNDANT_DEFAULT_FIXED, xsdAttr.xgetFixed()); - - isFixed = xsdAttr.isSetFixed(); - - if (xsdAttr.isSetDefault() && isFixed) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$DEFAULT_OR_FIXED, null, xsdAttr.xgetFixed()); - // recovery: ignore fixed - isFixed = false; - } - deftext = isFixed ? xsdAttr.getFixed() : xsdAttr.getDefault(); - // BUGBUG(radup) this is not good, since they should be compared by value - // in StscChecker; but there we don't have yet access to the referred attr - if (fmrfixedtext != null && !fmrfixedtext.equals(deftext)) - { - state.error(XmlErrorCodes.SCHEMA_ATTR$FIXED_NOT_MATCH, null, xsdAttr.xgetFixed()); - // recovery: reset fixed to the original value - deftext = fmrfixedtext; - } - } - - if (!local) - { - ((SchemaGlobalAttributeImpl)sAttr).setFilename(findFilename(xsdAttr)); - } - - SOAPArrayType wat = null; - XmlCursor c = xsdAttr.newCursor(); - String arrayType = c.getAttributeText(WSDL_ARRAYTYPE_NAME); - c.dispose(); - if (arrayType != null) - { - try - { - wat = new SOAPArrayType(arrayType, new NamespaceContext(xsdAttr)); - } - catch (XmlValueOutOfRangeException e) - { - state.error(XmlErrorCodes.SOAPARRAY, new Object[] {arrayType}, xsdAttr); - } - } - - SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdAttr); - sAttr.init( - qname, - sType.getRef(), - use, - deftext, xsdAttr, null, isFixed, - wat, ann, getUserData(xsdAttr)); - - return sAttr; - } - - static int translateUseCode(Attribute.Use attruse) - { - if (attruse == null) - return SchemaLocalAttribute.OPTIONAL; - - String val = attruse.getStringValue(); - if (val.equals("optional")) - return SchemaLocalAttribute.OPTIONAL; - if (val.equals("required")) - return SchemaLocalAttribute.REQUIRED; - if (val.equals("prohibited")) - return SchemaLocalAttribute.PROHIBITED; - return SchemaLocalAttribute.OPTIONAL; - } - - static BigInteger buildBigInt(XmlAnySimpleType value) - { - if (value == null) - return null; - String text = value.getStringValue(); - BigInteger bigInt; - try - { - bigInt = new BigInteger(text); - } - catch (NumberFormatException e) - { - StscState.get().error(XmlErrorCodes.INVALID_VALUE_DETAIL, new Object[] { text, "nonNegativeInteger", e.getMessage() }, value); - return null; - } - - if (bigInt.signum() < 0) - { - StscState.get().error(XmlErrorCodes.INVALID_VALUE, new Object[] { text, "nonNegativeInteger" }, value); - return null; - } - - return bigInt; - } - - - static XmlNonNegativeInteger buildNnInteger(XmlAnySimpleType value) - { - BigInteger bigInt = buildBigInt(value); - try - { - XmlNonNegativeIntegerImpl i = new XmlNonNegativeIntegerImpl(); - i.set(bigInt); - i.setImmutable(); - return i; - } - catch (XmlValueOutOfRangeException e) - { - StscState.get().error("Internal error processing number", XmlErrorCodes.MALFORMED_NUMBER, value); - return null; - } - } - - static XmlPositiveInteger buildPosInteger(XmlAnySimpleType value) - { - BigInteger bigInt = buildBigInt(value); - try - { - XmlPositiveIntegerImpl i = new XmlPositiveIntegerImpl(); - i.set(bigInt); - i.setImmutable(); - return i; - } - catch (XmlValueOutOfRangeException e) - { - StscState.get().error("Internal error processing number", XmlErrorCodes.MALFORMED_NUMBER, value); - return null; - } - } - - - private static Object getUserData(XmlObject pos) - { - XmlCursor.XmlBookmark b = pos.newCursor().getBookmark(SchemaBookmark.class); - if (b != null && b instanceof SchemaBookmark) - return ((SchemaBookmark) b).getValue(); - else - return null; - } - - private static boolean isEmptySchema(Schema schema) - { - XmlCursor cursor = schema.newCursor(); - boolean result = !cursor.toFirstChild(); - cursor.dispose(); - return result; - } - - private static boolean isReservedTypeName(QName name) - { - return (BuiltinSchemaTypeSystem.get().findType(name) != null); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/util/Base64.java b/src/typeimpl/org/apache/xmlbeans/impl/util/Base64.java deleted file mode 100644 index a12b02a..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/util/Base64.java +++ /dev/null @@ -1,361 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.util; - -import java.io.UnsupportedEncodingException; -/** - * This class provides encode/decode for RFC 2045 Base64 as - * defined by RFC 2045, N. Freed and N. Borenstein. - * RFC 2045: Multipurpose Internet Mail Extensions (MIME) - * Part One: Format of Internet Message Bodies. Reference - * 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt - * This class is used by XML Schema binary format validation - * - * This implementation does not encode/decode streaming - * data. You need the data that you will encode/decode - * already on a byte arrray. - * - * @author Jeffrey Rodriguez - * @author Sandy Gao - * @version $Id$ - */ -public final class Base64 { - - static private final int BASELENGTH = 255; - static private final int LOOKUPLENGTH = 64; - static private final int TWENTYFOURBITGROUP = 24; - static private final int EIGHTBIT = 8; - static private final int SIXTEENBIT = 16; - //static private final int SIXBIT = 6; - static private final int FOURBYTE = 4; - static private final int SIGN = -128; - static private final byte PAD = ( byte ) '='; - static private final boolean fDebug = false; - static private byte [] base64Alphabet = new byte[BASELENGTH]; - static private byte [] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; - - static { - - for (int i = 0; i= 'A'; i--) { - base64Alphabet[i] = (byte) (i-'A'); - } - for (int i = 'z'; i>= 'a'; i--) { - base64Alphabet[i] = (byte) ( i-'a' + 26); - } - - for (int i = '9'; i >= '0'; i--) { - base64Alphabet[i] = (byte) (i-'0' + 52); - } - - base64Alphabet['+'] = 62; - base64Alphabet['/'] = 63; - - for (int i = 0; i<=25; i++) - lookUpBase64Alphabet[i] = (byte) ('A'+i ); - - for (int i = 26, j = 0; i<=51; i++, j++) - lookUpBase64Alphabet[i] = (byte) ('a'+ j ); - - for (int i = 52, j = 0; i<=61; i++, j++) - lookUpBase64Alphabet[i] = (byte) ('0' + j ); - lookUpBase64Alphabet[62] = (byte) '+'; - lookUpBase64Alphabet[63] = (byte) '/'; - - } - - protected static boolean isWhiteSpace(byte octect) { - return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); - } - - protected static boolean isPad(byte octect) { - return (octect == PAD); - } - - protected static boolean isData(byte octect) { - return (base64Alphabet[octect] != -1); - } - - protected static boolean isBase64(byte octect) { - return (isWhiteSpace(octect) || isPad(octect) || isData(octect)); - } - - /** - * Encodes hex octects into Base64 - * - * @param binaryData Array containing binaryData - * @return Encoded Base64 array - */ - public static byte[] encode(byte[] binaryData) { - - if (binaryData == null) - return null; - - int lengthDataBits = binaryData.length*EIGHTBIT; - int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; - int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; - byte encodedData[] = null; - - if (fewerThan24bits != 0) //data not divisible by 24 bit - encodedData = new byte[ (numberTriplets + 1 )*4 ]; - else // 16 or 8 bit - encodedData = new byte[ numberTriplets*4 ]; - - byte k=0, l=0, b1=0,b2=0,b3=0; - - int encodedIndex = 0; - int dataIndex = 0; - int i = 0; - if (fDebug) { - System.out.println("number of triplets = " + numberTriplets ); - } - for (i = 0; i>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - } - - if (!isData( (d1 = base64Data[dataIndex++]) ) || - !isData( (d2 = base64Data[dataIndex++]) )) { - return null;//if found "no data" just return null - } - - b1 = base64Alphabet[d1]; - b2 = base64Alphabet[d2]; - - d3 = base64Data[dataIndex++]; - d4 = base64Data[dataIndex++]; - if (!isData( (d3 ) ) || - !isData( (d4 ) )) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - return null; - byte[] tmp = new byte[ i*3 + 1 ]; - System.arraycopy( decodedData, 0, tmp, 0, i*3 ); - tmp[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; - return tmp; - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - b3 = base64Alphabet[ d3 ]; - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - return null; - byte[] tmp = new byte[ i*3 + 2 ]; - System.arraycopy( decodedData, 0, tmp, 0, i*3 ); - tmp[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); - tmp[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - return tmp; - } else { - return null;//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { //No PAD e.g 3cQl - b3 = base64Alphabet[ d3 ]; - b4 = base64Alphabet[ d4 ]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - - } - - return decodedData; - } - -// /** -// * Decodes Base64 data into octects -// * -// * @param base64Data String containing Base64 data -// * @return string containing decoded data. -// */ -// public static String decode(String base64Data) { -// if (base64Data == null) -// return null; -// -// byte[] decoded = null; -// try { -// decoded = decode(base64Data.getBytes("utf-8")); -// } -// catch(UnsupportedEncodingException e) { -// } -// finally { -// return decoded == null ? null : new String(decoded); -// } -// } -// -// /** -// * Encodes octects (using utf-8) into Base64 data -// * -// * @param binaryData String containing Hex data -// * @return string containing decoded data. -// */ -// public static String encode(String binaryData) { -// if (binaryData == null) -// return null; -// -// byte[] encoded = null; -// try { -// encoded = encode(binaryData.getBytes("utf-8")); -// } -// catch(UnsupportedEncodingException e) {} -// finally { -// return encoded == null ? null : new String(encoded); -// } -// } - - /** - * remove WhiteSpace from MIME containing encoded Base64 data. - * - * @param data the byte array of base64 data (with WS) - * @return the byte array of base64 data (without WS) - */ - protected static byte[] removeWhiteSpace(byte[] data) { - if (data == null) - return null; - - // count characters that's not whitespace - int newSize = 0; - int len = data.length; - for (int i = 0; i < len; i++) { - if (!isWhiteSpace(data[i])) - newSize++; - } - - // if no whitespace, just return the input array - if (newSize == len) - return data; - - // create the array to return - byte[] newArray = new byte[newSize]; - - int j = 0; - for (int i = 0; i < len; i++) { - if (!isWhiteSpace(data[i])) - newArray[j++] = data[i]; - } - return newArray; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/util/FilerImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/util/FilerImpl.java deleted file mode 100755 index 2a07783..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/util/FilerImpl.java +++ /dev/null @@ -1,231 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.xmlbeans.impl.util; - -import org.apache.xmlbeans.Filer; - -import java.io.IOException; -import java.io.File; -import java.io.Writer; -import java.io.FileReader; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; -import java.util.Set; -import java.util.HashSet; -import java.util.List; -import java.util.ArrayList; - -import repackage.Repackager; - -/** - * This implementation of Filer writes to disk. - */ -public class FilerImpl implements Filer -{ - private File classdir; - private File srcdir; - private Repackager repackager; - private boolean verbose; - private List sourceFiles; - private boolean incrSrcGen; - private Set seenTypes; - private static final Charset CHARSET; - - static - { - Charset temp = null; - try - { - temp = Charset.forName(System.getProperty("file.encoding")); - } - catch (Exception e) {} - CHARSET = temp; - } - - public FilerImpl(File classdir, File srcdir, Repackager repackager, boolean verbose, boolean incrSrcGen) - { - this.classdir = classdir; - this.srcdir = srcdir; - this.repackager = repackager; - this.verbose = verbose; - this.sourceFiles = (sourceFiles != null ? sourceFiles : new ArrayList()); - this.incrSrcGen = incrSrcGen; - if (this.incrSrcGen) - seenTypes = new HashSet(); - } - - /** - * Creates a new schema binary file (.xsb) and returns a stream for writing to it. - * - * @param typename fully qualified type name - * @return a stream to write the type to - * @throws java.io.IOException - */ - public OutputStream createBinaryFile(String typename) throws IOException - { - if (verbose) - System.err.println("created binary: " + typename); - // KHK: for now the typename will already be a relative filename for the binary - //String filename = typename.replace('.', File.separatorChar) + ".xsb"; - File source = new File(classdir, typename); - source.getParentFile().mkdirs(); - - return new FileOutputStream( source ); - } - - /** - * Creates a new binding source file (.java) and returns a writer for it. - * - * @param typename fully qualified type name - * @return a stream to write the type to - * @throws java.io.IOException - */ - public Writer createSourceFile(String typename) throws IOException - { - if (incrSrcGen) - seenTypes.add(typename); - - if (typename.indexOf('$') > 0) - { - typename = - typename.substring( 0, typename.lastIndexOf( '.' ) ) + "." + - typename.substring( typename.indexOf( '$' ) + 1 ); - } - - String filename = typename.replace('.', File.separatorChar) + ".java"; - - File sourcefile = new File(srcdir, filename); - sourcefile.getParentFile().mkdirs(); - if (verbose) - System.err.println("created source: " + sourcefile.getAbsolutePath()); - - sourceFiles.add(sourcefile); - - if (incrSrcGen && sourcefile.exists()) - { - // Generate the file in a buffer and then compare it to the - // file already on disk - return new IncrFileWriter(sourcefile, repackager); - } - else - { - return repackager == null ? - (Writer) writerForFile( sourcefile ) : - (Writer) new RepackagingWriter( sourcefile, repackager ); - } - } - - public List getSourceFiles() - { - return new ArrayList(sourceFiles); - } - - public Repackager getRepackager() - { - return repackager; - } - - private static final Writer writerForFile(File f) throws IOException - { - if (CHARSET == null) - return new FileWriter(f); - - FileOutputStream fileStream = new FileOutputStream(f); - CharsetEncoder ce = CHARSET.newEncoder(); - ce.onUnmappableCharacter(CodingErrorAction.REPORT); - return new OutputStreamWriter(fileStream, ce); - } - - static class IncrFileWriter extends StringWriter - { - private File _file; - private Repackager _repackager; - - public IncrFileWriter(File file, Repackager repackager) - { - _file = file; - _repackager = repackager; - } - - public void close() throws IOException - { - super.close(); - - // This is where all the real work happens - StringBuffer sb = _repackager != null ? - _repackager.repackage(getBuffer()) : - getBuffer(); - String str = sb.toString(); - List diffs = new ArrayList(); - StringReader sReader = new StringReader(str); - FileReader fReader = new FileReader(_file); - - try - { - Diff.readersAsText(sReader, "", - fReader, _file.getName(), diffs); - } - finally - { - sReader.close(); - fReader.close(); - } - - if (diffs.size() > 0) - { - // Diffs encountered, replace the file on disk with text from - // the buffer - Writer fw = writerForFile(_file); - try - { fw.write(str); } - finally - { fw.close(); } - } - else - ; // If no diffs, don't do anything - } - } - - static class RepackagingWriter extends StringWriter - { - public RepackagingWriter ( File file, Repackager repackager ) - { - _file = file; - _repackager = repackager; - } - - public void close ( ) throws IOException - { - super.close(); - - Writer fw = writerForFile( _file ); - try - { fw.write( _repackager.repackage( getBuffer() ).toString() ); } - finally - { fw.close(); } - } - - private File _file; - private Repackager _repackager; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/util/HexBin.java b/src/typeimpl/org/apache/xmlbeans/impl/util/HexBin.java deleted file mode 100644 index bd72bd8..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/util/HexBin.java +++ /dev/null @@ -1,155 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.util; - -import java.io.UnsupportedEncodingException; -/** - * format validation - * - * This class encodes/decodes hexadecimal data - * @author Jeffrey Rodriguez - * @version $Id$ - */ -public final class HexBin { - static private final int BASELENGTH = 255; - static private final int LOOKUPLENGTH = 16; - static private byte [] hexNumberTable = new byte[BASELENGTH]; - static private byte [] lookUpHexAlphabet = new byte[LOOKUPLENGTH]; - - - static { - for (int i = 0; i= '0'; i--) { - hexNumberTable[i] = (byte) (i-'0'); - } - for ( int i = 'F'; i>= 'A'; i--) { - hexNumberTable[i] = (byte) ( i-'A' + 10 ); - } - for ( int i = 'f'; i>= 'a'; i--) { - hexNumberTable[i] = (byte) ( i-'a' + 10 ); - } - - for(int i = 0; i<10; i++ ) - lookUpHexAlphabet[i] = (byte) ('0'+i ); - for(int i = 10; i<=15; i++ ) - lookUpHexAlphabet[i] = (byte) ('A'+i -10); - } - - /** - * byte to be tested if it is Base64 alphabet - * - * @param octect - * @return - */ - static boolean isHex(byte octect) { - return (hexNumberTable[octect] != -1); - } - - /** - * Converts bytes to a hex string - */ - static public String bytesToString(byte[] binaryData) - { - if (binaryData == null) - return null; - return new String(encode(binaryData)); - } - - /** - * Converts a hex string to a byte array. - */ - static public byte[] stringToBytes(String hexEncoded) - { - return decode(hexEncoded.getBytes()); - } - - /** - * array of byte to encode - * - * @param binaryData - * @return return encode binary array - */ - static public byte[] encode(byte[] binaryData) { - if (binaryData == null) - return null; - int lengthData = binaryData.length; - int lengthEncode = lengthData * 2; - byte[] encodedData = new byte[lengthEncode]; - for( int i = 0; i> 4) & 0xf]; - encodedData[i*2+1] = lookUpHexAlphabet[ binaryData[i] & 0xf]; - } - return encodedData; - } - - static public byte[] decode(byte[] binaryData) { - if (binaryData == null) - return null; - int lengthData = binaryData.length; - if (lengthData % 2 != 0) - return null; - - int lengthDecode = lengthData / 2; - byte[] decodedData = new byte[lengthDecode]; - for( int i = 0; i 0) { - char ch = cs.charAt(cs.length() - 1); - if (ch == 'f' || ch == 'F') { - if (cs.charAt(cs.length() - 2) != 'N') - throw new NumberFormatException("Invalid char '" + ch + "' in float."); - } - } - return Float.parseFloat(v); - } - catch (NumberFormatException e) { - if (v.equals(POS_INF_LEX)) return Float.POSITIVE_INFINITY; - if (v.equals(NEG_INF_LEX)) return Float.NEGATIVE_INFINITY; - if (v.equals(NAN_LEX)) return Float.NaN; - - throw e; - } - } - - public static float lexFloat(CharSequence cs, Collection errors) - { - try { - return lexFloat(cs); - } - catch (NumberFormatException e) { - String msg = "invalid float: " + cs; - errors.add(XmlError.forMessage(msg)); - - return Float.NaN; - } - } - - public static String printFloat(float value) - { - if (value == Float.POSITIVE_INFINITY) - return POS_INF_LEX; - else if (value == Float.NEGATIVE_INFINITY) - return NEG_INF_LEX; - else if (Float.isNaN(value)) - return NAN_LEX; - else - return Float.toString(value); - } - - - // ======================== double ======================== - public static double lexDouble(CharSequence cs) - throws NumberFormatException - { - final String v = cs.toString(); - - try { - //current jdk impl of parseDouble calls trim() on the string. - //Any other space is illegal anyway, whether there are one or more spaces. - //so no need to do a collapse pass through the string. - if (cs.length() > 0) { - char ch = cs.charAt(cs.length() - 1); - if (ch == 'd' || ch == 'D') - throw new NumberFormatException("Invalid char '" + ch + "' in double."); - } - return Double.parseDouble(v); - } - catch (NumberFormatException e) { - if (v.equals(POS_INF_LEX)) return Double.POSITIVE_INFINITY; - if (v.equals(NEG_INF_LEX)) return Double.NEGATIVE_INFINITY; - if (v.equals(NAN_LEX)) return Double.NaN; - - throw e; - } - } - - public static double lexDouble(CharSequence cs, Collection errors) - { - try { - return lexDouble(cs); - } - catch (NumberFormatException e) { - String msg = "invalid double: " + cs; - errors.add(XmlError.forMessage(msg)); - - return Double.NaN; - } - } - - public static String printDouble(double value) - { - if (value == Double.POSITIVE_INFINITY) - return POS_INF_LEX; - else if (value == Double.NEGATIVE_INFINITY) - return NEG_INF_LEX; - else if (Double.isNaN(value)) - return NAN_LEX; - else - return Double.toString(value); - } - - - // ======================== decimal ======================== - public static BigDecimal lexDecimal(CharSequence cs) - throws NumberFormatException - { - final String v = cs.toString(); - - //TODO: review this - //NOTE: we trim unneeded zeros from the string because - //java.math.BigDecimal considers them significant for its - //equals() method, but the xml value - //space does not consider them significant. - //See http://www.w3.org/2001/05/xmlschema-errata#e2-44 - return new BigDecimal(trimTrailingZeros(v)); - } - - public static BigDecimal lexDecimal(CharSequence cs, Collection errors) - { - try { - return lexDecimal(cs); - } - catch (NumberFormatException e) { - String msg = "invalid long: " + cs; - errors.add(XmlError.forMessage(msg)); - return DECIMAL__ZERO; - } - } - - private static final char[] CH_ZEROS = new char[] {'0', '0', '0', '0', '0', '0', '0', '0', - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'}; - - public static String printDecimal(BigDecimal value) - { - // We can't simply use value.toString() here, because in JDK1.5 that returns an - // exponent String and exponents are not allowed in XMLSchema decimal values - // The following code comes from Apache Harmony - String intStr = value.unscaledValue().toString(); - int scale = value.scale(); - if ((scale == 0) || ((value.longValue() == 0) && (scale < 0))) - return intStr; - - int begin = (value.signum() < 0) ? 1 : 0; - int delta = scale; - // We take space for all digits, plus a possible decimal point, plus 'scale' - StringBuffer result = new StringBuffer(intStr.length() + 1 + Math.abs(scale)); - - if (begin == 1) - { - // If the number is negative, we insert a '-' character at front - result.append('-'); - } - if (scale > 0) - { - delta -= (intStr.length() - begin); - if (delta >= 0) - { - result.append("0."); //$NON-NLS-1$ - // To append zeros after the decimal point - for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) - result.append(CH_ZEROS); - result.append(CH_ZEROS, 0, delta); - result.append(intStr.substring(begin)); - } - else - { - delta = begin - delta; - result.append(intStr.substring(begin, delta)); - result.append('.'); - result.append(intStr.substring(delta)); - } - } - else - {// (scale <= 0) - result.append(intStr.substring(begin)); - // To append trailing zeros - for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) - result.append(CH_ZEROS); - result.append(CH_ZEROS, 0, -delta); - } - return result.toString(); - } - - // ======================== integer ======================== - public static BigInteger lexInteger(CharSequence cs) - throws NumberFormatException - { - if (cs.length() > 1) { - if (cs.charAt(0) == '+' && cs.charAt(1) == '-') - throw new NumberFormatException("Illegal char sequence '+-'"); - } - final String v = cs.toString(); - - //TODO: consider special casing zero and one to return static values - //from BigInteger to avoid object creation. - return new BigInteger(trimInitialPlus(v)); - } - - public static BigInteger lexInteger(CharSequence cs, Collection errors) - { - try { - return lexInteger(cs); - } - catch (NumberFormatException e) { - String msg = "invalid long: " + cs; - errors.add(XmlError.forMessage(msg)); - return BigInteger.ZERO; - } - } - - public static String printInteger(BigInteger value) - { - return value.toString(); - } - - // ======================== long ======================== - public static long lexLong(CharSequence cs) - throws NumberFormatException - { - final String v = cs.toString(); - return Long.parseLong(trimInitialPlus(v)); - } - - public static long lexLong(CharSequence cs, Collection errors) - { - try { - return lexLong(cs); - } - catch (NumberFormatException e) { - String msg = "invalid long: " + cs; - errors.add(XmlError.forMessage(msg)); - return 0L; - } - } - - public static String printLong(long value) - { - return Long.toString(value); - } - - - // ======================== short ======================== - public static short lexShort(CharSequence cs) - throws NumberFormatException - { - return parseShort(cs); - } - - public static short lexShort(CharSequence cs, Collection errors) - { - try { - return lexShort(cs); - } - catch (NumberFormatException e) { - String msg = "invalid short: " + cs; - errors.add(XmlError.forMessage(msg)); - return 0; - } - } - - public static String printShort(short value) - { - return Short.toString(value); - } - - - // ======================== int ======================== - public static int lexInt(CharSequence cs) - throws NumberFormatException - { - return parseInt(cs); - } - - public static int lexInt(CharSequence cs, Collection errors) - { - try { - return lexInt(cs); - } - catch (NumberFormatException e) { - String msg = "invalid int:" + cs; - errors.add(XmlError.forMessage(msg)); - return 0; - } - } - - public static String printInt(int value) - { - return Integer.toString(value); - } - - - // ======================== byte ======================== - public static byte lexByte(CharSequence cs) - throws NumberFormatException - { - return parseByte(cs); - } - - public static byte lexByte(CharSequence cs, Collection errors) - { - try { - return lexByte(cs); - } - catch (NumberFormatException e) { - String msg = "invalid byte: " + cs; - errors.add(XmlError.forMessage(msg)); - return 0; - } - } - - public static String printByte(byte value) - { - return Byte.toString(value); - } - - - // ======================== boolean ======================== - public static boolean lexBoolean(CharSequence v) - { - switch (v.length()) { - case 1: // "0" or "1" - final char c = v.charAt(0); - if ('0' == c) return false; - if ('1' == c) return true; - break; - case 4: //"true" - if ('t' == v.charAt(0) && - 'r' == v.charAt(1) && - 'u' == v.charAt(2) && - 'e' == v.charAt(3)) { - return true; - } - break; - case 5: //"false" - if ('f' == v.charAt(0) && - 'a' == v.charAt(1) && - 'l' == v.charAt(2) && - 's' == v.charAt(3) && - 'e' == v.charAt(4)) { - return false; - } - break; - } - - //reaching here means an invalid boolean lexical - String msg = "invalid boolean: " + v; - throw new InvalidLexicalValueException(msg); - } - - public static boolean lexBoolean(CharSequence value, Collection errors) - { - try { - return lexBoolean(value); - } - catch (InvalidLexicalValueException e) { - errors.add(XmlError.forMessage(e.getMessage())); - return false; - } - } - - public static String printBoolean(boolean value) - { - return (value ? "true" : "false"); - } - - - // ======================== string ======================== - public static String lexString(CharSequence cs, Collection errors) - { - final String v = cs.toString(); - - return v; - } - - - public static String lexString(CharSequence lexical_value) - { - return lexical_value.toString(); - } - - public static String printString(String value) - { - return value; - } - - - // ======================== QName ======================== - public static QName lexQName(CharSequence charSeq, NamespaceContext nscontext) - { - String prefix, localname; - - int firstcolon; - boolean hasFirstCollon = false; - for (firstcolon = 0; firstcolon < charSeq.length(); firstcolon++) - if (charSeq.charAt(firstcolon) == NAMESPACE_SEP) { - hasFirstCollon = true; - break; - } - - if (hasFirstCollon) { - prefix = charSeq.subSequence(0, firstcolon).toString(); - localname = charSeq.subSequence(firstcolon + 1, charSeq.length()).toString(); - if (firstcolon == 0) { - throw new InvalidLexicalValueException("invalid xsd:QName '" + charSeq.toString() + "'"); - } - } else { - prefix = EMPTY_PREFIX; - localname = charSeq.toString(); - } - - String uri = nscontext.getNamespaceURI(prefix); - - if (uri == null) { - if (prefix != null && prefix.length() > 0) - throw new InvalidLexicalValueException("Can't resolve prefix: " + prefix); - - uri = ""; - } - - return new QName(uri, localname); - } - - public static QName lexQName(String xsd_qname, Collection errors, - NamespaceContext nscontext) - { - try { - return lexQName(xsd_qname, nscontext); - } - catch (InvalidLexicalValueException e) { - errors.add(XmlError.forMessage(e.getMessage())); - final int idx = xsd_qname.indexOf(NAMESPACE_SEP); - return new QName(null, xsd_qname.substring(idx)); - } - } - - public static String printQName(QName qname, NamespaceContext nsContext, - Collection errors) - { - final String uri = qname.getNamespaceURI(); - assert uri != null; //qname is not allowed to have null uri values - final String prefix; - if (uri.length() > 0) { - prefix = nsContext.getPrefix(uri); - if (prefix == null) { - String msg = "NamespaceContext does not provide" + - " prefix for namespaceURI " + uri; - errors.add(XmlError.forMessage(msg)); - } - } else { - prefix = null; - } - return getQNameString(uri, qname.getLocalPart(), prefix); - - } - - public static String getQNameString(String uri, - String localpart, - String prefix) - { - if (prefix != null && - uri != null && - uri.length() > 0 && - prefix.length() > 0) { - return (prefix + NAMESPACE_SEP + localpart); - } else { - return localpart; - } - } - - // ======================== GDate ======================== - public static GDate lexGDate(CharSequence charSeq) - { - return new GDate(charSeq); - } - - public static GDate lexGDate(String xsd_gdate, Collection errors) - { - try { - return lexGDate(xsd_gdate); - } - catch (IllegalArgumentException e) { - errors.add(XmlError.forMessage(e.getMessage())); - return new GDateBuilder().toGDate(); - } - } - - public static String printGDate(GDate gdate, Collection errors) - { - return gdate.toString(); - } - - - // ======================== dateTime ======================== - public static XmlCalendar lexDateTime(CharSequence v) - { - GDateSpecification value = getGDateValue(v, SchemaType.BTC_DATE_TIME); - return value.getCalendar(); - } - - - public static String printDateTime(Calendar c) - { - return printDateTime(c, SchemaType.BTC_DATE_TIME); - } - - public static String printTime(Calendar c) - { - return printDateTime(c, SchemaType.BTC_TIME); - } - - public static String printDate(Calendar c) - { - return printDateTime(c, SchemaType.BTC_DATE); - } - - public static String printDate(Date d) - { - GDateSpecification value = getGDateValue(d, SchemaType.BTC_DATE); - return value.toString(); - } - - public static String printDateTime(Calendar c, int type_code) - { - GDateSpecification value = getGDateValue(c, type_code); - return value.toString(); - } - - public static String printDateTime(Date c) - { - GDateSpecification value = getGDateValue(c, SchemaType.BTC_DATE_TIME); - return value.toString(); - } - - - // ======================== hexBinary ======================== - public static CharSequence printHexBinary(byte[] val) - { - return HexBin.bytesToString(val); - } - - public static byte[] lexHexBinary(CharSequence lexical_value) - { - byte[] buf = HexBin.decode(lexical_value.toString().getBytes()); - if (buf != null) - return buf; - else - throw new InvalidLexicalValueException("invalid hexBinary value"); - } - - - // ======================== base64binary ======================== - public static CharSequence printBase64Binary(byte[] val) - { - final byte[] bytes = Base64.encode(val); - return new String(bytes); - } - - public static byte[] lexBase64Binary(CharSequence lexical_value) - { - byte[] buf = Base64.decode(lexical_value.toString().getBytes()); - if (buf != null) - return buf; - else - throw new InvalidLexicalValueException("invalid base64Binary value"); - } - - - // date utils - public static GDateSpecification getGDateValue(Date d, - int builtin_type_code) - { - GDateBuilder gDateBuilder = new GDateBuilder(d); - gDateBuilder.setBuiltinTypeCode(builtin_type_code); - GDate value = gDateBuilder.toGDate(); - return value; - } - - - public static GDateSpecification getGDateValue(Calendar c, - int builtin_type_code) - { - GDateBuilder gDateBuilder = new GDateBuilder(c); - gDateBuilder.setBuiltinTypeCode(builtin_type_code); - GDate value = gDateBuilder.toGDate(); - return value; - } - - public static GDateSpecification getGDateValue(CharSequence v, - int builtin_type_code) - { - GDateBuilder gDateBuilder = new GDateBuilder(v); - gDateBuilder.setBuiltinTypeCode(builtin_type_code); - GDate value = gDateBuilder.toGDate(); - return value; - } - - private static String trimInitialPlus(String xml) - { - if (xml.length() > 0 && xml.charAt(0) == '+') { - return xml.substring(1); - } else { - return xml; - } - } - - private static String trimTrailingZeros(String xsd_decimal) - { - final int last_char_idx = xsd_decimal.length() - 1; - if (xsd_decimal.charAt(last_char_idx) == '0') - { - final int last_point = xsd_decimal.lastIndexOf('.'); - if (last_point >= 0) { - //find last trailing zero - for (int idx = last_char_idx; idx > last_point; idx--) { - if (xsd_decimal.charAt(idx) != '0') { - return xsd_decimal.substring(0, idx + 1); - } - } - //reaching here means the string matched xxx.0* - return xsd_decimal.substring(0, last_point); - } - } - return xsd_decimal; - } - - private static int parseInt(CharSequence cs) - { - return parseIntXsdNumber(cs, Integer.MIN_VALUE, Integer.MAX_VALUE); - } - - private static short parseShort(CharSequence cs) - { - return (short)parseIntXsdNumber(cs, Short.MIN_VALUE, Short.MAX_VALUE); - } - - private static byte parseByte(CharSequence cs) - { - return (byte)parseIntXsdNumber(cs, Byte.MIN_VALUE, Byte.MAX_VALUE); - } - - private static int parseIntXsdNumber(CharSequence ch, int min_value, int max_value) - { - // int parser on a CharSequence - int length = ch.length(); - if (length < 1) - throw new NumberFormatException("For input string: \"" + ch.toString() + "\""); - - int sign = 1; - int result = 0; - int start = 0; - int limit; - int limit2; - - char c = ch.charAt(0); - if (c == '-') { - start++; - limit = (min_value / 10); - limit2 = -(min_value % 10); - } else if (c == '+') { - start++; - sign = -1; - limit = -(max_value / 10); - limit2 = (max_value % 10); - } else { - sign = -1; - limit = -(max_value / 10); - limit2 = (max_value % 10); - } - - for (int i = 0; i < length - start; i++) { - c = ch.charAt(i + start); - int v = Character.digit(c, 10); - - if (v < 0) - throw new NumberFormatException("For input string: \"" + ch.toString() + "\""); - - if (result < limit || (result==limit && v > limit2)) - throw new NumberFormatException("For input string: \"" + ch.toString() + "\""); - - result = result * 10 - v; - } - - return sign * result; - } - - // ======================== anyURI ======================== - public static CharSequence printAnyURI(CharSequence val) - { - return val; - } - - /** - * Checkes the regular expression of URI, defined by RFC2369 http://www.ietf.org/rfc/rfc2396.txt Appendix B. - * Note: The whitespace normalization rule collapse must be applied priot to calling this method. - * @param lexical_value the lexical value - * @return same input value if input value is in the lexical space - * @throws InvalidLexicalValueException - */ - public static CharSequence lexAnyURI(CharSequence lexical_value) - { - /* // Reg exp from RFC2396, but it's too forgiving for XQTS - Pattern p = Pattern.compile("^([^:/?#]+:)?(//[^/?#]*)?([^?#]*)(\\?[^#]*)?(#.*)?"); - Matcher m = p.matcher(lexical_value); - if ( !m.matches() ) - throw new InvalidLexicalValueException("invalid anyURI value"); - else - { - for ( int i = 0; i<= m.groupCount(); i++ ) - { - System.out.print(" " + i + ": " + m.group(i)); - } - System.out.println(""); - return lexical_value; - } */ - - // Per XMLSchema spec allow spaces inside URIs - StringBuffer s = new StringBuffer(lexical_value.toString()); - for (int ic = 0; ic= 0) - { - s.replace(i, i + 1, URI_CHARS_REPLACED_WITH[ic]); - i += 3; - } - } - - try - { - URI.create(s.toString()); - } - catch (IllegalArgumentException e) - { - throw new InvalidLexicalValueException("invalid anyURI value: " + lexical_value, e); - } - - return lexical_value; - } -} \ No newline at end of file diff --git a/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java b/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java deleted file mode 100644 index cc01bf2..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java +++ /dev/null @@ -1,389 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.validator; - -import org.apache.xmlbeans.impl.common.XMLNameHelper; -import org.apache.xmlbeans.impl.common.GenericXmlInputStream; -import org.apache.xmlbeans.impl.common.ValidatorListener.Event; -import org.apache.xmlbeans.impl.common.ValidatorListener; -import org.apache.xmlbeans.impl.common.XmlWhitespace; -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XMLStreamValidationException; -import java.util.Map; -import java.util.AbstractCollection; -import java.util.Iterator; -import java.util.Collections; - -import org.apache.xmlbeans.xml.stream.Attribute; -import org.apache.xmlbeans.xml.stream.AttributeIterator; -import org.apache.xmlbeans.xml.stream.CharacterData; -import org.apache.xmlbeans.xml.stream.StartElement; -import org.apache.xmlbeans.xml.stream.XMLEvent; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLName; -import org.apache.xmlbeans.xml.stream.XMLStreamException; -import javax.xml.namespace.QName; - -/** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ -public final class ValidatingXMLInputStream - extends GenericXmlInputStream implements Event -{ - public ValidatingXMLInputStream ( - XMLInputStream xis, - SchemaTypeLoader typeLoader, SchemaType sType, XmlOptions options ) - throws XMLStreamException - { - _source = xis; - - // Figure out the root type - - options = XmlOptions.maskNull( options ); - - SchemaType type = (SchemaType) options.get( XmlOptions.DOCUMENT_TYPE ); - - if (type == null) - type = sType; - - if (type == null) - { - type = BuiltinSchemaTypeSystem.ST_ANY_TYPE; - - xis = xis.getSubStream(); - - if (xis.skip( XMLEvent.START_ELEMENT )) - { - SchemaType docType = - typeLoader.findDocumentType( - XMLNameHelper.getQName( xis.next().getName() ) ); - - if (docType != null) - type = docType; - } - - xis.close(); - } - - // Create the validator - - _validator = - new Validator( - type, null, typeLoader, options, new ExceptionXmlErrorListener() ); - - nextEvent( ValidatorListener.BEGIN ); - } - - // TODO - this is the quick and dirty impl of streaming validation, - // may objects are created (like strings) which can be optimized - - protected XMLEvent nextEvent ( ) throws XMLStreamException - { - XMLEvent e = _source.next(); - - if (e == null) - { - if (!_finished) - { - flushText(); - nextEvent( ValidatorListener.END ); - _finished = true; - } - } - else - { - switch ( e.getType() ) - { - case XMLEvent.CHARACTER_DATA : - case XMLEvent.SPACE : - { - CharacterData cd = (CharacterData) e; - - if (cd.hasContent()) - _text.append( cd.getContent() ); - - break; - } - case XMLEvent.START_ELEMENT : - { - StartElement se = (StartElement) e; - - flushText(); - - // Used for prefix to namespace mapping - _startElement = se; - - // Prepare the xsi:* values - - AttributeIterator attrs = se.getAttributes(); - - while ( attrs.hasNext() ) - { - Attribute attr = attrs.next(); - - XMLName attrName = attr.getName(); - - if ("http://www.w3.org/2001/XMLSchema-instance".equals( - attrName.getNamespaceUri() )) - { - String local = attrName.getLocalName(); - - if (local.equals( "type" )) - _xsiType = attr.getValue(); - else if (local.equals( "nil" )) - _xsiNil = attr.getValue(); - else if (local.equals( "schemaLocation" )) - _xsiLoc = attr.getValue(); - else if (local.equals( "noNamespaceSchemaLocation" )) - _xsiNoLoc = attr.getValue(); - } - } - - // Emit the START - - // TODO - should delay the aquisition of the name - _name = e.getName(); - - nextEvent( ValidatorListener.BEGIN ); - - // Emit the attrs - - attrs = se.getAttributes(); - - while ( attrs.hasNext() ) - { - Attribute attr = attrs.next(); - - XMLName attrName = attr.getName(); - - if ("http://www.w3.org/2001/XMLSchema-instance".equals( - attrName.getNamespaceUri() )) - { - String local = attrName.getLocalName(); - - if (local.equals( "type" )) - continue; - else if (local.equals( "nil" )) - continue; - else if (local.equals( "schemaLocation" )) - continue; - else if (local.equals( "noNamespaceSchemaLocation" )) - continue; - } - - // TODO - God, this is lame :-) - - _text.append( attr.getValue() ); - _name = attr.getName(); - - nextEvent( ValidatorListener.ATTR ); - } - - clearText(); - - _startElement = null; - - break; - } - - case XMLEvent.END_ELEMENT : - { - flushText(); - - nextEvent( ValidatorListener.END ); - - break; - } - } - } - - return e; - } - - private void clearText ( ) - { - _text.delete( 0, _text.length() ); - } - - private void flushText ( ) throws XMLStreamException - { - if (_text.length() > 0) - { - nextEvent( ValidatorListener.TEXT ); - clearText(); - } - } - - public String getNamespaceForPrefix ( String prefix ) - { - if (_startElement == null) - return null; - - Map map = _startElement.getNamespaceMap(); - - if (map == null) - return null; - - return (String) map.get( prefix ); - } - - public XmlCursor getLocationAsCursor ( ) - { - return null; - } - - public javax.xml.stream.Location getLocation() - { - try - { - final org.apache.xmlbeans.xml.stream.Location xeLoc = _source.peek().getLocation(); - - if (xeLoc==null) - return null; - - javax.xml.stream.Location loc = new javax.xml.stream.Location() - { - public int getLineNumber() - { return xeLoc.getLineNumber(); } - - public int getColumnNumber() - { return xeLoc.getColumnNumber(); } - - public int getCharacterOffset() - { return -1;} - - public String getPublicId() - { return xeLoc.getPublicId(); } - - public String getSystemId() - { return xeLoc.getSystemId(); } - }; - - return loc; - } - catch (XMLStreamException e) - { - return null; - } - } - - public String getXsiType ( ) - { - return _xsiType; - } - - public String getXsiNil ( ) - { - return _xsiNil; - } - - public String getXsiLoc ( ) - { - return _xsiLoc; - } - - public String getXsiNoLoc ( ) - { - return _xsiNoLoc; - } - - public QName getName ( ) - { - return XMLNameHelper.getQName( _name ); - } - - public String getText ( ) - { - return _text.toString(); - } - - public String getText ( int wsr ) - { - return XmlWhitespace.collapse( _text.toString(), wsr ); - } - - public boolean textIsWhitespace ( ) - { - for ( int i = 0 ; i < _text.length() ; i++ ) - { - switch ( _text.charAt( i ) ) - { - case ' ': - case '\n': - case '\r': - case '\t': - break; - - default : - return false; - } - } - - return true; - } - - private final class ExceptionXmlErrorListener extends AbstractCollection - { - public boolean add(Object o) - { - assert ValidatingXMLInputStream.this._exception == null; - - ValidatingXMLInputStream.this._exception = - new XMLStreamValidationException( (XmlError)o ); - - return false; - } - - public Iterator iterator() - { - return Collections.EMPTY_LIST.iterator(); - } - - public int size() - { - return 0; - } - } - - private void nextEvent ( int kind ) - throws XMLStreamException - { - assert _exception == null; - - _validator.nextEvent( kind, this ); - - if (_exception != null) - throw _exception; - } - - private XMLStreamValidationException _exception; - - private XMLInputStream _source; - private Validator _validator; - private StringBuffer _text = new StringBuffer(); - private boolean _finished; - private String _xsiType; - private String _xsiNil; - private String _xsiLoc; - private String _xsiNoLoc; - private XMLName _name; - private StartElement _startElement; -} \ No newline at end of file diff --git a/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java b/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java deleted file mode 100644 index 280cfe5..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java +++ /dev/null @@ -1,1946 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.validator; - -import org.apache.xmlbeans.impl.common.IdentityConstraint; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.ValidatorListener; -import org.apache.xmlbeans.impl.common.XmlWhitespace; -import org.apache.xmlbeans.impl.common.InvalidLexicalValueException; -import org.apache.xmlbeans.impl.schema.SchemaTypeVisitorImpl; -import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; -import org.apache.xmlbeans.impl.values.JavaBase64HolderEx; -import org.apache.xmlbeans.impl.values.JavaBooleanHolder; -import org.apache.xmlbeans.impl.values.JavaBooleanHolderEx; -import org.apache.xmlbeans.impl.values.JavaDecimalHolderEx; -import org.apache.xmlbeans.impl.values.JavaDoubleHolderEx; -import org.apache.xmlbeans.impl.values.JavaFloatHolderEx; -import org.apache.xmlbeans.impl.values.JavaHexBinaryHolderEx; -import org.apache.xmlbeans.impl.values.JavaNotationHolderEx; -import org.apache.xmlbeans.impl.values.JavaQNameHolderEx; -import org.apache.xmlbeans.impl.values.JavaStringEnumerationHolderEx; -import org.apache.xmlbeans.impl.values.JavaUriHolderEx; -import org.apache.xmlbeans.impl.values.NamespaceContext; -import org.apache.xmlbeans.impl.values.XmlDateImpl; -import org.apache.xmlbeans.impl.values.XmlDurationImpl; -import org.apache.xmlbeans.impl.values.XmlListImpl; -import org.apache.xmlbeans.impl.values.XmlQNameImpl; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.apache.xmlbeans.impl.util.XsTypeConverter; -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.XmlQName; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaLocalElement; -import org.apache.xmlbeans.SchemaGlobalElement; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlValidationError; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.XmlString; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.ArrayList; -import java.util.Iterator; -import javax.xml.namespace.QName; - -public final class Validator - implements ValidatorListener -{ - public Validator ( - SchemaType type, SchemaField field, SchemaTypeLoader globalLoader, - XmlOptions options, Collection defaultErrorListener ) - { - options = XmlOptions.maskNull(options); - _errorListener = (Collection) options.get(XmlOptions.ERROR_LISTENER); - _treatLaxAsSkip = options.hasOption(XmlOptions.VALIDATE_TREAT_LAX_AS_SKIP); - _strict = options.hasOption(XmlOptions.VALIDATE_STRICT); - - if (_errorListener == null) - _errorListener = defaultErrorListener; - - _constraintEngine = new IdentityConstraint(_errorListener, type.isDocumentType()); - - _globalTypes = globalLoader; - _rootType = type; - _rootField = field; - - _vc = new ValidatorVC(); - } - - private class ValidatorVC implements ValidationContext - { - // KHK: remove this - public void invalid ( String message ) - { - // TODO (dutta) Addtional Attributes for validation error have limited information - //at this time but will be a part of the second round of refactoring - - Validator.this.emitError(_event, message, null, null, null, - XmlValidationError.ATTRIBUTE_TYPE_INVALID, null); - } - - public void invalid ( String code, Object[] args ) - { - // TODO (dutta) Addtional Attributes for validation error have limited information - //at this time but will be a part of the second round of refactoring - - Validator.this.emitError(_event, code, args, null, null, null, - XmlValidationError.ATTRIBUTE_TYPE_INVALID, null); - } - - Event _event; - } - - public boolean isValid ( ) - { - return !_invalid && _constraintEngine.isValid(); - } - - // KHK: remove this - private void emitError ( Event event, String message, QName offendingQName, - SchemaType expectedSchemaType, List expectedQNames, - int errorType, SchemaType badSchemaType) - { - emitError(event, message, null, null, XmlError.SEVERITY_ERROR, null, offendingQName , expectedSchemaType, - expectedQNames , errorType, badSchemaType); - } - - private void emitError ( Event event, String code, Object[] args, QName offendingQName, - SchemaType expectedSchemaType, List expectedQNames, - int errorType, SchemaType badSchemaType) - { - emitError(event, null, code, args, XmlError.SEVERITY_ERROR, null, offendingQName , expectedSchemaType, - expectedQNames , errorType, badSchemaType); - } - - // KHK: remove 'message' parameter - private void emitError ( Event event, String message, String code, Object[] args, int severity, - QName fieldName, QName offendingQName, - SchemaType expectedSchemaType, List expectedQNames, - int errorType, SchemaType badSchemaType ) - { - _errorState++; - - if (_suspendErrors == 0) - { - if (severity == XmlError.SEVERITY_ERROR) - _invalid = true; - - if (_errorListener != null) - { - assert event != null; - XmlError error; - XmlCursor curs = event.getLocationAsCursor(); - if (curs != null) - { - // non-streaming validation uses XmlCursor - error = XmlValidationError.forCursorWithDetails( message, code, args, severity, - curs, fieldName, offendingQName, expectedSchemaType, expectedQNames, - errorType, badSchemaType); - } - else - { - // streaming validation uses Location - error = XmlValidationError.forLocationWithDetails( message, code, args, severity, - event.getLocation(), fieldName, offendingQName, expectedSchemaType, expectedQNames, - errorType, badSchemaType); - } - - _errorListener.add(error); - } - } - } - - private void emitFieldError ( Event event, String code, Object[] args, QName offendingQName, - SchemaType expectedSchemaType, List expectedQNames, - int errorType, SchemaType badSchemaType ) - { - emitFieldError(event, null, code, args, XmlError.SEVERITY_ERROR, offendingQName, - expectedSchemaType, expectedQNames, errorType, badSchemaType); - } - - private void emitFieldError ( Event event, String message, String code, Object[] args, int severity, QName offendingQName, - SchemaType expectedSchemaType, List expectedQNames, - int errorType, SchemaType badSchemaType ) - { - QName fieldName = null; - if (_stateStack != null && _stateStack._field != null) - { - fieldName = _stateStack._field.getName(); - } - - Validator.this.emitError(event, message, code, args, severity, fieldName, offendingQName, expectedSchemaType, - expectedQNames, errorType, badSchemaType); - } - -// // For XmlEventListener.error -// -// public void error ( XmlError error ) -// { -// _errorState++; -// -// if (_suspendErrors == 0) -// { -// _invalid = true; -// -// if (_errorListener != null) -// _errorListener.add( error ); -// } -// } - - public void nextEvent ( int kind, Event event ) - { - resetValues(); - - if (_eatContent > 0) - { - switch ( kind ) - { - case END : _eatContent--; break; - case BEGIN : _eatContent++; break; - } - } - else - { - assert - kind == BEGIN || kind == ATTR || - kind == END || kind == TEXT || kind == ENDATTRS; - - switch ( kind ) - { - case BEGIN : beginEvent( event ); break; - case ATTR : attrEvent( event ); break; - case ENDATTRS : endAttrsEvent( event ); break; - case TEXT : textEvent( event ); break; - case END : endEvent( event ); break; - } - } - } - - private void beginEvent ( Event event ) - { - _localElement = null; - _wildcardElement = null; - State state = topState(); - - SchemaType elementType = null; - SchemaField elementField = null; - - if (state == null) - { - elementType = _rootType; - elementField = _rootField; - } - else - { - - QName name = event.getName(); - - assert name != null; - - state._isEmpty = false; - - if (state._isNil) - { - emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$NIL_WITH_CONTENT, - null, state._field.getName(), state._type, null, - XmlValidationError.NIL_ELEMENT, state._type); - - _eatContent = 1; - return; - } - - if (!state._isNil && state._field != null && state._field.isFixed()) - { - emitFieldError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_WITH_CONTENT, - new Object[] { QNameHelper.pretty(state._field.getName()) }, - state._field.getName(), state._type, null, - XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); - } - - if (!state.visit( name )) - { - findDetailedErrorBegin(event ,state , name); - - _eatContent = 1; - - return; - } - - SchemaParticle currentParticle = state.currentParticle(); - _wildcardElement = currentParticle; - - if (currentParticle.getParticleType() == SchemaParticle.WILDCARD) - { - //_wildcardElement = currentParticle; - QNameSet elemWildcardSet = currentParticle.getWildcardSet(); - - if (!elemWildcardSet.contains( name )) - { - // Additional processing may be needed to generate more - // descriptive messages - // KHK: cvc-complex-type.2.4? cvc-particle.1.3? cvc-wildcard-namespace ? - emitFieldError(event, XmlErrorCodes.PARTICLE_VALID$NOT_WILDCARD_VALID, - new Object[] { QNameHelper.pretty(name) }, - name, null, null, - XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); - - _eatContent = 1; - - return; - } - - int wildcardProcess = currentParticle.getWildcardProcess(); - - if (wildcardProcess == SchemaParticle.SKIP || - wildcardProcess == SchemaParticle.LAX && _treatLaxAsSkip) - { - _eatContent = 1; - return; - } - - _localElement = _globalTypes.findElement( name ); - elementField = _localElement; - - if (elementField == null) - { - if (wildcardProcess == SchemaParticle.STRICT) - { - // KHK: cvc-complex-type.2.4c? cvc-assess-elt.1.1.1.3.2? - emitFieldError( event, XmlErrorCodes.ASSESS_ELEM_SCHEMA_VALID$NOT_RESOLVED, - new Object[] { QNameHelper.pretty(name) }, - name, state._type, null, - XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); - } - - _eatContent = 1; - - return; - } - } - else - { - assert currentParticle.getParticleType() == SchemaParticle.ELEMENT; - - // If the current element particle name does not match the name - // of the event, then the current element is a substitute for - // the current particle. Replace the field with the global - // element for the replacement - - if (! currentParticle.getName().equals(name)) - { - if (((SchemaLocalElement)currentParticle).blockSubstitution()) - { - emitFieldError( event, XmlErrorCodes.PARTICLE_VALID$BLOCK_SUBSTITUTION, - new Object[] { QNameHelper.pretty(name) }, - name, state._type, null, - XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); - - _eatContent = 1; - return; - } - - SchemaGlobalElement newField = _globalTypes.findElement(name); - - assert newField != null; - - if (newField != null) - { - elementField = newField; - _localElement = newField; - } - } - else - { - elementField = (SchemaField) currentParticle; - } - } - - elementType = elementField.getType(); - } - - assert elementType != null; - - // - // the no-type is always invalid (even if there is an xsi:type) - // - - if (elementType.isNoType()) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$NO_TYPE, - null, event.getName(), null, null, - XmlValidationError.ELEMENT_TYPE_INVALID, null); - - _eatContent = 1; - } - - // - // See if the element has an xsi:type on it - // - - SchemaType xsiType = null; - - String value = event.getXsiType(); - - if (value != null) - { - // Turn off the listener so a public error message - // does not get generated, but I can see if there was - // an error through the error state - - int originalErrorState = _errorState; - - _suspendErrors++; - - try - { - _vc._event = null; - - xsiType = _globalTypes.findType( XmlQNameImpl.validateLexical( value, _vc, event ) ); - } - catch ( Throwable t ) - { - _errorState++; - } - finally - { - _suspendErrors--; - } - - if (originalErrorState != _errorState) - { - // not sure how to extract this one - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_INVALID_QNAME, - new Object[] { value }, event.getName(), xsiType, null, - XmlValidationError.ELEMENT_TYPE_INVALID, state._type); - - _eatContent = 1; - - return; - } - else if (xsiType == null) - { - // NOT SURE errorAttributes._expectedSchemaType = xsiType; - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_NOT_FOUND, - new Object[] { value }, event.getName(), null, null, - XmlValidationError.ELEMENT_TYPE_INVALID, null); - - _eatContent = 1; - - return; - } - } - - if (xsiType != null && !xsiType.equals(elementType)) - { - if (!elementType.isAssignableFrom(xsiType)) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_NOT_DERIVED, - new Object[] { xsiType, elementType }, event.getName(), elementType, null, - XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); - - _eatContent = 1; - - return; - } - - if (elementType.blockExtension()) - { - for ( SchemaType t = xsiType ; ! t.equals( elementType ) ; - t = t.getBaseType() ) - { - if (t.getDerivationType() == SchemaType.DT_EXTENSION) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_BLOCK_EXTENSION, - new Object[] { xsiType, elementType }, event.getName(), elementType, null, - XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); - - _eatContent = 1; - - return; - } - } - } - - if (elementType.blockRestriction()) - { - for ( SchemaType t = xsiType ; ! t.equals( elementType ) ; - t = t.getBaseType() ) - { - if (t.getDerivationType() == SchemaType.DT_RESTRICTION) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_BLOCK_RESTRICTION, - new Object[] { xsiType, elementType }, event.getName(), elementType, null, - XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); - - _eatContent = 1; - - return; - } - } - } - - if (elementField instanceof SchemaLocalElement) - { - SchemaLocalElement sle = (SchemaLocalElement)elementField; - _localElement = sle; - - if (sle.blockExtension() || sle.blockRestriction()) - { - for ( SchemaType t = xsiType ; ! t.equals( elementType ) ; - t = t.getBaseType() ) - { - if ((t.getDerivationType() == SchemaType.DT_RESTRICTION && sle.blockRestriction()) || - (t.getDerivationType() == SchemaType.DT_EXTENSION && sle.blockExtension())) - { - //need to find a way to get the right type - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$XSI_TYPE_PROHIBITED_SUBST, - new Object[] { xsiType, QNameHelper.pretty(sle.getName()) }, - sle.getName(), null, null, XmlValidationError.ELEMENT_TYPE_INVALID, null); - - _eatContent = 1; - - return; - } - } - } - } - - elementType = xsiType; - } - - if (elementField instanceof SchemaLocalElement) - { - SchemaLocalElement sle = (SchemaLocalElement)elementField; - _localElement = sle; - - if (sle.isAbstract()) - { - //todo (dutta) need to find a way to get the right type - emitError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$ABSTRACT, - new Object[] { QNameHelper.pretty(sle.getName()) }, - sle.getName(), null, null, XmlValidationError.ELEMENT_TYPE_INVALID, null); - - _eatContent = 1; - return; - } - } - - if (elementType != null && elementType.isAbstract()) - { - emitError(event, XmlErrorCodes.ELEM_LOCALLY_VALID$ABSTRACT, - new Object[] { elementType }, - event.getName(), elementType, null, XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); - - _eatContent = 1; - - return; - } - - boolean isNil = false; - boolean hasNil = false; - - String nilValue = event.getXsiNil(); - - if (nilValue != null) - { - _vc._event = event; - isNil = JavaBooleanHolder.validateLexical(nilValue, _vc); - hasNil = true; - } - - // note in schema spec 3.3.4, you're not even allowed to say xsi:nil="false" if you're not nillable! - if (hasNil && (elementField == null || !elementField.isNillable())) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$NOT_NILLABLE, null, - elementField == null ? null : elementField.getName(), elementType, null, - XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); - - _eatContent = 1; - return; - } - - if (isNil && elementField != null && elementField.isFixed()) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$NIL_WITH_FIXED, null, - elementField == null ? null : elementField.getName(), elementType, null, - XmlValidationError.ELEMENT_TYPE_INVALID, (state == null ? null : state._type)); - } - - newState( elementType, elementField, isNil ); - - // Dispatch this element event to any identity constraints - // As well as adding any new identity constraints that exist - - _constraintEngine.element( - event, - elementType, - elementField instanceof SchemaLocalElement - ? ((SchemaLocalElement) elementField).getIdentityConstraints() - : null ); - } - - private void attrEvent ( Event event ) - { - QName attrName = event.getName(); - - State state = topState(); - - if (state._attrs == null) - state._attrs = new HashSet(); - - if (state._attrs.contains( attrName )) - { - emitFieldError( event, XmlErrorCodes.XML_DUPLICATE_ATTRIBUTE, - new Object[] { QNameHelper.pretty( attrName ) }, - attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type ); - - return; - } - - state._attrs.add( attrName ); - - if (!state._canHaveAttrs) - { - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD, - new Object[] {QNameHelper.pretty( attrName )}, attrName, null, null, - XmlValidationError.INCORRECT_ATTRIBUTE, state._type); - return; - } - - SchemaLocalAttribute attrSchema = - state._attrModel == null - ? null - : state._attrModel.getAttribute( attrName ); - - if (attrSchema != null) - { - _localAttribute = attrSchema; - - if (attrSchema.getUse() == SchemaLocalAttribute.PROHIBITED) - { - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$PROHIBITED_ATTRIBUTE, - new Object[] { QNameHelper.pretty( attrName ) } , - attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type ); - - return; - } - - String value = - validateSimpleType( - attrSchema.getType(), attrSchema, event, false, false ); - - _constraintEngine.attr( event, attrName, attrSchema.getType(), value ); - - return; - } - - int wildcardProcess = state._attrModel.getWildcardProcess(); - - _wildcardAttribute = state._attrModel; - - if (wildcardProcess == SchemaAttributeModel.NONE) - { - // todo (dutta) need additional logic to determine the expectedSchemaType - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD, - new Object[] { QNameHelper.pretty( attrName ) }, - attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); - - return; - } - - QNameSet attrWildcardSet = state._attrModel.getWildcardSet(); - - if (!attrWildcardSet.contains( attrName )) - { - // todo (dutta) need additional logic to determine the expectedSchemaType - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NOT_WILDCARD_VALID, - new Object[] { QNameHelper.pretty( attrName ) }, - attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); - - return; - } - - if (wildcardProcess == SchemaAttributeModel.SKIP || - wildcardProcess == SchemaAttributeModel.LAX && _treatLaxAsSkip) - return; - - attrSchema = _globalTypes.findAttribute( attrName ); - _localAttribute = attrSchema; - - if (attrSchema == null) - { - if (wildcardProcess == SchemaAttributeModel.LAX) - return; - - assert wildcardProcess == SchemaAttributeModel.STRICT; - - // KHK: cvc-assess-attr.1.2 ? - // todo (dutta) need additional logic to determine the expectedSchemaType - emitFieldError( event, XmlErrorCodes.ASSESS_ATTR_SCHEMA_VALID$NOT_RESOLVED, - new Object[] { QNameHelper.pretty( attrName ) }, - attrName, null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); - - return; - } - - String value = - validateSimpleType( - attrSchema.getType(), attrSchema, event, false, false ); - - _constraintEngine.attr( event, attrName, attrSchema.getType(), value ); - } - - private void endAttrsEvent ( Event event ) - { - State state = topState(); - - if (state._attrModel != null) - { - SchemaLocalAttribute[] attrs = state._attrModel.getAttributes(); - - for ( int i = 0 ; i < attrs.length ; i++ ) - { - SchemaLocalAttribute sla = attrs[ i ]; - - if (state._attrs == null || - !state._attrs.contains( sla.getName() )) - { - if (sla.getUse() == SchemaLocalAttribute.REQUIRED) - { - // KHK: cvc-complex-type.4 - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_REQUIRED_ATTRIBUTE, - new Object[] { QNameHelper.pretty(sla.getName()) }, - sla.getName(), null, null, XmlValidationError.INCORRECT_ATTRIBUTE, state._type); - } - else if (sla.isDefault() || sla.isFixed()) - { - _constraintEngine.attr(event, sla.getName(), sla.getType(), sla.getDefaultText()); - - // We don't need to validate attribute defaults because this is done at compiletime. - /* - String value = sla.getDefaultText(); - SchemaType type = sla.getType(); - - if (XmlQName.type.isAssignableFrom(type)) - { - emitFieldError( - event, - "Default QName values are unsupported for attribute: " + - QNameHelper.pretty(sla.getName()), - XmlError.SEVERITY_INFO); - } - - else - { - validateSimpleType( - type, sla.getDefaultText(), event ); - - _constraintEngine.attr( event, type, value ); - } - */ - } - } - } - } - } - - private void endEvent ( Event event ) - { - _localElement = null; - _wildcardElement = null; - State state = topState(); - - if (!state._isNil) - { - if (!state.end()) - { - findDetailedErrorEnd(event,state); - } - - // This end event has no text, use this fact to pass no text to - // handleText - - if (state._isEmpty) - handleText( event, true, state._field ); - } - - popState( event ); - - _constraintEngine.endElement( event ); - } - - private void textEvent ( Event event ) - { - State state = topState(); - - if (state._isNil) - { - emitFieldError( event, XmlErrorCodes.ELEM_LOCALLY_VALID$NIL_WITH_CONTENT, null, - state._field.getName(), state._type, null, - XmlValidationError.NIL_ELEMENT, state._type ); - } - else - handleText( event, false, state._field ); - - state._isEmpty = false; - } - - - private void handleText ( - Event event, boolean emptyContent, SchemaField field ) - { - State state = topState(); - - if (!state._sawText) - { - if (state._hasSimpleContent) - { - String value = - validateSimpleType( - state._type, field, event, emptyContent, true ); - - _constraintEngine.text( event, state._type, value, false ); - } - else if (state._canHaveMixedContent) - { - // handles cvc-elt.5.2.2.2.1, checking mixed content against fixed. - // if we see ac, we validate against - // the first 'a' text and we check the content of mixedType to - // be empty in beginElem(). we don't care about checking against - // the 'c' text since there will already be an error for - String value = - validateSimpleType( - XmlString.type, field, event, emptyContent, true ); - - _constraintEngine.text( event, XmlString.type, value, false ); - } - else if (emptyContent) - { - _constraintEngine.text( event, state._type, null, true ); - } - else - _constraintEngine.text( event, state._type, "", false); - } - - if (!emptyContent && !state._canHaveMixedContent && - !event.textIsWhitespace() && !state._hasSimpleContent) - { - if (field instanceof SchemaLocalElement) - { - SchemaLocalElement e = (SchemaLocalElement)field; - - assert state._type.getContentType() == SchemaType.EMPTY_CONTENT || - state._type.getContentType() == SchemaType.ELEMENT_CONTENT; - - // KHK: cvc-complex-type.2.1 or .2.3 - String errorCode = (state._type.getContentType() == SchemaType.EMPTY_CONTENT ? - XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EMPTY_WITH_CONTENT : - XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_ONLY_WITH_TEXT); - - emitError(event, errorCode,new Object[] {QNameHelper.pretty(e.getName())}, - e.getName(), field.getType(), null, - XmlValidationError.ELEMENT_TYPE_INVALID, null); - } - else - { - // KHK: cvc-complex-type.2.1 or .2.3 - // todo (dutta) offendingQName = not sure how to get this(event.getName()??); - emitError(event, "Can't have mixed content", event.getName(), - state._type, null, XmlValidationError.ELEMENT_TYPE_INVALID, null); - } - } - - if (!emptyContent) - state._sawText = true; - } - - private void findDetailedErrorBegin(Event event, State state, QName qName) - { - ArrayList expectedNames = new ArrayList(); - ArrayList optionalNames = new ArrayList(); - - SchemaProperty[] eltProperties = state._type.getElementProperties(); - for (int ii = 0; ii < eltProperties.length; ii++) - { - //Get the element from the schema - SchemaProperty sProp = eltProperties[ii]; - - // test if the element is valid - if (state.test(sProp.getName())) - { - if (0 == BigInteger.ZERO.compareTo(sProp.getMinOccurs())) - optionalNames.add(sProp.getName()); - else - expectedNames.add(sProp.getName()); - } - } - - List names = (expectedNames.size() > 0 ? expectedNames : optionalNames); - - if (names.size() > 0) - { - StringBuffer buf = new StringBuffer(); - for (Iterator iter = names.iterator(); iter.hasNext();) - { - QName qname = (QName) iter.next(); - buf.append(QNameHelper.pretty(qname)); - if (iter.hasNext()) - buf.append(" "); - } - - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT, - new Object[] { new Integer(names.size()), buf.toString(), QNameHelper.pretty(qName) }, - qName, null, names, XmlValidationError.INCORRECT_ELEMENT, state._type); - } - else - { - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_NOT_ALLOWED, - new Object[] { QNameHelper.pretty(qName) }, - qName, null, null, XmlValidationError.INCORRECT_ELEMENT, state._type); - } - } - - private void findDetailedErrorEnd(Event event, State state) - { - SchemaProperty[] eltProperties = state._type.getElementProperties(); - - ArrayList expectedNames = new ArrayList(); - ArrayList optionalNames = new ArrayList(); - - for (int ii = 0; ii < eltProperties.length; ii++) - { - //Get the element from the schema - SchemaProperty sProp = eltProperties[ii]; - - // test if the element is valid - if (state.test(sProp.getName())) - { - if (0 == BigInteger.ZERO.compareTo(sProp.getMinOccurs())) - optionalNames.add(sProp.getName()); - else - expectedNames.add(sProp.getName()); - } - } - - List names = (expectedNames.size() > 0 ? expectedNames : optionalNames); - - if (names.size() > 0) - { - StringBuffer buf = new StringBuffer(); - for (Iterator iter = names.iterator(); iter.hasNext();) - { - QName qname = (QName) iter.next(); - buf.append(QNameHelper.pretty(qname)); - if (iter.hasNext()) - buf.append(" "); - } - - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_ELEMENT, - new Object[] { new Integer(names.size()), buf.toString() }, - null, null, names, XmlValidationError.INCORRECT_ELEMENT, state._type); - } - else - { - emitFieldError( event, XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_ELEMENT, - null, null, null, null, XmlValidationError.ELEMENT_NOT_ALLOWED, state._type); - } - } - - - private final class State - { - boolean visit ( QName name ) - { - return _canHaveElements && _visitor.visit( name ); - } - - boolean test( QName name ) - { - return _canHaveElements && _visitor.testValid( name ); - } - - boolean end ( ) - { - return !_canHaveElements || _visitor.visit( null ); - } - - SchemaParticle currentParticle ( ) - { - assert _visitor != null; - return _visitor.currentParticle(); - } - - SchemaType _type; - SchemaField _field; - - boolean _canHaveAttrs; - boolean _canHaveMixedContent; - boolean _hasSimpleContent; - - boolean _sawText; - boolean _isEmpty; - boolean _isNil; - - SchemaTypeVisitorImpl _visitor; - boolean _canHaveElements; - - SchemaAttributeModel _attrModel; - - HashSet _attrs; - - State _next; - } - - private boolean derivedFromInteger( SchemaType type ) - { - int btc = type.getBuiltinTypeCode(); - - while (btc == SchemaType.BTC_NOT_BUILTIN) - { - type = type.getBaseType(); - btc = type.getBuiltinTypeCode(); - } - // This depends on the ordering of the constant values, which is not ideal but is easier - return btc >= SchemaType.BTC_INTEGER && btc <= SchemaType.BTC_UNSIGNED_BYTE; - } - - private void newState ( SchemaType type, SchemaField field, boolean isNil ) - { - State state = new State(); - - state._type = type; - state._field = field; - state._isEmpty = true; - state._isNil = isNil; - - if (type.isSimpleType()) - { - state._hasSimpleContent = true; - } - else - { - state._canHaveAttrs = true; - state._attrModel = type.getAttributeModel(); - - switch ( type.getContentType() ) - { - case SchemaType.EMPTY_CONTENT : - break; - - case SchemaType.SIMPLE_CONTENT : - state._hasSimpleContent = true; - break; - - case SchemaType.MIXED_CONTENT : - state._canHaveMixedContent = true; - // Fall through - - case SchemaType.ELEMENT_CONTENT : - - SchemaParticle particle = type.getContentModel(); - - state._canHaveElements = particle != null; - - if (state._canHaveElements) - state._visitor = initVisitor( particle ); - - break; - - default : - throw new RuntimeException( "Unexpected content type" ); - } - } - - pushState( state ); - } - - private void popState ( Event e ) - { - if (_stateStack._visitor != null) - { - poolVisitor( _stateStack._visitor ); - _stateStack._visitor = null; - } - - _stateStack = _stateStack._next; - } - - private void pushState ( State state ) - { - state._next = _stateStack; - _stateStack = state; - } - - private LinkedList _visitorPool = new LinkedList(); - - private void poolVisitor( SchemaTypeVisitorImpl visitor ) - { - _visitorPool.add( visitor ); - } - - private SchemaTypeVisitorImpl initVisitor( SchemaParticle particle ) - { - if (_visitorPool.isEmpty()) - return new SchemaTypeVisitorImpl( particle ); - - SchemaTypeVisitorImpl result = - (SchemaTypeVisitorImpl) _visitorPool.removeLast(); - - result.init( particle ); - - return result; - } - - private State topState ( ) - { - return _stateStack; - } - - // - // Simple Type Validation - // - // emptyContent means that you can't use the event to get text: there is - // no text, but you can use the event to do prefix resolution (in the case - // where the default is a qname) - // - - private String validateSimpleType ( - SchemaType type, SchemaField field, Event event, - boolean emptyContent, boolean canApplyDefault ) - { - if (!type.isSimpleType() && - type.getContentType() != SchemaType.SIMPLE_CONTENT) - { - assert false; - // throw new RuntimeException( "Not a simple type" ); - return null; // should never happen - } - - // - // the no-type is always invalid - // - - if (type.isNoType()) - { - emitError(event, (field.isAttribute() ? XmlErrorCodes.ATTR_LOCALLY_VALID$NO_TYPE : XmlErrorCodes.ELEM_LOCALLY_VALID$NO_TYPE), - null, field.getName(), type, null, XmlValidationError.ELEMENT_TYPE_INVALID, null); - - return null; - } - - // Get the value as a string (as normalized by the white space rule - // TODO - will want to optimize this later - - String value = ""; - - if (!emptyContent) - { - int wsr = type.getWhiteSpaceRule(); - value = wsr == SchemaType.WS_PRESERVE ? event.getText() : event.getText( wsr ); - } - - // See if I can apply a default/fixed value - - if (value.length() == 0 && canApplyDefault && field != null && - (field.isDefault() || field.isFixed())) - { - if (XmlQName.type.isAssignableFrom(type)) - { - // TODO: will be fixed in XmlSchema 1.1 - emitError( event, "Default QName values are unsupported for " + - QNameHelper.readable(type) + " - ignoring.", null, null, - XmlError.SEVERITY_INFO, field.getName(), null, type, null, - XmlValidationError.ELEMENT_TYPE_INVALID, null); - - return null; - } - - String defaultValue = - XmlWhitespace.collapse( - field.getDefaultText(), type.getWhiteSpaceRule() ); - -// BUGBUG - should validate defaultValue at compile time - // KHK: cvc-elt.5.1.2 ? - return - validateSimpleType( type, defaultValue, event ) - ? defaultValue - : null; - } - - // KHK: cvc-elt.5.2.1 ? - if (!validateSimpleType( type, value, event )) - return null; - - if (field != null && field.isFixed()) - { -// TODO - fixed value should have been cooked at compile time - String fixedValue = - XmlWhitespace.collapse( - field.getDefaultText(), type.getWhiteSpaceRule() ); - - if (!validateSimpleType( type, fixedValue, event )) - return null; - - XmlObject val = type.newValue( value ); - XmlObject def = type.newValue( fixedValue ); - - if (!val.valueEquals( def )) - { - // TODO (dutta) - make this more verbose - if (field.isAttribute()) - { - // KHK: check for is cvc-complex-type.3.1 or cvc-au - emitError(event, XmlErrorCodes.ATTR_LOCALLY_VALID$FIXED, - new Object[] { value, fixedValue, QNameHelper.pretty(event.getName()) }, - null, field.getType(), null, XmlValidationError.ELEMENT_TYPE_INVALID, null); - } - else - { - String errorCode = null; - - // see rule 5 of cvc-elt: Element Locally Valid (Element) - if (field.getType().getContentType() == SchemaType.MIXED_CONTENT) - errorCode = XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_VALID_MIXED_CONTENT; - else if (type.isSimpleType()) - errorCode = XmlErrorCodes.ELEM_LOCALLY_VALID$FIXED_VALID_SIMPLE_TYPE; - else - assert false : "Element with fixed may not be EMPTY or ELEMENT_ONLY"; - - emitError(event, errorCode, - new Object[] { value, fixedValue }, - field.getName(), field.getType(), null, XmlValidationError.ELEMENT_TYPE_INVALID, null); - } - - return null; - } - } - - return value; - } - - private boolean validateSimpleType ( - SchemaType type, String value, Event event ) - { - if (!type.isSimpleType() && - type.getContentType() != SchemaType.SIMPLE_CONTENT) - { - assert false; - throw new RuntimeException( "Not a simple type" ); - } - - int retState = _errorState; - - switch ( type.getSimpleVariety() ) - { - case SchemaType.ATOMIC : validateAtomicType( type, value, event );break; - case SchemaType.UNION : validateUnionType( type, value, event );break; - case SchemaType.LIST : validateListType( type, value, event );break; - - default : throw new RuntimeException( "Unexpected simple variety" ); - } - - return retState == _errorState; - } - - private void validateAtomicType ( - SchemaType type, String value, Event event ) - { - // Now we should have only an atomic type to validate - - assert type.getSimpleVariety() == SchemaType.ATOMIC; - - // Record the current error state to see if any new errors are made - int errorState = _errorState; - _vc._event = event; - - switch ( type.getPrimitiveType().getBuiltinTypeCode() ) - { - case SchemaType.BTC_ANY_SIMPLE : - { - // Always valid! - _stringValue = value; - break; - } - case SchemaType.BTC_STRING : - { - JavaStringEnumerationHolderEx.validateLexical( value, type, _vc ); - _stringValue = value; - break; - } - case SchemaType.BTC_DECIMAL : - { - JavaDecimalHolderEx.validateLexical( value, type, _vc ); - - // An additional rule states that if the type is xs:integer or derived from it, - // then the decimal dot is not allowed. - // verify that values extending xsd:integer don't have a decimal point - if ( derivedFromInteger( type ) && value.lastIndexOf('.') >= 0 ) - { - _vc.invalid(XmlErrorCodes.INTEGER, new Object[] { value }); - } - - if (errorState == _errorState) - { - _decimalValue = new BigDecimal( value ); - JavaDecimalHolderEx.validateValue( _decimalValue, type, _vc ); - } - - break; - } - case SchemaType.BTC_BOOLEAN : - { - _booleanValue = JavaBooleanHolderEx.validateLexical( value, type, _vc ); - break; - } - case SchemaType.BTC_FLOAT : - { - float f = - JavaFloatHolderEx.validateLexical( value, type, _vc ); - - if (errorState == _errorState) - JavaFloatHolderEx.validateValue( f, type, _vc ); - - _floatValue = f; - break; - } - case SchemaType.BTC_DOUBLE : - { - double d = - JavaDoubleHolderEx.validateLexical( value, type, _vc ); - - if (errorState == _errorState) - JavaDoubleHolderEx.validateValue( d, type, _vc ); - - _doubleValue = d; - break; - } - case SchemaType.BTC_QNAME : - { - QName n = - JavaQNameHolderEx.validateLexical( - value, type, _vc, event ); - - if (errorState == _errorState) - JavaQNameHolderEx.validateValue( n, type, _vc ); - - _qnameValue = n; - break; - } - case SchemaType.BTC_ANY_URI : - { - JavaUriHolderEx.validateLexical( value, type, _vc ); - // Do strict validation - if (_strict) - { - try - { - XsTypeConverter.lexAnyURI( value ); - } - catch (InvalidLexicalValueException ilve) - { - _vc.invalid(XmlErrorCodes.ANYURI, new Object[] { value }); - } - } - _stringValue = value; - break; - } - case SchemaType.BTC_G_MONTH : - { - // In the case of gMonth, there is some strict mode validation to do - if (_strict && value.length() == 6 && - value.charAt( 4 ) == '-' && value.charAt( 5 ) == '-') - _vc.invalid(XmlErrorCodes.DATE, new Object[] { value }); - // Fall through - } - case SchemaType.BTC_DATE_TIME : - case SchemaType.BTC_TIME : - case SchemaType.BTC_DATE : - case SchemaType.BTC_G_YEAR_MONTH : - case SchemaType.BTC_G_YEAR : - case SchemaType.BTC_G_MONTH_DAY : - case SchemaType.BTC_G_DAY : - { - GDate d = XmlDateImpl.validateLexical( value, type, _vc ); - - if (d != null) - XmlDateImpl.validateValue( d, type, _vc ); - - _gdateValue = d; - break; - } - case SchemaType.BTC_DURATION : - { - GDuration d = XmlDurationImpl.validateLexical( value, type, _vc ); - - if (d != null) - XmlDurationImpl.validateValue( d, type, _vc ); - - _gdurationValue = d; - break; - } - case SchemaType.BTC_BASE_64_BINARY : - { - byte[] v = - JavaBase64HolderEx.validateLexical( value, type, _vc ); - - if (v != null) - JavaBase64HolderEx.validateValue( v, type, _vc ); - - _byteArrayValue = v; - break; - } - case SchemaType.BTC_HEX_BINARY : - { - byte[] v = - JavaHexBinaryHolderEx.validateLexical( value, type, _vc ); - - if (v != null) - JavaHexBinaryHolderEx.validateValue( v, type, _vc ); - - _byteArrayValue = v; - break; - } - case SchemaType.BTC_NOTATION : - { - QName n = - JavaNotationHolderEx.validateLexical( - value, type, _vc, event ); - - if (errorState == _errorState) - JavaNotationHolderEx.validateValue( n, type, _vc ); - - _qnameValue = n; - break; - } - - default : - throw new RuntimeException( "Unexpected primitive type code" ); - } - } - - private void validateListType ( - SchemaType type, String value, Event event ) - { - int errorState = _errorState; - - if (!type.matchPatternFacet( value )) - { - emitError(event, XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "list", value, QNameHelper.readable(type) }, - null, type, null, XmlValidationError.LIST_INVALID, null); - } - - String[] items = XmlListImpl.split_list(value); - - int i; - XmlObject o; - - if ((o = type.getFacet( SchemaType.FACET_LENGTH )) != null) - { - if ((i = ((SimpleValue)o).getIntValue()) != items.length) - { - //offending Qname not valid - emitError(event, XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, - new Object[] { value, new Integer(items.length), new Integer(i), QNameHelper.readable(type) }, - null, type, null, XmlValidationError.LIST_INVALID, null); - } - } - - if ((o = type.getFacet( SchemaType.FACET_MIN_LENGTH )) != null) - { - if ((i = ((SimpleValue)o).getIntValue()) > items.length) - { - //offending Qname not valid - emitError(event, XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, - new Object[] { value, new Integer(items.length), new Integer(i), QNameHelper.readable(type) }, - null, type, null, XmlValidationError.LIST_INVALID, null); - } - } - - if ((o = type.getFacet( SchemaType.FACET_MAX_LENGTH )) != null) - { - if ((i = ((SimpleValue)o).getIntValue()) < items.length) - { - //offending Qname not valid - emitError(event, XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, - new Object[] { value, new Integer(items.length), new Integer(i), QNameHelper.readable(type) }, - null, type, null, XmlValidationError.LIST_INVALID, null); - } - } - - SchemaType itemType = type.getListItemType(); - _listValue = new ArrayList(); - _listTypes = new ArrayList(); - - for ( i = 0 ; i < items.length ; i++ ) - { - validateSimpleType( - itemType, items[i], event ); - addToList(itemType); - } - - // If no errors up to this point, then I can create an - // XmlList from this value and campare it again enums. - - if (errorState == _errorState) - { - if (type.getEnumerationValues() != null) - { - // Lists which contain QNames will need a resolver - - NamespaceContext.push( - new NamespaceContext( event ) ); - - try - { - XmlObject listValue = ( (SchemaTypeImpl) type).newValidatingValue( value ); - } - catch (XmlValueOutOfRangeException e) - { - //offending Qname not valid ?? - emitError(event, XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "list", value, QNameHelper.readable(type) }, - null, type, null, XmlValidationError.LIST_INVALID, null); - } - finally - { - NamespaceContext.pop(); - } - } - } - } - - private void validateUnionType ( - SchemaType type, String value, Event event ) - { - // TODO - if xsi:type is specified on a union, it selects - // that union member type - - if (!type.matchPatternFacet( value )) - { - //offending Qname not valid ?? - emitError(event, XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "union", value, QNameHelper.readable(type) }, - null, type, null, XmlValidationError.UNION_INVALID, null); - } - - int currentWsr = SchemaType.WS_PRESERVE; - String currentValue = value; - - SchemaType[] types = type.getUnionMemberTypes(); - - int originalState = _errorState; - - int i; - for ( i = 0 ; i < types.length ; i++ ) - { - int memberWsr = types[ i ].getWhiteSpaceRule(); - - if (memberWsr == SchemaType.WS_UNSPECIFIED) - memberWsr = SchemaType.WS_PRESERVE; - - if (memberWsr != currentWsr) - { - currentWsr = memberWsr; - currentValue = XmlWhitespace.collapse( value, currentWsr ); - } - - int originalErrorState = _errorState; - - _suspendErrors++; - - try - { - validateSimpleType( types[ i ], currentValue, event ); - } - finally - { - _suspendErrors--; - } - - if (originalErrorState == _errorState) - { - _unionType = types[i]; - break; - } - } - - _errorState = originalState; - - if (i >= types.length) - { - //offending Qname not valid ?? - emitError(event, XmlErrorCodes.DATATYPE_VALID$UNION, - new Object[] { value, QNameHelper.readable(type) }, - null, type, null, XmlValidationError.UNION_INVALID, null); - } - else - { - XmlObject[] unionEnumvals = type.getEnumerationValues(); - - if (unionEnumvals != null) - { - // Unions which contain QNames will need a resolver - - NamespaceContext.push( new NamespaceContext( event ) ); - - try - { - XmlObject unionValue = type.newValue( value ); - - for ( i = 0 ; i < unionEnumvals.length ; i++ ) - { - if (unionValue.valueEquals( unionEnumvals[ i ] )) - break; - } - - if (i >= unionEnumvals.length) - { - //offending Qname not valid ?? - emitError(event, XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "union", value, QNameHelper.readable(type) }, - null, type, null, XmlValidationError.UNION_INVALID, null); - } - } - catch (XmlValueOutOfRangeException e) - { - // actually, the current union code always ends up here when invalid - - //offending Qname not valid ?? - emitError(event, XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "union", value, QNameHelper.readable(type) }, - null, type, null, XmlValidationError.UNION_INVALID, null); - } - finally - { - NamespaceContext.pop(); - } - } - } - } - - private void addToList(SchemaType type) - { - if (type.getSimpleVariety() != SchemaType.ATOMIC && - type.getSimpleVariety() != SchemaType.UNION) - return; - - if (type.getUnionMemberTypes().length>0 && getUnionType()!=null) - { - type = getUnionType(); - _unionType = null; - } - - _listTypes.add(type); - - if (type.getPrimitiveType() == null) - { - // instance has an error for this value so there is no primitive type. - // an error should already have been produced. - _listValue.add(null); - return; - } - - switch ( type.getPrimitiveType().getBuiltinTypeCode() ) - { - case SchemaType.BTC_ANY_SIMPLE : - { - _listValue.add(_stringValue); - break; - } - case SchemaType.BTC_STRING : - { - _listValue.add(_stringValue); - _stringValue = null; - break; - } - case SchemaType.BTC_DECIMAL : - { - _listValue.add( _decimalValue ); - _decimalValue = null; - break; - } - case SchemaType.BTC_BOOLEAN : - { - _listValue.add(_booleanValue ? Boolean.TRUE : Boolean.FALSE); - _booleanValue = false; - break; - } - case SchemaType.BTC_FLOAT : - { - _listValue.add(new Float(_floatValue)); - _floatValue = 0; - break; - } - case SchemaType.BTC_DOUBLE : - { - _listValue.add(new Double(_doubleValue)); - _doubleValue = 0; - break; - } - case SchemaType.BTC_QNAME : - { - _listValue.add(_qnameValue); - _qnameValue = null; - break; - } - case SchemaType.BTC_ANY_URI : - { - _listTypes.add(_stringValue); - break; - } - case SchemaType.BTC_DATE_TIME : - case SchemaType.BTC_TIME : - case SchemaType.BTC_DATE : - case SchemaType.BTC_G_YEAR_MONTH : - case SchemaType.BTC_G_YEAR : - case SchemaType.BTC_G_MONTH_DAY : - case SchemaType.BTC_G_DAY : - case SchemaType.BTC_G_MONTH : - { - _listValue.add(_gdateValue); - _gdateValue = null; - break; - } - case SchemaType.BTC_DURATION : - { - _listValue.add(_gdurationValue); - _gdurationValue = null; - break; - } - case SchemaType.BTC_BASE_64_BINARY : - { - _listValue.add(_byteArrayValue); - _byteArrayValue = null; - break; - } - case SchemaType.BTC_HEX_BINARY : - { - _listValue.add(_byteArrayValue); - _byteArrayValue = null; - break; - } - case SchemaType.BTC_NOTATION : - { - _listValue.add(_qnameValue); - _qnameValue = null; - break; - } - - default : - throw new RuntimeException( "Unexpected primitive type code" ); - } - } - - // - // Members of the validator class - // - - private boolean _invalid; - private SchemaType _rootType; - private SchemaField _rootField; - private SchemaTypeLoader _globalTypes; - private State _stateStack; - private int _errorState; - private Collection _errorListener; - private boolean _treatLaxAsSkip; - private boolean _strict; - private ValidatorVC _vc; - private int _suspendErrors; - private IdentityConstraint _constraintEngine; - private int _eatContent; - - private SchemaLocalElement _localElement; - private SchemaParticle _wildcardElement; - private SchemaLocalAttribute _localAttribute; - private SchemaAttributeModel _wildcardAttribute; - private SchemaType _unionType; - - // Strongly typed values - private String _stringValue; - private BigDecimal _decimalValue; - private boolean _booleanValue; - private float _floatValue; - private double _doubleValue; - private QName _qnameValue; - private GDate _gdateValue; - private GDuration _gdurationValue; - private byte[] _byteArrayValue; - private List _listValue; - private List _listTypes; - - private void resetValues() - { - _localAttribute = null; - _wildcardAttribute = null; - _stringValue = null; - _decimalValue = null; - _booleanValue = false; - _floatValue = 0; - _doubleValue = 0; - _qnameValue = null; - _gdateValue = null; - _gdurationValue = null; - _byteArrayValue = null; - _listValue = null; - _listTypes = null; - _unionType = null; - _localAttribute = null; - } - - /** - * @return Returns the SchemaType of the current element. - * This can be different than getCurrentElement().getType() if xsi:type attribute is used. - * Null is returned if no schema type is available. - * For attribute types use {@link #getCurrentAttribute()}.getType(). - * Warning: the returned SchemaType can be an {@link org.apache.xmlbeans.XmlBeans#NO_TYPE}, - * see {@link SchemaType#isNoType}. Or can be the parent type, for unrecognized elements - * that are part of wildcards. - */ - public SchemaType getCurrentElementSchemaType ( ) - { - State state = topState(); - if (state!=null) - return state._type; - - return null; - } - - /** - * @return Returns the curent local element, null if one is not available, see {@link #getCurrentWildcardElement()}. - */ - public SchemaLocalElement getCurrentElement ( ) - { - if (_localElement != null) - return _localElement; - - // it means the element is to be skiped and it doesn't have a known SchemaLocalElement - - if (_eatContent > 0) - return null; - - //try getting it from the stack (this should happen after END) - - if (_stateStack != null && _stateStack._field instanceof SchemaLocalElement) - return (SchemaLocalElement) _stateStack._field; - - return null; - } - - /** - * @return Returns the current particle, if this is a wildcard particle {@link SchemaParticle#WILDCARD} - * method {@link #getCurrentElement()} might return null if wildcard's processContents is skip or lax. - */ - public SchemaParticle getCurrentWildcardElement() - { - return _wildcardElement; - } - - /** - * @return Returns the curent local attribute, global attribute if the current attribute is part of an - * attribute wildcard, or null if none is available. - */ - public SchemaLocalAttribute getCurrentAttribute() - { - return _localAttribute; - } - - /** - * @return Returns the attribute model for attributes if available, else null is returned. - */ - public SchemaAttributeModel getCurrentWildcardAttribute() - { - return _wildcardAttribute; - } - - public String getStringValue() - { - return _stringValue; - } - - public BigDecimal getDecimalValue() - { - return _decimalValue; - } - - public boolean getBooleanValue() - { - return _booleanValue; - } - - public float getFloatValue() - { - return _floatValue; - } - - public double getDoubleValue() - { - return _doubleValue; - } - - public QName getQNameValue() - { - return _qnameValue; - } - - public GDate getGDateValue() - { - return _gdateValue; - } - - public GDuration getGDurationValue() - { - return _gdurationValue; - } - - public byte[] getByteArrayValue() - { - return _byteArrayValue; - } - - public List getListValue() - { - return _listValue; - } - - public List getListTypes() - { - return _listTypes; - } - - public SchemaType getUnionType() - { - return _unionType; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64Holder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64Holder.java deleted file mode 100644 index afa165f..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64Holder.java +++ /dev/null @@ -1,153 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; - -import org.apache.xmlbeans.impl.util.Base64; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlBase64Binary; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.io.UnsupportedEncodingException; - -public abstract class JavaBase64Holder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_BASE_64_BINARY; } - - protected byte[] _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets raw text value - protected String compute_text(NamespaceManager nsm) - { - return new String(Base64.encode(_value)); - } - protected void set_text(String s) - { - _hashcached = false; - if (_validateOnSet()) - _value = validateLexical(s, schemaType(), _voorVc); - else - _value = lex(s, _voorVc); - } - protected void set_nil() - { - _hashcached = false; - _value = null; - } - - public static byte[] lex(String v, ValidationContext c) - { - byte[] vBytes = null; - try - { - vBytes = v.getBytes("UTF-8"); - } - catch(UnsupportedEncodingException uee) - { - // should never happen - UTF-8 is always supported - } - final byte[] bytes = Base64.decode(vBytes); - - if (bytes == null) - { - // TODO - get a decent error with line numbers and such here - c.invalid(XmlErrorCodes.BASE64BINARY, new Object[] { "not encoded properly" }); - } - - return bytes; - } - - public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context) - { - final byte[] bytes = lex(v, context); - if (bytes == null) return null; - - if (!sType.matchPatternFacet(v)) - { - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID$NO_VALUE, - new Object[] { "base 64", QNameHelper.readable(sType) }); - return null; - } - - return bytes; - } - - public byte[] getByteArrayValue() - { - check_dated(); - if (_value == null) - return null; - - byte[] result = new byte[_value.length]; - System.arraycopy(_value, 0, result, 0, _value.length); - return result; - } - - // setters - protected void set_ByteArray(byte[] ba) - { - _hashcached = false; - _value = new byte[ba.length]; - System.arraycopy(ba, 0, _value, 0, ba.length); - } - - // comparators - protected boolean equal_to(XmlObject i) - { - byte[] ival = ((XmlBase64Binary) i).getByteArrayValue(); - return Arrays.equals(_value, ival); - } - - //because computing hashcode is expensive we'll cache it - protected boolean _hashcached = false; - protected int hashcode = 0; - protected static MessageDigest md5; - static - { - try - { - md5 = MessageDigest.getInstance("MD5"); - } - catch( NoSuchAlgorithmException e ) - { - throw new IllegalStateException("Cannot find MD5 hash Algorithm"); - } - } - - protected int value_hash_code() - { - if( _hashcached ) - return hashcode; - - _hashcached = true; - - if( _value == null ) - return hashcode = 0; - - byte[] res = md5.digest(_value); - return hashcode = res[0]<<24 + res[1]<<16 + res[2]<<8 + res[3]; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java deleted file mode 100644 index 52d4f72..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaBase64HolderEx.java +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -public abstract class JavaBase64HolderEx extends JavaBase64Holder -{ - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } - - public JavaBase64HolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - protected int get_wscanon_rule() - { - return schemaType().getWhiteSpaceRule(); - } - - protected void set_text(String s) - { - final byte[] v; - - if (_validateOnSet()) - v = validateLexical(s, schemaType(), _voorVc); - else - v = lex(s, _voorVc); - - if (v != null && _validateOnSet()) - validateValue(v, schemaType(), XmlObjectBase._voorVc); - - super.set_ByteArray(v); - } - - // setters - protected void set_ByteArray(byte[] v) - { - if (_validateOnSet()) - validateValue(v, schemaType(), _voorVc); - - super.set_ByteArray(v); - } - - public static void validateValue(byte[] v, SchemaType sType, ValidationContext context) - { - int i; - XmlObject o; - - if ((o = sType.getFacet(SchemaType.FACET_LENGTH)) != null) - { - if ((i = ((XmlObjectBase)o).bigIntegerValue().intValue()) != v.length) - { - context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$BINARY, - new Object[] { "base64Binary", new Integer(v.length), new Integer(i), QNameHelper.readable(sType) } ); - } - } - - if ((o = sType.getFacet( SchemaType.FACET_MIN_LENGTH )) != null) - { - if ((i = ((XmlObjectBase)o).bigIntegerValue().intValue()) > v.length) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$BINARY, - new Object[] { "base64Binary", new Integer(v.length), new Integer(i), QNameHelper.readable(sType) } ); - } - } - - if ((o = sType.getFacet( SchemaType.FACET_MAX_LENGTH )) != null) - { - if ((i = ((XmlObjectBase)o).bigIntegerValue().intValue()) < v.length) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$BINARY, - new Object[] { "base64Binary", new Integer(v.length), new Integer(i), QNameHelper.readable(sType) } ); - } - } - - XmlObject[] vals = sType.getEnumerationValues(); - - if (vals != null) - { - enumLoop: for ( i = 0 ; i < vals.length ; i++ ) - { - byte[] enumBytes = ((XmlObjectBase)vals[i]).byteArrayValue(); - - if (enumBytes.length != v.length) - continue; - - for ( int j = 0 ; j < enumBytes.length ; j++ ) - if (enumBytes[j] != v[j]) - continue enumLoop; - - break; - } - - if (i >= vals.length) - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID$NO_VALUE, - new Object[] { "base64Binary", QNameHelper.readable(sType) }); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(byteArrayValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java deleted file mode 100644 index 4687e84..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java +++ /dev/null @@ -1,177 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -public class JavaDecimalHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_DECIMAL; } - - private BigDecimal _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // sets/gets raw text value - protected String compute_text(NamespaceManager nsm) { return XsTypeConverter.printDecimal(_value); } - protected void set_text(String s) - { - if (_validateOnSet()) - validateLexical(s, _voorVc); - - try { - set_BigDecimal(new BigDecimal(s)); - } - catch (NumberFormatException e) - { - _voorVc.invalid(XmlErrorCodes.DECIMAL, new Object[] { s }); - } - } - protected void set_nil() - { - _value = null; - } - - /** - * Performs lexical validation only. - */ - - public static void validateLexical(String v, ValidationContext context) - { - // TODO - will want to validate Chars with built in white space handling - // However, this fcn sometimes takes a value with wsr applied - // already - int l = v.length(); - int i = 0; - - if (i < l) - { - int ch = v.charAt(i); - - if (ch == '+' || ch == '-') - i++; - } - - boolean sawDot = false; - boolean sawDigit = false; - - for ( ; i < l ; i++ ) - { - int ch = v.charAt(i); - - if (ch == '.') - { - if (sawDot) - { - context.invalid(XmlErrorCodes.DECIMAL, - new Object[] { "saw '.' more than once: " + v }); - return; - } - - sawDot = true; - } - else if (ch >= '0' && ch <= '9') - { - sawDigit = true; - } - else - { - // TODO - may need to escape error char - context.invalid(XmlErrorCodes.DECIMAL, - new Object[] { "unexpected char '" + ch + "'" }); - return; - } - } - - if (!sawDigit) - { - context.invalid(XmlErrorCodes.DECIMAL, - new Object[] { "expected at least one digit" }); - return; - } - } - - // numerics: fractional - public BigDecimal getBigDecimalValue() { check_dated(); return _value; } - - // setters - protected void set_BigDecimal(BigDecimal v) { _value = v; } - - // comparators - protected int compare_to(XmlObject decimal) - { - return _value.compareTo(((XmlObjectBase)decimal).bigDecimalValue()); - } - protected boolean equal_to(XmlObject decimal) - { - return (_value.compareTo(((XmlObjectBase)decimal).bigDecimalValue())) == 0; - } - - static private BigInteger _maxlong = BigInteger.valueOf(Long.MAX_VALUE); - static private BigInteger _minlong = BigInteger.valueOf(Long.MIN_VALUE); - - /** - * Note, this is carefully aligned with hash codes for all xsd:decimal - * primitives. - */ - protected int value_hash_code() - { - if (_value.scale() > 0) - { - if (_value.setScale(0, BigDecimal.ROUND_DOWN).compareTo(_value) != 0) - return decimalHashCode(); - } - - BigInteger intval = _value.toBigInteger(); - - if (intval.compareTo(_maxlong) > 0 || - intval.compareTo(_minlong) < 0) - return intval.hashCode(); - - long longval = intval.longValue(); - - return (int)((longval >> 32) * 19 + longval); - } - - /** - * This method will has BigDecimals with the same arithmetic value to - * the same hash code (eg, 2.3 & 2.30 will have the same hash.) - * This differs from BigDecimal.hashCode() - */ - protected int decimalHashCode() { - assert _value.scale() > 0; - - // Get decimal value as string, and strip off zeroes on the right - String strValue = _value.toString(); - int i; - for (i = strValue.length() - 1 ; i >= 0 ; i --) - if (strValue.charAt(i) != '0') break; - - assert strValue.indexOf('.') < i; - - // Return the canonicalized string hashcode - return strValue.substring(0, i + 1).hashCode(); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java deleted file mode 100644 index a57ed56..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java +++ /dev/null @@ -1,215 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - - -import java.math.BigDecimal; - -public abstract class JavaDecimalHolderEx extends JavaDecimalHolder -{ - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } - - public JavaDecimalHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - protected void set_text(String s) - { - if (_validateOnSet()) - validateLexical(s, _schemaType, _voorVc); - - BigDecimal v = null; - try { - v = new BigDecimal(s); - } - catch (NumberFormatException e) - { - _voorVc.invalid(XmlErrorCodes.DECIMAL, new Object[] { s }); - } - - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - - super.set_BigDecimal(v); - } - - protected void set_BigDecimal(BigDecimal v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - super.set_BigDecimal(v); - } - - public static void validateLexical(String v, SchemaType sType, ValidationContext context) - { - JavaDecimalHolder.validateLexical(v, context); - - // check pattern - if (sType.hasPatternFacet()) - { - if (!sType.matchPatternFacet(v)) - { - // TODO - describe string and pattern here in error - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "decimal", v, QNameHelper.readable(sType) }); - } - } - } - - /** - * Performs facet validation only. - */ - - public static void validateValue(BigDecimal v, SchemaType sType, ValidationContext context) - { - // fractional digits - XmlObject fd = sType.getFacet(SchemaType.FACET_FRACTION_DIGITS); - if (fd != null) - { - int scale = ((XmlObjectBase)fd).getBigIntegerValue().intValue(); - try - { - // used only for side-effect - this does not change v despite - // the name of the method - v.setScale(scale); - } - catch(ArithmeticException e) - { - // ArithmeticException will be thrown if cannot represent as an Integer - // with this scale - i.e. would need a fraction which would correspond - // to digits beyond the allowed number - context.invalid(XmlErrorCodes.DATATYPE_FRACTION_DIGITS_VALID, - new Object[] { new Integer(v.scale()), v.toString(), new Integer(scale), QNameHelper.readable(sType) }); - return; - } - } - - // total digits - XmlObject td = sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); - if (td != null) - { - String temp = v.unscaledValue().toString(); - int tdf = ((XmlObjectBase)td).getBigIntegerValue().intValue(); - int origLen = temp.length(); - int len = origLen; - if (origLen > 0) - { - // don't count leading minus - if (temp.charAt(0) == '-') - { - len -= 1; - } - - // don't count trailing zeros if we can absorb them into scale - int insignificantTrailingZeros = 0; - int vScale = v.scale(); - for(int j = origLen-1; - temp.charAt(j) == '0' && j > 0 && insignificantTrailingZeros < vScale; - j--) - { - insignificantTrailingZeros++; - } - - len -= insignificantTrailingZeros; - } - - if (len > tdf) - { - context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, - new Object[] { new Integer(len), v.toString(), new Integer(tdf), QNameHelper.readable(sType) }); - return; - } - } - - // min ex - XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (mine != null) - { - BigDecimal m = ((XmlObjectBase)mine).getBigDecimalValue(); - if (v.compareTo(m) <= 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "decimal", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // min in - XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (mini != null) - { - BigDecimal m = ((XmlObjectBase)mini).getBigDecimalValue(); - if (v.compareTo(m) < 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "decimal", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // max in - XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (maxi != null) - { - BigDecimal m = ((XmlObjectBase)maxi).getBigDecimalValue(); - if (v.compareTo(m) > 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "decimal", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // max ex - XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (maxe != null) - { - BigDecimal m = ((XmlObjectBase)maxe).getBigDecimalValue(); - if (v.compareTo(m) >= 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "decimal", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // enumeration - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - if (v.equals(((XmlObjectBase)vals[i]).getBigDecimalValue())) - return; - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "decimal", v, QNameHelper.readable(sType) }); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(getBigDecimalValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java deleted file mode 100644 index bed9552..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolder.java +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -import java.math.BigDecimal; -import java.math.BigInteger; - -public abstract class JavaDoubleHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_DOUBLE; } - - double _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets/sets raw text value - protected String compute_text(NamespaceManager nsm) { return serialize(_value); } - - public static String serialize(double d) - { - if (d == Double.POSITIVE_INFINITY) - return "INF"; - else if (d == Double.NEGATIVE_INFINITY) - return "-INF"; - else if (d == Double.NaN) - return "NaN"; - else - return Double.toString(d); - } - protected void set_text(String s) - { - set_double(validateLexical(s,_voorVc)); - } - public static double validateLexical(String v, ValidationContext context) - { - try - { - return XsTypeConverter.lexDouble(v); - } - catch(NumberFormatException e) - { - context.invalid(XmlErrorCodes.DOUBLE, new Object[]{v}); - - return Double.NaN; - } - } - protected void set_nil() - { - _value = 0.0; - } - - // numerics: fractional - public BigDecimal getBigDecimalValue() { check_dated(); return new BigDecimal(_value); } - public double getDoubleValue() { check_dated(); return _value; } - public float getFloatValue() { check_dated(); return (float)_value; } - - // setters - protected void set_double(double v) { _value = v; } - protected void set_float(float v) { set_double((double)v); } - protected void set_long(long v) { set_double((double)v); } - protected void set_BigDecimal(BigDecimal v) { set_double(v.doubleValue()); } - protected void set_BigInteger(BigInteger v) { set_double(v.doubleValue()); } - - // comparators - protected int compare_to(XmlObject d) - { - return compare(_value,((XmlObjectBase)d).doubleValue()); - } - static int compare(double thisValue, double thatValue) - { - if (thisValue < thatValue) return -1; - if (thisValue > thatValue) return 1; - - long thisBits = Double.doubleToLongBits(thisValue); - long thatBits = Double.doubleToLongBits(thatValue); - - return thisBits == thatBits ? 0 : thisBits < thatBits ? -1 : 1; - } - - protected boolean equal_to(XmlObject d) - { - return compare(_value, ((XmlObjectBase)d).doubleValue()) == 0; - } - - protected int value_hash_code() - { - long v = Double.doubleToLongBits(_value); - return (int)((v >> 32) * 19 + v); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java deleted file mode 100644 index cda2984..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDoubleHolderEx.java +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - - - -public abstract class JavaDoubleHolderEx extends JavaDoubleHolder -{ - public JavaDoubleHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } - - protected void set_double(double v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - super.set_double(v); - } - - public static double validateLexical(String v, SchemaType sType, ValidationContext context) - { - double d = JavaDoubleHolder.validateLexical(v, context); - - if (!sType.matchPatternFacet(v)) - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "double", v, QNameHelper.readable(sType) }); - - return d; - } - - public static void validateValue(double v, SchemaType sType, ValidationContext context) - { - XmlObject x; - double d; - - if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) - { - if (compare(v, d = ((XmlObjectBase)x).doubleValue()) <= 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "double", new Double(v), new Double(d), QNameHelper.readable(sType) }); - } - } - - if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) - { - if (compare(v, d = ((XmlObjectBase)x).doubleValue()) < 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "double", new Double(v), new Double(d), QNameHelper.readable(sType) }); - } - } - - if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) - { - if (compare(v, d = ((XmlObjectBase)x).doubleValue()) > 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "double", new Double(v), new Double(d), QNameHelper.readable(sType) }); - } - } - - if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) - { - if (compare(v, d = ((XmlObjectBase)x).doubleValue()) >= 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "double", new Double(v), new Double(d), QNameHelper.readable(sType) }); - } - } - - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - if (compare(v, ((XmlObjectBase)vals[i]).doubleValue()) == 0) - return; - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "double", new Double(v), QNameHelper.readable(sType) }); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(doubleValue(), schemaType(), ctx); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolder.java deleted file mode 100644 index dad176d..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolder.java +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -import java.math.BigDecimal; -import java.math.BigInteger; - -public abstract class JavaFloatHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_FLOAT; } - - private float _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets+sets raw text value - protected String compute_text(NamespaceManager nsm) { - return serialize(_value); - } - - public static String serialize(float f) - { - if (f == Float.POSITIVE_INFINITY) - return "INF"; - else if (f == Float.NEGATIVE_INFINITY) - return "-INF"; - else if (f == Float.NaN) - return "NaN"; - else - return Float.toString(f); - } - protected void set_text(String s) - { - set_float(validateLexical(s,_voorVc)); - } - public static float validateLexical(String v, ValidationContext context) - { - try - { - return XsTypeConverter.lexFloat(v); - } - catch(NumberFormatException e) - { - context.invalid(XmlErrorCodes.FLOAT, new Object[]{v}); - - return Float.NaN; - } - } - protected void set_nil() - { - _value = 0.0f; - } - // numerics: fractional - public BigDecimal getBigDecimalValue() { check_dated(); return new BigDecimal(_value); } - public double getDoubleValue() { check_dated(); return _value; } - public float getFloatValue() { check_dated(); return _value; } - - // setters - protected void set_double(double v) { set_float((float)v); } - protected void set_float(float v) { _value = v; } - protected void set_long(long v) { set_float((float)v); } - protected void set_BigDecimal(BigDecimal v) { set_float(v.floatValue()); } - protected void set_BigInteger(BigInteger v) { set_float(v.floatValue()); } - - // comparators - protected int compare_to(XmlObject f) - { - return compare(_value,((XmlObjectBase)f).floatValue()); - } - - static int compare(float thisValue, float thatValue) - { - if (thisValue < thatValue) return -1; - if (thisValue > thatValue) return 1; - - int thisBits = Float.floatToIntBits(thisValue); - int thatBits = Float.floatToIntBits(thatValue); - - return thisBits == thatBits ? 0 : thisBits < thatBits ? -1 : 1; - } - - protected boolean equal_to(XmlObject f) - { - return compare(_value, ((XmlObjectBase)f).floatValue()) == 0; - } - - protected int value_hash_code() - { - return Float.floatToIntBits(_value); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java deleted file mode 100644 index c47d34d..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaFloatHolderEx.java +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - - - -public abstract class JavaFloatHolderEx extends JavaFloatHolder -{ - public JavaFloatHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } - - protected void set_float(float v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - super.set_float(v); - } - - public static float validateLexical(String v, SchemaType sType, ValidationContext context) - { - float f = JavaFloatHolder.validateLexical(v, context); - - if (!sType.matchPatternFacet(v)) - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "float", v, QNameHelper.readable(sType) }); - - return f; - } - - public static void validateValue(float v, SchemaType sType, ValidationContext context) - { - XmlObject x; - float f; - - if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) - { - if (compare(v, f = ((XmlObjectBase)x).floatValue()) <= 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "float", new Float(v), new Float(f), QNameHelper.readable(sType) }); - } - } - - if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) - { - if (compare(v, f = ((XmlObjectBase)x).floatValue()) < 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "float", new Float(v), new Float(f), QNameHelper.readable(sType) }); - } - } - - if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) - { - if (compare(v, f = ((XmlObjectBase)x).floatValue()) > 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "float", new Float(v), new Float(f), QNameHelper.readable(sType) }); - } - } - - if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) - { - if (compare(v, f = ((XmlObjectBase)x).floatValue()) >= 0) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "float", new Float(v), new Float(f), QNameHelper.readable(sType) }); - } - } - - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - if (compare(v, ((XmlObjectBase)vals[i]).floatValue()) == 0) - return; - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "float", new Float(v), QNameHelper.readable(sType) }); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(floatValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java deleted file mode 100644 index 36d0f25..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java +++ /dev/null @@ -1,319 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDateSpecification; -import org.apache.xmlbeans.GDateBuilder; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -import java.util.Date; -import java.util.Calendar; - -public abstract class JavaGDateHolderEx extends XmlObjectBase -{ - public JavaGDateHolderEx(SchemaType type, boolean complex) - { - _schemaType = type; - initComplexType(complex, false); - } - - public SchemaType schemaType() - { return _schemaType; } - - private SchemaType _schemaType; - private GDate _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // sets/gets raw text value - protected String compute_text(NamespaceManager nsm) - { return _value == null ? "" : _value.toString(); } - - protected void set_text(String s) - { - GDate newVal; - if (_validateOnSet()) - newVal = validateLexical(s, _schemaType, _voorVc); - else - newVal = lex(s, _schemaType, _voorVc); - - if (_validateOnSet() && newVal != null) - validateValue(newVal, _schemaType, _voorVc); - - _value = newVal; - } - - public static GDate lex(String v, SchemaType sType, ValidationContext context) - { - GDate date = null; - - try - { - date = new GDate(v); - } - catch (Exception e) - { - context.invalid(XmlErrorCodes.DATE, new Object[] { v }); - } - - if (date != null) - { - if (date.getBuiltinTypeCode() != sType.getPrimitiveType().getBuiltinTypeCode()) - { - context.invalid(XmlErrorCodes.DATE, new Object[] { "wrong type: " + v }); - date = null; - } - else if (!date.isValid()) - { - context.invalid(XmlErrorCodes.DATE, new Object[] { v }); - date = null; - } - } - - return date; - } - - public static GDate validateLexical(String v, SchemaType sType, ValidationContext context) - { - - GDate date = lex(v, sType, context); - - if (date != null && sType.hasPatternFacet()) - if (!sType.matchPatternFacet(v)) - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "date", v, QNameHelper.readable(sType) }); - - return date; - } - - public static void validateValue(GDateSpecification v, SchemaType sType, ValidationContext context) - { - XmlObject x; - GDate g; - - if (v.getBuiltinTypeCode() != sType.getPrimitiveType().getBuiltinTypeCode()) - context.invalid(XmlErrorCodes.DATE, new Object[] { "Date (" + v + ") does not have the set of fields required for " + QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) - if (v.compareToGDate(g = ((XmlObjectBase)x).gDateValue()) <= 0) - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "date", v, g, QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) - if (v.compareToGDate(g = ((XmlObjectBase)x).gDateValue()) < 0) - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "date", v, g, QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) - if (v.compareToGDate(g = ((XmlObjectBase)x).gDateValue()) >= 0) - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "date", v, g, QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) - if (v.compareToGDate(g = ((XmlObjectBase)x).gDateValue()) > 0) - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "date", v, g, QNameHelper.readable(sType) }); - - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - if (v.compareToGDate(((XmlObjectBase)vals[i]).gDateValue()) == 0) - return; - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "date", v, QNameHelper.readable(sType) }); - } - } - - protected void set_nil() - { - _value = null; - } - - // numerics: gYear, gMonth, gDay accept an integer - public int getIntValue() - { - int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); - - if (code != SchemaType.BTC_G_DAY && - code != SchemaType.BTC_G_MONTH && - code != SchemaType.BTC_G_YEAR) - throw new XmlValueOutOfRangeException(); - - check_dated(); - - if (_value == null) - return 0; - - switch (code) - { - case SchemaType.BTC_G_DAY: - return _value.getDay(); - case SchemaType.BTC_G_MONTH: - return _value.getMonth(); - case SchemaType.BTC_G_YEAR: - return _value.getYear(); - default: - assert(false); - throw new IllegalStateException(); - } - } - - public GDate getGDateValue() - { - check_dated(); - - if (_value == null) - return null; - - return _value; - } - - public Calendar getCalendarValue() - { - check_dated(); - - if (_value == null) - return null; - - return _value.getCalendar(); - } - - public Date getDateValue() - { - check_dated(); - - if (_value == null) - return null; - - return _value.getDate(); - } - - // setters - protected void set_int(int v) - { - int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); - - if (code != SchemaType.BTC_G_DAY && - code != SchemaType.BTC_G_MONTH && - code != SchemaType.BTC_G_YEAR) - throw new XmlValueOutOfRangeException(); - - GDateBuilder value = new GDateBuilder(); - - switch (code) - { - case SchemaType.BTC_G_DAY: - value.setDay(v); break; - case SchemaType.BTC_G_MONTH: - value.setMonth(v); break; - case SchemaType.BTC_G_YEAR: - value.setYear(v); break; - } - - if (_validateOnSet()) - validateValue(value, _schemaType, _voorVc); - - _value = value.toGDate(); - } - - protected void set_GDate(GDateSpecification v) - { - int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); - - GDate candidate; - - if (v.isImmutable() && (v instanceof GDate) && v.getBuiltinTypeCode() == code) - candidate = (GDate)v; - else - { - // truncate extra fields from the date if necessary. - if (v.getBuiltinTypeCode() != code) - { - GDateBuilder gDateBuilder = new GDateBuilder(v); - gDateBuilder.setBuiltinTypeCode(code); - v = gDateBuilder; - } - candidate = new GDate(v); - } - - if (_validateOnSet()) - validateValue(candidate, _schemaType, _voorVc); - - _value = candidate; - } - - protected void set_Calendar(Calendar c) - { - int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); - - GDateBuilder gDateBuilder = new GDateBuilder(c); - gDateBuilder.setBuiltinTypeCode(code); - GDate value = gDateBuilder.toGDate(); - - if (_validateOnSet()) - validateValue(value, _schemaType, _voorVc); - - _value = value; - } - - protected void set_Date(Date v) - { - int code = schemaType().getPrimitiveType().getBuiltinTypeCode(); - - if (code != SchemaType.BTC_DATE && code != SchemaType.BTC_DATE_TIME || - v == null) - throw new XmlValueOutOfRangeException(); - - GDateBuilder gDateBuilder = new GDateBuilder(v); - gDateBuilder.setBuiltinTypeCode(code); - GDate value = gDateBuilder.toGDate(); - - if (_validateOnSet()) - validateValue(value, _schemaType, _voorVc); - - _value = value; - } - - - // comparators - protected int compare_to(XmlObject obj) - { - return _value.compareToGDate(((XmlObjectBase)obj).gDateValue()); - } - - protected boolean equal_to(XmlObject obj) - { - return _value.equals(((XmlObjectBase)obj).gDateValue()); - } - - protected int value_hash_code() - { - return _value.hashCode(); - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(gDateValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java deleted file mode 100644 index cd002c5..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDurationHolderEx.java +++ /dev/null @@ -1,160 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.GDurationSpecification; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; - -public abstract class JavaGDurationHolderEx extends XmlObjectBase -{ - public JavaGDurationHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - GDuration _value; - private SchemaType _schemaType; - - public SchemaType schemaType() { return _schemaType; } - - protected void set_text(String s) - { - GDuration newVal; - if (_validateOnSet()) - newVal = validateLexical(s, _schemaType, _voorVc); - else - newVal = lex(s, _voorVc); - - if (_validateOnSet() && newVal != null) - validateValue(newVal, _schemaType, _voorVc); - - _value = newVal; - } - - protected void set_GDuration(GDurationSpecification v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - - if (v.isImmutable() && (v instanceof GDuration)) - _value = (GDuration)v; - else - _value = new GDuration(v); - } - - protected String compute_text(NamespaceManager nsm) - { return _value == null ? "" : _value.toString(); } - - protected void set_nil() - { - _value = null; - } - - public GDuration getGDurationValue() - { - check_dated(); - - return _value == null ? null : _value; - } - - public static GDuration lex(String v, ValidationContext context) - { - GDuration duration = null; - - try - { - duration = new GDuration(v); - } - catch (Exception e) - { - context.invalid(XmlErrorCodes.DURATION, new Object[] { v }); - } - - return duration; - } - - public static GDuration validateLexical(String v, SchemaType sType, ValidationContext context) - { - GDuration duration = lex(v, context); - - if (duration != null && sType.hasPatternFacet()) - if (!sType.matchPatternFacet(v)) - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "duration", v, QNameHelper.readable(sType) }); - - return duration; - } - - public static void validateValue(GDurationSpecification v, SchemaType sType, ValidationContext context) - { - XmlObject x; - GDuration g; - - if ((x = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE)) != null) - if (v.compareToGDuration(g = ((XmlObjectBase)x).gDurationValue()) <= 0) - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "duration", v, g, QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE)) != null) - if (v.compareToGDuration(g = ((XmlObjectBase)x).gDurationValue()) < 0) - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "duration", v, g, QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE)) != null) - if (v.compareToGDuration(g = ((XmlObjectBase)x).gDurationValue()) >= 0) - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "duration", v, g, QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE)) != null) - if (v.compareToGDuration(g = ((XmlObjectBase)x).gDurationValue()) > 0) - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "duration", v, g, QNameHelper.readable(sType) }); - - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - if (v.compareToGDuration(((XmlObjectBase)vals[i]).gDurationValue()) == 0) - return; - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "duration", v, QNameHelper.readable(sType) }); - } - } - - protected int compare_to(XmlObject d) - { - return _value.compareToGDuration(((XmlObjectBase) d).gDurationValue()); - } - - protected boolean equal_to(XmlObject d) - { - return _value.equals(((XmlObjectBase) d).gDurationValue()); - } - - protected int value_hash_code() - { - return _value.hashCode(); - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(gDurationValue(), schemaType(), ctx); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java deleted file mode 100644 index a0c026d..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java +++ /dev/null @@ -1,155 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; - -import org.apache.xmlbeans.impl.util.HexBin; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlHexBinary; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -import java.security.NoSuchAlgorithmException; -import java.security.MessageDigest; -import java.util.Arrays; -import java.io.UnsupportedEncodingException; - -public abstract class JavaHexBinaryHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_HEX_BINARY; } - - protected byte[] _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets raw text value - protected String compute_text(NamespaceManager nsm) - { - return new String(HexBin.encode(_value)); - } - protected void set_text(String s) - { - _hashcached = false; - if (_validateOnSet()) - _value = validateLexical(s, schemaType(), _voorVc); - else - _value = lex(s, _voorVc); - } - protected void set_nil() - { - _hashcached = false; - _value = null; - } - - public static byte[] lex(String v, ValidationContext context) - { - byte[] vBytes = null; - try - { - vBytes = v.getBytes("UTF-8"); - } - catch(UnsupportedEncodingException uee) - { - // should never happen - UTF-8 is always supported - } - byte[] bytes = HexBin.decode(vBytes); - - if (bytes == null) - { - // TODO - get a decent error with line numbers and such here - context.invalid(XmlErrorCodes.HEXBINARY, new Object[] { "not encoded properly" }); - } - - return bytes; - } - - public static byte[] validateLexical(String v, SchemaType sType, ValidationContext context) - { - byte[] bytes = lex(v, context); - - if (bytes == null) - return null; - - if (!sType.matchPatternFacet(v)) - { - context.invalid( "Hex encoded data does not match pattern for " + QNameHelper.readable(sType)); - return null; - } - - return bytes; - } - - public byte[] getByteArrayValue() - { - check_dated(); - if (_value == null) - return null; - - byte[] result = new byte[_value.length]; - System.arraycopy(_value, 0, result, 0, _value.length); - return result; - } - - // setters - protected void set_ByteArray(byte[] ba) - { - _hashcached = false; - _value = new byte[ba.length]; - System.arraycopy(ba, 0, _value, 0, ba.length); - } - - // comparators - protected boolean equal_to(XmlObject i) - { - byte[] ival = ((XmlHexBinary) i).getByteArrayValue(); - return Arrays.equals(_value, ival); - } - - //because computing hashcode is expensive we'll cache it - protected boolean _hashcached = false; - protected int hashcode = 0; - protected static MessageDigest md5; - static - { - try - { - md5 = MessageDigest.getInstance("MD5"); - } - catch( NoSuchAlgorithmException e ) - { - throw new IllegalStateException("Cannot find MD5 hash Algorithm"); - } - } - - protected int value_hash_code() - { - if( _hashcached ) - return hashcode; - - _hashcached = true; - - if( _value == null ) - return hashcode = 0; - - byte[] res = md5.digest(_value); - return hashcode = res[0]<<24 + res[1]<<16 + res[2]<<8 + res[3]; - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java deleted file mode 100644 index de94381..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaHexBinaryHolderEx.java +++ /dev/null @@ -1,128 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.ValidationContext; - - -public abstract class JavaHexBinaryHolderEx extends JavaHexBinaryHolder -{ - private SchemaType _schemaType; - - - public SchemaType schemaType() - { return _schemaType; } - - public JavaHexBinaryHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - protected int get_wscanon_rule() - { - return schemaType().getWhiteSpaceRule(); - } - - protected void set_text(String s) - { - byte[] v; - - if (_validateOnSet()) - v = validateLexical(s, schemaType(), _voorVc); - else - v = lex(s, _voorVc); - - if (_validateOnSet() && v != null) - validateValue(v, schemaType(), XmlObjectBase._voorVc); - - super.set_ByteArray(v); - - _value = v; - } - - // setters - protected void set_ByteArray(byte[] v) - { - if (_validateOnSet()) - validateValue(v, schemaType(), _voorVc); - - super.set_ByteArray(v); - } - - public static void validateValue(byte[] v, SchemaType sType, ValidationContext context) - { - int i; - XmlObject o; - - if ((o = sType.getFacet(SchemaType.FACET_LENGTH)) != null) - { - if ((i = ((XmlObjectBase)o).bigIntegerValue().intValue()) != v.length) - { - context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$BINARY, - new Object[] { "hexBinary", new Integer(v.length), new Integer(i), QNameHelper.readable(sType) } ); - } - } - - if ((o = sType.getFacet( SchemaType.FACET_MIN_LENGTH )) != null) - { - if ((i = ((XmlObjectBase)o).bigIntegerValue().intValue()) > v.length) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$BINARY, - new Object[] { "hexBinary", new Integer(v.length), new Integer(i), QNameHelper.readable(sType) } ); - } - } - - if ((o = sType.getFacet( SchemaType.FACET_MAX_LENGTH )) != null) - { - if ((i = ((XmlObjectBase)o).bigIntegerValue().intValue()) < v.length) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$BINARY, - new Object[] { "hexBinary", new Integer(v.length), new Integer(i), QNameHelper.readable(sType) } ); - } - } - - XmlObject[] vals = sType.getEnumerationValues(); - - if (vals != null) - { - enumLoop: for ( i = 0 ; i < vals.length ; i++ ) - { - byte[] enumBytes = ((XmlObjectBase)vals[i]).byteArrayValue(); - - if (enumBytes.length != v.length) - continue; - - for ( int j = 0 ; j < enumBytes.length ; j++ ) - if (enumBytes[j] != v[j]) - continue enumLoop; - - break; - } - - if (i >= vals.length) - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID$NO_VALUE, - new Object[] { "hexBinary", QNameHelper.readable(sType) }); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(byteArrayValue(), schemaType(), ctx); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolder.java deleted file mode 100644 index 6651b70..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolder.java +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SimpleValue; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -public abstract class JavaIntHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_INT; } - - private int _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets raw text value - public String compute_text(NamespaceManager nsm) { return Long.toString(_value); } - protected void set_text(String s) - { - try { set_int(XsTypeConverter.lexInt(s)); } - catch (Exception e) { throw new XmlValueOutOfRangeException(XmlErrorCodes.INT, new Object[] { s }); } - } - protected void set_nil() - { - _value = 0; - } - // numerics: fractional - public BigDecimal getBigDecimalValue() { check_dated(); return new BigDecimal((double) _value); } - public BigInteger getBigIntegerValue() { check_dated(); return BigInteger.valueOf(_value); } - public long getLongValue() { check_dated(); return _value; } - public int getIntValue() { check_dated(); return _value; } - - static final BigInteger _max = BigInteger.valueOf(Integer.MAX_VALUE); - static final BigInteger _min = BigInteger.valueOf(Integer.MIN_VALUE); - - // setters - protected void set_BigDecimal(BigDecimal v) { set_BigInteger(v.toBigInteger()); } - protected void set_BigInteger(BigInteger v) - { - if (v.compareTo(_max) > 0 || v.compareTo(_min) < 0) - throw new XmlValueOutOfRangeException(); - set_int(v.intValue()); - } - protected void set_long(long l) - { - if (l > Integer.MAX_VALUE || l < Integer.MIN_VALUE) - throw new XmlValueOutOfRangeException(); - set_int((int)l); - } - protected void set_int(int i) - { - _value = i; - } - - // comparators - protected int compare_to(XmlObject i) - { - if (((SimpleValue)i).instanceType().getDecimalSize() > SchemaType.SIZE_INT) - return -i.compareTo(this); - - return _value == ((XmlObjectBase)i).intValue() ? 0 : - _value < ((XmlObjectBase)i).intValue() ? -1 : 1; - } - - protected boolean equal_to(XmlObject i) - { - if (((SimpleValue)i).instanceType().getDecimalSize() > SchemaType.SIZE_INT) - return i.valueEquals(this); - - return _value == ((XmlObjectBase)i).intValue(); - } - - /** - * Note, this is carefully aligned with hash codes for all xsd:decimal - * primitives. - */ - protected int value_hash_code() - { - return _value; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java deleted file mode 100644 index d9faf73..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntHolderEx.java +++ /dev/null @@ -1,183 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -public abstract class JavaIntHolderEx extends JavaIntHolder -{ - public JavaIntHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - private SchemaType _schemaType; - - - public SchemaType schemaType() - { return _schemaType; } - - protected void set_text(String s) - { - int v; - - try { v = XsTypeConverter.lexInt(s); } - catch (Exception e) { throw new XmlValueOutOfRangeException(); } - - if (_validateOnSet()) - { - validateValue(v, _schemaType, _voorVc); - validateLexical(s, _schemaType, _voorVc); - } - - super.set_int(v); - } - - protected void set_int(int v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - - super.set_int(v); - } - - public static void validateLexical(String v, SchemaType sType, ValidationContext context) - { - JavaDecimalHolder.validateLexical(v, context); - - // check pattern - if (sType.hasPatternFacet()) - { - if (!sType.matchPatternFacet(v)) - { - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "int", v, QNameHelper.readable(sType) }); - } - } - } - - private static void validateValue(int v, SchemaType sType, ValidationContext context) - { - // total digits - XmlObject td = sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); - if (td != null) - { - String temp = Integer.toString(v); - int len = temp.length(); - if (len > 0 && temp.charAt(0) == '-') - len -= 1; - int m = getIntValue(td); - if (len > m) - { - context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, - new Object[] { new Integer(len), temp, new Integer(getIntValue(td)), QNameHelper.readable(sType) }); - return; - } - } - - // min ex - XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (mine != null) - { - int m = getIntValue(mine); - if (!(v > m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "int", new Integer(v), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // min in - XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (mini != null) - { - int m = getIntValue(mini); - if (!(v >= m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "int", new Integer(v), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // max in - XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (maxi != null) - { - int m = getIntValue(maxi); - if (!(v <= m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "int", new Integer(v), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // max ex - XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (maxe != null) - { - int m = getIntValue(maxe); - if (!(v < m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "int", new Integer(v), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // enumeration - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - { - if (v == getIntValue(vals[i])) - return; - } - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "int", new Integer(v), QNameHelper.readable(sType) }); - } - } - - private static int getIntValue(XmlObject o) { - SchemaType s = o.schemaType(); - switch (s.getDecimalSize()) - { - case SchemaType.SIZE_BIG_DECIMAL: - return ((XmlObjectBase)o).getBigDecimalValue().intValue(); - case SchemaType.SIZE_BIG_INTEGER: - return ((XmlObjectBase)o).getBigIntegerValue().intValue(); - case SchemaType.SIZE_LONG: - return (int)((XmlObjectBase)o).getLongValue(); - default: - return ((XmlObjectBase)o).getIntValue(); - } - - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(getIntValue(), schemaType(), ctx); - } - -} - diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java deleted file mode 100644 index 172f8a1..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolder.java +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.impl.common.ValidationContext; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; - -public abstract class JavaIntegerHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_INTEGER; } - - private BigInteger _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets/sets raw text value - protected String compute_text(NamespaceManager nsm) { return _value.toString(); } - protected void set_text(String s) - { - set_BigInteger(lex(s, _voorVc)); - } - public static BigInteger lex(String s, ValidationContext vc) - { - if (s.length() > 0 && s.charAt( 0 ) == '+' ) - s = s.substring(1); - - try { return new BigInteger(s); } - catch (Exception e) { vc.invalid(XmlErrorCodes.INTEGER, new Object[] { s }); return null; } - } - protected void set_nil() - { - _value = null; - } - // numerics: fractional - public BigDecimal getBigDecimalValue() { check_dated(); return _value == null ? null : new BigDecimal(_value); } - public BigInteger getBigIntegerValue() { check_dated(); return _value; } - - // setters - protected void set_BigDecimal(BigDecimal v) { _value = v.toBigInteger(); } - protected void set_BigInteger(BigInteger v) { _value = v; } - - // comparators - protected int compare_to(XmlObject i) - { - if (((SimpleValue)i).instanceType().getDecimalSize() > SchemaType.SIZE_BIG_INTEGER) - return -i.compareTo(this); - - return _value.compareTo(((XmlObjectBase)i).bigIntegerValue()); - } - - protected boolean equal_to(XmlObject i) - { - if (((SimpleValue)i).instanceType().getDecimalSize() > SchemaType.SIZE_BIG_INTEGER) - return i.valueEquals(this); - - return _value.equals(((XmlObjectBase)i).bigIntegerValue()); - } - - static private BigInteger _maxlong = BigInteger.valueOf(Long.MAX_VALUE); - static private BigInteger _minlong = BigInteger.valueOf(Long.MIN_VALUE); - - /** - * Note, this is carefully aligned with hash codes for all xsd:decimal - * primitives. - */ - protected int value_hash_code() - { - if (_value.compareTo(_maxlong) > 0 || - _value.compareTo(_minlong) < 0) - return _value.hashCode(); - - long longval = _value.longValue(); - - return (int)((longval >> 32) * 19 + longval); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java deleted file mode 100644 index cdee3ae..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaIntegerHolderEx.java +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlPositiveInteger; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -public class JavaIntegerHolderEx extends JavaIntegerHolder -{ - public JavaIntegerHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - private SchemaType _schemaType; - - - public SchemaType schemaType() - { return _schemaType; } - - protected void set_text(String s) - { - BigInteger v = lex(s, _voorVc); - - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - - if (_validateOnSet()) - validateLexical(s, _schemaType, _voorVc); - - super.set_BigInteger(v); - } - - protected void set_BigInteger(BigInteger v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - - super.set_BigInteger(v); - } - - public static void validateLexical(String v, SchemaType sType, ValidationContext context) - { - JavaDecimalHolder.validateLexical(v, context); - if ( v.lastIndexOf('.')>=0 ) - context.invalid(XmlErrorCodes.INTEGER, - new Object[] { v }); - - // check pattern - if (sType.hasPatternFacet()) - { - if (!sType.matchPatternFacet(v)) - { - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "integer", v, QNameHelper.readable(sType) }); - } - } - } - - private static void validateValue(BigInteger v, SchemaType sType, ValidationContext context) - { - // total digits - XmlPositiveInteger td = (XmlPositiveInteger)sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); - if (td != null) - { - String temp = v.toString(); - int len = temp.length(); - if (len > 0 && temp.charAt(0) == '-') - len -= 1; - if (len > td.getBigIntegerValue().intValue()) - { - context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, - new Object[] { new Integer(len), temp, new Integer(td.getBigIntegerValue().intValue()), QNameHelper.readable(sType) }); - return; - } - } - - // min ex - XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (mine != null) - { - BigInteger m = getBigIntegerValue(mine); - if (!(v.compareTo(m) > 0)) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "integer", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // min in - XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (mini != null) - { - BigInteger m = getBigIntegerValue(mini); - if (!(v.compareTo(m) >= 0)) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "integer", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // max in - XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (maxi != null) - { - BigInteger m = getBigIntegerValue(maxi); - if (!(v.compareTo(m) <= 0)) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "integer", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // max ex - XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (maxe != null) - { - BigInteger m = getBigIntegerValue(maxe); - if (!(v.compareTo(m) < 0)) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "integer", v, m, QNameHelper.readable(sType) }); - return; - } - } - - // enumeration - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - { - if (v.equals(getBigIntegerValue(vals[i]))) - return; - } - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "integer", v, QNameHelper.readable(sType) }); - } - } - - private static BigInteger getBigIntegerValue(XmlObject o) - { - SchemaType s = o.schemaType(); - switch (s.getDecimalSize()) - { - case SchemaType.SIZE_BIG_DECIMAL: - return ((XmlObjectBase)o).bigDecimalValue().toBigInteger(); - case SchemaType.SIZE_BIG_INTEGER: - return ((XmlObjectBase)o).bigIntegerValue(); - default: - throw new IllegalStateException("Bad facet type for Big Int: " + s); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(getBigIntegerValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolder.java deleted file mode 100644 index 296c5ee..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolder.java +++ /dev/null @@ -1,95 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SimpleValue; - -import java.math.BigInteger; -import java.math.BigDecimal; - -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -public abstract class JavaLongHolder extends XmlObjectBase -{ - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_LONG; } - - private long _value; - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // gets raw text value - protected String compute_text(NamespaceManager nsm) { return Long.toString(_value); } - protected void set_text(String s) - { - try { set_long(XsTypeConverter.lexLong(s)); } - catch (Exception e) { throw new XmlValueOutOfRangeException(XmlErrorCodes.LONG, new Object[] { s }); } - } - protected void set_nil() - { - _value = 0L; - } - - // numerics: fractional - public BigDecimal getBigDecimalValue() { check_dated(); return BigDecimal.valueOf(_value); } - public BigInteger getBigIntegerValue() { check_dated(); return BigInteger.valueOf(_value); } - public long getLongValue() { check_dated(); return _value; } - - private static final BigInteger _max = BigInteger.valueOf(Long.MAX_VALUE); - private static final BigInteger _min = BigInteger.valueOf(Long.MIN_VALUE); - - // setters - protected void set_BigDecimal(BigDecimal v) { set_BigInteger(v.toBigInteger()); } - protected void set_BigInteger(BigInteger v) - { - if (v.compareTo(_max) > 0 || v.compareTo(_min) < 0) - throw new XmlValueOutOfRangeException(); - _value = v.longValue(); - } - protected void set_long(long l) { _value = l; } - - // comparators - protected int compare_to(XmlObject l) - { - if (((SimpleValue)l).instanceType().getDecimalSize() > SchemaType.SIZE_LONG) - return -l.compareTo(this); - - return _value == ((XmlObjectBase)l).longValue() ? 0 : - _value < ((XmlObjectBase)l).longValue() ? -1 : 1; - } - - protected boolean equal_to(XmlObject l) - { - if (((SimpleValue)l).instanceType().getDecimalSize() > SchemaType.SIZE_LONG) - return l.valueEquals(this); - - return _value == ((XmlObjectBase)l).longValue(); - } - - /** - * Note, this is carefully aligned with hash codes for all xsd:decimal - * primitives. - */ - protected int value_hash_code() - { - return (int)((_value >> 32) * 19 + _value); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java deleted file mode 100644 index 57db2a5..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaLongHolderEx.java +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.util.XsTypeConverter; - -public abstract class JavaLongHolderEx extends JavaLongHolder -{ - public JavaLongHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - private SchemaType _schemaType; - - - public SchemaType schemaType() - { return _schemaType; } - - protected void set_text(String s) - { - long v; - - try { v = XsTypeConverter.lexLong(s); } - catch (Exception e) { throw new XmlValueOutOfRangeException(); } - - if (_validateOnSet()) - { - validateValue(v, _schemaType, _voorVc); - validateLexical(s, _schemaType, _voorVc); - } - - super.set_long(v); - } - - protected void set_long(long v) - { - if (_validateOnSet()) - validateValue(v, _schemaType, _voorVc); - - super.set_long(v); - } - - public static void validateLexical(String v, SchemaType sType, ValidationContext context) - { - JavaDecimalHolder.validateLexical(v, context); - - // check pattern - if (sType.hasPatternFacet()) - { - if (!sType.matchPatternFacet(v)) - { - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "long", v, QNameHelper.readable(sType) }); - } - } - } - - private static void validateValue(long v, SchemaType sType, ValidationContext context) - { - // total digits - XmlObject td = sType.getFacet(SchemaType.FACET_TOTAL_DIGITS); - if (td != null) - { - long m = getLongValue(td); - String temp = Long.toString(v); - int len = temp.length(); - if (len > 0 && temp.charAt(0) == '-') - len -= 1; - if (len > m) - { - context.invalid(XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID, - new Object[] { new Integer(len), temp, new Long(m), QNameHelper.readable(sType) }); - return; - } - } - - // min ex - XmlObject mine = sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE); - if (mine != null) - { - long m = getLongValue(mine); - if (!(v > m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID, - new Object[] { "long", new Long(v), new Long(m), QNameHelper.readable(sType) }); - return; - } - } - - // min in - XmlObject mini = sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE); - if (mini != null) - { - long m = getLongValue(mini); - if (!(v >= m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID, - new Object[] { "long", new Long(v), new Long(m), QNameHelper.readable(sType) }); - return; - } - } - - // max in - XmlObject maxi = sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE); - if (maxi != null) - { - long m = getLongValue(maxi); - if (!(v <= m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID, - new Object[] { "long", new Long(v), new Long(m), QNameHelper.readable(sType) }); - return; - } - } - - // max ex - XmlObject maxe = sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE); - if (maxe != null) - { - long m = getLongValue(maxe); - if (!(v < m)) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID, - new Object[] { "long", new Long(v), new Long(m), QNameHelper.readable(sType) }); - return; - } - } - - // enumeration - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - { - if (v == getLongValue(vals[i])) - return; - } - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "long", new Long(v), QNameHelper.readable(sType) }); - } - } - - private static long getLongValue(XmlObject o) { - SchemaType s = o.schemaType(); - switch (s.getDecimalSize()) - { - case SchemaType.SIZE_BIG_DECIMAL: - return ((XmlObjectBase)o).getBigDecimalValue().longValue(); - case SchemaType.SIZE_BIG_INTEGER: - return ((XmlObjectBase)o).getBigIntegerValue().longValue(); - case SchemaType.SIZE_LONG: - return ((XmlObjectBase)o).getLongValue(); - default: - throw new IllegalStateException("Bad facet type: " + s); - } - - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(lexical, schemaType(), ctx); - validateValue(getLongValue(), schemaType(), ctx); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java deleted file mode 100644 index 2035929..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java +++ /dev/null @@ -1,199 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.impl.common.PrefixResolver; -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.XMLChar; -import org.apache.xmlbeans.impl.common.QNameHelper; - -import javax.xml.namespace.QName; -import org.apache.xmlbeans.impl.values.NamespaceContext; - -public class JavaQNameHolder extends XmlObjectBase -{ - public JavaQNameHolder() {} - - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_QNAME; } - - private QName _value; - - protected int get_wscanon_rule() - { return SchemaType.WS_PRESERVE; } - - // an ergonomic prefixer so that you can say stringValue() on a free-floating QName. - private static final NamespaceManager PRETTY_PREFIXER = new PrettyNamespaceManager(); - - private static class PrettyNamespaceManager implements NamespaceManager - { - public String find_prefix_for_nsuri(String nsuri, String suggested_prefix) - { - return QNameHelper.suggestPrefix(nsuri); - } - public String getNamespaceForPrefix(String prefix) - { - throw new RuntimeException( "Should not be called" ); - } - } - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - public String compute_text(NamespaceManager nsm) - { - if (nsm == null) - { - // we used to: throw new IllegalStateException("Cannot create QName prefix outside of a document"); - // but it's not nice to throw on stringValue() - nsm = PRETTY_PREFIXER; - } - -// TODO - what I really need to do here is that if there is no -// namespace for this qname, then instead of finding the prefix for the -// uri, I should make a call to set the default namespace for the -// immediate context for this qname to be "". - - String namespace = _value.getNamespaceURI(); - String localPart = _value.getLocalPart(); - - if (namespace == null || namespace.length() == 0) - return localPart; - - String prefix = nsm.find_prefix_for_nsuri( namespace, null ); - - assert prefix != null; - - return "".equals(prefix) ? localPart : prefix + ":" + localPart; - } - - public static QName validateLexical( - String v, ValidationContext context, PrefixResolver resolver) - { - QName name; - - try - { - name = parse(v, resolver); - } - catch ( XmlValueOutOfRangeException e ) - { - context.invalid(e.getMessage()); - name = null; - } - - return name; - } - - private static QName parse(String v, PrefixResolver resolver) - { - String prefix, localname; - int start; - int end; - for (end = v.length(); end > 0; end -= 1) - if (!XMLChar.isSpace(v.charAt(end-1))) - break; - for (start = 0; start < end; start += 1) - if (!XMLChar.isSpace(v.charAt(start))) - break; - - int firstcolon = v.indexOf(':', start); - if (firstcolon >= 0) - { - prefix = v.substring(start, firstcolon); - localname = v.substring(firstcolon + 1, end); - } - else - { - prefix = ""; - localname = v.substring(start, end); - } - - if ( prefix.length()>0 && !XMLChar.isValidNCName(prefix) ) - throw new XmlValueOutOfRangeException(XmlErrorCodes.QNAME, new Object[] { "Prefix not a valid NCName in '" + v + "'" }); - - if ( !XMLChar.isValidNCName(localname) ) - throw new XmlValueOutOfRangeException(XmlErrorCodes.QNAME, new Object[] { "Localname not a valid NCName in '" + v + "'" }); - - String uri = - resolver == null ? null : resolver.getNamespaceForPrefix(prefix); - - if (uri == null) - { - if (prefix.length() > 0) - throw new XmlValueOutOfRangeException(XmlErrorCodes.QNAME, new Object[] { "Can't resolve prefix '" + prefix + "'"}); - - uri = ""; - } - - if ( prefix!=null && prefix.length()>0 ) - return new QName(uri, localname, prefix ); - else - return new QName( uri, localname ); - } - - protected void set_text(String s) - { - PrefixResolver resolver = NamespaceContext.getCurrent(); - - if (resolver == null && has_store()) - resolver = get_store(); - - _value = parse(s, resolver); - } - - // BUGBUG - having prefix here may not work - protected void set_QName(QName name) - { - assert name != null; - - // Sync force of creation of namesapce mapping .. - - if (has_store()) - get_store().find_prefix_for_nsuri( name.getNamespaceURI(), null ); - - _value = name; - } - - protected void set_xmlanysimple(XmlAnySimpleType value) - { - _value = parse(value.getStringValue(), NamespaceContext.getCurrent()); - } - - protected void set_nil() { _value = null; } - - // setters, getters (setter already handled via set_text) - - public QName getQNameValue() - { - check_dated(); - return _value; - } - - // comparators - protected boolean equal_to(XmlObject obj) - { - return _value.equals(((XmlObjectBase)obj).qNameValue()); - } - - protected int value_hash_code() - { - return _value.hashCode(); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolder.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolder.java deleted file mode 100644 index 0247270..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolder.java +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; - -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; - -public class JavaStringHolder extends XmlObjectBase -{ - public JavaStringHolder() {} - - public SchemaType schemaType() - { return BuiltinSchemaTypeSystem.ST_STRING; } - - private String _value; - - protected int get_wscanon_rule() - { return SchemaType.WS_PRESERVE; } - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - public String compute_text(NamespaceManager nsm) { return _value; } - protected void set_text(String s) { _value = s; } - protected void set_nil() { _value = null; } - - // string setter and getter already handled by XmlObjectBase - - // comparators - protected boolean equal_to(XmlObject obj) - { - return _value.equals(((XmlObjectBase)obj).stringValue()); - } - - protected int value_hash_code() - { - return _value.hashCode(); - } - protected boolean is_defaultable_ws(String v) - { - return false; - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java deleted file mode 100644 index 0d74df7..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaStringHolderEx.java +++ /dev/null @@ -1,129 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -public abstract class JavaStringHolderEx extends JavaStringHolder -{ - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } - - public JavaStringHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - protected int get_wscanon_rule() - { - return schemaType().getWhiteSpaceRule(); - } - - protected void set_text(String s) - { - if (_validateOnSet()) - validateLexical(s, _schemaType, _voorVc); - - super.set_text(s); - } - - protected boolean is_defaultable_ws(String v) { - try { - validateLexical(v, _schemaType, _voorVc); - return false; - } - catch (XmlValueOutOfRangeException e) { - return true; - } - } - - public static void validateLexical(String v, SchemaType sType, ValidationContext context) - { - // check against pattern - if (!sType.matchPatternFacet(v)) - { - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, new Object[] { "string", v, QNameHelper.readable(sType) }); - return; - } - - // check against length - XmlObject len = sType.getFacet(SchemaType.FACET_LENGTH); - if (len != null) - { - int m = ((XmlObjectBase)len).bigIntegerValue().intValue(); - if (v.length() != m) - { - context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$STRING, - new Object[] { "string", new Integer(v.length()), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // check against min length - XmlObject min = sType.getFacet(SchemaType.FACET_MIN_LENGTH); - if (min != null) - { - int m = ((XmlObjectBase)min).bigIntegerValue().intValue(); - if (v.length() < m) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING, - new Object[] { "string", new Integer(v.length()), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // check against min length - XmlObject max = sType.getFacet(SchemaType.FACET_MAX_LENGTH); - if (max != null) - { - int m = ((XmlObjectBase)max).bigIntegerValue().intValue(); - if (v.length() > m) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING, - new Object[] { "string", new Integer(v.length()), new Integer(m), QNameHelper.readable(sType) }); - return; - } - } - - // enumeration - // NOTE: can't use .hasStringEnumValues() or .enumForString() - // here since we may be validating against a string enum value - // during StscSimpleTypeResolver.resolveFacets() and the string - // enum table hasn't been constructed yet. - XmlAnySimpleType[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - { - if (v.equals(vals[i].getStringValue())) - return; - } - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "string", v, QNameHelper.readable(sType) }); - } - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(stringValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java b/src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java deleted file mode 100644 index 566be4e..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/JavaUriHolderEx.java +++ /dev/null @@ -1,153 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -public class JavaUriHolderEx extends JavaUriHolder -{ - private SchemaType _schemaType; - - public SchemaType schemaType() - { return _schemaType; } - - public JavaUriHolderEx(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - protected int get_wscanon_rule() - { - return schemaType().getWhiteSpaceRule(); - } - - protected void set_text(String s) - { - if (_validateOnSet()) - { - if (!check(s, _schemaType)) - throw new XmlValueOutOfRangeException(); - - if (!_schemaType.matchPatternFacet(s)) - throw new XmlValueOutOfRangeException(); - } - - super.set_text(s); - } - -// // setters -// protected void set_uri(URI uri) -// { -// if (!check(uri.toString(), _schemaType)) -// throw new XmlValueOutOfRangeException(); -// -// super.set_uri(uri); -// } - - public static void validateLexical(String v, SchemaType sType, ValidationContext context) - { - XmlAnyUriImpl.validateLexical(v, context); - - XmlObject[] vals = sType.getEnumerationValues(); - - if (vals != null) - { - int i; - - for ( i = 0 ; i < vals.length ; i++ ) - { - String e = ((SimpleValue)vals[i]).getStringValue(); - - if (e.equals( v )) - break; - } - - if (i >= vals.length) - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "anyURI", v, QNameHelper.readable(sType) }); - } - - // check pattern - if (sType.hasPatternFacet()) - { - if (!sType.matchPatternFacet(v)) - { - // TODO - describe string and pattern here in error - context.invalid(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "anyURI", v, QNameHelper.readable(sType) }); - } - } - - XmlObject x; - int i; - - if ((x = sType.getFacet(SchemaType.FACET_LENGTH)) != null) - if ((i = ((SimpleValue)x).getBigIntegerValue().intValue()) != v.length()) - context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$STRING, - new Object[] { "anyURI", v, new Integer(i), QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MIN_LENGTH)) != null) - if ((i = ((SimpleValue)x).getBigIntegerValue().intValue()) > v.length()) - context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING, - new Object[] { "anyURI", v, new Integer(i), QNameHelper.readable(sType) }); - - if ((x = sType.getFacet(SchemaType.FACET_MAX_LENGTH)) != null) - if ((i = ((SimpleValue)x).getBigIntegerValue().intValue()) < v.length()) - context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING, - new Object[] { "anyURI", v, new Integer(i), QNameHelper.readable(sType) }); - } - - private static boolean check(String v, SchemaType sType) - { - int length = v==null ? 0 : v.length(); - // check against length - XmlObject len = sType.getFacet(SchemaType.FACET_LENGTH); - if (len != null) - { - int m = ((SimpleValue)len).getBigIntegerValue().intValue(); - if (!(length != m)) - return false; - } - - // check against min length - XmlObject min = sType.getFacet(SchemaType.FACET_MIN_LENGTH); - if (min != null) - { - int m = ((SimpleValue)min).getBigIntegerValue().intValue(); - if (!(length >= m)) - return false; - } - - // check against min length - XmlObject max = sType.getFacet(SchemaType.FACET_MAX_LENGTH); - if (max != null) - { - int m = ((SimpleValue)max).getBigIntegerValue().intValue(); - if (!(length <= m)) - return false; - } - - return true; - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateLexical(stringValue(), schemaType(), ctx); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java deleted file mode 100644 index 3ffe7e7..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlAnySimpleTypeImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem; - -/** - * This class implements the anySimpleType for XML. - * - */ -public class XmlAnySimpleTypeImpl extends XmlObjectBase implements XmlAnySimpleType -{ - public XmlAnySimpleTypeImpl(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - public XmlAnySimpleTypeImpl() - { _schemaType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE; } - - public SchemaType schemaType() - { return _schemaType; } - - private SchemaType _schemaType; - - String _textvalue = ""; - - protected int get_wscanon_rule() - { - return SchemaType.WS_PRESERVE; - } - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - // gets raw text value - protected String compute_text(NamespaceManager nsm) { return _textvalue; } - protected void set_text(String s) - { - _textvalue = s; - } - - protected void set_nil() - { - _textvalue = null; - } - - // comparators - protected boolean equal_to(XmlObject obj) - { - // compares against another anySimpleType - // rule is: lexical values must match. - return _textvalue.equals(((XmlAnySimpleType)obj).getStringValue()); - } - - protected int value_hash_code() - { - // matches JavaStringHolder's value_hash_code, so we can be hased against strings - return (_textvalue == null ? 0 : _textvalue.hashCode()); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java deleted file mode 100644 index fb279ff..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java +++ /dev/null @@ -1,1335 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.*; - -import java.lang.String; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Date; -import java.util.List; -import java.util.Calendar; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; -import org.apache.xmlbeans.impl.schema.SchemaTypeVisitorImpl; - -public class XmlComplexContentImpl extends XmlObjectBase -{ - public XmlComplexContentImpl(SchemaType type) - { - _schemaType = (SchemaTypeImpl)type; - initComplexType(true, true); - } - - public SchemaType schemaType() - { return _schemaType; } - - private SchemaTypeImpl _schemaType; - - public String compute_text(NamespaceManager nsm) - { return null; } - - protected final void set_String(String v) - { - assert _schemaType.getContentType() != SchemaType.SIMPLE_CONTENT; - - if (_schemaType.getContentType() != SchemaType.MIXED_CONTENT && - !_schemaType.isNoType()) - { - throw new IllegalArgumentException( - "Type does not allow for textual content: " + _schemaType ); - } - - super.set_String(v); - } - - public void set_text(String str) - { - assert - _schemaType.getContentType() == SchemaType.MIXED_CONTENT || - _schemaType.isNoType(); - } - - protected void update_from_complex_content() - { - // No complex caching yet ... - } - - public void set_nil() - { /* BUGBUG: what to do? */ } - - // LEFT - public boolean equal_to(XmlObject complexObject) - { - if (!_schemaType.equals(complexObject.schemaType())) - return false; - - // BUGBUG: by-value structure comparison undone - return true; - } - - // LEFT - protected int value_hash_code() - { - throw new IllegalStateException("Complex types cannot be used as hash keys"); - } - - // DONE - public TypeStoreVisitor new_visitor() - { - return new SchemaTypeVisitorImpl(_schemaType.getContentModel()); - } - - // DONE - public boolean is_child_element_order_sensitive() - { - return schemaType().isOrderSensitive(); - } - - public int get_elementflags(QName eltName) - { - SchemaProperty prop = schemaType().getElementProperty(eltName); - if (prop == null) - return 0; - if (prop.hasDefault() == SchemaProperty.VARIABLE || - prop.hasFixed() == SchemaProperty.VARIABLE || - prop.hasNillable() == SchemaProperty.VARIABLE) - return -1; - return - (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | - (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED) | - (prop.hasNillable() == SchemaProperty.NEVER ? 0 : TypeStore.NILLABLE); - } - - // DONE - public String get_default_attribute_text(QName attrName) - { - return super.get_default_attribute_text(attrName); - } - - // DONE - public String get_default_element_text(QName eltName) - { - SchemaProperty prop = schemaType().getElementProperty(eltName); - if (prop == null) - return ""; - return prop.getDefaultText(); - } - - // - // Code gen helpers - // - // So much redundant code ..... what I'd give for generics! - // - - protected void unionArraySetterHelper ( Object[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).objectSet( sources[ i ] ); - } - } - - protected SimpleValue[] arraySetterHelper ( int sourcesLength, QName elemName ) - { - SimpleValue[] dests = new SimpleValue[sourcesLength]; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > sourcesLength ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < sourcesLength ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - dests[i] = (SimpleValue) user; - } - - return dests; - } - - protected SimpleValue[] arraySetterHelper ( int sourcesLength, QName elemName, QNameSet set ) - { - SimpleValue[] dests = new SimpleValue[sourcesLength]; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > sourcesLength ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < sourcesLength ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - dests[i] = (SimpleValue) user; - } - - return dests; - } - - protected void arraySetterHelper ( boolean[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( float[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( double[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( byte[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( short[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( int[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( long[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( BigDecimal[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( BigInteger[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( String[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( byte[][] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( GDate[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( GDuration[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( Calendar[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( Date[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( QName[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( StringEnumAbstractBase[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( List[] sources, QName elemName ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( elemName ); - - for ( ; m > n ; m-- ) - store.remove_element( elemName, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void unionArraySetterHelper ( Object[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).objectSet( sources[ i ] ); - } - } - - protected void arraySetterHelper ( boolean[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( float[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( double[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( byte[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( short[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( int[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( long[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( BigDecimal[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( BigInteger[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( String[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( byte[][] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( GDate[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( GDuration[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( Calendar[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( Date[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( QName[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( StringEnumAbstractBase[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( List[] sources, QName elemName, QNameSet set ) - { - int n = sources == null ? 0 : sources.length; - - TypeStore store = get_store(); - - int m = store.count_elements( set ); - - for ( ; m > n ; m-- ) - store.remove_element( set, m - 1 ); - - for ( int i = 0 ; i < n ; i++ ) - { - TypeStoreUser user; - - if (i >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, i ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - - protected void arraySetterHelper ( XmlObject[] sources, QName elemName ) - { - TypeStore store = get_store(); - - if (sources == null || sources.length == 0) - { - int m = store.count_elements( elemName ); - for ( ; m > 0 ; m-- ) - store.remove_element( elemName, 0 ); - return; - } - - // Verify if the sources contain children of this node - int i; - int m = store.count_elements( elemName ); // how many elements in the original array - int startSrc = 0, startDest = 0; - for (i = 0; i < sources.length; i++) - { - if (sources[i].isImmutable()) - continue; - XmlCursor c = sources[i].newCursor(); - if (c.toParent() && c.getObject() == this) - { - c.dispose(); - break; - } - c.dispose(); - } - if (i < sources.length) - { - TypeStoreUser current = store.find_element_user( elemName, 0 ); - if (current == sources[i]) - { - // The new object matches what already exists in the array - // Heuristic: we optimize for the case where the new elements - // in the array are the same as the existing elements with - // potentially new elements inserted - - // First insert the new element in the array at position 0 - int j = 0; - for ( j = 0; j < i; j++ ) - { - TypeStoreUser user = store.insert_element_user( elemName, j ); - ((XmlObjectBase) user).set( sources[j] ); - } - for ( i++, j++; i < sources.length; i++, j++) - { - XmlCursor c = sources[i].isImmutable() ? null : sources[i].newCursor(); - if (c != null && c.toParent() && c.getObject() == this) - { - c.dispose(); - current = store.find_element_user( elemName, j ); - if (current == sources[i]) - ; // advance - else - { - // Fall back to the general case - break; - } - } - else - { - c.dispose(); - // Insert before the current element - TypeStoreUser user = store.insert_element_user( elemName, j ); - ((XmlObjectBase) user).set( sources[i] ); - } - } - startDest = j; - startSrc = i; - m = store.count_elements( elemName ); - } - // Fall through - } - else - { - // All of the elements in the existing array are to - // be deleted and replaced with elements from the - // sources array - } - - // The general case: we assume that some of the elements - // in the new array already exist, but at different indexes - - // Starting with position i in the sources array, copy the remaining elements - // to the end of the original array... - for (int j = i; j < sources.length; j++) - { - TypeStoreUser user = store.add_element_user( elemName ); - ((XmlObjectBase) user).set( sources[ j ] ); - } - - // ... then come back and insert the elements starting with startSource - // up to i from the sources array into the current array, starting with - // startDest - int n = i; - for ( ; m > n - startSrc + startDest; m-- ) - store.remove_element( elemName, m - 1 ); - - int j; - for ( i = startSrc, j = startDest ; i < n ; i++, j++ ) - { - TypeStoreUser user; - - if (j >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( elemName, j ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - - // We can't just delegate to array_setter because we need - // synchronization on the sources (potentially each element - // in the array on a different lock) -// get_store().array_setter( sources, elemName ); - } - - protected void arraySetterHelper ( XmlObject[] sources, QName elemName, QNameSet set ) - { - TypeStore store = get_store(); - - if (sources == null || sources.length == 0) - { - int m = store.count_elements( set ); - for ( ; m > 0 ; m-- ) - store.remove_element( set, 0 ); - return; - } - - // Verify if the sources contain children of this node - int i; - int m = store.count_elements( set ); // how many elements in the original array - int startSrc = 0, startDest = 0; - for (i = 0; i < sources.length; i++) - { - if (sources[i].isImmutable()) - continue; - XmlCursor c = sources[i].newCursor(); - if (c.toParent() && c.getObject() == this) - { - c.dispose(); - break; - } - c.dispose(); - } - if (i < sources.length) - { - TypeStoreUser current = store.find_element_user( set, 0 ); - if (current == sources[i]) - { - // The new object matches what already exists in the array - // Heuristic: we optimize for the case where the new elements - // in the array are the same as the existing elements with - // potentially new elements inserted - - // First insert the new element in the array at position 0 - int j = 0; - for ( j = 0; j < i; j++ ) - { - TypeStoreUser user = store.insert_element_user( set, elemName, j ); - ((XmlObjectBase) user).set( sources[j] ); - } - for ( i++, j++; i < sources.length; i++, j++) - { - XmlCursor c = sources[i].isImmutable() ? null : sources[i].newCursor(); - if (c != null && c.toParent() && c.getObject() == this) - { - c.dispose(); - current = store.find_element_user( set, j ); - if (current == sources[i]) - ; // advance - else - { - // Fall back to the general case - break; - } - } - else - { - c.dispose(); - // Insert before the current element - TypeStoreUser user = store.insert_element_user( set, elemName, j ); - ((XmlObjectBase) user).set( sources[i] ); - } - } - startDest = j; - startSrc = i; - m = store.count_elements( elemName ); - } - // Fall through - } - else - { - // All of the elements in the existing array are to - // be deleted and replaced with elements from the - // sources array - } - - // The general case: we assume that some of the elements - // in the new array already exist, but at different indexes - - // Starting with position i in the sources array, copy the remaining elements - // to the end of the original array... - for (int j = i; j < sources.length; j++) - { - TypeStoreUser user = store.add_element_user( elemName ); - ((XmlObjectBase) user).set( sources[ j ] ); - } - - // ... then come back and insert the elements starting with startSource - // up to i from the sources array into the current array, starting with - // startDest - int n = i; - for ( ; m > n - startSrc + startDest; m-- ) - store.remove_element( set, m - 1 ); - - int j; - for ( i = startSrc, j = startDest ; i < n ; i++, j++ ) - { - TypeStoreUser user; - - if (j >= m) - user = store.add_element_user( elemName ); - else - user = store.find_element_user( set, j ); - - ((XmlObjectBase) user).set( sources[ i ] ); - } - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlListImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/values/XmlListImpl.java deleted file mode 100644 index bd1dbf5..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlListImpl.java +++ /dev/null @@ -1,360 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlSimpleList; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.PrefixResolver; -import org.apache.xmlbeans.impl.common.XMLChar; - -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; - -public class XmlListImpl extends XmlObjectBase implements XmlAnySimpleType -{ - public XmlListImpl(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - public SchemaType schemaType() - { return _schemaType; } - - private SchemaType _schemaType; - private XmlSimpleList _value; - private XmlSimpleList _jvalue; - - - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - // gets raw text value - - private static String nullAsEmpty(String s) - { - if (s == null) - return ""; - return s; - } - - private static String compute_list_text(List xList) - { - if (xList.size() == 0) - return ""; - - StringBuffer sb = new StringBuffer(); - sb.append(nullAsEmpty(((SimpleValue)xList.get(0)).getStringValue())); - - for (int i = 1; i < xList.size(); i++) - { - sb.append(' '); - sb.append(nullAsEmpty(((SimpleValue)xList.get(i)).getStringValue())); - } - - return sb.toString(); - } - - protected String compute_text(NamespaceManager nsm) - { - return compute_list_text(_value); - } - - protected boolean is_defaultable_ws(String v) { - try { - XmlSimpleList savedValue = _value; - set_text(v); - - // restore the saved value - _value = savedValue; - - return false; - } - catch (XmlValueOutOfRangeException e) { - return true; - } - } - - protected void set_text(String s) - { - // first check against any patterns... - if (_validateOnSet() && !_schemaType.matchPatternFacet(s)) - throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "list", s, QNameHelper.readable(_schemaType) }); - - SchemaType itemType = _schemaType.getListItemType(); - - XmlSimpleList newval = lex(s, itemType, _voorVc, has_store() ? get_store() : null); - - // check enumeration - if (_validateOnSet()) - validateValue(newval, _schemaType, _voorVc); - - // we made it all the way through; so we're OK. - _value = newval; - _jvalue = null; - } - - private static final String[] EMPTY_STRINGARRAY = new String[0]; - - public static String[] split_list(String s) - { - if (s.length() == 0) - return EMPTY_STRINGARRAY; - - List result = new ArrayList(); - int i = 0; - int start = 0; - for (;;) - { - while (i < s.length() && XMLChar.isSpace(s.charAt(i))) - i += 1; - if (i >= s.length()) - return (String[])result.toArray(EMPTY_STRINGARRAY); - start = i; - while (i < s.length() && !XMLChar.isSpace(s.charAt(i))) - i += 1; - result.add(s.substring(start, i)); - } - } - - public static XmlSimpleList lex(String s, SchemaType itemType, ValidationContext ctx, PrefixResolver resolver) - { - String[] parts = split_list(s); - - XmlAnySimpleType[] newArray = new XmlAnySimpleType[parts.length]; - boolean pushed = false; - if (resolver != null) - { - NamespaceContext.push(new NamespaceContext(resolver)); - pushed = true; - } - int i = 0; - try - { - for (i = 0; i < parts.length; i++) - { - try - { - newArray[i] = itemType.newValue(parts[i]); - } - catch (XmlValueOutOfRangeException e) - { - ctx.invalid(XmlErrorCodes.LIST, new Object[] { "item '" + parts[i] + "' is not a valid value of " + QNameHelper.readable(itemType) }); - } - } - } - finally - { - if (pushed) - NamespaceContext.pop(); - } - return new XmlSimpleList(Arrays.asList(newArray)); - } - - protected void set_nil() - { - _value = null; - } - - public List xgetListValue() - { - check_dated(); - return _value; - } - - public List getListValue() - { - check_dated(); - if (_value == null) - return null; - if (_jvalue != null) - return _jvalue; - List javaResult = new ArrayList(); - for (int i = 0; i < _value.size(); i++) - javaResult.add(java_value((XmlObject)_value.get(i))); - _jvalue = new XmlSimpleList(javaResult); - return _jvalue; - } - - private static boolean permits_inner_space(XmlObject obj) - { - switch (((SimpleValue)obj).instanceType().getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_STRING: - case SchemaType.BTC_ANY_URI: - case SchemaType.BTC_ANY_SIMPLE: - case SchemaType.BTC_ANY_TYPE: - return true; - default: - return false; - } - } - - private static boolean contains_white_space(String s) - { - return s.indexOf(' ') >= 0 || - s.indexOf('\t') >= 0 || - s.indexOf('\n') >= 0 || - s.indexOf('\r') >= 0; - } - - public void set_list(List list) - { - SchemaType itemType = _schemaType.getListItemType(); - XmlSimpleList xList; - - boolean pushed = false; - if (has_store()) - { - NamespaceContext.push(new NamespaceContext(get_store())); - pushed = true; - } - - try - { - XmlAnySimpleType[] newval = new XmlAnySimpleType[list.size()]; - for (int i = 0; i < list.size(); i++) - { - Object entry = list.get(i); - if ((entry instanceof XmlObject) && permits_inner_space((XmlObject)list.get(i))) - { - String stringrep = list.get(i).toString(); - if (contains_white_space(stringrep)) - throw new XmlValueOutOfRangeException(); - } - newval[i] = itemType.newValue(entry); - } - xList = new XmlSimpleList(Arrays.asList(newval)); - } - finally - { - if (pushed) - NamespaceContext.pop(); - } - - if (_validateOnSet()) - { - // check enumeration + min/max/etc - validateValue(xList, _schemaType, _voorVc); - } - - _value = xList; - _jvalue = null; - } - - public static void validateValue(XmlSimpleList items, SchemaType sType, ValidationContext context) - { - XmlObject[] enumvals = sType.getEnumerationValues(); - checkEnum: if (enumvals != null) - { - for (int i = 0; i < enumvals.length; i++) - { - if (equal_xmlLists(items, ((XmlObjectBase)enumvals[i]).xlistValue())) - break checkEnum; - } - context.invalid(XmlErrorCodes.DATATYPE_ENUM_VALID, - new Object[] { "list", items, QNameHelper.readable(sType) }); - } - - XmlObject o; - int i; - - if ((o = sType.getFacet( SchemaType.FACET_LENGTH )) != null) - { - if ((i = ((SimpleValue)o).getIntValue()) != items.size()) - { - context.invalid(XmlErrorCodes.DATATYPE_LENGTH_VALID$LIST_LENGTH, - new Object[] { items, new Integer(items.size()), new Integer(i), QNameHelper.readable(sType) }); - } - } - - if ((o = sType.getFacet( SchemaType.FACET_MIN_LENGTH )) != null) - { - if ((i = ((SimpleValue)o).getIntValue()) > items.size()) - { - context.invalid(XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$LIST_LENGTH, - new Object[] { items, new Integer(items.size()), new Integer(i), QNameHelper.readable(sType) }); - } - } - - if ((o = sType.getFacet( SchemaType.FACET_MAX_LENGTH )) != null) - { - if ((i = ((SimpleValue)o).getIntValue()) < items.size()) - { - context.invalid(XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$LIST_LENGTH, - new Object[] { items, new Integer(items.size()), new Integer(i), QNameHelper.readable(sType) }); - } - } - } - - // comparators - // protected int compare_to(XmlObject i) - no sorting order; inherit from base - - protected boolean equal_to(XmlObject obj) - { - return equal_xmlLists(_value, ((XmlObjectBase)obj).xlistValue()); - } - - - private static boolean equal_xmlLists(List a, List b) - { - if (a.size() != b.size()) - return false; - for (int i = 0; i < a.size(); i++) - { - if (!a.get(i).equals(b.get(i))) - return false; - } - return true; - } - - protected int value_hash_code() - { - if (_value == null) - return 0; - - // hash code probes 9 distributed values, plus the last - int hash = _value.size(); - int incr = _value.size() / 9; - if (incr < 1) - incr = 1; - - int i; - for (i = 0; i < _value.size(); i += incr) - { - hash *= 19; - hash += _value.get(i).hashCode(); - } - - if (i < _value.size()) - { - hash *= 19; - hash += _value.get(i).hashCode(); - } - - return hash; - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - validateValue((XmlSimpleList)xlistValue(), schemaType(), ctx); - } - -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java b/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java deleted file mode 100644 index 2a2a12a..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java +++ /dev/null @@ -1,3217 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamReader; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -import java.math.BigInteger; -import java.math.BigDecimal; -import java.io.Serializable; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamException; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.lang.reflect.Array; -import java.util.Date; -import java.util.List; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import java.util.Calendar; -import java.util.Collection; -import java.util.ArrayList; - -import org.apache.xmlbeans.impl.common.XmlLocale; -import org.apache.xmlbeans.impl.common.XmlWhitespace; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.GlobalLock; -import org.apache.xmlbeans.impl.common.XmlErrorWatcher; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; -import org.apache.xmlbeans.impl.schema.SchemaTypeVisitorImpl; -import org.apache.xmlbeans.impl.validator.Validator; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaAttributeModel; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaField; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlRuntimeException; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.GDateSpecification; -import org.apache.xmlbeans.GDurationSpecification; -import org.apache.xmlbeans.StringEnumAbstractBase; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.DelegateXmlObject; -import org.apache.xmlbeans.SchemaTypeLoader; - -import org.w3c.dom.Node; - -import org.xml.sax.ContentHandler; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.SAXException; - -public abstract class XmlObjectBase implements TypeStoreUser, Serializable, XmlObject, SimpleValue -{ - public static final short MAJOR_VERSION_NUMBER = (short) 1; // for serialization - public static final short MINOR_VERSION_NUMBER = (short) 1; // for serialization - - public static final short KIND_SETTERHELPER_SINGLETON = 1; - public static final short KIND_SETTERHELPER_ARRAYITEM = 2; - - public final Object monitor() - { - if (has_store()) - return get_store().get_locale(); - return this; - } - - private static XmlObjectBase underlying(XmlObject obj) - { - if (obj == null) - return null; - if (obj instanceof XmlObjectBase) - return (XmlObjectBase)obj; - while (obj instanceof DelegateXmlObject) - obj = ((DelegateXmlObject)obj).underlyingXmlObject(); - if (obj instanceof XmlObjectBase) - return (XmlObjectBase)obj; - throw new IllegalStateException("Non-native implementations of XmlObject should extend FilterXmlObject or implement DelegateXmlObject"); - } - - public final XmlObject copy() - { - if (preCheck()) - return _copy(); - else - synchronized (monitor()) - { - return _copy(); - } - } - - public final XmlObject copy(XmlOptions options) - { - if (preCheck()) - return _copy(options); - else - synchronized (monitor()) - { - return _copy(options); - } - } - - private boolean preCheck() - { -// if ( isImmutable() ) -// return true; - if ( has_store() ) - return get_store().get_locale().noSync(); - return false; - } - - /** - * Same as copy() but unsynchronized. - * Warning: Using this method in mutithreaded environment can cause invalid states. - */ - public final XmlObject _copy() - { - return _copy(null); - } - - /** - * Same as copy() but unsynchronized. - * If Locale.COPY_USE_NEW_LOCALE is set in the options, a new locale will be created for the copy. - * Warning: Using this method in mutithreaded environment can cause invalid states. - */ - public final XmlObject _copy(XmlOptions xmlOptions) - { - // immutable objects don't get copied. They're immutable - if (isImmutable()) - return this; - - check_orphaned(); - - SchemaTypeLoader stl = get_store().get_schematypeloader(); - XmlObject result = (XmlObject)get_store().copy(stl, schemaType(), xmlOptions); - - return result; - } - - public XmlDocumentProperties documentProperties() - { XmlCursor cur = newCursorForce(); try { return cur.documentProperties(); } finally { cur.dispose(); } } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newXMLInputStream() - { return newXMLInputStream(null); } - - /** - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newXMLInputStream(XmlOptions options) - { XmlCursor cur = newCursorForce(); try { return cur.newXMLInputStream(makeInnerOptions(options)); } finally { cur.dispose(); } } - - public XMLStreamReader newXMLStreamReader() - { return newXMLStreamReader(null); } - - public XMLStreamReader newXMLStreamReader(XmlOptions options) - { XmlCursor cur = newCursorForce(); try { return cur.newXMLStreamReader(makeInnerOptions(options)); } finally { cur.dispose(); } } - - public InputStream newInputStream() - { return newInputStream(null); } - - public InputStream newInputStream(XmlOptions options) - { XmlCursor cur = newCursorForce(); try { return cur.newInputStream(makeInnerOptions(options)); } finally { cur.dispose(); } } - - public Reader newReader() - { return newReader(null); } - - public Reader newReader(XmlOptions options) - { XmlCursor cur = newCursorForce(); try { return cur.newReader(makeInnerOptions(options)); } finally { cur.dispose(); } } - - public Node getDomNode() - { XmlCursor cur = newCursorForce(); try { return cur.getDomNode(); } finally { cur.dispose(); } } - - public Node newDomNode() - { return newDomNode(null); } - - public Node newDomNode(XmlOptions options) - { XmlCursor cur = newCursorForce(); try { return cur.newDomNode(makeInnerOptions(options)); } finally { cur.dispose(); } } - - public void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException - { XmlCursor cur = newCursorForce(); try { cur.save(ch, lh, makeInnerOptions(options)); } finally { cur.dispose(); } } - - public void save(File file, XmlOptions options) throws IOException - { XmlCursor cur = newCursorForce(); try { cur.save(file, makeInnerOptions(options)); } finally { cur.dispose(); } } - - public void save(OutputStream os, XmlOptions options) throws IOException - { XmlCursor cur = newCursorForce(); try { cur.save(os, makeInnerOptions(options)); } finally { cur.dispose(); } } - - public void save(Writer w, XmlOptions options) throws IOException - { XmlCursor cur = newCursorForce(); try { cur.save(w, makeInnerOptions(options)); } finally { cur.dispose(); } } - - public void save(ContentHandler ch, LexicalHandler lh) throws SAXException - { save( ch, lh, null ); } - - public void save(File file) throws IOException - { save( file, null ); } - - public void save(OutputStream os) throws IOException - { save( os, null ); } - - public void save(Writer w) throws IOException - { save( w, null ); } - - public void dump() - { XmlCursor cur = newCursorForce(); try { cur.dump(); } finally { cur.dispose(); } } - - public XmlCursor newCursorForce() - { - synchronized (monitor()) - { - return ensureStore().newCursor(); - } - } - - private XmlObject ensureStore() - { - if ((_flags & FLAG_STORE) != 0) - return this; - - check_dated(); - - String value = - (_flags & FLAG_NIL) != 0 - ? "" - : compute_text( has_store() ? get_store() : null ); - - XmlOptions options = new XmlOptions().setDocumentType(schemaType()); - - XmlObject x = XmlObject.Factory.newInstance( options ); - - XmlCursor c = x.newCursor(); - c.toNextToken(); - c.insertChars( value ); - - return x; - } - - private static XmlOptions makeInnerOptions(XmlOptions options) - { - XmlOptions innerOptions = new XmlOptions( options ); - innerOptions.put( XmlOptions.SAVE_INNER ); - return innerOptions; - } - - public XmlCursor newCursor() - { - if ((_flags & FLAG_STORE) == 0) - throw new IllegalStateException("XML Value Objects cannot create cursors"); - - check_orphaned(); - - // Note that new_cursor does not really need sync .... - - XmlLocale l = getXmlLocale(); - - if (l.noSync()) { l.enter(); try { return get_store().new_cursor(); } finally { l.exit(); } } - else synchronized ( l ) { l.enter(); try { return get_store().new_cursor(); } finally { l.exit(); } } - - } - - public abstract SchemaType schemaType(); - - public SchemaType instanceType() - { synchronized (monitor()) { return isNil() ? null : schemaType(); } } - - private SchemaField schemaField() { - SchemaType st = schemaType(); - SchemaField field; - - // First check if this field has an anonymous type - field = st.getContainerField(); - - if (field == null) - field = get_store().get_schema_field(); - - return field; - } - - /** - * Use _voorVc when you want to throw a ValueOutOfRangeException when - * validating a simple type. - */ - private static final class ValueOutOfRangeValidationContext implements ValidationContext - { - public void invalid(String message) - { - throw new XmlValueOutOfRangeException( message ); - } - - public void invalid(String code, Object[] args) - { - throw new XmlValueOutOfRangeException( code, args ); - } - } - - /** - * Used to supply validation context for the validate_value methods - */ - private static final class ImmutableValueValidationContext implements ValidationContext - { - private XmlObject _loc; - private Collection _coll; - ImmutableValueValidationContext(Collection coll, XmlObject loc) - { - _coll = coll; - _loc = loc; - } - public void invalid(String message) - { - _coll.add(XmlError.forObject(message, _loc)); - } - public void invalid(String code, Object[] args) - { - _coll.add(XmlError.forObject(code, args, _loc)); - } - } - - public static final ValidationContext _voorVc = new ValueOutOfRangeValidationContext(); - - public boolean validate() - { return validate(null); } - - public boolean validate(XmlOptions options) - { - if ((_flags & FLAG_STORE) == 0) - { - if ((_flags & FLAG_IMMUTABLE) != 0) - { - return validate_immutable(options); - } - - throw new IllegalStateException( - "XML objects with no underlying store cannot be validated"); - } - - synchronized (monitor()) - { - if ((_flags & FLAG_ORPHANED) != 0) - throw new XmlValueDisconnectedException(); - - SchemaField field = schemaField(); - SchemaType type = schemaType(); - - TypeStore typeStore = get_store(); - - Validator validator = - new Validator( - type, field, typeStore.get_schematypeloader(), options, null); - - typeStore.validate( validator ); - - return validator.isValid(); - } - } - - private boolean validate_immutable(XmlOptions options) - { - Collection errorListener = options == null ? null : (Collection)options.get(XmlOptions.ERROR_LISTENER); - XmlErrorWatcher watcher = new XmlErrorWatcher(errorListener); - if (!(schemaType().isSimpleType() || options != null && - options.hasOption(XmlOptions.VALIDATE_TEXT_ONLY))) - { - // cannot have any required attributes or elements - SchemaProperty[] properties = schemaType().getProperties(); - for (int i = 0; i < properties.length; i++) - { - if (properties[i].getMinOccurs().signum() > 0) - { - // KHK: error code? - if (properties[i].isAttribute()) - watcher.add(XmlError.forObject(XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_REQUIRED_ATTRIBUTE, new Object[]{QNameHelper.pretty(properties[i].getName()), }, this)); - else - watcher.add(XmlError.forObject(XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$MISSING_ELEMENT, new Object[]{properties[i].getMinOccurs(), QNameHelper.pretty(properties[i].getName()), }, this)); - } - } - - if (schemaType().getContentType() != SchemaType.SIMPLE_CONTENT) - return !watcher.hasError(); // don't validate non-simple-content - } - - String text = (String)_textsource; - if (text == null) - text = ""; - validate_simpleval(text, new ImmutableValueValidationContext(watcher, this)); - return !watcher.hasError(); - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - return; - } - - private static XmlObject[] _typedArray(XmlObject[] input) - { - if (input.length == 0) - return input; - SchemaType commonType = input[0].schemaType(); - if (commonType.equals(XmlObject.type) || commonType.isNoType()) - return input; - for (int i = 1; i < input.length; i++) - { - if (input[i].schemaType().isNoType()) - return input; - commonType = commonType.getCommonBaseType(input[i].schemaType()); - if (commonType.equals(XmlObject.type)) - return input; - } - Class desiredClass = commonType.getJavaClass(); - while (desiredClass == null) - { - commonType = commonType.getBaseType(); - if (XmlObject.type.equals(commonType)) - return input; - desiredClass = commonType.getJavaClass(); - } - - XmlObject[] result = (XmlObject[])Array.newInstance(desiredClass, input.length); - System.arraycopy(input, 0, result, 0, input.length); - return result; - } - - public XmlObject[] selectPath ( String path ) - { - return selectPath( path, null ); - } - - public XmlObject[] selectPath ( String path, XmlOptions options ) - { - XmlObject [] selections; - - // all user-level code; doesn't need to be synchronized - - XmlCursor c = newCursor(); - - if (c == null) - throw new XmlValueDisconnectedException(); - - try - { - c.selectPath( path, options ); - - if (!c.hasNextSelection()) - selections = EMPTY_RESULT; - else - { - selections = new XmlObject [ c.getSelectionCount() ]; - - for (int i = 0 ; c.toNextSelection() ; i++) - { - if ((selections[ i ] = c.getObject()) == null) - { - if ( !c.toParent() || (selections[ i ] = c.getObject()) == null ) - throw - new XmlRuntimeException( - "Path must select only elements " + - "and attributes" ); - } - } - } - } - finally - { - c.dispose(); - } - - return _typedArray(selections); - } - - public XmlObject[] execQuery ( String path ) - { - return execQuery( path, null ); - } - - public XmlObject[] execQuery ( String queryExpr, XmlOptions options ) - { - synchronized (monitor()) - { - TypeStore typeStore = get_store(); - - if (typeStore == null) - { - throw - new XmlRuntimeException( - "Cannot do XQuery on XML Value Objects" ); - } - - try - { - return _typedArray(typeStore.exec_query( queryExpr, options )); - } - catch (XmlException e) - { - throw new XmlRuntimeException( e ); - } - } - } - - public XmlObject changeType(SchemaType type) - { - if (type == null) - throw new IllegalArgumentException( "Invalid type (null)" ); - - if ((_flags & FLAG_STORE) == 0) - { - throw - new IllegalStateException( - "XML Value Objects cannot have thier type changed" ); - } - - synchronized (monitor()) - { - check_orphaned(); - return (XmlObject) get_store().change_type( type ); - } - } - - public XmlObject substitute(QName name, SchemaType type) - { - if (name == null) - throw new IllegalArgumentException( "Invalid name (null)" ); - - if (type == null) - throw new IllegalArgumentException( "Invalid type (null)" ); - - if ((_flags & FLAG_STORE) == 0) - { - throw - new IllegalStateException( - "XML Value Objects cannot be used with substitution" ); - } - - synchronized (monitor()) - { - check_orphaned(); - return (XmlObject) get_store().substitute( name, type ); - } - } - - private int _flags; - private Object _textsource; - - protected XmlObjectBase() - { - _flags = FLAG_NILLABLE | FLAG_NIL; - } - - public void init_flags(SchemaProperty prop) - { - if (prop == null) return; - - if (prop.hasDefault() == SchemaProperty.VARIABLE || - prop.hasFixed() == SchemaProperty.VARIABLE || - prop.hasNillable() == SchemaProperty.VARIABLE) - return; - - _flags &= ~FLAGS_ELEMENT; - _flags |= - (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | - (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED) | - (prop.hasNillable() == SchemaProperty.NEVER ? 0 : TypeStore.NILLABLE) | - (FLAG_NOT_VARIABLE); - } - - { - assert TypeStore.NILLABLE == 1; - assert TypeStore.HASDEFAULT == 2; - assert TypeStore.FIXED == 4; - } - - private static final int FLAG_NILLABLE = TypeStore.NILLABLE; - private static final int FLAG_HASDEFAULT = TypeStore.HASDEFAULT; - private static final int FLAG_FIXED = TypeStore.FIXED; - private static final int FLAG_ATTRIBUTE = 8; - private static final int FLAG_STORE = 16; - private static final int FLAG_VALUE_DATED = 32; - private static final int FLAG_NIL = 64; - private static final int FLAG_NIL_DATED = 128; - private static final int FLAG_ISDEFAULT = 256; - private static final int FLAG_ELEMENT_DATED = 512; - private static final int FLAG_SETTINGDEFAULT = 1024; - private static final int FLAG_ORPHANED = 2048; - private static final int FLAG_IMMUTABLE = 4096; - private static final int FLAG_COMPLEXTYPE = 8192; - private static final int FLAG_COMPLEXCONTENT = 16384; - private static final int FLAG_NOT_VARIABLE = 32768; - private static final int FLAG_VALIDATE_ON_SET = 65536; - - - /** - * The three dated flags are always stacked: - * FLAG_ELEMENT_DATED implies FLAG_NIL_DATED is set - * FLAG_NIL_DATED implies FLAG_TEXT_DATED is set. - * checkers work on the flags from top to bottom. - */ - private static final int FLAGS_DATED = - FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED; - - /** - * The three element status flags have one interrlationshiop: - * FLAG_FIXED implies FLAG_HASDEFAULT is set. - * These flags are used when setting nils, defaults, strings. - * Since an initial get implies setting from text, they're - * also used during getting. - */ - private static final int FLAGS_ELEMENT = - FLAG_NILLABLE | FLAG_FIXED | FLAG_HASDEFAULT; - - - /** - * Called by restriction subclasses within their constructors to enable - * complex type support. - */ - protected void initComplexType(boolean complexType, boolean complexContent) - { - _flags |= (complexType ? FLAG_COMPLEXTYPE : 0) | - (complexContent ? FLAG_COMPLEXCONTENT : 0); - } - - protected boolean _isComplexType() - { return (_flags & FLAG_COMPLEXTYPE) != 0; } - - protected boolean _isComplexContent() - { return (_flags & FLAG_COMPLEXCONTENT) != 0; } - - public void setValidateOnSet() { - _flags |= FLAG_VALIDATE_ON_SET; - } - - protected boolean _validateOnSet() - { return (_flags & FLAG_VALIDATE_ON_SET) != 0; } - - /** - * True if the value is nilled. - */ - public final boolean isNil() - { - synchronized (monitor()) - { - check_dated(); - return ((_flags & FLAG_NIL) != 0); - } - } - - /** - * True if the value is fixed. - */ - public final boolean isFixed() - { - check_element_dated(); - return ((_flags & FLAG_FIXED) != 0); - } - - /** - * True if the value is allowed to be nil. - */ - public final boolean isNillable() - { - check_element_dated(); - return ((_flags & FLAG_NILLABLE) != 0); - } - - /** - * True if the value is currently defaulted. - */ - public final boolean isDefaultable() - { - check_element_dated(); - return ((_flags & FLAG_HASDEFAULT) != 0); - } - - /** - * True if the value is currently defaulted. - */ - public final boolean isDefault() - { - check_dated(); - return ((_flags & FLAG_ISDEFAULT) != 0); - } - - - /** - * Nils the value. - */ - public final void setNil() - { - synchronized (monitor()) - { - set_prepare(); - - // if we're not nillable, throw exception on setNil(true) - if ((_flags & FLAG_NILLABLE) == 0 && - (_flags & FLAG_VALIDATE_ON_SET) != 0) - throw new XmlValueNotNillableException(); - - // the implementation should zero the value to reflect nil - set_nil(); - - // set the nil flag - _flags |= FLAG_NIL; - - // ordinary commit except no clearing of nil flag - if ((_flags & FLAG_STORE) != 0) - { - get_store().invalidate_text(); - _flags &= ~FLAGS_DATED; - get_store().invalidate_nil(); - } - else - { - _textsource = null; - } - } - } - - /** - * Used for situations where these flags must be passed on to - * chained values. (See XmlAnySimpleType (allSimpleValue), union - * implementations). - */ - protected int elementFlags() - { - check_element_dated(); - return (_flags & FLAGS_ELEMENT); - } - - /** - * Used to make a free-standing xml simple value instance immutable. - * This is a one-way street, and it is illegal to attempt to make a - * value that is embedded in an xml document immutable. - * - * Once a value is marked as immutable, it is illegal to call setters - * of any kind. - */ - public void setImmutable() - { - if ((_flags & (FLAG_IMMUTABLE | FLAG_STORE)) != 0) - throw new IllegalStateException(); - - _flags |= FLAG_IMMUTABLE; - } - - /** - * Is this instance an immutable value? - */ - public boolean isImmutable() - { - return (_flags & FLAG_IMMUTABLE) != 0; - } - - - - - // TEXTUSER implementation - - /** - * Called to initialize the TypeStore associated with this XmlObject - * implementation. If not called, this is a free-floating value holder. - * - * When a value is first attached, it is put in a completely invalidated - * state. - */ - public final void attach_store(TypeStore store) - { - _textsource = store; - if ((_flags & FLAG_IMMUTABLE) != 0) - throw new IllegalStateException(); - _flags |= FLAG_STORE | FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED; - - if (store.is_attribute()) - _flags |= FLAG_ATTRIBUTE; - - if (store.validate_on_set()) - _flags |= FLAG_VALIDATE_ON_SET; - } - - /** - * Called by a TypeStore to indicate that the text has been - * invalidated and should be fetched next time the value is - * needed. - */ - public final void invalidate_value() - { - assert((_flags & FLAG_STORE) != 0); - _flags |= FLAG_VALUE_DATED; - } - - public final boolean uses_invalidate_value() - { - SchemaType type = schemaType(); - return type.isSimpleType() || type.getContentType() == SchemaType.SIMPLE_CONTENT; - } - - /** - * Called by a TypeStore to indicate that the xsi:nil attribute - * on the containing element (and possibly the text) has been - * invalidated and both should be consulted next time the value - * is needed. - */ - public final void invalidate_nilvalue() - { - assert((_flags & FLAG_STORE) != 0); - _flags |= FLAG_VALUE_DATED | FLAG_NIL_DATED; - } - - /** - * Called by a TypeStore to indicate that the element's default - * value, nillability, fixedness, etc, may have changed by - * virtue of the element order changing (and xsi:nil and the - * text may have changed too); so the store should be consulted - * next time any setter or getter is called. - */ - public final void invalidate_element_order() - { - assert((_flags & FLAG_STORE) != 0); - _flags |= FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED; - } - - /** - * Used by the ComplexTypeImpl subclass to get direct access - * to the store. - */ - public final TypeStore get_store() - { - assert((_flags & FLAG_STORE) != 0); - return (TypeStore)_textsource; - } - - public final XmlLocale getXmlLocale ( ) - { - return get_store().get_locale(); - } - - protected final boolean has_store() - { - return (_flags & FLAG_STORE) != 0; - } - - /** - * Called by a TypeStore to pull out the most reasonable - * text value from us. This is done after we have invalidated - * the store (typically when our value has been set). - */ - public final String build_text(NamespaceManager nsm) - { - assert((_flags & FLAG_STORE) != 0); - assert((_flags & FLAG_VALUE_DATED) == 0); - if ((_flags & (FLAG_NIL | FLAG_ISDEFAULT)) != 0) - return ""; - return compute_text( - nsm == null ? has_store() ? get_store() : null : nsm); - } - - /** - * A store will call back on build_nil after we've called invalidate_nil - * and it needs to know what the nil value is. - */ - public boolean build_nil() - { - assert((_flags & FLAG_STORE) != 0); - assert((_flags & FLAG_VALUE_DATED) == 0); - return (_flags & FLAG_NIL) != 0; - } - - /** - * A store will call back on validate_now to force us to look at - * the text if we're in an invalid state. We're allowed to throw - * an exception if the text isn't valid for our type. - */ - public void validate_now() - { - check_dated(); - } - - /** - * A store calls back here in order to force a disconnect. - * After this is done, the object should be considered invalid. - * Any attempt to access or set a value should result in an - * exception. - * - * Note that this is how we handle deletions and xsi:type changes. - */ - public void disconnect_store() - { - assert((_flags & FLAG_STORE) != 0); - _flags |= FLAGS_DATED | FLAG_ORPHANED; - // do NOT null out _textsource, because we need it non-null for synchronization - } - - /** - * A typestore user can create a new TypeStoreUser instance for - * a given element child name as long as you also pass the - * qname contained by the xsi:type attribute, if any. - * - * Note that we will ignore the xsiType if it turns out to be invalid. - * - * Returns null if there is no strongly typed information for that - * given element (which implies, recusively, no strongly typed information - * downwards). - */ - public TypeStoreUser create_element_user(QName eltName, QName xsiType) - { - return - (TypeStoreUser) - ((SchemaTypeImpl) schemaType()).createElementType( - eltName, xsiType, get_store().get_schematypeloader() ); - - /* - SchemaTypeImpl stype = (SchemaTypeImpl)schemaType().getElementType(eltName, xsiType, get_store().get_schematypeloader()); - if (stype == null) - return null; - return (TypeStoreUser)stype.createUnattachedNode(); - */ - } - - /** - * A typestore user can create a new TypeStoreUser instance for - * a given attribute child, based on the attribute name. - * - * Returns null if there is no strongly typed information for that - * given attributes. - */ - public TypeStoreUser create_attribute_user(QName attrName) - { - return (TypeStoreUser)((SchemaTypeImpl)schemaType()).createAttributeType(attrName, get_store().get_schematypeloader()); - } - - public SchemaType get_schema_type() - { - return schemaType(); - } - - public SchemaType get_element_type(QName eltName, QName xsiType) - { - return schemaType().getElementType( - eltName, xsiType, get_store().get_schematypeloader() ); - } - - public SchemaType get_attribute_type(QName attrName) - { - return schemaType().getAttributeType( - attrName, get_store().get_schematypeloader() ); - } - - /** - * Returns the default element text, if it's consistent. If it's - * not consistent, returns null, and requires a visitor walk. - * - * Also returns null if there is no default at all (although - * that can also be discovered via get_elementflags without - * doing a walk). - */ - public String get_default_element_text(QName eltName) - { - assert(_isComplexContent()); - if (!_isComplexContent()) - throw new IllegalStateException(); - - SchemaProperty prop = schemaType().getElementProperty(eltName); - if (prop == null) - return ""; - return prop.getDefaultText(); - } - - /** - * Returns the default attribute text for the attribute with - * the given name, or null if no default. - */ - public String get_default_attribute_text(QName attrName) - { - assert(_isComplexType()); - if (!_isComplexType()) - throw new IllegalStateException(); - - SchemaProperty prop = schemaType().getAttributeProperty(attrName); - if (prop == null) - return ""; - return prop.getDefaultText(); - } - - /** - * Returns the elementflags, if they're consistent. If they're - * not, returns -1, and requires a vistor walk. - */ - public int get_elementflags(QName eltName) - { - if (!_isComplexContent()) - return 0; - - SchemaProperty prop = schemaType().getElementProperty(eltName); - if (prop == null) - return 0; - if (prop.hasDefault() == SchemaProperty.VARIABLE || - prop.hasFixed() == SchemaProperty.VARIABLE || - prop.hasNillable() == SchemaProperty.VARIABLE) - return -1; - return - (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | - (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED) | - (prop.hasNillable() == SchemaProperty.NEVER ? 0 : TypeStore.NILLABLE); - } - - /** - * Returns the flags for the given attribute. - */ - public int get_attributeflags(QName attrName) - { - if (!_isComplexType()) - return 0; - SchemaProperty prop = schemaType().getAttributeProperty(attrName); - if (prop == null) - return 0; - return - (prop.hasDefault() == SchemaProperty.NEVER ? 0 : TypeStore.HASDEFAULT) | - (prop.hasFixed() == SchemaProperty.NEVER ? 0 : TypeStore.FIXED); - // BUGBUG: todo: hook up required? - } - - /** - * Returns false if child elements are insensitive to order; - * if it returns true, you're required to call invalidate_element_order - * on children to the right of any child order rearrangement. - */ - public boolean is_child_element_order_sensitive() - { - if (!_isComplexType()) - return false; - return schemaType().isOrderSensitive(); - } - - /** - * Inserting a new element is always unambiguous except in one - * situation: when adding an element after the last one with - * that name (or the first one if there are none). - * - * In that case, add the element at the first possible slot - * BEFORE any element whose qname is contained in the QNameSet - * given. (If the QNameSet is empty, that means add the new - * element at the very end.) - * - * If the returned QNameSet is null, treat it as if the QNameSet - * contained all QNames, i.e., add the new element at the very - * first position possible (adjacent to the last element of the - * same name, or at the very first slot if it is the first elt - * with that name). - */ - public final QNameSet get_element_ending_delimiters(QName eltname) - { - SchemaProperty prop = schemaType().getElementProperty(eltname); - if (prop == null) - return null; - return prop.getJavaSetterDelimiter(); - } - - /** - * A typestore user can return a visitor that is used to compute - * default text and elementflags for an arbitrary element. - */ - public TypeStoreVisitor new_visitor() - { - if (!_isComplexContent()) - return null; - return new SchemaTypeVisitorImpl(schemaType().getContentModel()); - } - - public SchemaField get_attribute_field(QName attrName) - { - SchemaAttributeModel model = schemaType().getAttributeModel(); - if (model == null) - return null; - return model.getAttribute(attrName); - } - - - /** - * Setting a string preserves any noncanonical literal - * representation. This is done by storing the actual - * string in the underlying store after checking it - * against the primitive type for validity. - */ - protected void set_String(String v) - { - if ((_flags & FLAG_IMMUTABLE) != 0) - throw new IllegalStateException(); - - boolean wasNilled = ((_flags & FLAG_NIL) != 0); - - // update the underlying value from the string - String wscanon = apply_wscanon(v); - update_from_wscanon_text(wscanon); - - // Now store the literal text immediately in the underlying - if ((_flags & FLAG_STORE) != 0) - { - _flags &= ~FLAG_VALUE_DATED; - if ((_flags & FLAG_SETTINGDEFAULT) == 0) - get_store().store_text(v); - if (wasNilled) - get_store().invalidate_nil(); - } - else - _textsource = v; - } - - /** - * Update the value based on complex content. - */ - protected void update_from_complex_content() - { - throw new XmlValueNotSupportedException("Complex content"); - } - - /** - * Utility to update the value based on a string that - * was passed either from the text store or from the user. - * This function handles the cases where there is a default - * that must be applied, and where the value must match - * a fixed value. - */ - private final void update_from_wscanon_text(String v) - { - // Whitespace is default if this type treats this space as defaultable - if ((_flags & FLAG_HASDEFAULT) != 0 && (_flags & FLAG_SETTINGDEFAULT) == 0) - { - // This isn't quite correct since the .equals("") test should be - // done on the actual text, not the wscanon text - if ((_flags & FLAG_ATTRIBUTE) == 0 && v.equals("")) - { - String def = get_store().compute_default_text(); - if (def == null) - throw new XmlValueOutOfRangeException(); - - // protect against recursion with this flag - _flags |= FLAG_SETTINGDEFAULT; - try { this.setStringValue(def); } - finally { _flags &= ~FLAG_SETTINGDEFAULT; } - _flags &= ~FLAG_NIL; - _flags |= FLAG_ISDEFAULT; - return; - } - } - // If we haven't returned yet, the default doesn't apply. - - // Ask underlying impl to parse ordinary non-default text - set_text(v); - _flags &= ~(FLAG_NIL | FLAG_ISDEFAULT); - } - - /** - * Types should return false if they don't treat the given - * whitespace as a default value. - */ - protected boolean is_defaultable_ws(String v) - { - return true; - } - - /** - * Returns the whitespace rule that will be applied before - * building a string to pass to get_text(). - * - * Overridden by subclasses that don't need their text - * for set_text canonicalized; perhaps they already implement - * scanners that can deal with whitespace, and they know - * they have no regex pattern restrictions. - */ - protected int get_wscanon_rule() - { - return SchemaType.WS_COLLAPSE; - } - - /** - * Called to canonicalize whitespace before calling set_text. - * - * Tries to avoid allocation when the string is already canonical, but - * otherwise this is not particularly efficient. Hopefully the common - * case is that we pass our wscanon rule to the store via fetch_text - * and it's canonicalized before we even see it as a string. - */ - private final String apply_wscanon(String v) - { - return XmlWhitespace.collapse(v, get_wscanon_rule()); - } - - /** - * Called before every set and get, to ensure that we have - * a correct picture of whether we're nillable, fixed, or - * if we have a default that can be applied. - */ - private final void check_element_dated() - { - if ((_flags & FLAG_ELEMENT_DATED) != 0 && - (_flags & FLAG_NOT_VARIABLE) == 0) - { - if ((_flags & FLAG_ORPHANED) != 0) - throw new XmlValueDisconnectedException(); - - int eltflags = get_store().compute_flags(); - // int eltflags = 0; - _flags &= ~(FLAGS_ELEMENT | FLAG_ELEMENT_DATED); - _flags |= eltflags; - } - if ((_flags & FLAG_NOT_VARIABLE) != 0) - _flags &= ~(FLAG_ELEMENT_DATED); - } - - /** - * Describes the orphaned status of this object. - */ - protected final boolean is_orphaned() - { - return (_flags & FLAG_ORPHANED) != 0; - } - - /** - * Called before every getter and setter on the strongly - * typed classes to ensure that the object has not been - * orphaned. - */ - protected final void check_orphaned() - { - if (is_orphaned()) - throw new XmlValueDisconnectedException(); - } - - /** - * Called prior to every get operation, to ensure - * that the value being read is valid. If the value - * has been invalidated, it is re-read from the underlying - * text store, and this may cause an out of range exception. - * - * This method deals with nils, nillability, defaults, etc. - */ - public final void check_dated() - { - if ((_flags & FLAGS_DATED) != 0) - { - if ((_flags & FLAG_ORPHANED) != 0) - throw new XmlValueDisconnectedException(); - - assert((_flags & FLAG_STORE) != 0); - - check_element_dated(); - - if ((_flags & FLAG_ELEMENT_DATED) != 0) - { - int eltflags = get_store().compute_flags(); - _flags &= ~(FLAGS_ELEMENT | FLAG_ELEMENT_DATED); - _flags |= eltflags; - } - - boolean nilled = false; - - if ((_flags & FLAG_NIL_DATED) != 0) - { - if (get_store().find_nil()) - { - if ((_flags & FLAG_NILLABLE) == 0 && - (_flags & FLAG_VALIDATE_ON_SET) != 0) - throw new XmlValueOutOfRangeException(); // nil not allowed - - // let the implementation know that we're nil now - set_nil(); - - _flags |= FLAG_NIL; - nilled = true; - } - else - { - _flags &= ~FLAG_NIL; - } - _flags &= ~FLAG_NIL_DATED; - } - - if (!nilled) - { - String text; - - if ((_flags & FLAG_COMPLEXCONTENT) != 0 || (text = get_wscanon_text()) == null) - update_from_complex_content(); - else - { - NamespaceContext.push(new NamespaceContext(get_store())); - try { update_from_wscanon_text(text); } - finally { NamespaceContext.pop(); } - } - } - - _flags &= ~FLAG_VALUE_DATED; - } - } - - /** - * Called before every set operation (except for the - * special case of setting a string) to: - * (1) get the nillable, fixed, etc flags - * (2) throw an exception if it's fixed (not for strings) - */ - private final void set_prepare() - { - check_element_dated(); - if ((_flags & FLAG_IMMUTABLE) != 0) - throw new IllegalStateException(); - } - - /** - * Called after every set operation to invalidate - * the attached raw text. Also, if we were dated, - * we make a note that we're now current, since the - * latest set beats the previous invalidate. Also, - * if we were nil, we're no longer. - */ - private final void set_commit() - { - boolean wasNilled = ((_flags & FLAG_NIL) != 0); - _flags &= ~(FLAG_NIL | FLAG_ISDEFAULT); - - if ((_flags & FLAG_STORE) != 0) - { - _flags &= ~(FLAGS_DATED); - get_store().invalidate_text(); - if (wasNilled) - get_store().invalidate_nil(); - } - else - { - _textsource = null; - } - } - - /** - * Grabs the undelying litral representation, applying the - * implementation's wscanon rule. - * Null if not simple content. - */ - public final String get_wscanon_text() - { - if ((_flags & FLAG_STORE) == 0) - { - return apply_wscanon((String)_textsource); - } - else return get_store().fetch_text(get_wscanon_rule()); - } - - /** - * This should set the value of the type from text, - * or throw an XmlValueOutOfRangeException if it can't. - */ - abstract protected void set_text(String text); - - /** - * This should clear the value, and set it to whatever - * is supposed to be returned when the value is nilled. - */ - abstract protected void set_nil(); - - /** - * This should return the canonical string value of the primitive. - * Only called when non-nil. - */ - abstract protected String compute_text(NamespaceManager nsm); - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - - // numerics: fractional - public float getFloatValue() - { BigDecimal bd = getBigDecimalValue(); return bd == null ? 0.0f : bd.floatValue(); } - public double getDoubleValue() - { BigDecimal bd = getBigDecimalValue(); return bd == null ? 0.0 : bd.doubleValue(); } - public BigDecimal getBigDecimalValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "numeric"}); } - - // numerics: integral - public BigInteger getBigIntegerValue() - { BigDecimal bd = bigDecimalValue(); return bd == null ? null : bd.toBigInteger(); } - - public byte getByteValue() - { - long l = getIntValue(); - if (l > Byte.MAX_VALUE) throw new XmlValueOutOfRangeException(); - if (l < Byte.MIN_VALUE) throw new XmlValueOutOfRangeException(); - return (byte)l; - } - - public short getShortValue() - { - long l = getIntValue(); - if (l > Short.MAX_VALUE) throw new XmlValueOutOfRangeException(); - if (l < Short.MIN_VALUE) throw new XmlValueOutOfRangeException(); - return (short)l; - } - - public int getIntValue() - { - long l = getLongValue(); - if (l > Integer.MAX_VALUE) throw new XmlValueOutOfRangeException(); - if (l < Integer.MIN_VALUE) throw new XmlValueOutOfRangeException(); - return (int)l; - } - private static final BigInteger _max = BigInteger.valueOf(Long.MAX_VALUE); - private static final BigInteger _min = BigInteger.valueOf(Long.MIN_VALUE); - - public long getLongValue() - { - BigInteger b = getBigIntegerValue(); - if (b == null) return 0L; - if (b.compareTo(_max) >= 0) throw new XmlValueOutOfRangeException(); - if (b.compareTo(_min) <= 0) throw new XmlValueOutOfRangeException(); - return b.longValue(); - } - - private static final XmlOptions _toStringOptions = - buildInnerPrettyOptions(); - - static final XmlOptions buildInnerPrettyOptions() - { - XmlOptions options = new XmlOptions(); - options.put( XmlOptions.SAVE_INNER ); - options.put( XmlOptions.SAVE_PRETTY_PRINT ); - options.put( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES ); - options.put( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE ); - return options; - } - - /* - private static final void dumpStack ( String msg ) - { - try - { - java.io.FileOutputStream fos = new java.io.FileOutputStream( "C:\\ee.txt", true ); - java.io.PrintStream ps = new java.io.PrintStream( fos ); - ps.println( "======================================" ); - ps.println( msg ); - new Exception().printStackTrace( ps ); - ps.close(); - fos.close(); - } - catch ( Exception e ) - { - } - - } - */ - - public final String toString( ) - { - synchronized (monitor()) - { - return ensureStore().xmlText(_toStringOptions); - } - } - - public String xmlText() - { - return xmlText(null); - } - - public String xmlText (XmlOptions options) - { - XmlCursor cur = newCursorForce(); - - try - { - return cur.xmlText(makeInnerOptions(options)); - } - finally - { - cur.dispose(); - } - } - - // enums - public StringEnumAbstractBase getEnumValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "enum"}); } - - // various - public String getStringValue() - { - if (isImmutable()) - { - if ((_flags & FLAG_NIL) != 0) - return null; - return compute_text(null); - } - // Since complex-content types don't have a "natural" string value, we - // emit the deeply concatenated, tag-removed content of the tag. - synchronized (monitor()) - { - if (_isComplexContent()) - return get_store().fetch_text(TypeStore.WS_PRESERVE); - - check_dated(); - if ((_flags & FLAG_NIL) != 0) - return null; - return compute_text(has_store() ? get_store() : null); - } - } - - /** @deprecated replaced with {@link #getStringValue} */ - public String stringValue() - { return getStringValue(); } - /** @deprecated replaced with {@link #getBooleanValue} */ - public boolean booleanValue() - { return getBooleanValue(); } - /** @deprecated replaced with {@link #getByteValue} */ - public byte byteValue() - { return getByteValue(); } - /** @deprecated replaced with {@link #getShortValue} */ - public short shortValue() - { return getShortValue(); } - /** @deprecated replaced with {@link #getIntValue} */ - public int intValue() - { return getIntValue(); } - /** @deprecated replaced with {@link #getLongValue} */ - public long longValue() - { return getLongValue(); } - /** @deprecated replaced with {@link #getBigIntegerValue} */ - public BigInteger bigIntegerValue() - { return getBigIntegerValue(); } - /** @deprecated replaced with {@link #getBigDecimalValue} */ - public BigDecimal bigDecimalValue() - { return getBigDecimalValue(); } - /** @deprecated replaced with {@link #getFloatValue} */ - public float floatValue() - { return getFloatValue(); } - /** @deprecated replaced with {@link #getDoubleValue} */ - public double doubleValue() - { return getDoubleValue(); } - /** @deprecated replaced with {@link #getByteArrayValue} */ - public byte[] byteArrayValue() - { return getByteArrayValue(); } - /** @deprecated replaced with {@link #getEnumValue} */ - public StringEnumAbstractBase enumValue() - { return getEnumValue(); } - /** @deprecated replaced with {@link #getCalendarValue} */ - public Calendar calendarValue() - { return getCalendarValue(); } - /** @deprecated replaced with {@link #getDateValue} */ - public Date dateValue() - { return getDateValue(); } - /** @deprecated replaced with {@link #getGDateValue} */ - public GDate gDateValue() - { return getGDateValue(); } - /** @deprecated replaced with {@link #getGDurationValue} */ - public GDuration gDurationValue() - { return getGDurationValue(); } - /** @deprecated replaced with {@link #getQNameValue} */ - public QName qNameValue() - { return getQNameValue(); } - /** @deprecated replaced with {@link #xgetListValue} */ - public List xlistValue() - { return xgetListValue(); } - /** @deprecated replaced with {@link #getListValue} */ - public List listValue() - { return getListValue(); } - /** @deprecated replaced with {@link #getObjectValue} */ - public Object objectValue() - { return getObjectValue(); } - - /** @deprecated replaced with {@link #setStringValue} */ - public void set(String obj) - { setStringValue(obj); } - /** @deprecated replaced with {@link #setBooleanValue} */ - public void set(boolean v) - { setBooleanValue(v); } - /** @deprecated replaced with {@link #setByteValue} */ - public void set(byte v) - { setByteValue(v); } - /** @deprecated replaced with {@link #setShortValue} */ - public void set(short v) - { setShortValue(v); } - /** @deprecated replaced with {@link #setIntValue} */ - public void set(int v) - { setIntValue(v); } - /** @deprecated replaced with {@link #setLongValue} */ - public void set(long v) - { setLongValue(v); } - /** @deprecated replaced with {@link #setBigIntegerValue} */ - public void set(BigInteger obj) - { setBigIntegerValue(obj); } - /** @deprecated replaced with {@link #setBigDecimalValue} */ - public void set(BigDecimal obj) - { setBigDecimalValue(obj); } - /** @deprecated replaced with {@link #setFloatValue} */ - public void set(float v) - { setFloatValue(v); } - /** @deprecated replaced with {@link #setDoubleValue} */ - public void set(double v) - { setDoubleValue(v); } - /** @deprecated replaced with {@link #setByteArrayValue} */ - public void set(byte[] obj) - { setByteArrayValue(obj); } - /** @deprecated replaced with {@link #setEnumValue} */ - public void set(StringEnumAbstractBase obj) - { setEnumValue(obj); } - /** @deprecated replaced with {@link #setCalendarValue} */ - public void set(Calendar obj) - { setCalendarValue(obj); } - /** @deprecated replaced with {@link #setDateValue} */ - public void set(Date obj) - { setDateValue(obj); } - /** @deprecated replaced with {@link #setGDateValue} */ - public void set(GDateSpecification obj) - { setGDateValue(obj); } - /** @deprecated replaced with {@link #setGDurationValue} */ - public void set(GDurationSpecification obj) - { setGDurationValue(obj); } - /** @deprecated replaced with {@link #setQNameValue} */ - public void set(QName obj) - { setQNameValue(obj); } - /** @deprecated replaced with {@link #setListValue} */ - public void set(List obj) - { setListValue(obj); } - /** @deprecated replaced with {@link #setObjectValue} */ - public void objectSet(Object obj) - { setObjectValue(obj); } - - public byte[] getByteArrayValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "byte[]"}); } - public boolean getBooleanValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "boolean"}); } - public GDate getGDateValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "Date"}); } - public Date getDateValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "Date"}); } - public Calendar getCalendarValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "Calendar"}); } - public GDuration getGDurationValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "Duration"}); } - public QName getQNameValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "QName"}); } - public List getListValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "List"}); } - public List xgetListValue() - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_S2J, - new Object[] {getPrimitiveTypeName(), "List"}); } - public Object getObjectValue() - { return java_value(this); } - - // set this value - public final void setBooleanValue(boolean v) - { synchronized (monitor()) { set_prepare(); set_boolean(v); set_commit(); } } - public final void setByteValue(byte v) - { synchronized (monitor()) { set_prepare(); set_byte(v); set_commit(); } } - public final void setShortValue(short v) - { synchronized (monitor()) { set_prepare(); set_short(v); set_commit(); } } - public final void setIntValue(int v) - { synchronized (monitor()) { set_prepare(); set_int(v); set_commit(); } } - public final void setLongValue(long v) - { synchronized (monitor()) { set_prepare(); set_long(v); set_commit(); } } - public final void setFloatValue(float v) - { synchronized (monitor()) { set_prepare(); set_float(v); set_commit(); } } - public final void setDoubleValue(double v) - { synchronized (monitor()) { set_prepare(); set_double(v); set_commit(); } } - public final void setByteArrayValue(byte[] obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_ByteArray(obj); set_commit(); } } } - public final void setEnumValue(StringEnumAbstractBase obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_enum(obj); set_commit(); } } } - public final void setBigIntegerValue(BigInteger obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_BigInteger(obj); set_commit(); } } } - public final void setBigDecimalValue(BigDecimal obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_BigDecimal(obj); set_commit(); } } } - public final void setCalendarValue(Calendar obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_Calendar(obj); set_commit(); } } } - public final void setDateValue(Date obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_Date(obj); set_commit(); } } } - public final void setGDateValue(GDate obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_GDate(obj); set_commit(); } } } - public final void setGDateValue(GDateSpecification obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_GDate(obj); set_commit(); } } } - public final void setGDurationValue(GDuration obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_GDuration(obj); set_commit(); } } } - public final void setGDurationValue(GDurationSpecification obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_GDuration(obj); set_commit(); } } } - public final void setQNameValue(QName obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_QName(obj); set_commit(); } } } - public final void setListValue(List obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_list(obj); set_commit(); } } } - public final void setStringValue(String obj) - { if (obj == null) setNil(); else { synchronized (monitor()) { set_prepare(); set_String(obj); /* strings are special, so set_String does its own commit.*/ } } } - - public void setObjectValue(Object o) - { - if (o == null) - { - setNil(); - return; - } - - if (o instanceof XmlObject) - set( (XmlObject) o ); - else if (o instanceof String) - setStringValue( (String) o ); - else if (o instanceof StringEnumAbstractBase) - setEnumValue( (StringEnumAbstractBase) o ); - else if (o instanceof BigInteger) - setBigIntegerValue( (BigInteger) o ); - else if (o instanceof BigDecimal) - setBigDecimalValue( (BigDecimal) o ); - else if (o instanceof Byte) - setByteValue( ((Byte)o).byteValue() ); - else if (o instanceof Short) - setShortValue( ((Short)o).shortValue() ); - else if (o instanceof Integer) - setIntValue( ((Integer)o).intValue() ); - else if (o instanceof Long) - setLongValue( ((Long)o).longValue() ); - else if (o instanceof Boolean) - setBooleanValue( ((Boolean)o).booleanValue() ); - else if (o instanceof Float) - setFloatValue( ((Float)o).floatValue() ); - else if (o instanceof Double) - setDoubleValue( ((Double)o).doubleValue() ); - else if (o instanceof Calendar) - setCalendarValue( ((Calendar)o) ); - else if (o instanceof Date) - setDateValue( (Date) o ); - else if (o instanceof GDateSpecification) - setGDateValue( (GDateSpecification) o ); - else if (o instanceof GDurationSpecification) - setGDurationValue( (GDurationSpecification) o ); - else if (o instanceof QName) - setQNameValue( (QName) o ); - else if (o instanceof List) - setListValue( (List) o ); - else if (o instanceof byte[]) - setByteArrayValue( (byte[]) o ); - else - { - throw - new XmlValueNotSupportedException( - "Can't set union object of class : " + - o.getClass().getName() ); - } - } - - public final void set_newValue(XmlObject obj) - { - if (obj == null || obj.isNil()) - { - setNil(); - return; - } - - primitive: - if (obj instanceof XmlAnySimpleType) - { - XmlAnySimpleType v = (XmlAnySimpleType)obj; - SchemaType instanceType = ((SimpleValue)v).instanceType(); - assert(instanceType != null) : "Nil case should have been handled already"; - - // handle lists - if (instanceType.getSimpleVariety() == SchemaType.LIST) - { - synchronized (monitor()) - { - set_prepare(); - set_list(((SimpleValue)v).xgetListValue()); - set_commit(); - return; - } - } - - // handle atomic types - synchronized (monitor()) - { - assert(instanceType.getSimpleVariety() == SchemaType.ATOMIC); - switch (instanceType.getPrimitiveType().getBuiltinTypeCode()) - { - default: - assert(false) : "encountered nonprimitive type."; - // case SchemaType.BTC_ANY_SIMPLE: This is handled below... - // but we eventually want to handle it with a treecopy, so - // eventually we should break here. - break primitive; - - case SchemaType.BTC_BOOLEAN: - { - boolean bool = ((SimpleValue)v).getBooleanValue(); - set_prepare(); - set_boolean(bool); - break; - } - case SchemaType.BTC_BASE_64_BINARY: - { - byte[] byteArr = ((SimpleValue)v).getByteArrayValue(); - set_prepare(); - set_b64(byteArr); - break; - } - case SchemaType.BTC_HEX_BINARY: - { - byte[] byteArr = ((SimpleValue)v).getByteArrayValue(); - set_prepare(); - set_hex(byteArr); - break; - } - case SchemaType.BTC_QNAME: - { - QName name = ((SimpleValue)v).getQNameValue(); - set_prepare(); - set_QName(name); - break; - } - case SchemaType.BTC_FLOAT: - { - float f = ((SimpleValue)v).getFloatValue(); - set_prepare(); - set_float(f); - break; - } - case SchemaType.BTC_DOUBLE: - { - double d = ((SimpleValue)v).getDoubleValue(); - set_prepare(); - set_double(d); - break; - } - case SchemaType.BTC_DECIMAL: - { - switch (instanceType.getDecimalSize()) - { - case SchemaType.SIZE_BYTE: - { - byte b = ((SimpleValue)v).getByteValue(); - set_prepare(); - set_byte(b); - break; - } - case SchemaType.SIZE_SHORT: - { - short s = ((SimpleValue)v).getShortValue(); - set_prepare(); - set_short(s); - break; - } - case SchemaType.SIZE_INT: - { - int i = ((SimpleValue)v).getIntValue(); - set_prepare(); - set_int(i); - break; - } - case SchemaType.SIZE_LONG: - { - long l = ((SimpleValue)v).getLongValue(); - set_prepare(); - set_long(l); - break; - } - case SchemaType.SIZE_BIG_INTEGER: - { - BigInteger bi = ((SimpleValue)v).getBigIntegerValue(); - set_prepare(); - set_BigInteger(bi); - break; - } - default: - { - assert(false) : "invalid numeric bit count"; - // fallthrough - } - case SchemaType.SIZE_BIG_DECIMAL: - { - BigDecimal bd = ((SimpleValue)v).getBigDecimalValue(); - set_prepare(); - set_BigDecimal(bd); - break; - } - } - break; - } - case SchemaType.BTC_ANY_URI: - { - String uri = v.getStringValue(); - set_prepare(); - set_text(uri); - break; - } - case SchemaType.BTC_NOTATION: - { - String s = v.getStringValue(); - set_prepare(); - set_notation(s); - break; - } - case SchemaType.BTC_DURATION: - { - GDuration gd = ((SimpleValue)v).getGDurationValue(); - set_prepare(); - set_GDuration(gd); - break; - } - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - { - GDate gd = ((SimpleValue)v).getGDateValue(); - set_prepare(); - set_GDate(gd); - break; - } - case SchemaType.BTC_STRING: - { - String s = v.getStringValue(); - set_prepare(); - set_String(s); - break; - } - case SchemaType.BTC_ANY_SIMPLE: - { - boolean pushed = false; - if (!v.isImmutable()) - { - pushed = true; - NamespaceContext.push(new NamespaceContext(v)); - } - try - { - set_prepare(); - set_xmlanysimple(v); - } - finally - { - if (pushed) - NamespaceContext.pop(); - } - break; - } - } - set_commit(); - return; // primitive node tree copy handled. - } - } - - throw new IllegalStateException("Complex type unexpected"); - } - - private TypeStoreUser setterHelper ( XmlObjectBase src ) - { - check_orphaned(); - - src.check_orphaned(); - - return - get_store().copy_contents_from( src.get_store() ). - get_store().change_type( src.schemaType() ); - } - - public final XmlObject set(XmlObject src) - { - if (isImmutable()) - throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); - - XmlObjectBase obj = underlying(src); - - TypeStoreUser newObj = this; - - if (obj == null) - { - setNil(); - return this; - } - - if (obj.isImmutable()) - setStringValue(obj.getStringValue()); - else - { - boolean noSyncThis = preCheck(); - boolean noSyncObj = obj.preCheck(); - - if (monitor() == obj.monitor()) // both are in the same locale - { - if (noSyncThis) // the locale is not sync - newObj = setterHelper( obj ); - else // the locale is sync - { - synchronized (monitor()) { - newObj = setterHelper( obj ); - } - } - } - else // on different locale's - { - if (noSyncThis) - { - if (noSyncObj) // both unsync - { - newObj = setterHelper( obj ); - } - else // only obj is sync - { - synchronized (obj.monitor()) { - newObj = setterHelper( obj ); - } - } - } - else - { - if (noSyncObj) // only this is sync - { - synchronized (monitor()) { - newObj = setterHelper( obj ); - } - } - else // both are sync can't avoid the global lock - { - boolean acquired = false; - - try - { - // about to grab two locks: don't deadlock ourselves - GlobalLock.acquire(); - acquired = true; - - synchronized (monitor()) - { - synchronized (obj.monitor()) - { - GlobalLock.release(); - acquired = false; - - newObj = setterHelper( obj ); - } - } - } - catch (InterruptedException e) - { - throw new XmlRuntimeException(e); - } - finally - { - if (acquired) - GlobalLock.release(); - } - } - } - } - } - - return (XmlObject) newObj; - } - - public final XmlObject generatedSetterHelperImpl(XmlObject src, QName propName, int index, - short kindSetterHelper) - { - - XmlObjectBase srcObj = underlying(src); - - if (srcObj == null) - { - synchronized (monitor()) - { - XmlObjectBase target = getTargetForSetter(propName, index, kindSetterHelper); - target.setNil(); - return target; - } - } - - if (srcObj.isImmutable()) - { - synchronized (monitor()) - { - XmlObjectBase target = getTargetForSetter(propName, index, kindSetterHelper); - target.setStringValue(srcObj.getStringValue()); - return (XmlObject) target; - } - } - - - boolean noSyncThis = preCheck(); - boolean noSyncObj = srcObj.preCheck(); - - if (monitor() == srcObj.monitor()) // both are in the same locale - { - if (noSyncThis) // the locale is not sync - { - return (XmlObject)objSetterHelper(srcObj, propName, index, kindSetterHelper); - } - else // the locale is sync - { - synchronized (monitor()) - { - return (XmlObject)objSetterHelper(srcObj, propName, index, kindSetterHelper); - } - } - } - - // on different locale's - if (noSyncThis) - { - if (noSyncObj) // both unsync - { - return (XmlObject)objSetterHelper(srcObj, propName, index, kindSetterHelper); - } - else // only obj is sync - { - synchronized (srcObj.monitor()) - { - return (XmlObject)objSetterHelper(srcObj, propName, index, kindSetterHelper); - } - } - } - else - { - if (noSyncObj) // only this is sync - { - synchronized (monitor()) - { - return (XmlObject)objSetterHelper(srcObj, propName, index, kindSetterHelper); - } - } - else // both are sync can't avoid the global lock - { - boolean acquired = false; - - try - { - // about to grab two locks: don't deadlock ourselves - GlobalLock.acquire(); - acquired = true; - - synchronized (monitor()) - { - synchronized (srcObj.monitor()) - { - GlobalLock.release(); - acquired = false; - - return (XmlObject)objSetterHelper(srcObj, propName, index, kindSetterHelper); - } - } - } - catch (InterruptedException e) - { - throw new XmlRuntimeException(e); - } - finally - { - if (acquired) - GlobalLock.release(); - } - } - } - } - - private TypeStoreUser objSetterHelper(XmlObjectBase srcObj, QName propName, int index, short kindSetterHelper) - { - XmlObjectBase target = getTargetForSetter(propName, index, kindSetterHelper); - - target.check_orphaned(); - srcObj.check_orphaned(); - - return target.get_store().copy_contents_from( srcObj.get_store() ). - get_store().change_type( srcObj.schemaType() ); - } - - private XmlObjectBase getTargetForSetter(QName propName, int index, short kindSetterHelper) - { - switch (kindSetterHelper) - { - case KIND_SETTERHELPER_SINGLETON: - { - check_orphaned(); - XmlObjectBase target = null; - target = (XmlObjectBase)get_store().find_element_user(propName, index); - if (target == null) - { - target = (XmlObjectBase)get_store().add_element_user(propName); - } - - if (target.isImmutable()) - throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); - - return target; - } - - case KIND_SETTERHELPER_ARRAYITEM: - { - check_orphaned(); - XmlObjectBase target = null; - target = (XmlObjectBase)get_store().find_element_user(propName, index); - if (target == null) - { - throw new IndexOutOfBoundsException(); - } - - if (target.isImmutable()) - throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); - - return target; - } - - default: - throw new IllegalArgumentException("Unknown kindSetterHelper: " + kindSetterHelper); - } - } - - /** - * Same as set() but unsynchronized. - * Warning: Using this method in mutithreaded environment can cause invalid states. - */ - public final XmlObject _set(XmlObject src) - { - if (isImmutable()) - throw new IllegalStateException("Cannot set the value of an immutable XmlObject"); - - XmlObjectBase obj = underlying(src); - - TypeStoreUser newObj = this; - - if (obj == null) - { - setNil(); - return this; - } - - if (obj.isImmutable()) - set(obj.stringValue()); - else - { - check_orphaned(); - obj.check_orphaned(); - - newObj = get_store().copy_contents_from( obj.get_store() ). - get_store().change_type( obj.schemaType() ); - } - return (XmlObject) newObj; - } - - protected void set_list(List list) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"List", getPrimitiveTypeName() }); } - protected void set_boolean(boolean v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"boolean", getPrimitiveTypeName() }); } - protected void set_byte(byte v) - { set_int((int) v); } - protected void set_short(short v) - { set_int((int) v); } - protected void set_int(int v) - { set_long((long) v); } - protected void set_long(long v) - { set_BigInteger(BigInteger.valueOf(v)); } - protected void set_char(char v) - { set_String(Character.toString(v)); } - protected void set_float(float v) - { set_BigDecimal(new BigDecimal(v)); } - protected void set_double(double v) - { set_BigDecimal(new BigDecimal(v)); } - - protected void set_enum(StringEnumAbstractBase e) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"enum", getPrimitiveTypeName() }); } - - protected void set_ByteArray(byte[] b) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"byte[]", getPrimitiveTypeName() }); } - protected void set_b64(byte[] b) - { set_ByteArray(b); } - protected void set_hex(byte[] b) - { set_ByteArray(b); } - protected void set_BigInteger(BigInteger v) - { set_BigDecimal(new BigDecimal(v)); } - protected void set_BigDecimal(BigDecimal v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"numeric", getPrimitiveTypeName() }); } - protected void set_Date(Date v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"Date", getPrimitiveTypeName() }); } - protected void set_Calendar(Calendar v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"Calendar", getPrimitiveTypeName() }); } - protected void set_GDate(GDateSpecification v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"Date", getPrimitiveTypeName() }); } - protected void set_GDuration(GDurationSpecification v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"Duration", getPrimitiveTypeName() }); } - protected void set_ComplexXml(XmlObject v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"complex content", getPrimitiveTypeName() }); } - protected void set_QName(QName v) - { throw new XmlValueNotSupportedException(XmlErrorCodes.EXCEPTION_VALUE_NOT_SUPPORTED_J2S, - new Object[] {"QName", getPrimitiveTypeName() }); } - - protected void set_notation(String v) - { throw new XmlValueNotSupportedException(); } - - protected void set_xmlanysimple(XmlAnySimpleType v) - { set_String(v.getStringValue()); } - - private final String getPrimitiveTypeName() - { - SchemaType type = schemaType(); - if (type.isNoType()) - return "unknown"; - SchemaType t = type.getPrimitiveType(); - if (t == null) - return "complex"; - else - return t.getName().getLocalPart(); - } - - private final boolean comparable_value_spaces(SchemaType t1, SchemaType t2) - { - assert(t1.getSimpleVariety() != SchemaType.UNION && t2.getSimpleVariety() != SchemaType.UNION); - - if (!t1.isSimpleType() && !t2.isSimpleType()) - return (t1.getContentType() == t2.getContentType()); - - if (!t1.isSimpleType() || !t2.isSimpleType()) - return false; - - if (t1.getSimpleVariety() == SchemaType.LIST && t2.getSimpleVariety() == SchemaType.LIST) - return true; - - if (t1.getSimpleVariety() == SchemaType.LIST || t2.getSimpleVariety() == SchemaType.LIST) - return false; - - return (t1.getPrimitiveType().equals(t2.getPrimitiveType())); - } - - private final boolean valueEqualsImpl(XmlObject xmlobj) - { - check_dated(); - - SchemaType typethis = instanceType(); - SchemaType typeother = ((SimpleValue)xmlobj).instanceType(); - - if (typethis == null && typeother == null) // detects nil - return true; - - if (typethis == null || typeother == null) - return false; - - if (!comparable_value_spaces(typethis, typeother)) - return false; - - if (xmlobj.schemaType().getSimpleVariety() == SchemaType.UNION) - return (underlying(xmlobj)).equal_to(this); - - return equal_to(xmlobj); - } - - public final boolean valueEquals(XmlObject xmlobj) - { - boolean acquired = false; - try - { - if (isImmutable()) - { - if (xmlobj.isImmutable()) - { - return valueEqualsImpl(xmlobj); - } - else - { - synchronized (xmlobj.monitor()) - { - return valueEqualsImpl(xmlobj); - } - } - } - else - { - if (xmlobj.isImmutable() || monitor() == xmlobj.monitor()) - { - synchronized (monitor()) - { - return valueEqualsImpl(xmlobj); - } - } - else - { - GlobalLock.acquire(); - acquired = true; - synchronized (monitor()) - { - synchronized (xmlobj.monitor()) - { - GlobalLock.release(); - acquired = false; - return valueEqualsImpl(xmlobj); - } - } - } - } - - } - catch (InterruptedException e) - { - throw new XmlRuntimeException(e); - } - finally - { - if (acquired) - GlobalLock.release(); - } - } - - /** - * Implements Comparable. This compareTo is inconsistent with - * equals unless isImmutable() is true. - */ - public final int compareTo(Object obj) - { - int result = compareValue((XmlObject)obj); // can throw ClassCast - if (result == 2) - throw new ClassCastException(); - return result; - } - - /** - * Allowed to return 2 for incomparable. - */ - private final int compareValueImpl(XmlObject xmlobj) - { - SchemaType type1, type2; - - try - { - type1 = instanceType(); - type2 = ((SimpleValue)xmlobj).instanceType(); - } - catch (XmlValueOutOfRangeException e) - { - return 2; - } - - if (type1 == null && type2 == null) - return 0; - if (type1 == null || type2 == null) - return 2; - - if (!type1.isSimpleType() || type1.isURType()) - return 2; - - if (!type2.isSimpleType() || type2.isURType()) - return 2; - - type1 = type1.getPrimitiveType(); - type2 = type2.getPrimitiveType(); - - // Different value spaces: different - if (type1.getBuiltinTypeCode() != type2.getBuiltinTypeCode()) - return 2; - - // now we'll depend on our impl class to do the work - return compare_to(xmlobj); - } - - public final int compareValue(XmlObject xmlobj) - { - if (xmlobj == null) - return 2; - - boolean acquired = false; - try - { - if (isImmutable()) - { - if (xmlobj.isImmutable()) - { - return compareValueImpl(xmlobj); - } - else - { - synchronized (xmlobj.monitor()) - { - return compareValueImpl(xmlobj); - } - } - } - else - { - if (xmlobj.isImmutable() || monitor() == xmlobj.monitor()) - { - synchronized (monitor()) - { - return compareValueImpl(xmlobj); - } - } - else - { - GlobalLock.acquire(); - acquired = true; - synchronized (monitor()) - { - synchronized (xmlobj.monitor()) - { - GlobalLock.release(); - acquired = false; - return compareValueImpl(xmlobj); - } - } - } - } - - } - catch (InterruptedException e) - { - throw new XmlRuntimeException(e); - } - finally - { - if (acquired) - GlobalLock.release(); - } - } - /** - * This implementation of compare_to is allowed to do two - * unusual things: - * (1) it can assume that the xmlobj passed has a primitive - * type underlying the instance type that matches the - * current instance, and that neither is nil. - * (2) it is allowed to return 2 for "incomparable"; - * it should not throw an exception. - */ - protected int compare_to(XmlObject xmlobj) - { - if (equal_to(xmlobj)) - return 0; - return 2; - } - - protected abstract boolean equal_to(XmlObject xmlobj); - - protected abstract int value_hash_code(); - - public int valueHashCode() - { - synchronized (monitor()) - { - return value_hash_code(); - } - } - - - public boolean isInstanceOf(SchemaType type) - { - SchemaType myType; - - if (type.getSimpleVariety() != SchemaType.UNION) - { - for (myType = instanceType(); myType != null; myType = myType.getBaseType()) - if (type == myType) - return true; - return false; - } - else - { - Set ctypes = new HashSet(Arrays.asList(type.getUnionConstituentTypes())); - for (myType = instanceType(); myType != null; myType = myType.getBaseType()) - if (ctypes.contains(myType)) - return true; - return false; - } - } - - public final boolean equals(Object obj) - { - if (!isImmutable()) - return super.equals(obj); - - if (!(obj instanceof XmlObject)) - return false; - - XmlObject xmlobj = (XmlObject)obj; - if (!xmlobj.isImmutable()) - return false; - - return valueEquals(xmlobj); - } - - public final int hashCode() - { - if (!isImmutable()) - return super.hashCode(); - - synchronized (monitor()) - { - if (isNil()) - return 0; - - return value_hash_code(); - } - } - - private static final XmlObject[] EMPTY_RESULT = new XmlObject[0]; - - /** - * Selects the contents of the children elements with the given name. - */ - public XmlObject[] selectChildren(QName elementName) - { - XmlCursor xc = this.newCursor(); - try - { - if (!xc.isContainer()) - return EMPTY_RESULT; - - List result = new ArrayList(); - - if (xc.toChild(elementName)) - { - // look for elements - do - { - result.add(xc.getObject()); - } - while (xc.toNextSibling(elementName)); - } - if (result.size() == 0) - return EMPTY_RESULT; - else - return (XmlObject[]) result.toArray(EMPTY_RESULT); - } - finally - { - xc.dispose(); - } - } - - /** - * Selects the contents of the children elements with the given name. - */ - public XmlObject[] selectChildren(String elementUri, String elementLocalName) - { - return selectChildren(new QName(elementUri, elementLocalName)); - } - - /** - * Selects the contents of the children elements that are contained in the elementNameSet. - */ - public XmlObject[] selectChildren(QNameSet elementNameSet) - { - if (elementNameSet==null) - throw new IllegalArgumentException(); - - XmlCursor xc = this.newCursor(); - try - { - if (!xc.isContainer()) - return EMPTY_RESULT; - - List result = new ArrayList(); - - if (xc.toFirstChild()) - { - // look for elements - do - { - assert xc.isContainer(); - if (elementNameSet.contains(xc.getName())) - { - result.add(xc.getObject()); - } - } - while (xc.toNextSibling()); - } - if (result.size() == 0) - return EMPTY_RESULT; - else - return (XmlObject[]) result.toArray(EMPTY_RESULT); - } - finally - { - xc.dispose(); - } - } - - /** - * Selects the content of the attribute with the given name. - */ - public XmlObject selectAttribute(QName attributeName) - { - XmlCursor xc = this.newCursor(); - - try - { - if (!xc.isContainer()) - return null; - - if (xc.toFirstAttribute()) - { - //look for attributes - do - { - if (xc.getName().equals(attributeName)) - { - return xc.getObject(); - } - } - while (xc.toNextAttribute()); - } - return null; - } - finally - { - xc.dispose(); - } - } - - /** - * Selects the content of the attribute with the given name. - */ - public XmlObject selectAttribute(String attributeUri, String attributeLocalName) - { - return selectAttribute(new QName(attributeUri, attributeLocalName)); - } - - /** - * Selects the contents of the attributes that are contained in the elementNameSet. - */ - public XmlObject[] selectAttributes(QNameSet attributeNameSet) - { - if (attributeNameSet==null) - throw new IllegalArgumentException(); - - XmlCursor xc = this.newCursor(); - try - { - if (!xc.isContainer()) - return EMPTY_RESULT; - - List result = new ArrayList(); - - if (xc.toFirstAttribute()) - { - //look for attributes - do - { - if (attributeNameSet.contains(xc.getName())) - { - result.add(xc.getObject()); - } - } - while (xc.toNextAttribute()); - } - - if (result.size() == 0) - return EMPTY_RESULT; - else - return (XmlObject[]) result.toArray(EMPTY_RESULT); - } - finally - { - xc.dispose(); - } - } - - /** - * This method can writeReplace either an unwrapped XmlObjectBase - * or an XBean proxy. A "true" argument means unwrapped. - * - * The serialization strategy for XmlObjects is this: - * - * (1) Only the root XmlObject for a document actually gets - * fully serialized; it is serialized as a SerializedRootObject, - * which simply saves itself as XML text. - * - * (2) Interior XmlObjects get serialized as a reference to the - * root XmlObject for their document, plus an integer which - * indicates the position of the XmlObject within the owner - * document. This pair is stored as a SerializedInteriorObject. - * - * Both objects can be maked as wrapped or unwrapped. If wrapped, - * then the proxy is returned when deserializing; if unwrapped, then - * the proxy is stripped when deserializing. - */ - public Object writeReplace() - { - synchronized (monitor()) - { - if (isRootXmlObject()) - return new SerializedRootObject(this); - - return new SerializedInteriorObject(this, getRootXmlObject()); - } - } - - /** - * True if the object is at the root of the document. - */ - private boolean isRootXmlObject() - { - XmlCursor cur = newCursor(); - if (cur == null) - return false; - - boolean result = !cur.toParent(); - cur.dispose(); - return result; - } - - /** - * Gets the root XmlObject for this document. - */ - private XmlObject getRootXmlObject() - { - XmlCursor cur = newCursor(); - if (cur == null) - return this; - cur.toStartDoc(); - XmlObject result = cur.getObject(); - cur.dispose(); - return result; - } - - /** - * Serializable rewrite object that knows how to resolve - * to an XmlObjectBase or a proxy for the root object of - * a document. - */ - private static class SerializedRootObject implements Serializable - { - private static final long serialVersionUID = 1; - - transient Class _xbeanClass; - transient XmlObject _impl; - - private SerializedRootObject() - { - } - - private SerializedRootObject(XmlObject impl) - { - _xbeanClass = impl.schemaType().getJavaClass(); - _impl = impl; - } - - private void writeObject(ObjectOutputStream out) throws IOException - { - out.writeObject(_xbeanClass); - // the first short is written out for backwards compatibility - // it will always be zero for objects written with - // this code, but it used to be the first 2 bytes of the - // writeUTF() method - out.writeShort((short)0); - out.writeShort(MAJOR_VERSION_NUMBER); - out.writeShort(MINOR_VERSION_NUMBER); - // CR122401 - need to use writeObject instead of writeUTF - // for xmlText as writeUTF has a length limitation of - // 65535 bytes - String xmlText = _impl.xmlText(); - out.writeObject(xmlText); - out.writeBoolean(false); - } - - private void readObject(ObjectInputStream in) throws IOException - { - try - { - // read class object first - this is - // first just for historical reasons - really - // it would be better to have the version numbers - // first - _xbeanClass = (Class)in.readObject(); - - int utfBytes = in.readUnsignedShort(); - - // determine version numbers - // if utfBytes is non-zero then we default to 0.0 - // otherwise expect major and minor version numbers - // to be next entries in stream - int majorVersionNum = 0; - int minorVersionNum = 0; - if (utfBytes == 0) - { - majorVersionNum = in.readUnsignedShort(); - minorVersionNum = in.readUnsignedShort(); - } - - String xmlText = null; - switch (majorVersionNum) - { - case 0: // original, unnumbered version - // minorVersionNum is always zero - xmlText = readObjectV0(in, utfBytes); - in.readBoolean(); // ignored - break; - - case 1: - switch (minorVersionNum) - { - case 1: - xmlText = (String)in.readObject(); - in.readBoolean(); // ignored - break; - - default: - throw new IOException("Deserialization error: " + - "version number " + majorVersionNum + "." + - minorVersionNum + " not supported."); - } - break; - - default: - throw new IOException("Deserialization error: " + - "version number " + majorVersionNum + "." + - minorVersionNum + " not supported."); - } - - XmlOptions opts = new XmlOptions().setDocumentType(XmlBeans.typeForClass(_xbeanClass)); - _impl = XmlBeans.getContextTypeLoader().parse(xmlText, null, opts); - } - catch (Exception e) - { - throw (IOException)(new IOException(e.getMessage()).initCause(e)); - } - } - - // this method is for reading the UTF-8 String that used to be - // written out for a serialized XmlObject according to the - // original format before this fix, i.e. it expects it - // to have been written using the following algorithm: - // - // writeObject(Class object) - // writeUTF(xmlText of object as String) - // writeBoolean() - // - // this method is passed the original input stream positioned as though - // it had just read the class object plus the next 2 bytes. Those 2 - // bytes are interpreted as an unsigned short saying how many more - // bytes there are representing the bytes of the UTF-8-formatted String; - // this value is passed in as the argument utfBytes - private String readObjectV0(ObjectInputStream in, int utfBytes) - throws IOException - { - // allow an extra 2 bytes up front for the unsigned short - byte[] bArray = new byte[utfBytes+2]; - - // for format of these first 2 bytes see - // Java API docs - DataOutputStream.writeShort() - bArray[0] = (byte)( 0xff & (utfBytes >> 8) ); - bArray[1] = (byte)( 0xff & utfBytes ); - - // read the next numBytes bytes from the input stream - // into the byte array starting at offset 2; this may - // take multiple calls to read() - int totalBytesRead = 0; - int numRead; - while (totalBytesRead < utfBytes) - { - numRead = - in.read(bArray, 2+totalBytesRead, utfBytes-totalBytesRead); - if (numRead == -1) // reached end of stream - break; - - totalBytesRead += numRead; - } - - if (totalBytesRead != utfBytes) - { - throw new IOException("Error reading backwards compatible " + - "XmlObject: number of bytes read (" + totalBytesRead + - ") != number expected (" + utfBytes + ")" ); - } - - // now set up a DataInputStream to read those - // bytes as a UTF-8 String i.e. as though we'd never - // read the first 2 bytes from the original stream - DataInputStream dis = null; - String str = null; - try - { - dis = new DataInputStream(new ByteArrayInputStream(bArray)); - str = dis.readUTF(); - } - finally - { - if (dis != null) - dis.close(); - } - - return str; - } - - private Object readResolve() throws ObjectStreamException - { - return _impl; - } - } - - /** - * Serializable rewrite object that knows how to resolve - * to an XmlObjectBase or a proxy for an interior position - * within a document. - */ - private static class SerializedInteriorObject implements Serializable - { - private static final long serialVersionUID = 1; - - transient XmlObject _impl; - transient XmlObject _root; - - private SerializedInteriorObject() - { - } - - private SerializedInteriorObject(XmlObject impl, XmlObject root) - { - _impl = impl; - _root = root; - } - - private void writeObject(ObjectOutputStream out) throws IOException - { - out.writeObject(_root); - out.writeBoolean(false); - out.writeInt(distanceToRoot()); - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException - { - _root = (XmlObject)in.readObject(); - in.readBoolean(); - _impl = objectAtDistance(in.readInt()); - } - - private Object readResolve() throws ObjectStreamException - { - return _impl; - } - - private int distanceToRoot() - { - XmlCursor cur = _impl.newCursor(); - int count = 0; - while (!cur.toPrevToken().isNone()) - { - if (!cur.currentTokenType().isNamespace()) - { - count += 1; - // System.out.println("Count: " + count + " " + cur.currentTokenType().toString() + " " + QName.pretty(cur.getName())); - } - } - cur.dispose(); - return count; - } - - private XmlObject objectAtDistance(int count) - { - XmlCursor cur = _root.newCursor(); - while (count > 0) - { - cur.toNextToken(); - if (!cur.currentTokenType().isNamespace()) - { - count -= 1; - // System.out.println("Count: " + count + " " + cur.currentTokenType().toString() + " " + QName.pretty(cur.getName())); - } - } - XmlObject result = cur.getObject(); - cur.dispose(); - return result; - } - } - - protected static Object java_value(XmlObject obj) - { - if (obj.isNil()) - return null; - - if (!(obj instanceof XmlAnySimpleType)) - return obj; - - SchemaType instanceType = ((SimpleValue)obj).instanceType(); - assert(instanceType != null) : "Nil case should have been handled above"; - - // handle lists - if (instanceType.getSimpleVariety() == SchemaType.LIST) - return ((SimpleValue)obj).getListValue(); - - SimpleValue base = (SimpleValue)obj; - - switch (instanceType.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_BOOLEAN: - return base.getBooleanValue() ? Boolean.TRUE : Boolean.FALSE; - - case SchemaType.BTC_BASE_64_BINARY: - case SchemaType.BTC_HEX_BINARY: - return base.getByteArrayValue(); - - case SchemaType.BTC_QNAME: - return base.getQNameValue(); - - case SchemaType.BTC_FLOAT: - return new Float(base.getFloatValue()); - - case SchemaType.BTC_DOUBLE: - return new Double(base.getDoubleValue()); - - case SchemaType.BTC_DECIMAL: - { - switch (instanceType.getDecimalSize()) - { - case SchemaType.SIZE_BYTE: - return new Byte(base.getByteValue()); - - case SchemaType.SIZE_SHORT: - return new Short(base.getShortValue()); - - case SchemaType.SIZE_INT: - return new Integer(base.getIntValue()); - - case SchemaType.SIZE_LONG: - return new Long(base.getLongValue()); - - case SchemaType.SIZE_BIG_INTEGER: - return base.getBigIntegerValue(); - - default: - assert(false) : "invalid numeric bit count"; - // fallthrough - case SchemaType.SIZE_BIG_DECIMAL: - return base.getBigDecimalValue(); - } - } - case SchemaType.BTC_ANY_URI: - return base.getStringValue(); - - case SchemaType.BTC_DURATION: - return base.getGDurationValue(); - - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - return base.getCalendarValue(); - - default: - assert(false) : "encountered nonprimitive type."; - // fallthrough - - // NB: for string enums we just do java.lang.String - // when in the context of unions. It's easier on users. - case SchemaType.BTC_NOTATION: - case SchemaType.BTC_STRING: - case SchemaType.BTC_ANY_SIMPLE: - // return base.getStringValue(); - return base.getStringValue(); - } - } - - /** - * Called by code generated code to get the default attribute value - * for a given attribute name, or null if none. - */ - protected XmlAnySimpleType get_default_attribute_value(QName name) - { - SchemaType sType = schemaType(); - SchemaAttributeModel aModel = sType.getAttributeModel(); - if (aModel == null) - return null; - SchemaLocalAttribute sAttr = aModel.getAttribute(name); - if (sAttr == null) - return null; - return sAttr.getDefaultValue(); - } -} diff --git a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java b/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java deleted file mode 100644 index cfde14b..0000000 --- a/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java +++ /dev/null @@ -1,665 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.values; - -import java.util.Date; -import java.util.List; -import java.util.Calendar; -import java.math.BigInteger; -import java.math.BigDecimal; - -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.StringEnumAbstractBase; -import org.apache.xmlbeans.GDateSpecification; -import org.apache.xmlbeans.GDurationSpecification; -import org.apache.xmlbeans.SimpleValue; - -import org.apache.xmlbeans.impl.schema.SchemaTypeImpl; -import org.apache.xmlbeans.impl.common.ValidationContext; -import org.apache.xmlbeans.impl.common.QNameHelper; - -import javax.xml.namespace.QName; - - -/** - * This class implements simple union types. - * - */ -public class XmlUnionImpl extends XmlObjectBase implements XmlAnySimpleType -{ - public XmlUnionImpl(SchemaType type, boolean complex) - { _schemaType = type; initComplexType(complex, false); } - - public SchemaType schemaType() - { return _schemaType; } - - public SchemaType instanceType() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).instanceType(); } - - private SchemaType _schemaType; - private XmlAnySimpleType _value; // underlying value - private String _textvalue = ""; // textual value - - - - - // SIMPLE VALUE ACCESSORS BELOW ------------------------------------------- - // gets raw text value - - protected String compute_text(NamespaceManager nsm) - { return _textvalue; } - - protected boolean is_defaultable_ws(String v) { - try { - XmlAnySimpleType savedValue = _value; - set_text(v); - - // restore the saved value - _value = savedValue; - - return false; - } - catch (XmlValueOutOfRangeException e) { - return true; - } - } - - protected void set_text(String s) - { - // first check against any patterns... - if (!_schemaType.matchPatternFacet(s) && _validateOnSet()) - throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID, - new Object[] { "string", s, QNameHelper.readable(_schemaType) }); - - - // save state for rollback - String original = _textvalue; - _textvalue = s; - - // iterate through the types, trying to create a type - SchemaType[] members = _schemaType.getUnionConstituentTypes(); - assert(members != null); - - boolean pushed = false; - // boolean wasstrict = set_strict(true); // tell types to complain ferverently about errors - if (has_store()) - { - NamespaceContext.push(new NamespaceContext(get_store())); - pushed = true; - } - try - { - for (boolean validate = true; validate || !_validateOnSet(); validate = false) - { - for (int i = 0; i < members.length; i++) - { - // From the point of view of the following call, "this" is a generic - // XmlAnySimpleType implementation, for which only getText can be called. - // (Note that "this" is not wrapped in the proxy object.) - try - { - XmlAnySimpleType newval = ((SchemaTypeImpl)members[i]).newValue(s, validate); - - // now we need to check against (enuemration) restrictions - if (!check(newval, _schemaType)) - continue; - - // found one that works! - _value = newval; - return; - } - catch (XmlValueOutOfRangeException e) - { - continue; - } - catch (Exception e) - { - throw new RuntimeException("Troublesome union exception caused by unexpected " + e, e); - // assert(false) : "Unexpected " + e; - // continue; - } - } - if (!validate) - break; - } - } - finally - { - if (pushed) - NamespaceContext.pop(); - // set_strict(wasstrict); - } - - - // doesn't match any of the members; rollback and throw - _textvalue = original; - throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$UNION, - new Object[] { s, QNameHelper.readable(_schemaType) }); - } - - protected void set_nil() - { - _value = null; - _textvalue = null; - } - - protected int get_wscanon_rule() { return SchemaType.WS_PRESERVE; } - - - // numerics - public float getFloatValue() - { check_dated(); return _value == null ? 0.0f : ((SimpleValue)_value).getFloatValue(); } - - public double getDoubleValue() - { check_dated(); return _value == null ? 0.0 : ((SimpleValue)_value).getDoubleValue(); } - - public BigDecimal getBigDecimalValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getBigDecimalValue(); } - - public BigInteger getBigIntegerValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getBigIntegerValue(); } - - public byte getByteValue() - { check_dated(); return _value == null ? 0 : ((SimpleValue)_value).getByteValue(); } - - public short getShortValue() - { check_dated(); return _value == null ? 0 : ((SimpleValue)_value).getShortValue(); } - - public int getIntValue() - { check_dated(); return _value == null ? 0 : ((SimpleValue)_value).getIntValue(); } - - public long getLongValue() - { check_dated(); return _value == null ? 0 : ((SimpleValue)_value).getLongValue(); } - - - // various - public byte[] getByteArrayValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getByteArrayValue(); } - - public boolean getBooleanValue() - { check_dated(); return _value == null ? false : ((SimpleValue)_value).getBooleanValue(); } - - public Calendar getCalendarValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getCalendarValue(); } - - public Date getDateValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getDateValue(); } - - public GDate getGDateValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getGDateValue(); } - - public GDuration getGDurationValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getGDurationValue(); } - - public QName getQNameValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getQNameValue(); } - - public List getListValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getListValue(); } - - public List xgetListValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).xgetListValue(); } - - public StringEnumAbstractBase getEnumValue() - { check_dated(); return _value == null ? null : ((SimpleValue)_value).getEnumValue(); } - - public String getStringValue() - { check_dated(); return _value == null ? null : _value.getStringValue(); } - - /** - * Returns true if the space of canonical lexical forms - * of the first (source) type overlaps with the full lexical space - * of the second (target) type. Both types must be primitives. - */ - static boolean lexical_overlap(int source, int target) - { - // types are the same - if (source == target) - return true; - - // one of the types has the full lexical space - if (source == SchemaType.BTC_ANY_SIMPLE || - target == SchemaType.BTC_ANY_SIMPLE || - source == SchemaType.BTC_STRING || - target == SchemaType.BTC_STRING || - source == SchemaType.BTC_ANY_URI || - target == SchemaType.BTC_ANY_URI) - return true; - - switch (source) - { - case SchemaType.BTC_BOOLEAN: switch(target) - { - case SchemaType.BTC_QNAME: // "true" is valid NcName and therefore QName - case SchemaType.BTC_NOTATION: // "true" is valid NCName - return true; - default: - return false; - } - case SchemaType.BTC_BASE_64_BINARY: switch(target) - { - case SchemaType.BTC_BOOLEAN: // "0" is valid boolean - case SchemaType.BTC_HEX_BINARY: // "0" is valid hex - case SchemaType.BTC_QNAME: // "a" is valid NcName and therefore QName - case SchemaType.BTC_NOTATION: // "a" is valid NcName - case SchemaType.BTC_FLOAT: // "0" is valid float - case SchemaType.BTC_DOUBLE: // "0" is valid double - case SchemaType.BTC_DECIMAL: // "0" is valid decimal - case SchemaType.BTC_DURATION: // "P1Y2M3DT10H30M" is both b64 and duration - case SchemaType.BTC_G_YEAR: // "1999" is valid year - return true; - default: - return false; // "-" and ":" cannot come from b64 - } - case SchemaType.BTC_HEX_BINARY: switch(target) - { - case SchemaType.BTC_BOOLEAN: // "0" is valid boolean - case SchemaType.BTC_BASE_64_BINARY: // "0" is valid b64 - case SchemaType.BTC_QNAME: // "A" is valid NcName and therefore QName - case SchemaType.BTC_NOTATION: // "A" is valid NcName - case SchemaType.BTC_FLOAT: // "0" is valid float - case SchemaType.BTC_DOUBLE: // "0" is valid double - case SchemaType.BTC_DECIMAL: // "0" is valid decimal - case SchemaType.BTC_G_YEAR: // "1999" is valid year - return true; - default: - return false; // "-" and ":" cannot come from b64 - } - case SchemaType.BTC_QNAME: - case SchemaType.BTC_NOTATION: switch(target) - { - case SchemaType.BTC_BOOLEAN: // "true" is valid boolean - case SchemaType.BTC_BASE_64_BINARY: // "a" is valid b64 - case SchemaType.BTC_HEX_BINARY: // "a" is valid hex - case SchemaType.BTC_QNAME: // "A" is valid NcName and therefore QName - case SchemaType.BTC_NOTATION: // "A" is valid NcName and therefore QName - case SchemaType.BTC_DURATION: // "P1Y2M3DT10H30M" is both NcName and duration - return true; - default: - return false; - } - case SchemaType.BTC_FLOAT: - case SchemaType.BTC_DOUBLE: - case SchemaType.BTC_DECIMAL: - case SchemaType.BTC_G_YEAR: switch(target) - { - case SchemaType.BTC_BASE_64_BINARY: // "0" is valid b64 - case SchemaType.BTC_HEX_BINARY: // "0" is valid hex - case SchemaType.BTC_FLOAT: // "0" is valid float - case SchemaType.BTC_DOUBLE: // "0" is valid double - case SchemaType.BTC_DECIMAL: // "0" is valid decimal - case SchemaType.BTC_G_YEAR: // "1999" is valid year - return true; - default: - return false; - } - case SchemaType.BTC_DURATION: switch(target) - { - case SchemaType.BTC_QNAME: - case SchemaType.BTC_NOTATION: - case SchemaType.BTC_BASE_64_BINARY: - return true; - default: - return false; - } - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - default: - return false; - } - } - - /** - * True if the given schema type's logical type is a match for - * the given category of java concepts. - */ - - private static final int JAVA_NUMBER = SchemaType.BTC_LAST_BUILTIN + 1; - private static final int JAVA_DATE = SchemaType.BTC_LAST_BUILTIN + 2; - private static final int JAVA_CALENDAR = SchemaType.BTC_LAST_BUILTIN + 3; - private static final int JAVA_BYTEARRAY = SchemaType.BTC_LAST_BUILTIN + 4; - private static final int JAVA_LIST = SchemaType.BTC_LAST_BUILTIN + 5; - - private static boolean logical_overlap(SchemaType type, int javacode) - { - // non-union types because it's being applied on irreducible union members! - assert(type.getSimpleVariety() != SchemaType.UNION); - - if (javacode <= SchemaType.BTC_LAST_BUILTIN) - { - if (type.getSimpleVariety() != SchemaType.ATOMIC) - return false; - - return (type.getPrimitiveType().getBuiltinTypeCode() == javacode); - } - - switch (javacode) - { - case JAVA_NUMBER: - { - if (type.getSimpleVariety() != SchemaType.ATOMIC) - return false; - - switch (type.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_FLOAT: - case SchemaType.BTC_DOUBLE: - case SchemaType.BTC_DECIMAL: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH: - case SchemaType.BTC_G_DAY: - return true; - } - return false; - } - case JAVA_DATE: - { - if (type.getSimpleVariety() != SchemaType.ATOMIC) - return false; - - switch (type.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_DATE: - return true; - } - return false; - } - case JAVA_CALENDAR: - { - if (type.getSimpleVariety() != SchemaType.ATOMIC) - return false; - - switch (type.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_TIME: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH: - case SchemaType.BTC_G_DAY: - return true; - } - return false; - } - - case JAVA_BYTEARRAY: - { - if (type.getSimpleVariety() != SchemaType.ATOMIC) - return false; - - switch (type.getPrimitiveType().getBuiltinTypeCode()) - { - case SchemaType.BTC_BASE_64_BINARY: - case SchemaType.BTC_HEX_BINARY: - return true; - } - return false; - } - case JAVA_LIST: - { - return (type.getSimpleVariety() == SchemaType.LIST); - } - } - - assert(false) : "missing case"; - return false; - } - - /** - * Grabs a chained value of type st, creating and attaching - * one if not present. - */ - private void set_primitive(int typecode, Object val) - { - SchemaType[] members = _schemaType.getUnionConstituentTypes(); - assert(members != null); - - boolean pushed = false; - if (has_store()) - { - NamespaceContext.push(new NamespaceContext(get_store())); - pushed = true; - } - try - { - for (boolean validate = true; validate || !_validateOnSet(); validate = false) - { - outer: for (int i = 0; i < members.length; i++) - { - // candidates must be a logical match for the desired typecode - if (logical_overlap(members[i], typecode)) - { - XmlAnySimpleType newval; - - try - { - newval = ((SchemaTypeImpl) members[i]).newValue(val, validate); - } - catch (XmlValueOutOfRangeException e) - { - // doesn't match this type even though logical categories - // line up (probably because of restriciton); try the next type. - continue outer; - } - catch (Exception e) - { - assert(false) : "Unexpected " + e; - continue outer; - } - - /* TODO: rethink this - disabling for now. - - // OK, now we've got a newval... We have to verify - // that lexically it doesn't overlap with previous types - - String newvaltext = null; - - inner: for (int j = 0; j < i; j++) - { - if (members[j].getSimpleVariety() == SchemaType.LIST || - lexical_overlap(members[j].getPrimitiveType().getBuiltinTypeCode(), - newval.schemaType().getPrimitiveType().getBuiltinTypeCode())) - { - // there is a preceding type that may lexically overlap with ours... - // if it lexically contains the string representation of our new - // proposed value, then it's impossible for the union to have our - // logical value (because it would have been masked) and throw an - // error. - if (newvaltext == null) - newvaltext = newval.stringValue(); - try - { - // discard return value - members[i].newValue(newvaltext); - - // oh bad, we succeeded. Our instance lexically looks like a - // previous type, and this isn't a valid value. Keep on hunting. - continue outer; - } - catch (XmlValueOutOfRangeException e) - { - // this is good: this error means that our value doesn't look like - // the other type. - continue inner; - } - } - } - - */ - - // No lexical masking: we're OK - _value = newval; - _textvalue = _value.stringValue(); - return; - } - } - if (!validate) - break; - } - } - finally - { - if (pushed) - NamespaceContext.pop(); - } - - // doesn't match any of the members; throw - throw new XmlValueOutOfRangeException(XmlErrorCodes.DATATYPE_VALID$UNION, - new Object[] { val.toString(), QNameHelper.readable(_schemaType) }); - } - - // here are the setters - - protected void set_boolean(boolean v) - { set_primitive(SchemaType.BTC_BOOLEAN, new Boolean(v)); } - - protected void set_byte(byte v) - { set_primitive(JAVA_NUMBER, new Byte(v)); } - protected void set_short(short v) - { set_primitive(JAVA_NUMBER, new Short(v)); } - protected void set_int(int v) - { set_primitive(JAVA_NUMBER, new Integer(v)); } - protected void set_long(long v) - { set_primitive(JAVA_NUMBER, new Long(v)); } - protected void set_float(float v) - { set_primitive(JAVA_NUMBER, new Float(v)); } - protected void set_double(double v) - { set_primitive(JAVA_NUMBER, new Double(v)); } - - protected void set_ByteArray(byte[] b) - { set_primitive(JAVA_BYTEARRAY, b); } - protected void set_hex(byte[] b) - { set_primitive(JAVA_BYTEARRAY, b); } - protected void set_b64(byte[] b) - { set_primitive(JAVA_BYTEARRAY, b); } - protected void set_BigInteger(BigInteger v) - { set_primitive(JAVA_NUMBER, v); } - protected void set_BigDecimal(BigDecimal v) - { set_primitive(JAVA_NUMBER, v); } - protected void set_QName(QName v) - { set_primitive(SchemaType.BTC_QNAME, v); } - - protected void set_Calendar(Calendar c) - { set_primitive(JAVA_CALENDAR, c); } - protected void set_Date(Date d) - { set_primitive(JAVA_DATE, d); } - protected void set_GDate(GDateSpecification d) - { - int btc = d.getBuiltinTypeCode(); - if (btc <= 0) - throw new XmlValueOutOfRangeException(); - set_primitive(btc, d); - } - - protected void set_GDuration(GDurationSpecification d) - { set_primitive(SchemaType.BTC_DURATION, d); } - - protected void set_enum(StringEnumAbstractBase e) - { set_primitive(SchemaType.BTC_STRING, e); } - - protected void set_list(List v) - { set_primitive(JAVA_LIST, v); } - - - protected void set_xmlfloat(XmlObject v) - { set_primitive(SchemaType.BTC_FLOAT, v); } - protected void set_xmldouble(XmlObject v) - { set_primitive(SchemaType.BTC_DOUBLE, v); } - protected void set_xmldecimal(XmlObject v) - { set_primitive(SchemaType.BTC_DECIMAL, v); } - protected void set_xmlduration(XmlObject v) - { set_primitive(SchemaType.BTC_DURATION, v); } - protected void set_xmldatetime(XmlObject v) - { set_primitive(SchemaType.BTC_DATE_TIME, v); } - protected void set_xmltime(XmlObject v) - { set_primitive(SchemaType.BTC_TIME, v); } - protected void set_xmldate(XmlObject v) - { set_primitive(SchemaType.BTC_DATE, v); } - protected void set_xmlgyearmonth(XmlObject v) - { set_primitive(SchemaType.BTC_G_YEAR_MONTH, v); } - protected void set_xmlgyear(XmlObject v) - { set_primitive(SchemaType.BTC_G_YEAR, v); } - protected void set_xmlgmonthday(XmlObject v) - { set_primitive(SchemaType.BTC_G_MONTH_DAY, v); } - protected void set_xmlgday(XmlObject v) - { set_primitive(SchemaType.BTC_G_DAY, v); } - protected void set_xmlgmonth(XmlObject v) - { set_primitive(SchemaType.BTC_G_MONTH, v); } - - - - private static boolean check(XmlObject v, SchemaType sType) - { - XmlObject[] vals = sType.getEnumerationValues(); - if (vals != null) - { - for (int i = 0; i < vals.length; i++) - { - if (vals[i].valueEquals(v)) - return true; - } - return false; - } - - return true; - } - - protected boolean equal_to(XmlObject xmlobj) - { - return _value.valueEquals(xmlobj); - } - - protected int value_hash_code() - { - return _value.hashCode(); - } - - protected void validate_simpleval(String lexical, ValidationContext ctx) - { - try - { - check_dated(); - } - catch (Exception e) - { - ctx.invalid(XmlErrorCodes.UNION, new Object[] { "'" + lexical + "' does not match any of the member types for " + QNameHelper.readable(schemaType()) }); - return; - } - if (_value == null) - { - ctx.invalid(XmlErrorCodes.UNION, new Object[] { "'" + lexical + "' does not match any of the member types for " + QNameHelper.readable(schemaType()) }); - return; - } - - ((XmlObjectBase)_value).validate_simpleval(lexical, ctx); - } - - -} - diff --git a/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java b/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java deleted file mode 100644 index 5f8a7aa..0000000 --- a/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java +++ /dev/null @@ -1,457 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.soap; - -import javax.xml.namespace.QName; - -import java.util.ArrayList; -import java.util.List; -import java.util.Iterator; - -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.apache.xmlbeans.impl.common.XmlWhitespace; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.common.PrefixResolver; - -public final class SOAPArrayType -{ - // Example foo:bar[,][][,,][7,9] - // -> _type = QName(foo:bar) - // -> _ranks = {2,1,3} - // -> _dimensions = {7,9} - private QName _type; - private int[] _ranks; // if ranks is empty, it means there are no nested arrays - private int[] _dimensions; // Any dimension can be -1 to indicate "any". - - /** - * True if the ranks for the passed SOAPArrayType - * are equal to this one. - * - * Does NOT compare the _type fields. - */ - public boolean isSameRankAs(SOAPArrayType otherType) - { - if (_ranks.length != otherType._ranks.length) - return false; - for (int i = 0; i < _ranks.length; i++) - { - if (_ranks[i] != otherType._ranks[i]) - return false; - } - if (_dimensions.length != otherType._dimensions.length) - return false; - return true; - } - - /** - * Given SOAP 1.1-formatted index string, returns an array - * index. For example, given "[4,3,5]", returns an int array - * containing 4, 3, and 5. - */ - public static int[] parseSoap11Index(String inbraces) - { - inbraces = XmlWhitespace.collapse(inbraces, XmlWhitespace.WS_COLLAPSE); - if (!inbraces.startsWith("[") || !inbraces.endsWith("]")) - throw new IllegalArgumentException("Misformed SOAP 1.1 index: must be contained in braces []"); - return internalParseCommaIntString(inbraces.substring(1, inbraces.length() - 1)); - } - - private static int[] internalParseCommaIntString(String csl) - { - List dimStrings = new ArrayList(); - int i = 0; - for (;;) - { - int j = csl.indexOf(',', i); - if (j < 0) - { - dimStrings.add(csl.substring(i)); - break; - } - dimStrings.add(csl.substring(i, j)); - i = j + 1; - } - - int[] result = new int[dimStrings.size()]; - i = 0; - for (Iterator it = dimStrings.iterator(); it.hasNext(); i++) - { - String dimString = XmlWhitespace.collapse((String)it.next(), XmlWhitespace.WS_COLLAPSE); - if (dimString.equals("*") || dimString.equals("")) - { - result[i] = -1; - } - else - { - try - { - result[i] = Integer.parseInt(dimString); - } - catch (Exception e) - { - throw new XmlValueOutOfRangeException("Malformed integer in SOAP array index"); - } - } - } - return result; - } - - /** - * Parses a SOAP 1.1 array type string. - * - * Since an array type string contains a QName, a prefix resolver - * must be passed. - */ - public SOAPArrayType(String s, PrefixResolver m) - { - int firstbrace = s.indexOf('['); - if (firstbrace < 0) - throw new XmlValueOutOfRangeException(); - - // grab the QName - String firstpart = XmlWhitespace.collapse(s.substring(0, firstbrace), XmlWhitespace.WS_COLLAPSE); - int firstcolon = firstpart.indexOf(':'); - String prefix = ""; - if (firstcolon >= 0) - prefix = firstpart.substring(0, firstcolon); - - String uri = m.getNamespaceForPrefix(prefix); - if (uri == null) - throw new XmlValueOutOfRangeException(); - - _type = QNameHelper.forLNS(firstpart.substring(firstcolon + 1), uri); - - initDimensions(s, firstbrace); - } - - private static int[] EMPTY_INT_ARRAY = new int[0]; - - /** - * Parses SOAP 1.1(advanced) array type strings. - * - * Since in SOAP 1.1(advanced) the dimension specification is separated from the - * QName for the underlying type, these are passed in separate - * arguments. - */ - public SOAPArrayType(QName name, String dimensions) - { - int firstbrace = dimensions.indexOf('['); - if (firstbrace < 0) - { - _type = name; - _ranks = EMPTY_INT_ARRAY; - dimensions = XmlWhitespace.collapse(dimensions, XmlWhitespace.WS_COLLAPSE); - String[] dimStrings = dimensions.split(" "); - for (int i = 0; i < dimStrings.length; i++) - { - String dimString = dimStrings[i]; - if (dimString.equals("*")) - { - _dimensions[i] = -1; - // _hasIndeterminateDimensions = true; - } - else - { - try - { - _dimensions[i] = Integer.parseInt(dimStrings[i]); - } - catch (Exception e) - { - throw new XmlValueOutOfRangeException(); - } - } - } - } - else - { - _type = name; - initDimensions(dimensions, firstbrace); - } - } - - /** - * Given a nested SOAPArrayType and a set of dimensions for the outermost - * array, comes up with the right SOAPArrayType for the whole thing. - * - * E.g., - * Nested foo:bar[,][][,,][1,2] - * Dimensions [6,7,8] - * Result -> foo:bar[,][][,,][,][6,7,8] - */ - public SOAPArrayType(SOAPArrayType nested, int[] dimensions) - { - _type = nested._type; - - _ranks = new int[nested._ranks.length + 1]; - System.arraycopy(nested._ranks, 0, _ranks, 0, nested._ranks.length); - _ranks[_ranks.length - 1] = nested._dimensions.length; - - _dimensions = new int[dimensions.length]; - System.arraycopy(dimensions, 0, _dimensions, 0, dimensions.length); - } - - /** - * Initialize dimensions based on SOAP11 parsed dimension substring - */ - private void initDimensions(String s, int firstbrace) - { - List braces = new ArrayList(); - int lastbrace = -1; - for (int i = firstbrace; i >= 0; ) - { - lastbrace = s.indexOf(']', i); - if (lastbrace < 0) - throw new XmlValueOutOfRangeException(); - braces.add(s.substring(i + 1, lastbrace)); - i = s.indexOf('[', lastbrace); - } - - String trailer = s.substring(lastbrace + 1); - if (!XmlWhitespace.isAllSpace(trailer)) - throw new XmlValueOutOfRangeException(); - - // now fill in rank array - _ranks = new int[braces.size() - 1]; - for (int i = 0; i < _ranks.length; i++) - { - String commas = (String)braces.get(i); - int commacount = 0; - for (int j = 0; j < commas.length(); j++) - { - char ch = commas.charAt(j); - if (ch == ',') - commacount += 1; - else if (!XmlWhitespace.isSpace(ch)) - throw new XmlValueOutOfRangeException(); - } - _ranks[i] = commacount + 1; - } - - // finally fill in dimension array - _dimensions = internalParseCommaIntString((String)braces.get(braces.size() - 1)); - - /* - for (int i = 0; i < _dimensions.length; i++) - { - if (_dimensions[i] < 0) - _hasIndeterminateDimensions = true; - } - */ - } - - /** - * Returns the QName for the referenced type. - */ - public QName getQName() - { - return _type; - } - - /** - * Returns the array of ranks for inner nested arrays. - * In SOAP 1.1-advanced, this is always an array of length zero. - * In SOAP 1.1, this array reflects the ranks of nested - * arrays. For example foo:bar[,][,,][][5,6] will produce - * a ranks result of 2, 3, 1. - */ - public int[] getRanks() - { - int[] result = new int[_ranks.length]; - System.arraycopy(_ranks, 0, result, 0, result.length); - return result; - } - - /** - * Returns the array of dimensions. - */ - public int[] getDimensions() - { - int[] result = new int[_dimensions.length]; - System.arraycopy(_dimensions, 0, result, 0, result.length); - return result; - } - - /** - * True if this array contains nested arrays. Equivalent - * to (getRanks().length > 0). - */ - public boolean containsNestedArrays() - { - return (_ranks.length > 0); - } - - /** - * Returns the dimensions as a string, e.g., [,][2,3,4] - */ - public String soap11DimensionString() - { - return soap11DimensionString(_dimensions); - } - - /** - * Given an actual set of dimensions that may differ from - * the default that is stored, outputs the soap arrayType - * string. - */ - public String soap11DimensionString(int[] actualDimensions) - { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < _ranks.length; i++) - { - sb.append('['); - for (int j = 1; j < _ranks[i]; j++) - sb.append(','); - sb.append(']'); - } - - sb.append('['); - for (int i = 0; i < actualDimensions.length; i++) - { - if (i > 0) - sb.append(','); - if (actualDimensions[i] >= 0) - sb.append(actualDimensions[i]); - } - sb.append(']'); - return sb.toString(); - } - - private SOAPArrayType() - { - } - - /** - * SOAP 1.2 - * Constructs a SOAPArrayType from soap-enc:itemType and - * soap-enc:arraySize attributes - * @param itemType the item type QName - * @param arraySize a string with dimentions like: * 3 4 - * @return a SOAPArrayType to represent this - */ - public static SOAPArrayType newSoap12Array(QName itemType, String arraySize) - { - int [] ranks = EMPTY_INT_ARRAY; - arraySize = XmlWhitespace.collapse(arraySize, XmlWhitespace.WS_COLLAPSE); - String[] dimStrings = arraySize.split(" "); - int[] dimensions = new int[dimStrings.length]; - for (int i = 0; i < dimStrings.length; i++) - { - String dimString = dimStrings[i]; - if (i==0 && dimString.equals("*")) - { - dimensions[i] = -1; - // _hasIndeterminateDimensions = true; - } - else - { - try - { - dimensions[i] = Integer.parseInt(dimStrings[i]); - } - catch (Exception e) - { - throw new XmlValueOutOfRangeException(); - } - } - } - SOAPArrayType sot = new SOAPArrayType(); - sot._ranks = ranks; - sot._type = itemType; - sot._dimensions = dimensions; - return sot; - } - - /** - * SOAP 1.2 - * Given an actual set of dimensions that may differ from - * the default that is stored, outputs the soap arraySize - * string. - */ - public String soap12DimensionString(int[] actualDimensions) - { - StringBuffer sb = new StringBuffer(); - - for (int i = 0; i < actualDimensions.length; i++) - { - if (i > 0) - sb.append(' '); - if (actualDimensions[i] >= 0) - sb.append(actualDimensions[i]); - } - return sb.toString(); - } - - /** - * Constructs a SOAPArrayType reflecting the dimensions - * of the next nested array. - */ - public SOAPArrayType nestedArrayType() - { - if (!containsNestedArrays()) - throw new IllegalStateException(); - - SOAPArrayType result = new SOAPArrayType(); - - result._type = _type; - - result._ranks = new int[_ranks.length - 1]; - System.arraycopy(_ranks, 0, result._ranks, 0, result._ranks.length); - - result._dimensions = new int[_ranks[_ranks.length - 1]]; - for (int i = 0; i < result._dimensions.length; i++) - result._dimensions[i] = -1; - - // result._hasIndeterminateDimensions = (result._dimensions.length > 0); - - return result; - } - - public int hashCode() - { - return (_type.hashCode() + _dimensions.length + _ranks.length + (_dimensions.length == 0 ? 0 : _dimensions[0])); - } - - public boolean equals(Object obj) - { - if (obj == this) - return true; - - if (!obj.getClass().equals(getClass())) - return false; - - SOAPArrayType sat = (SOAPArrayType)obj; - - if (!_type.equals(sat._type)) - return false; - - if (_ranks.length != sat._ranks.length) - return false; - - if (_dimensions.length != sat._dimensions.length) - return false; - - for (int i = 0; i < _ranks.length; i++) - if (_ranks[i] != sat._ranks[i]) - return false; - - for (int i = 0; i < _dimensions.length; i++) - if (_dimensions[i] != sat._dimensions[i]) - return false; - - return true; - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java deleted file mode 100644 index d6ae6ff..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java +++ /dev/null @@ -1,719 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument; -import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemaEntry; -import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument.DownloadedSchemas; -import org.apache.xmlbeans.impl.util.HexBin; -import org.apache.xmlbeans.impl.common.IOUtil; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlBeans; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ByteArrayOutputStream; -import java.io.ByteArrayInputStream; -import java.util.Set; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.HashMap; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -public abstract class BaseSchemaResourceManager extends SchemaImportResolver -{ - private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")"; - - private String _defaultCopyDirectory; - private DownloadedSchemasDocument _importsDoc; - private Map _resourceForFilename = new HashMap(); - private Map _resourceForURL = new HashMap(); - private Map _resourceForNamespace = new HashMap(); - private Map _resourceForDigest = new HashMap(); - private Map _resourceForCacheEntry = new HashMap(); - private Set _redownloadSet = new HashSet(); - - protected BaseSchemaResourceManager() - { - // concrete subclasses should call init in their constructors - } - - protected final void init() - { - if (fileExists(getIndexFilename())) - { - try - { - _importsDoc = DownloadedSchemasDocument.Factory.parse( inputStreamForFile( getIndexFilename() ) ); - } - catch (IOException e) - { - _importsDoc = null; - } - catch (Exception e) - { - throw (IllegalStateException)(new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file")).initCause(e); - } - } - if (_importsDoc == null) - { - try - { - _importsDoc = DownloadedSchemasDocument.Factory.parse( - "" - ); - } - catch (Exception e) - { - throw (IllegalStateException)(new IllegalStateException()).initCause(e); - } - } - - String defaultDir = _importsDoc.getDownloadedSchemas().getDefaultDirectory(); - if (defaultDir == null) - defaultDir = getDefaultSchemaDir();; - _defaultCopyDirectory = defaultDir; - - // now initialize data structures - DownloadedSchemaEntry[] entries = _importsDoc.getDownloadedSchemas().getEntryArray(); - for (int i = 0; i < entries.length; i++) - { - updateResource(entries[i]); - } - } - - public final void writeCache() throws IOException - { - InputStream input = _importsDoc.newInputStream(new XmlOptions().setSavePrettyPrint()); - writeInputStreamToFile(input, getIndexFilename()); - } - - public final void processAll(boolean sync, boolean refresh, boolean imports) - { - if (refresh) - { - _redownloadSet = new HashSet(); - } - else - { - _redownloadSet = null; - } - - String[] allFilenames = getAllXSDFilenames(); - - if (sync) - syncCacheWithLocalXsdFiles(allFilenames, false); - - SchemaResource[] starters = (SchemaResource[]) - _resourceForFilename.values().toArray(new SchemaResource[0]); - - if (refresh) - redownloadEntries(starters); - - if (imports) - resolveImports(starters); - - _redownloadSet = null; - } - - public final void process(String[] uris, String[] filenames, boolean sync, boolean refresh, boolean imports) - { - if (refresh) - { - _redownloadSet = new HashSet(); - } - else - { - _redownloadSet = null; - } - - if (filenames.length > 0) - syncCacheWithLocalXsdFiles(filenames, true); - else if (sync) - syncCacheWithLocalXsdFiles(getAllXSDFilenames(), false); - - Set starterset = new HashSet(); - - for (int i = 0; i < uris.length; i++) - { - SchemaResource resource = (SchemaResource)lookupResource(null, uris[i]); - if (resource != null) - starterset.add(resource); - } - - for (int i = 0; i < filenames.length; i++) - { - SchemaResource resource = (SchemaResource)_resourceForFilename.get(filenames); - if (resource != null) - starterset.add(resource); - } - - SchemaResource[] starters = (SchemaResource[]) - starterset.toArray(new SchemaResource[0]); - - if (refresh) - redownloadEntries(starters); - - if (imports) - resolveImports(starters); - - _redownloadSet = null; - } - - /** - * Adds items to the cache that point to new files that aren't - * described in the cache, and optionally deletes old entries. - * - * If an old file is gone and a new file is - * found with exactly the same contents, the cache entry is moved - * to point to the new file. - */ - public final void syncCacheWithLocalXsdFiles(String[] filenames, boolean deleteOnlyMentioned) - { - Set seenResources = new HashSet(); - Set vanishedResources = new HashSet(); - - for (int i = 0; i < filenames.length; i++) - { - String filename = filenames[i]; - - // first, if the filename matches exactly, trust the filename - SchemaResource resource = (SchemaResource)_resourceForFilename.get(filename); - if (resource != null) - { - if (fileExists(filename)) - seenResources.add(resource); - else - vanishedResources.add(resource); - continue; - } - - // new file that is not in the index? - // not if the digest is known to the index and the original file is gone - that's a rename! - String digest = null; - try - { - digest = shaDigestForFile(filename); - resource = (SchemaResource)_resourceForDigest.get(digest); - if (resource != null) - { - String oldFilename = resource.getFilename(); - if (!fileExists(oldFilename)) - { - warning("File " + filename + " is a rename of " + oldFilename); - resource.setFilename(filename); - seenResources.add(resource); - if (_resourceForFilename.get(oldFilename) == resource) - _resourceForFilename.remove(oldFilename); - if (_resourceForFilename.containsKey(filename)) - _resourceForFilename.put(filename, resource); - continue; - } - } - } - catch (IOException e) - { - // unable to read digest... no problem, ignore then - } - - // ok, this really is a new XSD file then, of unknown URL origin - DownloadedSchemaEntry newEntry = addNewEntry(); - newEntry.setFilename(filename); - warning("Caching information on new local file " + filename); - if (digest != null) - newEntry.setSha1(digest); - - seenResources.add(updateResource(newEntry)); - } - - if (deleteOnlyMentioned) - deleteResourcesInSet(vanishedResources, true); - else - deleteResourcesInSet(seenResources, false); - } - - /** - * Iterates through every entry and refetches it from its primary URL, - * if known. Replaces the contents of the file if the data is different. - */ - private void redownloadEntries(SchemaResource[] resources) - { - for (int i = 0; i < resources.length; i++) - { - redownloadResource(resources[i]); - } - } - - private void deleteResourcesInSet(Set seenResources, boolean setToDelete) - { - Set seenCacheEntries = new HashSet(); - for (Iterator i = seenResources.iterator(); i.hasNext(); ) - { - SchemaResource resource = (SchemaResource)i.next(); - seenCacheEntries.add(resource._cacheEntry); - } - - DownloadedSchemas downloadedSchemas = _importsDoc.getDownloadedSchemas(); - for (int i = 0; i < downloadedSchemas.sizeOfEntryArray(); i++) - { - DownloadedSchemaEntry cacheEntry = downloadedSchemas.getEntryArray(i); - - if (seenCacheEntries.contains(cacheEntry) == setToDelete) - { - SchemaResource resource = (SchemaResource)_resourceForCacheEntry.get(cacheEntry); - warning("Removing obsolete cache entry for " + resource.getFilename()); - - if (resource != null) - { - _resourceForCacheEntry.remove(cacheEntry); - - if (resource == _resourceForFilename.get(resource.getFilename())) - _resourceForFilename.remove(resource.getFilename()); - - if (resource == _resourceForDigest.get(resource.getSha1())) - _resourceForDigest.remove(resource.getSha1()); - - if (resource == _resourceForNamespace.get(resource.getNamespace())) - _resourceForNamespace.remove(resource.getNamespace()); - - // Finally, any or all URIs - String[] urls = resource.getSchemaLocationArray(); - for (int j = 0; j < urls.length; j++) - { - if (resource == _resourceForURL.get(urls[j])) - _resourceForURL.remove(urls[j]); - } - } - - downloadedSchemas.removeEntry(i); - i -= 1; - } - } - } - - private SchemaResource updateResource(DownloadedSchemaEntry entry) - { - // The file - String filename = entry.getFilename(); - if (filename == null) - return null; - - SchemaResource resource = new SchemaResource(entry); - _resourceForCacheEntry.put(entry, resource); - - if (!_resourceForFilename.containsKey(filename)) - _resourceForFilename.put(filename, resource); - - // The digest - String digest = resource.getSha1(); - if (digest != null) - { - if (!_resourceForDigest.containsKey(digest)) - _resourceForDigest.put(digest, resource); - } - - // Next, the namespace - String namespace = resource.getNamespace(); - if (namespace != null) - { - if (!_resourceForNamespace.containsKey(namespace)) - _resourceForNamespace.put(namespace, resource); - } - - // Finally, any or all URIs - String[] urls = resource.getSchemaLocationArray(); - for (int j = 0; j < urls.length; j++) - { - if (!_resourceForURL.containsKey(urls[j])) - _resourceForURL.put(urls[j], resource); - } - - return resource; - } - - private static DigestInputStream digestInputStream(InputStream input) - { - MessageDigest sha; - try - { - sha = MessageDigest.getInstance("SHA"); - } - catch (NoSuchAlgorithmException e) - { - throw (IllegalStateException)(new IllegalStateException().initCause(e)); - } - - DigestInputStream str = new DigestInputStream(input, sha); - - return str; - } - - private DownloadedSchemaEntry addNewEntry() - { - return _importsDoc.getDownloadedSchemas().addNewEntry(); - } - - private class SchemaResource implements SchemaImportResolver.SchemaResource - { - SchemaResource(DownloadedSchemaEntry entry) - { - _cacheEntry = entry; - } - - DownloadedSchemaEntry _cacheEntry; - - public void setFilename(String filename) - { - _cacheEntry.setFilename(filename); - } - - public String getFilename() - { - return _cacheEntry.getFilename(); - } - - public Schema getSchema() - { - if (!fileExists(getFilename())) - redownloadResource(this); - - try - { - return SchemaDocument.Factory.parse(inputStreamForFile(getFilename())).getSchema(); - } - catch (Exception e) - { - return null; // return null if _any_ problems reading schema file - } - } - - public String getSha1() - { - return _cacheEntry.getSha1(); - } - - public String getNamespace() - { - return _cacheEntry.getNamespace(); - } - - public void setNamespace(String namespace) - { - _cacheEntry.setNamespace(namespace); - } - - public String getSchemaLocation() - { - if (_cacheEntry.sizeOfSchemaLocationArray() > 0) - return _cacheEntry.getSchemaLocationArray(0); - return null; - } - - public String[] getSchemaLocationArray() - { - return _cacheEntry.getSchemaLocationArray(); - } - - public int hashCode() - { - return getFilename().hashCode(); - } - - public boolean equals(Object obj) - { - return this == obj || getFilename().equals(((SchemaResource)obj).getFilename()); - } - - public void addSchemaLocation(String schemaLocation) - { - _cacheEntry.addSchemaLocation(schemaLocation); - } - } - - /** - * Called when the ImportLoader wishes to resolve the - * given import. Should return a SchemaResource whose - * "equals" relationship reveals when a SchemaResource is - * duplicated and shouldn't be examined again. - * - * Returns null if the resource reference should be ignored. - */ - public SchemaImportResolver.SchemaResource lookupResource(String nsURI, String schemaLocation) - { - SchemaResource result = fetchFromCache(nsURI, schemaLocation); - if (result != null) - { - if (_redownloadSet != null) - { - redownloadResource(result); - } - return result; - } - - if (schemaLocation == null) - { - warning("No cached schema for namespace '" + nsURI + "', and no url specified"); - return null; - } - - result = copyOrIdentifyDuplicateURL(schemaLocation, nsURI); - if (_redownloadSet != null) - _redownloadSet.add(result); - return result; - } - - private SchemaResource fetchFromCache(String nsURI, String schemaLocation) - { - SchemaResource result; - - if (schemaLocation != null) - { - result = (SchemaResource)_resourceForURL.get(schemaLocation); - if (result != null) - return result; - } - - if (nsURI != null) - { - result = (SchemaResource)_resourceForNamespace.get(nsURI); - if (result != null) - return result; - } - - return null; - } - - private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException - { - String localFilename = new URI( schemaLocation ).getRawPath(); - int i = localFilename.lastIndexOf('/'); - if (i >= 0) - localFilename = localFilename.substring(i + 1); - if (localFilename.endsWith(".xsd")) - localFilename = localFilename.substring(0, localFilename.length() - 4); - if (localFilename.length() == 0) - localFilename = "schema"; - - // TODO: remove other unsafe characters for filenames? - - String candidateFilename = localFilename; - int suffix = 1; - while (suffix < 1000) - { - String candidate = _defaultCopyDirectory + "/" + candidateFilename + ".xsd"; - if (!fileExists(candidate)) - return candidate; - suffix += 1; - candidateFilename = localFilename + suffix; - } - - throw new IOException("Problem with filename " + localFilename + ".xsd"); - } - - private void redownloadResource(SchemaResource resource) - { - if (_redownloadSet != null) - { - if (_redownloadSet.contains(resource)) - return; - _redownloadSet.add(resource); - } - - String filename = resource.getFilename(); - String schemaLocation = resource.getSchemaLocation(); - String digest = null; - - // nothing to do? - if (schemaLocation == null || filename == null) - return; - - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - try - { - URL url = new URL( schemaLocation ); - URLConnection conn = url.openConnection(); - conn.addRequestProperty("User-Agent", USER_AGENT); - conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); - DigestInputStream input = digestInputStream(conn.getInputStream()); - IOUtil.copyCompletely(input, buffer); - digest = HexBin.bytesToString(input.getMessageDigest().digest()); - } - catch (Exception e) - { - warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); - return; - } - - if (digest.equals(resource.getSha1()) && fileExists(filename)) - { - warning("Resource " + filename + " is unchanged from " + schemaLocation + "."); - return; - } - - try - { - InputStream source = new ByteArrayInputStream(buffer.toByteArray()); - writeInputStreamToFile(source, filename); - } - catch (IOException e) - { - warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage()); - return; - } - - warning("Refreshed " + filename + " from " + schemaLocation); - } - - private SchemaResource copyOrIdentifyDuplicateURL(String schemaLocation, String namespace) - { - String targetFilename; - String digest; - SchemaResource result; - - try - { - targetFilename = uniqueFilenameForURI(schemaLocation); - } - catch (URISyntaxException e) - { - warning("Invalid URI '" + schemaLocation + "':" + e.getMessage()); - return null; - } - catch (IOException e) - { - warning("Could not create local file for " + schemaLocation + ":" + e.getMessage()); - return null; - } - - try - { - URL url = new URL( schemaLocation ); - DigestInputStream input = digestInputStream(url.openStream()); - writeInputStreamToFile(input, targetFilename); - digest = HexBin.bytesToString(input.getMessageDigest().digest()); - } - catch (Exception e) - { - warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); - return null; - } - - result = (SchemaResource)_resourceForDigest.get(digest); - if (result != null) - { - deleteFile(targetFilename); - result.addSchemaLocation(schemaLocation); - if (!_resourceForURL.containsKey(schemaLocation)) - _resourceForURL.put(schemaLocation, result); - return result; - } - - warning("Downloaded " + schemaLocation + " to " + targetFilename); - - DownloadedSchemaEntry newEntry = addNewEntry(); - newEntry.setFilename(targetFilename); - newEntry.setSha1(digest); - if (namespace != null) - newEntry.setNamespace(namespace); - newEntry.addSchemaLocation(schemaLocation); - return updateResource(newEntry); - } - - /** - * Updates actual namespace in the table. - */ - public void reportActualNamespace(SchemaImportResolver.SchemaResource rresource, String actualNamespace) - { - SchemaResource resource = (SchemaResource)rresource; - String oldNamespace = resource.getNamespace(); - if (oldNamespace != null && _resourceForNamespace.get(oldNamespace) == resource) - _resourceForNamespace.remove(oldNamespace); - if (!_resourceForNamespace.containsKey(actualNamespace)) - _resourceForNamespace.put(actualNamespace, resource); - resource.setNamespace(actualNamespace); - } - - private String shaDigestForFile(String filename) throws IOException - { - DigestInputStream str = digestInputStream(inputStreamForFile(filename)); - - byte[] dummy = new byte[4096]; - for (int i = 1; i > 0; i = str.read(dummy)); - - str.close(); - - return HexBin.bytesToString(str.getMessageDigest().digest()); - } - - // SOME METHODS TO OVERRIDE ============================ - - protected String getIndexFilename() - { - return "./xsdownload.xml"; - } - - protected String getDefaultSchemaDir() - { - return "./schema"; - } - - /** - * Produces diagnostic messages such as "downloading X to file Y". - */ - abstract protected void warning(String msg); - - /** - * Returns true if the given filename exists. The filenames - * are of the form "/foo/bar/zee.xsd" and should be construed - * as rooted at the root of the project. - */ - abstract protected boolean fileExists(String filename); - - /** - * Gets the data in the given filename as an InputStream. - */ - abstract protected InputStream inputStreamForFile(String filename) throws IOException; - - /** - * Writes an entire file in one step. An InputStream is passed and - * copied to the file. - */ - abstract protected void writeInputStreamToFile(InputStream input, String filename) throws IOException; - - /** - * Deletes a file. Sometimes immediately after writing a new file - * we notice that it's exactly the same as an existing file and - * we delete it. We never delete a file that was given to us - * by the user. - */ - abstract protected void deleteFile(String filename); - - /** - * Returns a list of all the XSD filesnames in the project. - */ - abstract protected String[] getAllXSDFilenames(); -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java deleted file mode 100644 index 03c72de..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java +++ /dev/null @@ -1,424 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.SystemProperties; - -import java.util.ArrayList; -import java.util.List; -import java.util.Iterator; -import java.util.Arrays; -import java.io.File; -import java.io.InputStream; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.FileFilter; -import java.io.FileWriter; -import java.net.URI; -import java.net.URISyntaxException; - -public class CodeGenUtil -{ - public static String DEFAULT_MEM_START = "8m"; - public static String DEFAULT_MEM_MAX = "256m"; - public static String DEFAULT_COMPILER = "javac"; - public static String DEFAULT_JAR = "jar"; - - //workaround for Sun bug # 4723726 - public static URI resolve(URI base, URI child) - { - URI ruri = base.resolve(child); - - //fix up normalization bug - if ("file".equals(ruri.getScheme()) && ! child.equals(ruri)) - { - if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//")) - { - String path = "///".concat(ruri.getPath()); - try - { - ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment()); - } - catch(URISyntaxException uris) - {} - } - } - return ruri; - } - - static void addAllJavaFiles(List srcFiles, List args) - { - for (Iterator i = srcFiles.iterator(); i.hasNext(); ) - { - File f = (File)i.next(); - if (!f.isDirectory()) - { - args.add(quoteAndEscapeFilename(f.getAbsolutePath())); - } - else - { - List inside = (Arrays.asList(f.listFiles( - new FileFilter() - { - public boolean accept(File file) - { return (file.isFile() && file.getName().endsWith(".java")) || file.isDirectory(); } - } - ))); - addAllJavaFiles(inside, args); - } - } - } - - static private String quoteAndEscapeFilename(String filename) - { - // don't quote if there's no space - if (filename.indexOf(" ") < 0) - return filename; - - // bizarre. javac expects backslash escaping if we quote the classpath - // bizarre also. replaceAll expects replacement backslashes to be double escaped. - return "\"" + filename.replaceAll("\\\\", "\\\\\\\\") + "\""; - } - - static private String quoteNoEscapeFilename(String filename) - { - // don't quote if there's no space, and don't quote on linux - if (filename.indexOf(" ") < 0 || File.separatorChar == '/') - return filename; - - return "\"" + filename + "\""; - } - - /** - * Invokes javac on the generated source files in order to turn them - * into binary files in the output directory. This will return a list of - * GenFiles for all of the classes produced or null if an - * error occurred. - * - * @deprecated - */ - static public boolean externalCompile(List srcFiles, File outdir, File[] cp, boolean debug) - { - return externalCompile(srcFiles, outdir, cp, debug, DEFAULT_COMPILER, null, DEFAULT_MEM_START, DEFAULT_MEM_MAX, false, false); - } - - // KHK: temporary to avoid build break - static public boolean externalCompile(List srcFiles, File outdir, File[] cp, boolean debug, String javacPath, String memStart, String memMax, boolean quiet, boolean verbose) - { - return externalCompile(srcFiles, outdir, cp, debug, javacPath, null, memStart, memMax, quiet, verbose); - } - - /** - * Invokes javac on the generated source files in order to turn them - * into binary files in the output directory. This will return a list of - * GenFiles for all of the classes produced or null if an - * error occurred. - */ - static public boolean externalCompile(List srcFiles, File outdir, File[] cp, boolean debug, String javacPath, String genver, String memStart, String memMax, boolean quiet, boolean verbose) - { - List args = new ArrayList(); - - File javac = findJavaTool(javacPath == null ? DEFAULT_COMPILER : javacPath); - assert (javac.exists()) : "compiler not found " + javac; - args.add(javac.getAbsolutePath()); - - if (outdir == null) - { - outdir = new File("."); - } - else - { - args.add("-d"); - args.add(quoteAndEscapeFilename(outdir.getAbsolutePath())); - } - - if (cp == null) - { - cp = systemClasspath(); - } - - if (cp.length > 0) - { - StringBuffer classPath = new StringBuffer(); - // Add the output directory to the classpath. We do this so that - // javac will be able to find classes that were compiled - // previously but are not in the list of sources this time. - classPath.append(outdir.getAbsolutePath()); - - // Add everything on our classpath. - for (int i = 0; i < cp.length; i++) - { - classPath.append(File.pathSeparator); - classPath.append(cp[i].getAbsolutePath()); - } - - args.add("-classpath"); - - // bizarre. javac expects backslash escaping if we quote the classpath - args.add(quoteAndEscapeFilename(classPath.toString())); - } - - if (genver == null) - genver = "1.4"; - - args.add("-source"); - args.add(genver); - - args.add("-target"); - args.add(genver); - - args.add(debug ? "-g" : "-g:none"); - - if (verbose) - args.add("-verbose"); - - addAllJavaFiles(srcFiles, args); - - File clFile = null; - try - { - clFile = File.createTempFile("javac", ""); - FileWriter fw = new FileWriter(clFile); - Iterator i = args.iterator(); - for (i.next(); i.hasNext();) - { - String arg = (String)i.next(); - fw.write(arg); - fw.write('\n'); - } - fw.close(); - List newargs = new ArrayList(); - newargs.add(args.get(0)); - - if (memStart != null && memStart.length() != 0) - newargs.add("-J-Xms" + memStart); - if (memMax != null && memMax.length() != 0) - newargs.add("-J-Xmx" + memMax); - - newargs.add("@" + clFile.getAbsolutePath()); - args = newargs; - } - catch (Exception e) - { - System.err.println("Could not create command-line file for javac"); - } - - try - { - String[] strArgs = (String[]) args.toArray(new String[args.size()]); - - if (verbose) - { - System.out.print("compile command:"); - for (int i = 0; i < strArgs.length; i++) - System.out.print(" " + strArgs[i]); - System.out.println(); - } - - final Process proc = Runtime.getRuntime().exec(strArgs); - - StringBuffer errorBuffer = new StringBuffer(); - StringBuffer outputBuffer = new StringBuffer(); - - ThreadedReader out = new ThreadedReader(proc.getInputStream(), outputBuffer); - ThreadedReader err = new ThreadedReader(proc.getErrorStream(), errorBuffer); - - proc.waitFor(); - - if (verbose || proc.exitValue() != 0) - { - if (outputBuffer.length() > 0) { - System.out.println(outputBuffer.toString()); - System.out.flush(); - } - if (errorBuffer.length() > 0) { - System.err.println(errorBuffer.toString()); - System.err.flush(); - } - - if (proc.exitValue() != 0) - return false; - } - } - catch (Throwable e) - { - System.err.println(e.toString()); - System.err.println(e.getCause()); - e.printStackTrace(System.err); - return false; - } - - if (clFile != null) - clFile.delete(); - - return true; - } - - public static File[] systemClasspath() - { - List cp = new ArrayList(); - String[] systemcp = SystemProperties.getProperty("java.class.path").split(File.pathSeparator); - for (int i = 0; i < systemcp.length; i++) - { - cp.add(new File(systemcp[i])); - } - return (File[])cp.toArray(new File[cp.size()]); - } - - /** - * @deprecated Use org.apache.xmlbeans.impl.common.JarHelper instead. - */ - static public boolean externalJar(File srcdir, File outfile) - { - return externalJar(srcdir, outfile, DEFAULT_JAR, false, false); - } - - /** - * @deprecated Use org.apache.xmlbeans.impl.common.JarHelper instead. - */ - static public boolean externalJar(File srcdir, File outfile, String jarPath, boolean quiet, boolean verbose) - { - List args = new ArrayList(); - - File jar = findJavaTool(jarPath == null ? DEFAULT_JAR : jarPath); - assert (jar.exists()) : "jar not found " + jar; - args.add(jar.getAbsolutePath()); - - args.add("cf"); - args.add(quoteNoEscapeFilename(outfile.getAbsolutePath())); - - args.add("-C"); - args.add(quoteNoEscapeFilename(srcdir.getAbsolutePath())); - - args.add("."); - - try - { - String[] strArgs = (String[]) args.toArray(new String[args.size()]); - - if (verbose) - { - System.out.print("jar command:"); - for (int i = 0; i < strArgs.length; i++) - System.out.print(" " + strArgs[i]); - System.out.println(); - } - - final Process proc = Runtime.getRuntime().exec(strArgs); - - StringBuffer errorBuffer = new StringBuffer(); - StringBuffer outputBuffer = new StringBuffer(); - - ThreadedReader out = new ThreadedReader(proc.getInputStream(), outputBuffer); - ThreadedReader err = new ThreadedReader(proc.getErrorStream(), errorBuffer); - - proc.waitFor(); - - if (verbose || proc.exitValue() != 0) - { - if (outputBuffer.length() > 0) { - System.out.println(outputBuffer.toString()); - System.out.flush(); - } - if (errorBuffer.length() > 0) { - System.err.println(errorBuffer.toString()); - System.err.flush(); - } - - if (proc.exitValue() != 0) - return false; - } - } - catch (Throwable e) - { - e.printStackTrace(System.err); - return false; - } - return true; - } - - /** - * Look for tool in current directory and ${JAVA_HOME}/../bin and - * try with .exe file extension. - */ - private static File findJavaTool(String tool) - { - File toolFile = new File(tool); - if (toolFile.isFile()) { - return toolFile; - } - - File result = new File(tool + ".exe"); - if (result.isFile()) { - return result; - } - - String home = SystemProperties.getProperty("java.home"); - - String sep = File.separator; - result = new File(home + sep + ".." + sep + "bin", tool); - - if (result.isFile()) { - return result; - } - - result = new File(result.getPath() + ".exe"); - if (result.isFile()) { - return result; - } - - result = new File(home + sep + "bin", tool); - if (result.isFile()) { - return result; - } - - result = new File(result.getPath() + ".exe"); - if (result.isFile()) { - return result; - } - - // just return the original toolFile and hope that it is on the PATH. - return toolFile; - } - - /** - * Reads the given input stream into the given buffer until there is - * nothing left to read. - */ - static private class ThreadedReader - { - public ThreadedReader(InputStream stream, final StringBuffer output) - { - final BufferedReader reader = - new BufferedReader(new InputStreamReader(stream)); - - Thread readerThread = new Thread(new Runnable() { - public void run() - { - String s; - try - { - while ((s = reader.readLine()) != null) - output.append(s + "\n"); - } - catch (Exception e) - {} - } - }); - readerThread.start(); - } - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/Diff.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/Diff.java deleted file mode 100644 index b8837ea..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/Diff.java +++ /dev/null @@ -1,384 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; - -import java.io.*; -import java.util.List; -import java.util.Arrays; -import java.util.Comparator; -import java.util.ArrayList; -import java.util.jar.JarFile; -import java.util.Enumeration; -import java.util.zip.ZipEntry; - -public class Diff -{ - public static void main(String[] args) - { - if (args.length != 2) - { - System.out.println("Usage: diff to compare two jars"); - System.out.println(" or diff to compare two dirs"); - return; - } - File file1 = new File(args[0]); - if (!file1.exists()) - { - System.out.println("File \"" + args[0] + "\" not found."); - return; - } - File file2 = new File(args[1]); - if (!file2.exists()) - { - System.out.println("File \"" + args[1] + "\" not found."); - return; - } - List result = new ArrayList(); - if (file1.isDirectory()) - { - if (!file2.isDirectory()) - { - System.out.println("Both parameters have to be directories if the first parameter is a directory."); - return; - } - dirsAsTypeSystems(file1, file2, result); - } - else - { - if (file2.isDirectory()) - { - System.out.println("Both parameters have to be jar files if the first parameter is a jar file."); - return; - } - try - { - JarFile jar1 = new JarFile(file1); - JarFile jar2 = new JarFile(file2); - jarsAsTypeSystems(jar1, jar2, result); - } - catch (IOException ioe) - { ioe.printStackTrace(); } - } - if (result.size() < 1) - System.out.println("No differences encountered."); - else - { - System.out.println("Differences:"); - for (int i = 0; i < result.size(); i++) - System.out.println(result.get(i).toString()); - } - } - - /** - * Diffs the contents of two jars, looking only at the schema typesystems - * saved inside those jars - */ - public static void jarsAsTypeSystems(JarFile jar1, JarFile jar2, List diffs) - { - Enumeration entries1 = jar1.entries(); - Enumeration entries2 = jar2.entries(); - List list1 = new ArrayList(); - List list2 = new ArrayList(); - for (; entries1.hasMoreElements(); ) - { - ZipEntry ze = (ZipEntry) entries1.nextElement(); - String name = ze.getName(); - if (name.startsWith("schema" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb")) - list1.add(ze); - } - for (; entries2.hasMoreElements(); ) - { - ZipEntry ze = (ZipEntry) entries2.nextElement(); - String name = ze.getName(); - if (name.startsWith("schema" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system/s") && name.endsWith(".xsb")) - list2.add(ze); - } - ZipEntry[] files1 = (ZipEntry[]) list1.toArray(new ZipEntry[list1.size()]); - ZipEntry[] files2 = (ZipEntry[]) list2.toArray(new ZipEntry[list2.size()]); - ZipEntryNameComparator comparator = new ZipEntryNameComparator(); - Arrays.sort(files1, comparator); - Arrays.sort(files2, comparator); - int i1 = 0; - int i2 = 0; - while (i1 < files1.length && i2 < files2.length) - { - String name1 = files1[i1].getName(); - String name2 = files2[i2].getName(); - int dif = name1.compareTo(name2); - if (dif == 0) - { - // Compare the files - zipEntriesAsXsb(files1[i1], jar1, files2[i2], jar2, diffs); - i1++; i2++; // Move to next pair - } - else if (dif < 0) - { - // dir1 contains a file that dir2 doesn't - diffs.add("Jar \"" + jar1.getName() + "\" contains an extra file: \"" + - name1 + "\""); - i1++; - } - else if (dif > 0) - { - // dir2 contains a file that dir1 doesn't - diffs.add("Jar \"" + jar2.getName() + "\" contains an extra file: \"" + - name2 + "\""); - i2++; - } - } - while (i1 < files1.length) - { - diffs.add("Jar \"" + jar1.getName() + "\" contains an extra file: \"" + - files1[i1].getName() + "\""); - i1++; - } - while (i2 < files2.length) - { - diffs.add("Jar \"" + jar2.getName() + "\" contains an extra file: \"" + - files2[i2].getName() + "\""); - i2++; - } - } - - /** - * Diffs the contents of two dirs looking only at the xsb files - * contained in these two dirs - * Updated diffs with a list of differences (for the time being, strings - * describing the difference) - */ - public static void dirsAsTypeSystems(File dir1, File dir2, List diffs) - { - assert dir1.isDirectory() : "Parameters must be directories"; - assert dir2.isDirectory() : "Parameters must be directories"; - - /** - * Navigate three directories deep to get to the type system. - * Assume the schema[METADATA_PACKAGE_LOAD]/system/* structure - */ - File temp1 = new File(dir1, "schema" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system"); - File temp2 = new File(dir2, "schema" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/system"); - if (temp1.exists() && temp2.exists()) - { - File[] files1 = temp1.listFiles(); - File[] files2 = temp2.listFiles(); - if (files1.length == 1 && files2.length == 1) - { - temp1 = files1[0]; - temp2 = files2[0]; - } - else - { - if (files1.length == 0) - temp1 = null; - if (files2.length == 0) - temp2 = null; - if (files1.length > 1) - { - diffs.add("More than one typesystem found in dir \"" + - dir1.getName() + "\""); - return; - } - if (files2.length > 1) - { - diffs.add("More than one typesystem found in dir \"" + - dir2.getName() + "\""); - return; - } - } - } - else - { - if (!temp1.exists()) - temp1 = null; - if (!temp2.exists()) - temp2 = null; - } - if (temp1 == null && temp2 == null) - return; - else if (temp1 == null || temp2 == null) - { - if (temp1 == null) - diffs.add("No typesystems found in dir \"" + dir1 + "\""); - if (temp2 == null) - diffs.add("No typesystems found in dir \"" + dir2 + "\""); - return; - } - else - { - dir1 = temp1; - dir2 = temp2; - } - - boolean diffIndex = isDiffIndex(); - XsbFilenameFilter xsbName = new XsbFilenameFilter(); - File[] files1 = dir1.listFiles(xsbName); - File[] files2 = dir2.listFiles(xsbName); - FileNameComparator comparator = new FileNameComparator(); - Arrays.sort(files1, comparator); - Arrays.sort(files2, comparator); - int i1 = 0; - int i2 = 0; - while (i1 < files1.length && i2 < files2.length) - { - String name1 = files1[i1].getName(); - String name2 = files2[i2].getName(); - int dif = name1.compareTo(name2); - if (dif == 0) - { - if (diffIndex || !files1[i1].getName().equals("index.xsb")) - filesAsXsb(files1[i1], files2[i2], diffs); // Compare the files - i1++; i2++; // Move to next pair - } - else if (dif < 0) - { - // dir1 contains a file that dir2 doesn't - diffs.add("Dir \"" + dir1.getName() + "\" contains an extra file: \"" + - name1 + "\""); - i1++; - } - else if (dif > 0) - { - // dir2 contains a file that dir1 doesn't - diffs.add("Dir \"" + dir2.getName() + "\" contains an extra file: \"" + - name2 + "\""); - i2++; - } - } - while (i1 < files1.length) - { - diffs.add("Dir \"" + dir1.getName() + "\" contains an extra file: \"" + - files1[i1].getName() + "\""); - i1++; - } - while (i2 < files2.length) - { - diffs.add("Dir \"" + dir2.getName() + "\" contains an extra file: \"" + - files2[i2].getName() + "\""); - i2++; - } - } - - private static boolean isDiffIndex() - { - String prop = SystemProperties.getProperty("xmlbeans.diff.diffIndex"); - if (prop == null) - return true; - if ("0".equals(prop) || "false".equalsIgnoreCase(prop)) - return false; - return true; - } - - /** - * Diffs the two given files assuming they are in xsb format - * Updates diffs with differences in string format - */ - public static void filesAsXsb(File file1, File file2, List diffs) - { - assert file1.exists() : "File \"" + file1.getAbsolutePath() + "\" does not exist."; - assert file2.exists() : "File \"" + file2.getAbsolutePath() + "\" does not exist."; - try - { - FileInputStream stream1 = new FileInputStream(file1); - FileInputStream stream2 = new FileInputStream(file2); - streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs); - } - catch (FileNotFoundException fnfe) - { } - catch (IOException ioe) - { } - } - - public static void zipEntriesAsXsb(ZipEntry file1, JarFile jar1, - ZipEntry file2, JarFile jar2, List diffs) - { - try - { - InputStream stream1 = jar1.getInputStream(file1); - InputStream stream2 = jar2.getInputStream(file2); - streamsAsXsb(stream1, file1.getName(), stream2, file2.getName(), diffs); - } - catch (IOException ioe) - { } - } - - public static void streamsAsXsb(InputStream stream1, String name1, - InputStream stream2, String name2, List diffs) - throws IOException - { - ByteArrayOutputStream buf1 = new ByteArrayOutputStream(); - ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); - XsbDumper.dump(stream1, "", new PrintStream(buf1)); - XsbDumper.dump(stream2, "", new PrintStream(buf2)); - stream1.close(); - stream2.close(); - readersAsText(new StringReader(buf1.toString()), name1, - new StringReader(buf2.toString()), name2, diffs); - } - - public static void readersAsText(Reader r1, String name1, Reader r2, String name2, - List diffs) - throws IOException - { - org.apache.xmlbeans.impl.util.Diff.readersAsText(r1, name1, r2, name2, diffs); - } - - private static class XsbFilenameFilter implements FilenameFilter - { - public boolean accept(File dir, String name) - { - return name.endsWith(".xsb"); - } - } - - private static class ZipEntryNameComparator implements Comparator - { - public boolean equals(Object object) - { - return this == object; - } - - public int compare(Object object1, Object object2) - { - assert (object1 instanceof ZipEntry) : "Must pass in a java.util.zip.ZipEntry as argument"; - assert (object2 instanceof ZipEntry) : "Must pass in a java.util.zip.ZipEntry as argument"; - - String name1 = ((ZipEntry) object1).getName(); - String name2 = ((ZipEntry) object2).getName(); - return name1.compareTo(name2); - } - } - - private static class FileNameComparator implements Comparator - { - public boolean equals(Object object) - { - return this == object; - } - - public int compare(Object object1, Object object2) - { - assert (object1 instanceof File) : "Must pass in a java.io.File as argument"; - assert (object2 instanceof File) : "Must pass in a java.io.File as argument"; - - String name1 = ((File) object1).getName(); - String name2 = ((File) object2).getName(); - return name1.compareTo(name2); - } - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/Extension.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/Extension.java deleted file mode 100644 index ffd7b8d..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/Extension.java +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import java.util.List; -import java.util.ArrayList; - - - /** - * An extension is a javabean that represents a SchemaCompilerExtension to be passed for callback into the - * XmlBeans Schema Compiler. - */ -public class Extension { - private Class className; - private List params = new ArrayList(); - - public Class getClassName() { - return className; - } - - public void setClassName(Class className) { - this.className = className; - } - public List getParams() { - return params; - } - - public Param createParam() { - Param p = new Param(); - params.add(p); - return p; - } - - /** - * A Param is just a name value pair applicable to the extension. - */ - public class Param { - private String name; - private String value; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - } - } \ No newline at end of file diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java deleted file mode 100644 index bf1dd21..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java +++ /dev/null @@ -1,475 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelSimpleType; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelElement; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelAttribute; -import org.apache.xmlbeans.impl.xb.xsdschema.NamedGroup; -import org.apache.xmlbeans.impl.xb.xsdschema.NamedAttributeGroup; -import org.apache.xmlbeans.impl.xb.xsdschema.FormChoice; -import org.apache.xmlbeans.impl.xb.xsdschema.IncludeDocument; - -import java.util.Arrays; -import java.util.Set; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.HashMap; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; - -import javax.xml.namespace.QName; - -/** - * This program takes a collection of .xsd files as input, finds all duplicate - * name definitions, and factors out the first instance of each of those into - * a common.xsd file, adding an appropriate statement in the original - * xsd file. - */ -public class FactorImports -{ - public static void printUsage() - { - System.out.println("Refactors a directory of XSD files to remove name conflicts."); - System.out.println("Usage: sfactor [-import common.xsd] [-out outputdir] inputdir"); - System.out.println(" -import common.xsd - The XSD file to contain redundant "); - System.out.println(" definitions for importing."); - System.out.println(" -out outputdir - The directory into which to place XSD "); - System.out.println(" files resulting from refactoring, "); - System.out.println(" plus a commonly imported common.xsd."); - System.out.println(" inputdir - The directory containing the XSD files with"); - System.out.println(" redundant definitions."); - System.out.println(" -license - Print license information."); - System.out.println(); - - } - - public static void main(String[] args) throws Exception - { - Set flags = new HashSet(); - flags.add("h"); - flags.add("help"); - flags.add("usage"); - flags.add("license"); - flags.add("version"); - - CommandLine cl = new CommandLine(args, flags, Arrays.asList(new String[] {"import", "out"})); - if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null || args.length < 1) - { - printUsage(); - System.exit(0); - return; - } - - String[] badopts = cl.getBadOpts(); - if (badopts.length > 0) - { - for (int i = 0; i < badopts.length; i++) - System.out.println("Unrecognized option: " + badopts[i]); - printUsage(); - System.exit(0); - return; - } - - if (cl.getOpt("license") != null) - { - CommandLine.printLicense(); - System.exit(0); - return; - } - - if (cl.getOpt("version") != null) - { - CommandLine.printVersion(); - System.exit(0); - return; - } - - args = cl.args(); - if (args.length != 1) - { - System.exit(0); - return; - } - - String commonName = cl.getOpt("import"); - if (commonName == null) - commonName = "common.xsd"; - - String out = cl.getOpt("out"); - if (out == null) - { - System.out.println("Using output directory 'out'"); - out = "out"; - } - File outdir = new File(out); - File basedir = new File(args[0]); - - // first, parse all the schema files - File[] files = cl.getFiles(); - Map schemaDocs = new HashMap(); - Set elementNames = new HashSet(); - Set attributeNames = new HashSet(); - Set typeNames = new HashSet(); - Set modelGroupNames = new HashSet(); - Set attrGroupNames = new HashSet(); - - Set dupeElementNames = new HashSet(); - Set dupeAttributeNames = new HashSet(); - Set dupeTypeNames = new HashSet(); - Set dupeModelGroupNames = new HashSet(); - Set dupeAttrGroupNames = new HashSet(); - Set dupeNamespaces = new HashSet(); - - for (int i = 0; i < files.length; i++) - { - try - { - // load schema - SchemaDocument doc = SchemaDocument.Factory.parse(files[i]); - schemaDocs.put(doc, files[i]); - - // warn about for imports, includes - if (doc.getSchema().sizeOfImportArray() > 0 || doc.getSchema().sizeOfIncludeArray() > 0) - System.out.println("warning: " + files[i] + " contains imports or includes that are being ignored."); - - // collect together names - String targetNamespace = doc.getSchema().getTargetNamespace(); - if (targetNamespace == null) - targetNamespace = ""; - - TopLevelComplexType ct[] = doc.getSchema().getComplexTypeArray(); - for (int j = 0; j < ct.length; j++) - noteName(ct[j].getName(), targetNamespace, typeNames, dupeTypeNames, dupeNamespaces); - - TopLevelSimpleType st[] = doc.getSchema().getSimpleTypeArray(); - for (int j = 0; j < st.length; j++) - noteName(st[j].getName(), targetNamespace, typeNames, dupeTypeNames, dupeNamespaces); - - TopLevelElement el[] = doc.getSchema().getElementArray(); - for (int j = 0; j < el.length; j++) - noteName(el[j].getName(), targetNamespace, elementNames, dupeElementNames, dupeNamespaces); - - TopLevelAttribute at[] = doc.getSchema().getAttributeArray(); - for (int j = 0; j < at.length; j++) - noteName(at[j].getName(), targetNamespace, attributeNames, dupeAttributeNames, dupeNamespaces); - - NamedGroup gr[] = doc.getSchema().getGroupArray(); - for (int j = 0; j < gr.length; j++) - noteName(gr[j].getName(), targetNamespace, modelGroupNames, dupeModelGroupNames, dupeNamespaces); - - NamedAttributeGroup ag[] = doc.getSchema().getAttributeGroupArray(); - for (int j = 0; j < ag.length; j++) - noteName(ag[j].getName(), targetNamespace, attrGroupNames, dupeAttrGroupNames, dupeNamespaces); - - } - catch (XmlException e) - { - System.out.println("warning: " + files[i] + " is not a schema file - " + e.getError().toString()); - } - catch (IOException e) - { - System.err.println("Unable to load " + files[i] + " - " + e.getMessage()); - System.exit(1); - return; - } - } - - if (schemaDocs.size() == 0) - { - System.out.println("No schema files found."); - System.exit(0); - return; - } - - if (dupeTypeNames.size() + dupeElementNames.size() + dupeAttributeNames.size() + - dupeModelGroupNames.size() + dupeAttrGroupNames.size() == 0) - { - System.out.println("No duplicate names found."); - System.exit(0); - return; - } - - // create a schema doc for each namespace to be imported - Map commonDocs = new HashMap(); - Map commonFiles = new HashMap(); - int count = dupeNamespaces.size() == 1 ? 0 : 1; - for (Iterator i = dupeNamespaces.iterator(); i.hasNext(); ) - { - String namespace = (String)i.next(); - SchemaDocument commonDoc = SchemaDocument.Factory.parse( - "" - ); - if (namespace.length() > 0) - commonDoc.getSchema().setTargetNamespace(namespace); - commonDoc.getSchema().setElementFormDefault(FormChoice.QUALIFIED); - commonDocs.put(namespace, commonDoc); - commonFiles.put(commonDoc, commonFileFor(commonName, namespace, count++, outdir)); - } - - // pull out all the duplicate definitions and drop them into the file - // we reuse the elementNames (etc) sets to keep track of which definitions - // we have already inserted. - for (Iterator i = schemaDocs.keySet().iterator(); i.hasNext(); ) - { - SchemaDocument doc = (SchemaDocument)i.next(); - - // collect together names - String targetNamespace = doc.getSchema().getTargetNamespace(); - if (targetNamespace == null) - targetNamespace = ""; - - SchemaDocument commonDoc = (SchemaDocument)commonDocs.get(targetNamespace); - - boolean needImport = false; - - TopLevelComplexType ct[] = doc.getSchema().getComplexTypeArray(); - for (int j = ct.length - 1; j >= 0; j--) - { - if (!isDuplicate(ct[j].getName(), targetNamespace, dupeTypeNames)) - continue; - if (isFirstDuplicate(ct[j].getName(), targetNamespace, typeNames, dupeTypeNames)) - commonDoc.getSchema().addNewComplexType().set(ct[j]); - needImport = true; - doc.getSchema().removeComplexType(j); - } - - TopLevelSimpleType st[] = doc.getSchema().getSimpleTypeArray(); - for (int j = 0; j < st.length; j++) - { - if (!isDuplicate(st[j].getName(), targetNamespace, dupeTypeNames)) - continue; - if (isFirstDuplicate(st[j].getName(), targetNamespace, typeNames, dupeTypeNames)) - commonDoc.getSchema().addNewSimpleType().set(st[j]); - needImport = true; - doc.getSchema().removeSimpleType(j); - } - - TopLevelElement el[] = doc.getSchema().getElementArray(); - for (int j = 0; j < el.length; j++) - { - if (!isDuplicate(el[j].getName(), targetNamespace, dupeElementNames)) - continue; - if (isFirstDuplicate(el[j].getName(), targetNamespace, elementNames, dupeElementNames)) - commonDoc.getSchema().addNewElement().set(el[j]); - needImport = true; - doc.getSchema().removeElement(j); - } - - TopLevelAttribute at[] = doc.getSchema().getAttributeArray(); - for (int j = 0; j < at.length; j++) - { - if (!isDuplicate(at[j].getName(), targetNamespace, dupeAttributeNames)) - continue; - if (isFirstDuplicate(at[j].getName(), targetNamespace, attributeNames, dupeAttributeNames)) - commonDoc.getSchema().addNewElement().set(at[j]); - needImport = true; - doc.getSchema().removeElement(j); - } - - NamedGroup gr[] = doc.getSchema().getGroupArray(); - for (int j = 0; j < gr.length; j++) - { - if (!isDuplicate(gr[j].getName(), targetNamespace, dupeModelGroupNames)) - continue; - if (isFirstDuplicate(gr[j].getName(), targetNamespace, modelGroupNames, dupeModelGroupNames)) - commonDoc.getSchema().addNewElement().set(gr[j]); - needImport = true; - doc.getSchema().removeElement(j); - } - - NamedAttributeGroup ag[] = doc.getSchema().getAttributeGroupArray(); - for (int j = 0; j < ag.length; j++) - { - if (!isDuplicate(ag[j].getName(), targetNamespace, dupeAttrGroupNames)) - continue; - if (isFirstDuplicate(ag[j].getName(), targetNamespace, attrGroupNames, dupeAttrGroupNames)) - commonDoc.getSchema().addNewElement().set(ag[j]); - needImport = true; - doc.getSchema().removeElement(j); - } - - if (needImport) - { - IncludeDocument.Include newInclude = doc.getSchema().addNewInclude(); - File inputFile = (File)schemaDocs.get(doc); - File outputFile = outputFileFor(inputFile, basedir, outdir); - File commonFile = (File)commonFiles.get(commonDoc); - if (targetNamespace != null) - newInclude.setSchemaLocation(relativeURIFor(outputFile, commonFile)); - } - } - - // make the directory for output - if (!outdir.isDirectory() && !outdir.mkdirs()) - { - System.err.println("Unable to makedir " + outdir); - System.exit(1); - return; - } - - // now write all those docs back out. - for (Iterator i = schemaDocs.keySet().iterator(); i.hasNext(); ) - { - SchemaDocument doc = (SchemaDocument)i.next(); - File inputFile = (File)schemaDocs.get(doc); - File outputFile = outputFileFor(inputFile, basedir, outdir); - if (outputFile == null) - System.out.println("Cannot copy " + inputFile); - else - doc.save(outputFile, new XmlOptions().setSavePrettyPrint().setSaveAggresiveNamespaces()); - } - - for (Iterator i = commonFiles.keySet().iterator(); i.hasNext(); ) - { - SchemaDocument doc = (SchemaDocument)i.next(); - File outputFile = (File)commonFiles.get(doc); - doc.save(outputFile, new XmlOptions().setSavePrettyPrint().setSaveAggresiveNamespaces()); - } - - } - - private static File outputFileFor(File file, File baseDir, File outdir) - { - URI base = baseDir.getAbsoluteFile().toURI(); - URI abs = file.getAbsoluteFile().toURI(); - URI rel = base.relativize(abs); - if (rel.isAbsolute()) - { - System.out.println("Cannot relativize " + file); - return null; - } - - URI outbase = outdir.toURI(); - URI out = CodeGenUtil.resolve(outbase, rel); - return new File(out); - } - - private static URI commonAncestor(URI first, URI second) - { - String firstStr = first.toString(); - String secondStr = second.toString(); - int len = firstStr.length(); - if (secondStr.length() < len) - len = secondStr.length(); - int i; - for (i = 0; i < len; i++) - { - if (firstStr.charAt(i) != secondStr.charAt(i)) - break; - } - i -= 1; - if (i >= 0) - i = firstStr.lastIndexOf('/', i); - if (i < 0) - return null; - try - { - return new URI(firstStr.substring(0, i)); - } - catch (URISyntaxException e) - { - return null; - } - } - - - private static String relativeURIFor(File source, File target) - { - URI base = source.getAbsoluteFile().toURI(); - URI abs = target.getAbsoluteFile().toURI(); - // find common substring... - URI commonBase = commonAncestor(base, abs); - if (commonBase == null) - return abs.toString(); - - URI baserel = commonBase.relativize(base); - URI targetrel = commonBase.relativize(abs); - if (baserel.isAbsolute() || targetrel.isAbsolute()) - return abs.toString(); - String prefix = ""; - String sourceRel = baserel.toString(); - for (int i = 0; i < sourceRel.length();) - { - i = sourceRel.indexOf('/', i); - if (i < 0) - break; - prefix += "../"; - i += 1; - } - return prefix + targetrel.toString(); - } - - private static File commonFileFor(String commonName, String namespace, int i, File outdir) - { - String name = commonName; - if (i > 0) - { - int index = commonName.lastIndexOf('.'); - if (index < 0) - index = commonName.length(); - name = commonName.substring(0, index) + i + commonName.substring(index); - } - return new File(outdir, name); - } - - - private static void noteName(String name, String targetNamespace, Set seen, Set dupes, Set dupeNamespaces) - { - if (name == null) - return; - QName qName = new QName(targetNamespace, name); - if (seen.contains(qName)) - { - dupes.add(qName); - dupeNamespaces.add(targetNamespace); - } - else - seen.add(qName); - - } - - private static boolean isFirstDuplicate(String name, String targetNamespace, Set notseen, Set dupes) - { - if (name == null) - return false; - QName qName = new QName(targetNamespace, name); - if (dupes.contains(qName) && notseen.contains(qName)) - { - notseen.remove(qName); - return true; - } - return false; - } - - private static boolean isDuplicate(String name, String targetNamespace, Set dupes) - { - if (name == null) - return false; - QName qName = new QName(targetNamespace, name); - return (dupes.contains(qName)); - } - - -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/InstanceValidator.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/InstanceValidator.java deleted file mode 100644 index f0e9dac..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/InstanceValidator.java +++ /dev/null @@ -1,225 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlException; - -import java.util.Collections; -import java.util.List; -import java.util.ArrayList; -import java.util.Set; -import java.util.HashSet; -import java.util.Collection; -import java.util.Iterator; -import java.io.File; - -public class InstanceValidator -{ - public static void printUsage() - { - System.out.println("Validates the specified instance against the specified schema."); - System.out.println("Contrast with the svalidate tool, which validates using a stream."); - System.out.println("Usage: validate [-dl] [-nopvr] [-noupa] [-license] schema.xsd instance.xml"); - System.out.println("Options:"); - System.out.println(" -dl - permit network downloads for imports and includes (default is off)"); - System.out.println(" -noupa - do not enforce the unique particle attribution rule"); - System.out.println(" -nopvr - do not enforce the particle valid (restriction) rule"); - System.out.println(" -strict - performs strict(er) validation"); - System.out.println(" -partial - allow partial schema type system"); - System.out.println(" -license - prints license information"); - } - - public static void main(String[] args) - { - System.exit(extraMain(args)); - } - - /** - * Use this method to avoid calling {@link java.lang.System#exit(int)} - * @param args are command line options - * @return exitCode - */ - public static int extraMain(String[] args) - { - Set flags = new HashSet(); - flags.add("h"); - flags.add("help"); - flags.add("usage"); - flags.add("license"); - flags.add("version"); - flags.add("dl"); - flags.add("noupa"); - flags.add("nopvr"); - flags.add("strict"); - flags.add("partial"); - - CommandLine cl = new CommandLine(args, flags, Collections.EMPTY_SET); - - if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null || args.length < 1) - { - printUsage(); - return 0; - } - - String[] badopts = cl.getBadOpts(); - if (badopts.length > 0) - { - for (int i = 0; i < badopts.length; i++) - System.out.println("Unrecognized option: " + badopts[i]); - printUsage(); - return 0; - } - - if (cl.getOpt("license") != null) - { - CommandLine.printLicense(); - return 0; - } - - if (cl.getOpt("version") != null) - { - CommandLine.printVersion(); - return 0; - } - - if (cl.args().length == 0) - { - return 0; - } - - boolean dl = (cl.getOpt("dl") != null); - boolean nopvr = (cl.getOpt("nopvr") != null); - boolean noupa = (cl.getOpt("noupa") != null); - boolean strict = (cl.getOpt("strict") != null); - boolean partial = (cl.getOpt("partial") != null); - - File[] schemaFiles = cl.filesEndingWith(".xsd"); - File[] instanceFiles = cl.filesEndingWith(".xml"); - File[] jarFiles = cl.filesEndingWith(".jar"); - - List sdocs = new ArrayList(); - - - for (int i = 0; i < schemaFiles.length; i++) - { - try - { - sdocs.add( - XmlObject.Factory.parse( - schemaFiles[i], (new XmlOptions()).setLoadLineNumbers().setLoadMessageDigest())); - } - catch (Exception e) - { - System.err.println( schemaFiles[i] + " not loadable: " + e ); - } - } - - XmlObject[] schemas = (XmlObject[])sdocs.toArray(new XmlObject[0]); - - SchemaTypeLoader sLoader = null; - Collection compErrors = new ArrayList(); - XmlOptions schemaOptions = new XmlOptions(); - schemaOptions.setErrorListener(compErrors); - if (dl) - schemaOptions.setCompileDownloadUrls(); - if (nopvr) - schemaOptions.setCompileNoPvrRule(); - if (noupa) - schemaOptions.setCompileNoUpaRule(); - if (partial) - schemaOptions.put("COMPILE_PARTIAL_TYPESYSTEM"); - - if (jarFiles != null && jarFiles.length > 0) - sLoader = XmlBeans.typeLoaderForResource(XmlBeans.resourceLoaderForPath(jarFiles)); - - int returnCode = 0; - - try - { - if (schemas != null && schemas.length > 0) - sLoader = XmlBeans.compileXsd(schemas, sLoader, schemaOptions); - } - catch (Exception e) - { - if (compErrors.isEmpty() || !(e instanceof XmlException)) - { - e.printStackTrace(System.err); - } - System.out.println("Schema invalid:" + (partial ? " couldn't recover from errors" : "")); - for (Iterator i = compErrors.iterator(); i.hasNext(); ) - System.out.println(i.next()); - - returnCode = 10; - return returnCode; - } - - // recovered from errors, print out errors - if (partial && !compErrors.isEmpty()) - { - returnCode = 11; - System.out.println("Schema invalid: partial schema type system recovered"); - for (Iterator i = compErrors.iterator(); i.hasNext(); ) - System.out.println(i.next()); - } - - if (sLoader == null) - sLoader = XmlBeans.getContextTypeLoader(); - - for (int i = 0; i < instanceFiles.length; i++) - { - XmlObject xobj; - - try - { - xobj = - sLoader.parse( instanceFiles[i], null, (new XmlOptions()).setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT) ); - } - catch (Exception e) - { - System.err.println(instanceFiles[i] + " not loadable: " + e); - e.printStackTrace(System.err); - continue; - } - - Collection errors = new ArrayList(); - - if (xobj.schemaType() == XmlObject.type) - { - System.out.println(instanceFiles[i] + " NOT valid. "); - System.out.println(" Document type not found." ); - } - else if (xobj.validate(strict ? - new XmlOptions().setErrorListener(errors).setValidateStrict() : - new XmlOptions().setErrorListener(errors))) - System.out.println(instanceFiles[i] + " valid."); - else - { - returnCode = 1; - System.out.println(instanceFiles[i] + " NOT valid."); - for (Iterator it = errors.iterator(); it.hasNext(); ) - { - System.out.println(it.next()); - } - } - } - - return returnCode; - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/RunXQuery.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/RunXQuery.java deleted file mode 100644 index c93c6c1..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/RunXQuery.java +++ /dev/null @@ -1,244 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import java.io.*; -import java.util.*; -import org.apache.xmlbeans.*; - -public class RunXQuery -{ - public static void printUsage() - { - System.out.println("Run an XQuery against an XML instance"); - System.out.println("Usage:"); - System.out.println("xquery [-verbose] [-pretty] [-q | -qf query.xq] [file.xml]*"); - System.out.println(" -q to specify a query on the command-line"); - System.out.println(" -qf to specify a file containing a query"); - System.out.println(" -pretty pretty-prints the results"); - System.out.println(" -license prints license information"); - System.out.println(" the query is run on each XML file specified"); - System.out.println(""); - } - - public static void main ( String[] args ) throws Exception - { - Set flags = new HashSet(); - flags.add("h"); - flags.add("help"); - flags.add("usage"); - flags.add("license"); - flags.add("version"); - flags.add("verbose"); - flags.add("pretty"); - - CommandLine cl = - new CommandLine( - args, flags, - Arrays.asList( new String[] { "q", "qf" } ) ); - - if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) - { - printUsage(); - System.exit(0); - return; - } - - String[] badopts = cl.getBadOpts(); - if (badopts.length > 0) - { - for (int i = 0; i < badopts.length; i++) - System.out.println("Unrecognized option: " + badopts[i]); - printUsage(); - System.exit(0); - return; - } - - if (cl.getOpt("license") != null) - { - CommandLine.printLicense(); - System.exit(0); - return; - } - - if (cl.getOpt("version") != null) - { - CommandLine.printVersion(); - System.exit(0); - return; - } - - args = cl.args(); - - if (args.length == 0) - { - printUsage(); - System.exit(0); - return; - } - - boolean verbose = cl.getOpt( "verbose" ) != null; - boolean pretty = cl.getOpt( "pretty" ) != null; - - // - // Get and compile the query - // - - String query = cl.getOpt( "q" ); - String queryfile = cl.getOpt( "qf" ); - - if (query == null && queryfile == null) - { - System.err.println( "No query specified" ); - System.exit(0); - return; - } - - if (query != null && queryfile != null) - { - System.err.println( "Specify -qf or -q, not both." ); - System.exit(0); - return; - } - - try - { - if (queryfile != null) - { - File queryFile = new File( queryfile ); - FileInputStream is = new FileInputStream( queryFile ); - InputStreamReader r = new InputStreamReader( is ); - - StringBuffer sb = new StringBuffer(); - - for ( ; ; ) - { - int ch = r.read(); - - if (ch < 0) - break; - - sb.append( (char) ch ); - } - - r.close(); - is.close(); - - query = sb.toString(); - } - } - catch ( Throwable e ) - { - System.err.println( "Cannot read query file: " + e.getMessage() ); - System.exit(1); - return; - } - - if (verbose) - { - System.out.println( "Compile Query:" ); - System.out.println( query ); - System.out.println(); - } - - try - { - query= XmlBeans.compileQuery( query ); - } - catch ( Exception e ) - { - System.err.println( "Error compiling query: " + e.getMessage() ); - System.exit(1); - return; - } - - // - // Get the instance - // - - File[] files = cl.getFiles(); - - for (int i = 0; i < files.length; i++) - { - XmlObject x; - - try - { - if (verbose) - { - InputStream is = new FileInputStream( files[i] ); - - for ( ; ; ) - { - int ch = is.read(); - - if (ch < 0) - break; - - System.out.write( ch ); - } - - is.close(); - - System.out.println(); - } - - x = XmlObject.Factory.parse( files[i] ); - } - catch ( Throwable e ) - { - System.err.println( "Error parsing instance: " + e.getMessage() ); - System.exit(1); - return; - } - - if (verbose) - { - System.out.println( "Executing Query..." ); - System.err.println(); - } - - XmlObject[] result = null; - - try - { - result = x.execQuery( query ); - } - catch ( Throwable e ) - { - System.err.println( "Error executing query: " + e.getMessage() ); - System.exit(1); - return; - } - - if (verbose) - { - System.out.println( "Query Result:" ); - } - - XmlOptions opts = new XmlOptions(); - opts.setSaveOuter(); - if (pretty) - opts.setSavePrettyPrint(); - - for (int j = 0; j < result.length; j++) - { - result[j].save( System.out, opts ); - System.out.println(); - } - } - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java deleted file mode 100644 index e8bd8dc..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java +++ /dev/null @@ -1,253 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.impl.common.IOUtil; -import org.apache.xmlbeans.impl.common.XmlErrorWatcher; -import org.apache.xmlbeans.impl.schema.SchemaTypeCodePrinter; -import org.apache.xmlbeans.impl.schema.SchemaTypeSystemCompiler; -import org.apache.xmlbeans.impl.util.FilerImpl; -import org.apache.xmlbeans.SchemaCodePrinter; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.Filer; -import repackage.Repackager; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Reader; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class SchemaCodeGenerator -{ - /** - * Saves a SchemaTypeSystem to the specified directory. - * - * @param system the SchemaTypeSystem to save - * @param classesDir the destination directory for xsb's - * @param sourceFile if present, the TypeSystemHolder source will be - * generated in this file for subsequent compilation, - * if null then the source will be generated in a temp - * directory and then compiled to the destination dir - * @param repackager the repackager to use when generating the holder class - * @param options options. Can be null - * @deprecated Use {@link SchemaTypeSystem.save()} instead. - */ - public static void saveTypeSystem(SchemaTypeSystem system, File classesDir, - File sourceFile, Repackager repackager, XmlOptions options) - throws IOException - { - Filer filer = new FilerImpl(classesDir, null, repackager, false, false); - system.save(filer); - } - - static void deleteObsoleteFiles(File rootDir, File srcDir, Set seenFiles) - { - if (!(rootDir.isDirectory() && srcDir.isDirectory())) - throw new IllegalArgumentException(); - String absolutePath = srcDir.getAbsolutePath(); - // Do a sanity check to make sure we don't delete by mistake some important dir - if (absolutePath.length() <= 5) - return; - if (absolutePath.startsWith("/home/") && - (absolutePath.indexOf("/", 6) >= absolutePath.length() - 1 || - absolutePath.indexOf("/", 6) < 0)) - return; - - // Go recursively starting with srcDir and delete all files that are - // not in the given Set - File[] files = srcDir.listFiles(); - for (int i = 0; i < files.length; i++) - { - if (files[i].isDirectory()) - deleteObsoleteFiles(rootDir, files[i], seenFiles); - else if (seenFiles.contains(files[i])) - ; - else - { - deleteXmlBeansFile(files[i]); - deleteDirRecursively(rootDir, files[i].getParentFile()); - } - } - } - - private static void deleteXmlBeansFile(File file) - { - if (file.getName().endsWith(".java")) - file.delete(); - } - - private static void deleteDirRecursively(File root, File dir) - { - String[] list = dir.list(); - while (list != null && list.length == 0 && !dir.equals(root)) - { - dir.delete(); - dir = dir.getParentFile(); - list = dir.list(); - } - } - - protected static File createTempDir() throws IOException - { - -// Some beta builds of JDK1.5 are having troubles creating temp directories -// if the java.io.tmpdir doesn't exist. This seems to help. -try { - File tmpDirFile = new File(SystemProperties.getProperty("java.io.tmpdir")); - tmpDirFile.mkdirs(); -} catch(Exception e) { e.printStackTrace(); } - - File tmpFile = File.createTempFile("xbean", null); - String path = tmpFile.getAbsolutePath(); - if (!path.endsWith(".tmp")) - throw new IOException("Error: createTempFile did not create a file ending with .tmp"); - path = path.substring(0, path.length() - 4); - File tmpSrcDir = null; - - for (int count = 0; count < 100; count++) - { - String name = path + ".d" + (count == 0 ? "" : Integer.toString(count++)); - - tmpSrcDir = new File(name); - - if (!tmpSrcDir.exists()) - { - boolean created = tmpSrcDir.mkdirs(); - assert created : "Could not create " + tmpSrcDir.getAbsolutePath(); - break; - } - } - tmpFile.deleteOnExit(); - - return tmpSrcDir; - } - - protected static void tryHardToDelete(File dir) - { - tryToDelete(dir); - if (dir.exists()) - tryToDeleteLater(dir); - } - - private static void tryToDelete(File dir) - { - if (dir.exists()) - { - if (dir.isDirectory()) - { - String[] list = dir.list(); // can return null if I/O error - if (list != null) - for (int i = 0; i < list.length; i++) - tryToDelete(new File(dir, list[i])); - } - if (!dir.delete()) - return; // don't try very hard, because we're just deleting tmp - } - } - - private static Set deleteFileQueue = new HashSet(); - private static int triesRemaining = 0; - - private static boolean tryNowThatItsLater() - { - List files; - - synchronized (deleteFileQueue) - { - files = new ArrayList(deleteFileQueue); - deleteFileQueue.clear(); - } - - List retry = new ArrayList(); - - for (Iterator i = files.iterator(); i.hasNext(); ) - { - File file = (File)i.next(); - tryToDelete(file); - if (file.exists()) - retry.add(file); - } - - synchronized (deleteFileQueue) - { - if (triesRemaining > 0) - triesRemaining -= 1; - - if (triesRemaining <= 0 || retry.size() == 0) // done? - triesRemaining = 0; - else - deleteFileQueue.addAll(retry); // try again? - - return (triesRemaining <= 0); - } - } - - private static void giveUp() - { - synchronized (deleteFileQueue) - { - deleteFileQueue.clear(); - triesRemaining = 0; - } - } - - private static void tryToDeleteLater(File dir) - { - synchronized (deleteFileQueue) - { - deleteFileQueue.add(dir); - if (triesRemaining == 0) - { - new Thread() - { - public void run() - { - // repeats tryNow until triesRemaining == 0 - try - { - for (;;) - { - if (tryNowThatItsLater()) - return; // succeeded - Thread.sleep(1000 * 3); // wait three seconds - } - } - catch (InterruptedException e) - { - giveUp(); - } - } - }; - } - - if (triesRemaining < 10) - triesRemaining = 10; - } - } - -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java deleted file mode 100644 index 11f4c9d..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java +++ /dev/null @@ -1,1269 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.SchemaCodePrinter; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.ResourceLoader; -import org.apache.xmlbeans.impl.common.IOUtil; -import org.apache.xmlbeans.impl.common.ResolverUtil; -import org.apache.xmlbeans.impl.common.XmlErrorPrinter; -import org.apache.xmlbeans.impl.common.XmlErrorWatcher; -import org.apache.xmlbeans.impl.schema.PathResourceLoader; -import org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl; -import org.apache.xmlbeans.impl.schema.SchemaTypeSystemCompiler; -import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; -import org.apache.xmlbeans.impl.schema.StscState; -import org.apache.xmlbeans.impl.common.JarHelper; -import org.apache.xmlbeans.impl.util.FilerImpl; -import org.apache.xmlbeans.impl.values.XmlListImpl; -import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument; -import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.xml.sax.EntityResolver; -import org.apache.xmlbeans.impl.config.BindingConfigImpl; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; -import repackage.Repackager; - -public class SchemaCompiler -{ - public static void printUsage() - { - System.out.println("Compiles a schema into XML Bean classes and metadata."); - System.out.println("Usage: scomp [opts] [dirs]* [schema.xsd]* [service.wsdl]* [config.xsdconfig]*"); - System.out.println("Options include:"); - System.out.println(" -cp [a;b;c] - classpath"); - System.out.println(" -d [dir] - target binary directory for .class and .xsb files"); - System.out.println(" -src [dir] - target directory for generated .java files"); - System.out.println(" -srconly - do not compile .java files or jar the output."); - System.out.println(" -out [xmltypes.jar] - the name of the output jar"); - System.out.println(" -dl - permit network downloads for imports and includes (default is off)"); - System.out.println(" -noupa - do not enforce the unique particle attribution rule"); - System.out.println(" -nopvr - do not enforce the particle valid (restriction) rule"); - System.out.println(" -noann - ignore annotations"); - System.out.println(" -novdoc - do not validate contents of "); - System.out.println(" -noext - ignore all extension (Pre/Post and Interface) found in .xsdconfig files"); - System.out.println(" -compiler - path to external java compiler"); - System.out.println(" -javasource [version] - generate java source compatible for a Java version (1.4 or 1.5)"); - System.out.println(" -ms - initial memory for external java compiler (default '" + CodeGenUtil.DEFAULT_MEM_START + "')"); - System.out.println(" -mx - maximum memory for external java compiler (default '" + CodeGenUtil.DEFAULT_MEM_MAX + "')"); - System.out.println(" -debug - compile with debug symbols"); - System.out.println(" -quiet - print fewer informational messages"); - System.out.println(" -verbose - print more informational messages"); - System.out.println(" -version - prints version information"); - System.out.println(" -license - prints license information"); - System.out.println(" -allowmdef \"[ns] [ns] [ns]\" - ignores multiple defs in given namespaces (use ##local for no-namespace)"); - System.out.println(" -catalog [file] - catalog file for org.apache.xml.resolver.tools.CatalogResolver. (Note: needs resolver.jar from http://xml.apache.org/commons/components/resolver/index.html)"); - /* Undocumented feature - pass in one schema compiler extension and related parameters - System.out.println(" -repackage - repackage specification"); - System.out.println(" -extension - registers a schema compiler extension"); - System.out.println(" -extensionParms - specify parameters for the compiler extension"); - System.out.println(" -schemaCodePrinter - specify SchemaCodePrinter class"); - */ - System.out.println(); - } - - public static void main(String[] args) - { - if (args.length == 0) - { - printUsage(); - System.exit(0); - return; - } - - Set flags = new HashSet(); - flags.add("h"); - flags.add("help"); - flags.add("usage"); - flags.add("license"); - flags.add("quiet"); - flags.add("verbose"); - flags.add("version"); - flags.add("dl"); - flags.add("noupa"); - flags.add("nopvr"); - flags.add("noann"); - flags.add("novdoc"); - flags.add("noext"); - flags.add("srconly"); - flags.add("debug"); - - Set opts = new HashSet(); - opts.add("out"); - opts.add("name"); - opts.add("src"); - opts.add("d"); - opts.add("cp"); - opts.add("compiler"); - opts.add("javasource"); - opts.add("jar"); // deprecated - opts.add("ms"); - opts.add("mx"); - opts.add("repackage"); - opts.add("schemaCodePrinter"); - opts.add("extension"); - opts.add("extensionParms"); - opts.add("allowmdef"); - opts.add("catalog"); - CommandLine cl = new CommandLine(args, flags, opts); - - if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) - { - printUsage(); - System.exit(0); - return; - } - - String[] badopts = cl.getBadOpts(); - if (badopts.length > 0) - { - for (int i = 0; i < badopts.length; i++) - System.out.println("Unrecognized option: " + badopts[i]); - printUsage(); - System.exit(0); - return; - } - - if (cl.getOpt("license") != null) - { - CommandLine.printLicense(); - System.exit(0); - return; - } - - if (cl.getOpt("version") != null) - { - CommandLine.printVersion(); - System.exit(0); - return; - } - - args = cl.args(); - boolean verbose = (cl.getOpt("verbose") != null); - boolean quiet = (cl.getOpt("quiet") != null); - if (verbose) - quiet = false; - - if (verbose) - CommandLine.printVersion(); - - String outputfilename = cl.getOpt("out"); - - String repackage = cl.getOpt("repackage"); - - String codePrinterClass = cl.getOpt("schemaCodePrinter"); - SchemaCodePrinter codePrinter = null; - if (codePrinterClass != null) - { - try - { - codePrinter = (SchemaCodePrinter) - Class.forName(codePrinterClass).newInstance(); - } - catch (Exception e) - { - System.err.println - ("Failed to load SchemaCodePrinter class " + - codePrinterClass + "; proceeding with default printer"); - } - } - - String name = cl.getOpt("name"); - - boolean download = (cl.getOpt("dl") != null); - boolean noUpa = (cl.getOpt("noupa") != null); - boolean noPvr = (cl.getOpt("nopvr") != null); - boolean noAnn = (cl.getOpt("noann") != null); - boolean noVDoc= (cl.getOpt("novdoc") != null); - boolean noExt= (cl.getOpt("noext") != null); - boolean nojavac = (cl.getOpt("srconly") != null); - boolean debug = (cl.getOpt("debug") != null); - - String allowmdef = cl.getOpt("allowmdef"); - Set mdefNamespaces = (allowmdef == null ? Collections.EMPTY_SET : - new HashSet(Arrays.asList(XmlListImpl.split_list(allowmdef)))); - - List extensions = new ArrayList(); - if (cl.getOpt("extension") != null) { - try { - Extension e = new Extension(); - e.setClassName(Class.forName(cl.getOpt("extension"), false, Thread.currentThread().getContextClassLoader())); - extensions.add(e); - } catch (ClassNotFoundException e) { - System.err.println("Could not find extension class: " + cl.getOpt("extension") + " Is it on your classpath?"); - System.exit(1); - } - } - - if (extensions.size() > 0) - { - // example: -extensionParms typeMappingFileLocation=d:\types - if (cl.getOpt("extensionParms") != null) { - Extension e = (Extension) extensions.get(0); - // extensionParms are delimited by ';' - StringTokenizer parmTokens = new StringTokenizer(cl.getOpt("extensionParms"), ";"); - while (parmTokens.hasMoreTokens()) { - // get name value pair for each extension parms and stick into extension parms - String nvPair = parmTokens.nextToken(); - int index = nvPair.indexOf('='); - if (index < 0) - { - System.err.println("extensionParms should be name=value;name=value"); - System.exit(1); - } - String n = nvPair.substring(0, index); - String v = nvPair.substring(index + 1); - Extension.Param param = e.createParam(); - param.setName(n); - param.setValue(v); - } - } - } - - String classesdir = cl.getOpt("d"); - File classes = null; - if (classesdir != null) - classes = new File(classesdir); - - String srcdir = cl.getOpt("src"); - File src = null; - if (srcdir != null) - src = new File(srcdir); - if (nojavac && srcdir == null && classes != null) - src = classes; - - // create temp directory - File tempdir = null; - if (src == null || classes == null) - { - try - { - tempdir = SchemaCodeGenerator.createTempDir(); - } - catch (java.io.IOException e) - { - System.err.println("Error creating temp dir " + e); - System.exit(1); - } - } - - File jarfile = null; - if (outputfilename == null && classes == null && !nojavac) - outputfilename = "xmltypes.jar"; - if (outputfilename != null) - jarfile = new File(outputfilename); - - if (src == null) - src = IOUtil.createDir(tempdir, "src"); - if (classes == null) - classes = IOUtil.createDir(tempdir, "classes"); - - File[] classpath = null; - String cpString = cl.getOpt("cp"); - if (cpString != null) - { - String[] cpparts = cpString.split(File.pathSeparator); - List cpList = new ArrayList(); - for (int i = 0; i < cpparts.length; i++) - cpList.add(new File(cpparts[i])); - classpath = (File[])cpList.toArray(new File[cpList.size()]); - } - else - { - classpath = CodeGenUtil.systemClasspath(); - } - - String javasource = cl.getOpt("javasource"); - String compiler = cl.getOpt("compiler"); - String jar = cl.getOpt("jar"); - if (verbose && jar != null) - System.out.println("The 'jar' option is no longer supported."); - - String memoryInitialSize = cl.getOpt("ms"); - String memoryMaximumSize = cl.getOpt("mx"); - - File[] xsdFiles = cl.filesEndingWith(".xsd"); - File[] wsdlFiles = cl.filesEndingWith(".wsdl"); - File[] javaFiles = cl.filesEndingWith(".java"); - File[] configFiles = cl.filesEndingWith(".xsdconfig"); - URL[] urlFiles = cl.getURLs(); - - if (xsdFiles.length + wsdlFiles.length + urlFiles.length == 0) - { - System.out.println("Could not find any xsd or wsdl files to process."); - System.exit(0); - } - File baseDir = cl.getBaseDir(); - URI baseURI = baseDir == null ? null : baseDir.toURI(); - - XmlErrorPrinter err = new XmlErrorPrinter(verbose, baseURI); - - String catString = cl.getOpt("catalog"); - - Parameters params = new Parameters(); - params.setBaseDir(baseDir); - params.setXsdFiles(xsdFiles); - params.setWsdlFiles(wsdlFiles); - params.setJavaFiles(javaFiles); - params.setConfigFiles(configFiles); - params.setUrlFiles(urlFiles); - params.setClasspath(classpath); - params.setOutputJar(jarfile); - params.setName(name); - params.setSrcDir(src); - params.setClassesDir(classes); - params.setCompiler(compiler); - params.setJavaSource(javasource); - params.setMemoryInitialSize(memoryInitialSize); - params.setMemoryMaximumSize(memoryMaximumSize); - params.setNojavac(nojavac); - params.setQuiet(quiet); - params.setVerbose(verbose); - params.setDownload(download); - params.setNoUpa(noUpa); - params.setNoPvr(noPvr); - params.setNoAnn(noAnn); - params.setNoVDoc(noVDoc); - params.setNoExt(noExt); - params.setDebug(debug); - params.setErrorListener(err); - params.setRepackage(repackage); - params.setExtensions(extensions); - params.setMdefNamespaces(mdefNamespaces); - params.setCatalogFile(catString); - params.setSchemaCodePrinter(codePrinter); - - boolean result = compile(params); - - if (tempdir != null) - SchemaCodeGenerator.tryHardToDelete(tempdir); - - if (!result) - System.exit(1); - - System.exit(0); - } - - public static class Parameters - { - private File baseDir; - private File[] xsdFiles; - private File[] wsdlFiles; - private File[] javaFiles; - private File[] configFiles; - private URL[] urlFiles; - private File[] classpath; - private File outputJar; - private String name; - private File srcDir; - private File classesDir; - private String memoryInitialSize; - private String memoryMaximumSize; - private String compiler; - private String javasource; - private boolean nojavac; - private boolean quiet; - private boolean verbose; - private boolean download; - private Collection errorListener; - private boolean noUpa; - private boolean noPvr; - private boolean noAnn; - private boolean noVDoc; - private boolean noExt; - private boolean debug; - private boolean incrementalSrcGen; - private String repackage; - private List extensions = Collections.EMPTY_LIST; - private Set mdefNamespaces = Collections.EMPTY_SET; - private String catalogFile; - private SchemaCodePrinter schemaCodePrinter; - private EntityResolver entityResolver; - - public File getBaseDir() - { - return baseDir; - } - - public void setBaseDir(File baseDir) - { - this.baseDir = baseDir; - } - - public File[] getXsdFiles() - { - return xsdFiles; - } - - public void setXsdFiles(File[] xsdFiles) - { - this.xsdFiles = xsdFiles; - } - - public File[] getWsdlFiles() - { - return wsdlFiles; - } - - public void setWsdlFiles(File[] wsdlFiles) - { - this.wsdlFiles = wsdlFiles; - } - - public File[] getJavaFiles() - { - return javaFiles; - } - - public void setJavaFiles(File[] javaFiles) - { - this.javaFiles = javaFiles; - } - - public File[] getConfigFiles() - { - return configFiles; - } - - public void setConfigFiles(File[] configFiles) - { - this.configFiles = configFiles; - } - - public URL[] getUrlFiles() - { - return urlFiles; - } - - public void setUrlFiles(URL[] urlFiles) - { - this.urlFiles = urlFiles; - } - - public File[] getClasspath() - { - return classpath; - } - - public void setClasspath(File[] classpath) - { - this.classpath = classpath; - } - - public File getOutputJar() - { - return outputJar; - } - - public void setOutputJar(File outputJar) - { - this.outputJar = outputJar; - } - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public File getSrcDir() - { - return srcDir; - } - - public void setSrcDir(File srcDir) - { - this.srcDir = srcDir; - } - - public File getClassesDir() - { - return classesDir; - } - - public void setClassesDir(File classesDir) - { - this.classesDir = classesDir; - } - - public boolean isNojavac() - { - return nojavac; - } - - public void setNojavac(boolean nojavac) - { - this.nojavac = nojavac; - } - - public boolean isQuiet() - { - return quiet; - } - - public void setQuiet(boolean quiet) - { - this.quiet = quiet; - } - - public boolean isVerbose() - { - return verbose; - } - - public void setVerbose(boolean verbose) - { - this.verbose = verbose; - } - - public boolean isDownload() - { - return download; - } - - public void setDownload(boolean download) - { - this.download = download; - } - - public boolean isNoUpa() - { - return noUpa; - } - - public void setNoUpa(boolean noUpa) - { - this.noUpa = noUpa; - } - - public boolean isNoPvr() - { - return noPvr; - } - - public void setNoPvr(boolean noPvr) - { - this.noPvr = noPvr; - } - - public boolean isNoAnn() - { - return noAnn; - } - - public void setNoAnn(boolean noAnn) - { - this.noAnn = noAnn; - } - - public boolean isNoVDoc() - { - return noVDoc; - } - - public void setNoVDoc(boolean newNoVDoc) - { - this.noVDoc = newNoVDoc; - } - - public boolean isNoExt() - { - return noExt; - } - - public void setNoExt(boolean newNoExt) - { - this.noExt = newNoExt; - } - - public boolean isIncrementalSrcGen() - { - return incrementalSrcGen; - } - - public void setIncrementalSrcGen(boolean incrSrcGen) - { - this.incrementalSrcGen = incrSrcGen; - } - - public boolean isDebug() - { - return debug; - } - - public void setDebug(boolean debug) - { - this.debug = debug; - } - - public String getMemoryInitialSize() - { - return memoryInitialSize; - } - - public void setMemoryInitialSize(String memoryInitialSize) - { - this.memoryInitialSize = memoryInitialSize; - } - - public String getMemoryMaximumSize() - { - return memoryMaximumSize; - } - - public void setMemoryMaximumSize(String memoryMaximumSize) - { - this.memoryMaximumSize = memoryMaximumSize; - } - - public String getCompiler() - { - return compiler; - } - - public void setCompiler(String compiler) - { - this.compiler = compiler; - } - - public String getJavaSource() - { - return javasource; - } - - public void setJavaSource(String javasource) - { - this.javasource = javasource; - } - - /** @deprecated */ - public String getJar() - { - return null; - } - - /** @deprecated */ - public void setJar(String jar) - { - // no op - } - - public Collection getErrorListener() - { - return errorListener; - } - - public void setErrorListener(Collection errorListener) - { - this.errorListener = errorListener; - } - - public String getRepackage() - { - return repackage; - } - - public void setRepackage(String newRepackage) - { - repackage = newRepackage; - } - - public List getExtensions() { - return extensions; - } - - public void setExtensions(List extensions) { - this.extensions = extensions; - } - - public Set getMdefNamespaces() - { - return mdefNamespaces; - } - - public void setMdefNamespaces(Set mdefNamespaces) - { - this.mdefNamespaces = mdefNamespaces; - } - - public String getCatalogFile() - { - return catalogFile; - } - - public void setCatalogFile(String catalogPropFile) - { - this.catalogFile = catalogPropFile; - } - - public SchemaCodePrinter getSchemaCodePrinter() - { - return schemaCodePrinter; - } - - public void setSchemaCodePrinter(SchemaCodePrinter schemaCodePrinter) - { - this.schemaCodePrinter = schemaCodePrinter; - } - - public EntityResolver getEntityResolver() { - return entityResolver; - } - - public void setEntityResolver(EntityResolver entityResolver) { - this.entityResolver = entityResolver; - } - } - - private static SchemaTypeSystem loadTypeSystem(String name, File[] xsdFiles, File[] wsdlFiles, URL[] urlFiles, File[] configFiles, - File[] javaFiles, ResourceLoader cpResourceLoader, - boolean download, boolean noUpa, boolean noPvr, boolean noAnn, boolean noVDoc, boolean noExt, - Set mdefNamespaces, File baseDir, Map sourcesToCopyMap, - Collection outerErrorListener, File schemasDir, EntityResolver entResolver, File[] classpath, String javasource) - { - XmlErrorWatcher errorListener = new XmlErrorWatcher(outerErrorListener); - - // construct the state (have to initialize early in case of errors) - StscState state = StscState.start(); - state.setErrorListener(errorListener); - - // For parsing XSD and WSDL files, we should use the SchemaDocument - // classloader rather than the thread context classloader. This is - // because in some situations (such as when being invoked by ant - // underneath the ide) the context classloader is potentially weird - // (because of the design of ant). - - SchemaTypeLoader loader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader()); - - // step 1, parse all the XSD files. - ArrayList scontentlist = new ArrayList(); - if (xsdFiles != null) - { - for (int i = 0; i < xsdFiles.length; i++) - { - try - { - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setLoadMessageDigest(); - options.setEntityResolver(entResolver); - - XmlObject schemadoc = loader.parse(xsdFiles[i], null, options); - if (!(schemadoc instanceof SchemaDocument)) - { - StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, - new Object[] { xsdFiles[i], "schema" }, schemadoc); - } - else - { - addSchema(xsdFiles[i].toString(), (SchemaDocument)schemadoc, - errorListener, noVDoc, scontentlist); - } - } - catch (XmlException e) - { - errorListener.add(e.getError()); - } - catch (Exception e) - { - StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, - new Object[] { "xsd", xsdFiles[i], e.getMessage() }, xsdFiles[i]); - } - } - } - - // step 2, parse all WSDL files - if (wsdlFiles != null) - { - for (int i = 0; i < wsdlFiles.length; i++) - { - try - { - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setLoadSubstituteNamespaces(Collections.singletonMap( - "http://schemas.xmlsoap.org/wsdl/", "http://www.apache.org/internal/xmlbeans/wsdlsubst" - )); - options.setEntityResolver(entResolver); - - XmlObject wsdldoc = loader.parse(wsdlFiles[i], null, options); - - if (!(wsdldoc instanceof org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument)) - StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, - new Object[] { wsdlFiles[i], "wsdl" }, wsdldoc); - else - { - addWsdlSchemas(wsdlFiles[i].toString(), (org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument)wsdldoc, errorListener, noVDoc, scontentlist); - } - } - catch (XmlException e) - { - errorListener.add(e.getError()); - } - catch (Exception e) - { - StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, - new Object[] { "wsdl", wsdlFiles[i], e.getMessage() }, wsdlFiles[i]); - } - } - } - - // step 3, parse all URL files - // XMLBEANS-58 - Ability to pass URLs instead of Files for Wsdl/Schemas - if (urlFiles != null) - { - for (int i = 0; i < urlFiles.length; i++) - { - try - { - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - options.setLoadSubstituteNamespaces(Collections.singletonMap("http://schemas.xmlsoap.org/wsdl/", "http://www.apache.org/internal/xmlbeans/wsdlsubst")); - options.setEntityResolver(entResolver); - - XmlObject urldoc = loader.parse(urlFiles[i], null, options); - - if ((urldoc instanceof org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument)) - { - addWsdlSchemas(urlFiles[i].toString(), (org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument)urldoc, errorListener, noVDoc, scontentlist); - } - else if ((urldoc instanceof SchemaDocument)) - { - addSchema(urlFiles[i].toString(), (SchemaDocument)urldoc, - errorListener, noVDoc, scontentlist); - } - else - { - StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, - new Object[]{urlFiles[i], "wsdl or schema"}, urldoc); - } - - } - catch (XmlException e) - { - errorListener.add(e.getError()); - } - catch (Exception e) - { - StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, - new Object[]{"url", urlFiles[i], e.getMessage()}, urlFiles[i]); - } - } - } - - SchemaDocument.Schema[] sdocs = (SchemaDocument.Schema[])scontentlist.toArray(new SchemaDocument.Schema[scontentlist.size()]); - - // now the config files. - ArrayList cdoclist = new ArrayList(); - if (configFiles != null) - { - if (noExt) - System.out.println("Pre/Post and Interface extensions will be ignored."); - - for (int i = 0; i < configFiles.length; i++) - { - try - { - XmlOptions options = new XmlOptions(); - options.put( XmlOptions.LOAD_LINE_NUMBERS ); - options.setEntityResolver(entResolver); - options.setLoadSubstituteNamespaces(MAP_COMPATIBILITY_CONFIG_URIS); - - XmlObject configdoc = loader.parse(configFiles[i], null, options); - if (!(configdoc instanceof ConfigDocument)) - StscState.addError(errorListener, XmlErrorCodes.INVALID_DOCUMENT_TYPE, - new Object[] { configFiles[i], "xsd config" }, configdoc); - else - { - StscState.addInfo(errorListener, "Loading config file " + configFiles[i]); - if (configdoc.validate(new XmlOptions().setErrorListener(errorListener))) - { - ConfigDocument.Config config = ((ConfigDocument)configdoc).getConfig(); - cdoclist.add(config); - if (noExt) - { - //disable extensions - config.setExtensionArray(new Extensionconfig[] {}); - } - } - } - } - catch (XmlException e) - { - errorListener.add(e.getError()); - } - catch (Exception e) - { - StscState.addError(errorListener, XmlErrorCodes.CANNOT_LOAD_FILE, - new Object[] { "xsd config", configFiles[i], e.getMessage() }, configFiles[i]); - } - } - } - ConfigDocument.Config[] cdocs = (ConfigDocument.Config[])cdoclist.toArray(new ConfigDocument.Config[cdoclist.size()]); - - SchemaTypeLoader linkTo = SchemaTypeLoaderImpl.build(null, cpResourceLoader, null); - - URI baseURI = null; - if (baseDir != null) - baseURI = baseDir.toURI(); - - XmlOptions opts = new XmlOptions(); - if (download) - opts.setCompileDownloadUrls(); - if (noUpa) - opts.setCompileNoUpaRule(); - if (noPvr) - opts.setCompileNoPvrRule(); - if (noAnn) - opts.setCompileNoAnnotations(); - if (mdefNamespaces != null) - opts.setCompileMdefNamespaces(mdefNamespaces); - opts.setCompileNoValidation(); // already validated here - opts.setEntityResolver(entResolver); - if (javasource != null) - opts.setGenerateJavaVersion(javasource); - - // now pass it to the main compile function - SchemaTypeSystemCompiler.Parameters params = new SchemaTypeSystemCompiler.Parameters(); - params.setName(name); - params.setSchemas(sdocs); - params.setConfig(BindingConfigImpl.forConfigDocuments(cdocs, javaFiles, classpath)); - params.setLinkTo(linkTo); - params.setOptions(opts); - params.setErrorListener(errorListener); - params.setJavaize(true); - params.setBaseURI(baseURI); - params.setSourcesToCopyMap(sourcesToCopyMap); - params.setSchemasDir(schemasDir); - return SchemaTypeSystemCompiler.compile(params); - } - - private static void addSchema(String name, SchemaDocument schemadoc, - XmlErrorWatcher errorListener, boolean noVDoc, List scontentlist) - { - StscState.addInfo(errorListener, "Loading schema file " + name); - XmlOptions opts = new XmlOptions().setErrorListener(errorListener); - if (noVDoc) - opts.setValidateTreatLaxAsSkip(); - if (schemadoc.validate(opts)) - scontentlist.add((schemadoc).getSchema()); - } - - private static void addWsdlSchemas(String name, - org.apache.xmlbeans.impl.xb.substwsdl.DefinitionsDocument wsdldoc, - XmlErrorWatcher errorListener, boolean noVDoc, List scontentlist) - { - if (wsdlContainsEncoded(wsdldoc)) - StscState.addWarning(errorListener, "The WSDL " + name + " uses SOAP encoding. SOAP encoding is not compatible with literal XML Schema.", XmlErrorCodes.GENERIC_ERROR, wsdldoc); - StscState.addInfo(errorListener, "Loading wsdl file " + name); - XmlOptions opts = new XmlOptions().setErrorListener(errorListener); - if (noVDoc) - opts.setValidateTreatLaxAsSkip(); - XmlObject[] types = wsdldoc.getDefinitions().getTypesArray(); - int count = 0; - for (int j = 0; j < types.length; j++) - { - XmlObject[] schemas = types[j].selectPath("declare namespace xs=\"http://www.w3.org/2001/XMLSchema\" xs:schema"); - if (schemas.length == 0) - { - StscState.addWarning(errorListener, "The WSDL " + name + " did not have any schema documents in namespace 'http://www.w3.org/2001/XMLSchema'", XmlErrorCodes.GENERIC_ERROR, wsdldoc); - continue; - } - - for (int k = 0; k < schemas.length; k++) - { - if (schemas[k] instanceof SchemaDocument.Schema && - schemas[k].validate(opts)) - { - count++; - scontentlist.add(schemas[k]); - } - } - } - StscState.addInfo(errorListener, "Processing " + count + " schema(s) in " + name); - } - - public static boolean compile(Parameters params) - { - File baseDir = params.getBaseDir(); - File[] xsdFiles = params.getXsdFiles(); - File[] wsdlFiles = params.getWsdlFiles(); - URL[] urlFiles = params.getUrlFiles(); - File[] javaFiles = params.getJavaFiles(); - File[] configFiles = params.getConfigFiles(); - File[] classpath = params.getClasspath(); - File outputJar = params.getOutputJar(); - String name = params.getName(); - File srcDir = params.getSrcDir(); - File classesDir = params.getClassesDir(); - String compiler = params.getCompiler(); - String javasource = params.getJavaSource(); - String memoryInitialSize = params.getMemoryInitialSize(); - String memoryMaximumSize = params.getMemoryMaximumSize(); - boolean nojavac = params.isNojavac(); - boolean debug = params.isDebug(); - boolean verbose = params.isVerbose(); - boolean quiet = params.isQuiet(); - boolean download = params.isDownload(); - boolean noUpa = params.isNoUpa(); - boolean noPvr = params.isNoPvr(); - boolean noAnn = params.isNoAnn(); - boolean noVDoc = params.isNoVDoc(); - boolean noExt = params.isNoExt(); - boolean incrSrcGen = params.isIncrementalSrcGen(); - Collection outerErrorListener = params.getErrorListener(); - - String repackage = params.getRepackage(); - - if (repackage!=null) - { - SchemaTypeLoaderImpl.METADATA_PACKAGE_LOAD = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN; - - String stsPackage = SchemaTypeSystem.class.getPackage().getName(); - Repackager repackager = new Repackager( repackage ); - - SchemaTypeSystemImpl.METADATA_PACKAGE_GEN = repackager.repackage(new StringBuffer(stsPackage)).toString().replace('.','_'); - - System.out.println("\n\n\n" + stsPackage + ".SchemaCompiler Metadata LOAD:" + SchemaTypeLoaderImpl.METADATA_PACKAGE_LOAD + " GEN:" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN); - } - - SchemaCodePrinter codePrinter = params.getSchemaCodePrinter(); - List extensions = params.getExtensions(); - Set mdefNamespaces = params.getMdefNamespaces(); - - EntityResolver cmdLineEntRes = params.getEntityResolver() == null ? - ResolverUtil.resolverForCatalog(params.getCatalogFile()) : params.getEntityResolver(); - - if (srcDir == null || classesDir == null) - throw new IllegalArgumentException("src and class gen directories may not be null."); - - long start = System.currentTimeMillis(); - - // Calculate the usenames based on the relativized filenames on the filesystem - if (baseDir == null) - baseDir = new File(SystemProperties.getProperty("user.dir")); - - ResourceLoader cpResourceLoader = null; - - Map sourcesToCopyMap = new HashMap(); - - if (classpath != null) - cpResourceLoader = new PathResourceLoader(classpath); - - boolean result = true; - - File schemasDir = IOUtil.createDir(classesDir, "schema" + SchemaTypeSystemImpl.METADATA_PACKAGE_GEN + "/src"); - - // build the in-memory type system - XmlErrorWatcher errorListener = new XmlErrorWatcher(outerErrorListener); - SchemaTypeSystem system = loadTypeSystem(name, xsdFiles, wsdlFiles, urlFiles, configFiles, - javaFiles, cpResourceLoader, download, noUpa, noPvr, noAnn, noVDoc, noExt, mdefNamespaces, - baseDir, sourcesToCopyMap, errorListener, schemasDir, cmdLineEntRes, classpath, javasource); - if (errorListener.hasError()) - result = false; - long finish = System.currentTimeMillis(); - if (!quiet) - System.out.println("Time to build schema type system: " + ((double)(finish - start) / 1000.0) + " seconds" ); - - // now code generate and compile the JAR - if (result && system != null) // todo: don't check "result" here if we want to compile anyway, ignoring invalid schemas - { - start = System.currentTimeMillis(); - - // filer implementation writes binary .xsd and generated source to disk - Repackager repackager = (repackage == null ? null : new Repackager(repackage)); - FilerImpl filer = new FilerImpl(classesDir, srcDir, repackager, verbose, incrSrcGen); - - // currently just for schemaCodePrinter - XmlOptions options = new XmlOptions(); - if (codePrinter != null) - options.setSchemaCodePrinter(codePrinter); - if (javasource != null) - options.setGenerateJavaVersion(javasource); - - // save .xsb files - system.save(filer); - - // gen source files - result &= SchemaTypeSystemCompiler.generateTypes(system, filer, options); - - if (incrSrcGen) - { - // We have to delete extra source files that may be out of date - SchemaCodeGenerator.deleteObsoleteFiles(srcDir, srcDir, - new HashSet(filer.getSourceFiles())); - } - - if (result) - { - finish = System.currentTimeMillis(); - if (!quiet) - System.out.println("Time to generate code: " + ((double)(finish - start) / 1000.0) + " seconds" ); - } - - // compile source - if (result && !nojavac) - { - start = System.currentTimeMillis(); - - List sourcefiles = filer.getSourceFiles(); - - if (javaFiles != null) - sourcefiles.addAll(java.util.Arrays.asList(javaFiles)); - if (!CodeGenUtil.externalCompile(sourcefiles, classesDir, classpath, debug, compiler, javasource, memoryInitialSize, memoryMaximumSize, quiet, verbose)) - result = false; - - finish = System.currentTimeMillis(); - if (result && !params.isQuiet()) - System.out.println("Time to compile code: " + ((double)(finish - start) / 1000.0) + " seconds" ); - - // jar classes and .xsb - if (result && outputJar != null) - { - try - { - new JarHelper().jarDir(classesDir, outputJar); - } - catch (IOException e) - { - System.err.println("IO Error " + e); - result = false; - } - - if (result && !params.isQuiet()) - System.out.println("Compiled types to: " + outputJar); - } - } - } - - if (!result && !quiet) - { - System.out.println("BUILD FAILED"); - } - else { - // call schema compiler extension if registered - runExtensions(extensions, system, classesDir); - } - - if (cpResourceLoader != null) - cpResourceLoader.close(); - return result; - } - - private static void runExtensions(List extensions, SchemaTypeSystem system, File classesDir) - { - if (extensions != null && extensions.size() > 0) - { - SchemaCompilerExtension sce = null; - Iterator i = extensions.iterator(); - Map extensionParms = null; - String classesDirName = null; - try - { - classesDirName = classesDir.getCanonicalPath(); - } - catch(java.io.IOException e) - { - System.out.println("WARNING: Unable to get the path for schema jar file"); - classesDirName = classesDir.getAbsolutePath(); - } - - while (i.hasNext()) - { - Extension extension = (Extension) i.next(); - try - { - sce = (SchemaCompilerExtension) extension.getClassName().newInstance(); - } - catch (InstantiationException e) - { - System.out.println("UNABLE to instantiate schema compiler extension:" + extension.getClassName().getName()); - System.out.println("EXTENSION Class was not run"); - break; - } - catch (IllegalAccessException e) - { - System.out.println("ILLEGAL ACCESS Exception when attempting to instantiate schema compiler extension: " + extension.getClassName().getName()); - System.out.println("EXTENSION Class was not run"); - break; - } - - System.out.println("Running Extension: " + sce.getExtensionName()); - extensionParms = new HashMap(); - Iterator parmsi = extension.getParams().iterator(); - while (parmsi.hasNext()) - { - Extension.Param p = (Extension.Param) parmsi.next(); - extensionParms.put(p.getName(), p.getValue()); - } - extensionParms.put("classesDir", classesDirName); - sce.schemaCompilerExtension(system, extensionParms); - } - } - } - - - private static boolean wsdlContainsEncoded(XmlObject wsdldoc) - { - // search for any etc. - XmlObject[] useAttrs = wsdldoc.selectPath( - "declare namespace soap='http://schemas.xmlsoap.org/wsdl/soap/' " + - ".//soap:body/@use|.//soap:header/@use|.//soap:fault/@use"); - for (int i = 0; i < useAttrs.length; i++) - { - if ("encoded".equals(((SimpleValue)useAttrs[i]).getStringValue())) - return true; - } - return false; - } - - private static final String CONFIG_URI = "http://xml.apache.org/xmlbeans/2004/02/xbean/config"; - private static final String COMPATIBILITY_CONFIG_URI = "http://www.bea.com/2002/09/xbean/config"; - private static final Map MAP_COMPATIBILITY_CONFIG_URIS; - static - { - MAP_COMPATIBILITY_CONFIG_URIS = new HashMap(); - MAP_COMPATIBILITY_CONFIG_URIS.put(COMPATIBILITY_CONFIG_URI, CONFIG_URI); - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java deleted file mode 100644 index 325affb..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java +++ /dev/null @@ -1,870 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.Reference; -import org.apache.tools.ant.taskdefs.MatchingTask; -import org.apache.tools.ant.taskdefs.Javac; -import org.apache.tools.ant.taskdefs.Jar; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.FileScanner; -import org.apache.tools.ant.Project; - -import java.io.File; -import java.io.StringWriter; -import java.io.PrintWriter; -import java.util.*; -import java.net.URI; - -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.impl.common.IOUtil; - -/** - * Modeled after Ant's javac and zip tasks. - * - * Schema files to process, or directories of schema files, are set with the 'schema' - * attribute, and can be filtered with 'includes' and 'excludes'. - * Alternatively, one or more nested <fileset> elements can specify the - * files and directories to be used to generate this XMLBean. - * The include set can also define .java files that should be built as well. - * See the FileSet documentation at http://jakarta.apache.org/ant/manual/index.html - * for instructions on FileSets if you are unfamiliar with their usage. - */ - -public class XMLBean extends MatchingTask -{ - private ArrayList schemas = new ArrayList(); - - private Set mdefnamespaces; - - private Path classpath; - - private File destfile, - schema, - srcgendir, - classgendir; - - private boolean quiet, - verbose, - debug, - optimize, - download, - srconly, - noupa, - nopvr, - noann, - novdoc, - noext = false, - failonerror = true, - fork = true, - includeAntRuntime = true, - noSrcRegen, - includeJavaRuntime = false; - - private String typesystemname, - forkedExecutable, - compiler, - debugLevel, - memoryInitialSize, - memoryMaximumSize, - catalog, - javasource; - - private List extensions = new ArrayList(); - - private HashMap _extRouter = new HashMap(5); - - private static final String XSD = ".xsd", - WSDL = ".wsdl", - JAVA = ".java", - XSDCONFIG = ".xsdconfig"; - - - public void execute() throws BuildException - { - /* VALIDATION */ - //required - if (schemas.size() == 0 - && schema == null - && fileset.getDir(project) == null) - { - String msg = "The 'schema' or 'dir' attribute or a nested fileset is required."; - if (failonerror) - throw new BuildException(msg); - else - { - log(msg, Project.MSG_ERR); - return; - } - } - - _extRouter.put(XSD, new HashSet()); - _extRouter.put(WSDL, new HashSet()); - _extRouter.put(JAVA, new HashSet()); - _extRouter.put(XSDCONFIG, new HashSet()); - - File theBasedir = schema; - - if (schema != null) - { - if (schema.isDirectory()) - { - FileScanner scanner = getDirectoryScanner(schema); - String[] paths = scanner.getIncludedFiles(); - processPaths(paths, scanner.getBasedir()); - } - else - { - theBasedir = schema.getParentFile(); - processPaths(new String[] { schema.getName() }, theBasedir); - } - } - - if (fileset.getDir(project) != null) - schemas.add(fileset); - - Iterator si = schemas.iterator(); - while (si.hasNext()) - { - FileSet fs = (FileSet) si.next(); - FileScanner scanner = fs.getDirectoryScanner(project); - File basedir = scanner.getBasedir(); - String[] paths = scanner.getIncludedFiles(); - - processPaths(paths, basedir); - } - - Set xsdList = (Set) _extRouter.get(XSD); - Set wsdlList = (Set) _extRouter.get(WSDL); - - if (xsdList.size() + wsdlList.size() == 0) - { - log("Could not find any xsd or wsdl files to process.", Project.MSG_WARN); - return; - } - - //optional - Set javaList = (Set) _extRouter.get(JAVA); - Set xsdconfigList = (Set) _extRouter.get(XSDCONFIG); - - if (srcgendir == null && srconly) - srcgendir = classgendir; - - if (destfile == null && classgendir == null && ! srconly) - destfile = new File("xmltypes.jar"); - - if (verbose) - quiet = false; - - /* EXECUTION */ - - File[] xsdArray = (File[]) xsdList.toArray(new File[xsdList.size()]); - File[] wsdlArray = (File[]) wsdlList.toArray(new File[wsdlList.size()]); - File[] javaArray = (File[]) javaList.toArray(new File[javaList.size()]); - File[] xsdconfigArray = (File[]) xsdconfigList.toArray(new File[xsdconfigList.size()]); - ErrorLogger err = new ErrorLogger(verbose); - - boolean success = false; - - try - { - // create a temp directory - File tmpdir = null; - if (srcgendir == null || classgendir == null) - { - tmpdir = SchemaCodeGenerator.createTempDir(); - } - if (srcgendir == null) - srcgendir = IOUtil.createDir(tmpdir, "src"); - if (classgendir == null) - classgendir = IOUtil.createDir(tmpdir, "classes"); - - // use the system classpath if user didn't provide any - if (classpath == null) - { - classpath = new Path(project); - classpath.concatSystemClasspath(); - } - - // prepend the output directory on the classpath - Path.PathElement pathElement = classpath.createPathElement(); - pathElement.setLocation(classgendir); - - String[] paths = classpath.list(); - File[] cp = new File[paths.length]; - for (int i = 0; i < paths.length; i++) - cp[i] = new File(paths[i]); - - // generate the source - SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setBaseDir(theBasedir); - params.setXsdFiles(xsdArray); - params.setWsdlFiles(wsdlArray); - params.setJavaFiles(javaArray); - params.setConfigFiles(xsdconfigArray); - params.setClasspath(cp); - params.setName(typesystemname); - params.setSrcDir(srcgendir); - params.setClassesDir(classgendir); - params.setNojavac(true); // always compile using javac task below - params.setDebug(debug); - params.setVerbose(verbose); - params.setQuiet(quiet); - params.setDownload(download); - params.setExtensions(extensions); - params.setErrorListener(err); - params.setCatalogFile(catalog); - params.setIncrementalSrcGen(noSrcRegen); - params.setMdefNamespaces(mdefnamespaces); - params.setNoUpa(noupa); - params.setNoPvr(nopvr); - params.setNoAnn(noann); - params.setNoVDoc(novdoc); - params.setNoExt(noext); - params.setJavaSource(javasource); - success = SchemaCompiler.compile(params); - - if (success && !srconly) { - long start = System.currentTimeMillis(); - - // compile the source - Javac javac = new Javac(); - javac.setProject(project); - javac.setTaskName(getTaskName()); - javac.setClasspath(classpath); - if (compiler != null) javac.setCompiler(compiler); - javac.setDebug(debug); - if (debugLevel != null) javac.setDebugLevel(debugLevel); - javac.setDestdir(classgendir); - javac.setExecutable(forkedExecutable); - javac.setFailonerror(failonerror); - javac.setFork(fork); - if (javasource != null) - { - javac.setSource(javasource); - javac.setTarget(javasource); - } - else - { - javac.setSource("1.4"); - javac.setTarget("1.4"); - } - javac.setIncludeantruntime(includeAntRuntime); - javac.setIncludejavaruntime(includeJavaRuntime); - javac.setSrcdir(new Path(project, srcgendir.getAbsolutePath())); - if (memoryInitialSize != null) javac.setMemoryInitialSize(memoryInitialSize); - if (memoryMaximumSize != null) javac.setMemoryMaximumSize(memoryMaximumSize); - javac.setOptimize(optimize); - javac.setVerbose(verbose); - javac.execute(); - - long finish = System.currentTimeMillis(); - if (!quiet) - log("Time to compile code: " + ((double)(finish - start) / 1000.0) + " seconds"); - - if (destfile != null) - { - // jar the compiled classes - Jar jar = new Jar(); - jar.setProject(project); - jar.setTaskName(getTaskName()); - jar.setBasedir(classgendir); - jar.setDestFile(destfile); - jar.execute(); - } - } - - if (tmpdir != null) { - SchemaCodeGenerator.tryHardToDelete(tmpdir); - } - } - catch (BuildException e) - { - // re-throw anything thrown from javac or jar task - throw e; - } - catch (Throwable e) - { - //interrupted means cancel - if (e instanceof InterruptedException || failonerror) - throw new BuildException(e); - - log("Exception while building schemas: " + e.getMessage(), Project.MSG_ERR); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - log(sw.toString(), Project.MSG_VERBOSE); - } - - if (!success && failonerror) - throw new BuildException(); //stop the build - } - - private void processPaths(String[] paths, File baseDir) - { - for (int i = 0; i < paths.length; i++) - { - int dot = paths[i].lastIndexOf('.'); - if (dot > -1) - { - String path = paths[i]; - String possExt = path.substring(dot).toLowerCase(); - Set set = (Set) _extRouter.get(possExt); - - if (set != null) - set.add(new File(baseDir, path)); - } - } - } - - public void addFileset(FileSet fileset) - { - schemas.add(fileset); - } - - ///////////////////////////// - //Getter/Setters - public File getSchema() - { - return schema; - } - - /** - * A file that points to either an individual schema file or a directory of files. - * It is optional only if one or more <fileset> elements are nested in this - * task. - * @param schema Required, unless a fileset element is nested. - */ - public void setSchema(File schema) - { - this.schema = schema; - } - - /** - * The classpath to use if schemas in the fileset import definitions that are - * supplied by other compiled xml beans JAR files, or if .java files are in the - * schema fileset. - * @param classpath Optional. - */ - public void setClasspath(Path classpath) - { - if (this.classpath != null) - this.classpath.append(classpath); - else - this.classpath = classpath; - } - - /** - * Adds a path to the classpath. - */ - public Path createClasspath() { - if (classpath == null) { - classpath = new Path(project); - } - return classpath.createPath(); - } - - /** - * Adds a reference to a classpath defined elsewhere. - * @param classpathref Optional. - */ - public void setClasspathRef(Reference classpathref) - { - if (classpath == null) - classpath = new Path(project); - - classpath.createPath().setRefid(classpathref); - } - - public Path getClasspath() - { - return classpath; - } - - public File getDestfile() - { - return destfile; - } - - /** - * Define the name of the jar file created. For instance, "myXMLBean.jar" - * will output the results of this task into a jar with the same name. - * Optional, defaults to "xmltypes.jar". - * @param destfile Optional. - */ - public void setDestfile(File destfile) - { - this.destfile = destfile; - } - - public File getSrcgendir() - { - return srcgendir; - } - - /** - * Set a location to generate .java files into. Optional, defaults to - * a temp dir. - * @param srcgendir Optional. - */ - public void setSrcgendir(File srcgendir) - { - this.srcgendir = srcgendir; - } - - public File getClassgendir() - { - return classgendir; - } - - /** - * Set a location to generate .class files into. Optional, defaults to - * a temp dir. - * @param classgendir Optional. - */ - public void setClassgendir(File classgendir) - { - this.classgendir = classgendir; - } - - /** - * Choose the implementation for this particular task. - * - * @since Ant 1.5 - */ - public void setCompiler(String compiler) - { - this.compiler = compiler; - } - - public boolean isDownload() - { - return download; - } - - /** - * Set to true to permit the compiler to download URLs for imports - * and includes. Defaults to false, meaning all imports and includes - * must be copied locally. - * @param download Optional. - */ - public void setDownload(boolean download) - { - this.download = download; - } - - /** - * If true, compiles with optimization enabled. - */ - public void setOptimize(boolean optimize) { - this.optimize = optimize; - } - - /** Gets the optimize flag. */ - public boolean getOptimize() { - return optimize; - } - - public boolean isVerbose() - { - return verbose; - } - - /** - * Controls the amount of output. Defaults to true. - * @param verbose Optional. - */ - public void setVerbose(boolean verbose) - { - this.verbose = verbose; - } - - public boolean isQuiet() - { - return quiet; - } - - /** - * Controls the amount of output. Defaults to false. - * @param quiet Optional. - */ - public void setQuiet(boolean quiet) - { - this.quiet = quiet; - } - - public boolean isDebug() - { - return debug; - } - - /** - * Get the value of debugLevel. - * @return value of debugLevel. - */ - public String getDebugLevel() { - return debugLevel; - } - - /** - * Keyword list to be appended to the -g command-line switch. - * - * This will be ignored by all implementations except modern - * and classic(ver >= 1.2). Legal values are none or a - * comma-separated list of the following keywords: lines, vars, - * and source. If debuglevel is not specified, by default, :none - * will be appended to -g. If debug is not turned on, this attribute - * will be ignored. - * - * @param v Value to assign to debugLevel. - */ - public void setDebugLevel(String v) { - this.debugLevel = v; - } - - /** - * Generate debugging symbols. - * @param debug Optional. - */ - public void setDebug(boolean debug) - { - this.debug = debug; - } - - /** - * If true, forks the javac compiler. - * - * @param f "true|false|on|off|yes|no" - */ - public void setFork(boolean f) { - fork = f; - } - - /** - * Sets the the name of the javac executable. - * - *

      Ignored unless fork is true or extJavac has been specified - * as the compiler.

      - */ - public void setExecutable(String forkExec) { - forkedExecutable = forkExec; - } - - public String getExecutable() { - return forkedExecutable; - } - - public boolean isSrconly() - { - return srconly; - } - - /** - * A value of true means that only source will be generated. Optional, - * default is false. - * @param srconly Optional. - */ - public void setSrconly(boolean srconly) - { - this.srconly = srconly; - } - - public String getTypesystemname() - { - return typesystemname; - } - - /** - * One or more SchemaCompiler extensions can be passed in via the <extension> subelement. - * Schema Compiler extensions must implement the interface com.xbean.too.SchemaCompilerExtension - */ - public Extension createExtension() { - Extension e = new Extension(); - extensions.add(e); - return e; - } - - /** - * One or more namespaces in which duplicate definitions are to be ignored - * can be passed in via the <ignoreDuplicatesInNamespaces> subelement. - */ - public void setIgnoreDuplicatesInNamespaces(String namespaces) { - mdefnamespaces = new HashSet(); - StringTokenizer st = new StringTokenizer(namespaces, ","); - while (st.hasMoreTokens()) - { - String namespace = st.nextToken().trim(); - mdefnamespaces.add(namespace); - } - } - - public String getIgnoreDuplicatesInNamespaces() { - if (mdefnamespaces == null) { - return null; - } - StringBuffer buf = new StringBuffer(); - Iterator i = mdefnamespaces.iterator(); - while (i.hasNext()) { - buf.append((String)i.next()); - if (i.hasNext()) { - buf.append(","); - } - } - return buf.toString(); - } - - /** - * The name of the package that the TypeSystemHolder class should be - * generated in. Normally this should be left unspecified. None of - * the xml beans are generated in this package. - *

      Use .xsdconfig files to modify xml bean package or class names. - * @param typesystemname Optional. - */ - public void setTypesystemname(String typesystemname) - { - this.typesystemname = typesystemname; - } - - public boolean isFailonerror() - { - return failonerror; - } - - /** - * Determines whether or not the ant target will continue if the XMLBean - * creation encounters a build error. Defaults to true. Optional. - * @param failonerror Optional. - */ - public void setFailonerror(boolean failonerror) - { - this.failonerror = failonerror; - } - - public boolean isIncludeAntRuntime() - { - return includeAntRuntime; - } - - public void setIncludeAntRuntime(boolean includeAntRuntime) - { - this.includeAntRuntime = includeAntRuntime; - } - - public boolean isIncludeJavaRuntime() - { - return includeJavaRuntime; - } - - public void setIncludeJavaRuntime(boolean includeJavaRuntime) - { - this.includeJavaRuntime = includeJavaRuntime; - } - - public boolean isNoSrcRegen() - { - return noSrcRegen; - } - - public void setNoSrcRegen(boolean noSrcRegen) - { - this.noSrcRegen = noSrcRegen; - } - - /** - * Set the initial memory size of the underlying javac process. - */ - public String getMemoryInitialSize() - { - return memoryInitialSize; - } - - public void setMemoryInitialSize(String memoryInitialSize) - { - this.memoryInitialSize = memoryInitialSize; - } - - /** - * Set the maximum memory size of the underlying javac process. - */ - public String getMemoryMaximumSize() - { - return memoryMaximumSize; - } - - public void setMemoryMaximumSize(String memoryMaximumSize) - { - this.memoryMaximumSize = memoryMaximumSize; - } - - /** - * Do not enforce the unique particle attribution rule. - */ - public void setNoUpa(boolean noupa) - { - this.noupa = noupa; - } - - public boolean isNoUpa() - { - return noupa; - } - - /** - * Do not enforce the particle valid (restriction) rule. - */ - public void setNoPvr(boolean nopvr) - { - this.nopvr = nopvr; - } - - public boolean isNoPvr() - { - return nopvr; - } - - /** - * Skip over schema <annotation%gt; elements. - */ - public void setNoAnnotations(boolean noann) - { - this.noann = noann; - } - - public boolean isNoAnnotations() - { - return noann; - } - - /** - * Do not validate the contents of schema <documentation> elements. - */ - public void setNoValidateDoc(boolean novdoc) - { - this.novdoc = novdoc; - } - - public boolean isNoValidateDoc() - { - return novdoc; - } - - /** - * Ignore extensions found in .xsdconfig files - * @param novdoc - */ - public void setNoExt(boolean noext) - { - this.noext = noext; - } - - public boolean isNoExt() - { - return noext; - } - - /** - * Generate java source compatible with the given version. Currently, - * only "1.4" or "1.5" are supported and "1.4" is the default. - */ - public void setJavaSource(String javasource) - { - this.javasource = javasource; - } - - public String getJavaSource() - { - return javasource; - } - - //REVIEW this allows people to deal with the case where they drag in - //more files for compilation than they should. not sure if this is - //a good thing or not - private String source = null; - public void setSource(String s) { source = s; } - - /** - * Gets the XML Catalog file for org.apache.xml.resolver.tools.CatalogResolver. (Note: needs resolver.jar from http://xml.apache.org/commons/components/resolver/index.html) - */ - public String getCatalog() - { - return catalog; - } - - /** - * Sets the XML Catalog file for org.apache.xml.resolver.tools.CatalogResolver. (Note: needs resolver.jar from http://xml.apache.org/commons/components/resolver/index.html) - */ - public void setCatalog(String catalog) - { - this.catalog = catalog; - } - - private static URI uriFromFile(File f) - { - if (f == null) - return null; - - try - { - return f.getCanonicalFile().toURI(); - } - catch(java.io.IOException e) - { - // Don't spit out an exception here because on Windows you'll get one - // if the filename is "aux", "lpt1", etc. It's the caller's responsibility - // to deal with those cases correctly, usually by calling FileSvc.invalidPathCheck() - // MessageSvc.get().logException(e); - return f.getAbsoluteFile().toURI(); - } - } - - public class ErrorLogger extends AbstractCollection - { - private boolean _noisy; - private URI _baseURI; - - public ErrorLogger(boolean noisy) - { - _noisy = noisy; - _baseURI = uriFromFile(project.getBaseDir()); - } - - public boolean add(Object o) - { - if (o instanceof XmlError) - { - XmlError err = (XmlError)o; - if (err.getSeverity() == XmlError.SEVERITY_ERROR) - log(err.toString(_baseURI), Project.MSG_ERR); - else if (err.getSeverity() == XmlError.SEVERITY_WARNING) - log(err.toString(_baseURI), Project.MSG_WARN); - else if (_noisy) - log(err.toString(_baseURI), Project.MSG_INFO); - } - return false; - } - - public Iterator iterator() - { - return Collections.EMPTY_LIST.iterator(); - } - - public int size() - { - return 0; - } - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java deleted file mode 100644 index bf87c72..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBeanXSTCHarness.java +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.XmlException; - -import java.util.Collection; -import java.util.ArrayList; -import java.util.Collections; -import java.io.PrintWriter; -import java.io.StringWriter; - -public class XMLBeanXSTCHarness implements XSTCTester.Harness -{ - public void runTestCase(XSTCTester.TestCaseResult result) - { - XSTCTester.TestCase testCase = result.getTestCase(); - - // System.out.println("Running case " + testCase.getDescription()); - - try - { - Collection errors = new ArrayList(); - boolean schemaValid = true; - boolean instanceValid = true; - - if (testCase.getSchemaFile() == null) - return; - - // step 1, load schema file etc. - SchemaTypeLoader loader = null; - try - { - XmlObject schema = XmlObject.Factory.parse(testCase.getSchemaFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers()); - XmlObject schema2 = null; - if (testCase.getResourceFile() != null) - schema2 = XmlObject.Factory.parse(testCase.getResourceFile(), new XmlOptions().setErrorListener(errors).setLoadLineNumbers()); - XmlObject[] schemas = schema2 == null ? new XmlObject[] { schema } : new XmlObject[] { schema, schema2 }; - SchemaTypeSystem system = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), new XmlOptions().setErrorListener(errors)); - loader = XmlBeans.typeLoaderUnion(new SchemaTypeLoader[] { system, XmlBeans.getBuiltinTypeSystem() }); - } - catch (Exception e) - { - schemaValid = false; - if (!(e instanceof XmlException) || errors.isEmpty()) - { - result.setCrash(true); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - result.addSvMessages(Collections.singleton(sw.toString())); - } - } - - result.addSvMessages(errors); - result.setSvActual(schemaValid); - errors.clear(); - - if (loader == null) - return; - - if (testCase.getInstanceFile() == null) - return; - - // step 2, load instance file and validate - try - { - XmlObject instance = loader.parse(testCase.getInstanceFile(), null, new XmlOptions().setErrorListener(errors).setLoadLineNumbers()); - if (!instance.validate(new XmlOptions().setErrorListener(errors))) - instanceValid = false; - } - catch (Exception e) - { - instanceValid = false; - if (!(e instanceof XmlException) || errors.isEmpty()) - { - result.setCrash(true); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - result.addIvMessages(Collections.singleton(sw.toString())); - } - } - result.addIvMessages(errors); - result.setIvActual(instanceValid); - - } - finally - { - // System.out.println(result.succeeded() ? "Success.": "Failure."); - } - } -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java deleted file mode 100644 index f7ea835..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java +++ /dev/null @@ -1,510 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.impl.xb.ltgfmt.TestsDocument; -import org.apache.xmlbeans.impl.xb.ltgfmt.FileDesc; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlCalendar; - -import java.io.File; -import java.io.PrintWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Collection; -import java.util.ArrayList; -import java.util.Set; -import java.util.HashSet; -import java.util.Collections; -import java.util.Iterator; -import java.util.Date; -import java.util.regex.Pattern; -import java.net.URI; - -public class XSTCTester -{ - public static void printUsage() - { - System.out.println("Usage: xstc [-showpass] [-errcode] foo_LTGfmt.xml ..."); - } - - public static void main(String[] args) throws IOException - { - Set flags = new HashSet(); - flags.add("h"); - flags.add("help"); - flags.add("usage"); - flags.add("version"); - flags.add("showpass"); - flags.add("errcode"); - - long start = System.currentTimeMillis(); - - CommandLine cl = new CommandLine(args, flags, Collections.EMPTY_SET); - if (cl.getOpt("h") != null || cl.getOpt("help") != null || cl.getOpt("usage") != null) - { - printUsage(); - System.exit(0); - return; - } - - if (cl.getOpt("version") != null) - { - CommandLine.printVersion(); - System.exit(0); - return; - } - - String[] badopts = cl.getBadOpts(); - if (badopts.length > 0) - { - for (int i = 0; i < badopts.length; i++) - System.out.println("Unrecognized option: " + badopts[i]); - printUsage(); - System.exit(0); - return; - } - - if (cl.args().length == 0) { - printUsage(); - return; - } - - boolean showpass = (cl.getOpt("showpass") != null); - boolean errcode = (cl.getOpt("errcode") != null); - - File[] allFiles = cl.getFiles(); - Collection ltgFiles = new ArrayList(); - Harness harness = new XMLBeanXSTCHarness(); - - for (int i = 0; i < allFiles.length; i++) - { - if (allFiles[i].getName().indexOf("LTG") >= 0) - ltgFiles.add(allFiles[i]); - } - - File resultsFile = new File("out.html"); - PrintWriter writer = new PrintWriter(new FileWriter(resultsFile)); - writer.println(""); - writer.println(""); - writer.println(""); - - writer.println(""); - - writer.println("

      XML Schema Test Collection Results

      "); - writer.println("

      Run on " + (new XmlCalendar(new Date())) + "

      "); - writer.println("

      Values in schema or instance valid columns are results from compiling or validating respectively."); - writer.println("Red or orange background mean the test failed.

      "); - writer.println(""); - writer.println(""); - int failures = 0; - int cases = 0; - for (Iterator i = ltgFiles.iterator(); i.hasNext(); ) - { - File ltgFile = (File)i.next(); - System.out.println("Processing test cases in " + ltgFile); - Collection ltgErrors = new ArrayList(); - TestCase[] testCases = parseLTGFile(ltgFile, ltgErrors); - Collection results = new ArrayList(); - if (testCases != null) for (int j = 0; j < testCases.length; j++) - { - TestCaseResult result = new TestCaseResult(); - result.testCase = testCases[j]; - harness.runTestCase(result); - cases += 1; - if (!result.succeeded(errcode)) - failures += 1; - else if (!showpass) - continue; - results.add(result); - } - writer.println(""); - if (!ltgErrors.isEmpty()) - { - writer.println(""); - } - else - { - if (results.size() == 0) - writer.println(""); - } - if (results == null) - continue; - for (Iterator j = results.iterator(); j.hasNext() ;) - { - summarizeResultAsHTMLTableRows((TestCaseResult)j.next(), writer, errcode); - } - } - writer.println(""); - writer.println("
      idDescriptionsch vins v
      " + ltgFile + "
      Errors within the LTG file:"); - writer.println(""); - for (Iterator j = ltgErrors.iterator(); j.hasNext(); ) - writer.println(j.next()); - writer.println(""); - writer.println("
      Nothing to report
      Summary: " + failures + " failures out of " + cases + " cases run.
      "); - writer.close(); - - long finish = System.currentTimeMillis(); - System.out.println("Time run tests: " + ((double)(finish - start) / 1000.0) + " seconds" ); - - // Launch results - System.out.println("Results output to " + resultsFile); - if (SystemProperties.getProperty("os.name").toLowerCase().indexOf("windows") >= 0) - Runtime.getRuntime().exec("cmd /c start iexplore \"" + resultsFile.getAbsolutePath() + "\""); - else - Runtime.getRuntime().exec("mozilla file://" + resultsFile.getAbsolutePath()); - } - - public static class TestCase - { - private File ltgFile; - private String id; - private String origin; - private String description; - private File schemaFile; - private File instanceFile; - private File resourceFile; - private boolean svExpected; - private boolean ivExpected; - private boolean rvExpected; - private String errorCode; - - public File getLtgFile() - { - return ltgFile; - } - - public String getId() - { - return id; - } - - public String getOrigin() - { - return origin; - } - - public String getDescription() - { - return description; - } - - public File getSchemaFile() - { - return schemaFile; - } - - public File getInstanceFile() - { - return instanceFile; - } - - public File getResourceFile() - { - return resourceFile; - } - - public boolean isSvExpected() - { - return svExpected; - } - - public boolean isIvExpected() - { - return ivExpected; - } - - public boolean isRvExpected() - { - return rvExpected; - } - - public String getErrorCode() - { - return errorCode; - } - - } - - public static class TestCaseResult - { - private TestCase testCase; - private boolean svActual; - private Collection svMessages = new ArrayList(); - private boolean ivActual; - private Collection ivMessages = new ArrayList(); - private boolean crash; - - public TestCase getTestCase() - { - return testCase; - } - - public boolean isSvActual() - { - return svActual; - } - - public void setSvActual(boolean svActual) - { - this.svActual = svActual; - } - - public boolean isIvActual() - { - return ivActual; - } - - public void setIvActual(boolean ivActual) - { - this.ivActual = ivActual; - } - - public Collection getSvMessages() - { - return Collections.unmodifiableCollection(svMessages); - } - - public void addSvMessages(Collection svMessages) - { - this.svMessages.addAll(svMessages); - } - - public Collection getIvMessages() - { - return Collections.unmodifiableCollection(ivMessages); - } - - public void addIvMessages(Collection ivMessages) - { - this.ivMessages.addAll(ivMessages); - } - - public void setCrash(boolean crash) - { - this.crash = crash; - } - - public boolean isCrash() - { - return crash; - } - - public boolean succeeded(boolean errcode) - { - boolean success = !crash && - (isIvActual() == testCase.isIvExpected()) && - (isSvActual() == testCase.isSvExpected()); - if (errcode && testCase.getErrorCode() != null) - success &= errorReported(testCase.getErrorCode(), svMessages) || errorReported(testCase.getErrorCode(), ivMessages); - return success; - } - - } - - public static interface Harness - { - public void runTestCase(TestCaseResult result); - } - - public static String makeHTMLLink(File file, boolean value) - { - if (file == null) - return " "; - URI uri = file.getAbsoluteFile().toURI(); - return "" + Boolean.toString(value) + ""; - } - - private static final Pattern leadingSpace = Pattern.compile("^\\s+", Pattern.MULTILINE); - - public static String makeHTMLDescription(TestCase testCase) - { - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(leadingSpace.matcher(testCase.getDescription()).replaceAll("")); - sb.append(""); - return sb.toString(); - } - - public static void summarizeResultAsHTMLTableRows(TestCaseResult result, PrintWriter out, boolean errcode) - { - TestCase testCase = result.getTestCase(); - - boolean errorRow = errcode && testCase.getErrorCode() != null; - boolean messagesRow = !result.getIvMessages().isEmpty() || !result.getSvMessages().isEmpty(); - - boolean sRight = testCase.getSchemaFile() == null || testCase.isSvExpected() == result.isSvActual(); - boolean iRight = testCase.getInstanceFile() == null || testCase.isIvExpected() == result.isIvActual(); - boolean codeRight = true; - if (errorRow) - codeRight = (errorReported(testCase.getErrorCode(), result.svMessages) || errorReported(testCase.getErrorCode(), result.ivMessages)); - - out.println(result.isCrash() ? "" : ""); - int idRowSpan = 1 + (errorRow ? 1 : 0) + (messagesRow ? 1 : 0); - out.println("" + testCase.getId() + ""); - out.println("" + makeHTMLDescription(testCase) + ""); - String sLinks; - if (testCase.getResourceFile() == null) - sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual()); - else - sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual()) + "
      " + makeHTMLLink(testCase.getResourceFile(), result.isSvActual()); - - out.println((sRight ? "" : result.isSvActual() ? "" : "") + sLinks + ""); - out.println((iRight ? "" : result.isIvActual() ? "" : "") + makeHTMLLink(testCase.getInstanceFile(), result.isIvActual()) + ""); - out.println(""); - if (errorRow) - { - out.println(""); - out.println((codeRight ? "" : "") + "expected error: " + testCase.getErrorCode() + ""); - out.println(""); - } - if (messagesRow) - { - if (!result.succeeded(errcode)) - out.println(""); - else - out.println("<tr><td colspan=4><xmp>"); - for (Iterator j = result.getSvMessages().iterator(); j.hasNext(); ) - out.println(j.next()); - for (Iterator j = result.getIvMessages().iterator(); j.hasNext(); ) - out.println(j.next()); - out.println(""); - } - } - - public static TestCase[] parseLTGFile(File ltgFile, Collection outerErrors) - { - Collection errors = new ArrayList(); - try - { - XmlOptions ltgOptions = new XmlOptions(); - ltgOptions.setLoadSubstituteNamespaces(Collections.singletonMap("", "http://www.bea.com/2003/05/xmlbean/ltgfmt")); - ltgOptions.setErrorListener(errors); - ltgOptions.setLoadLineNumbers(); - TestsDocument doc = TestsDocument.Factory.parse(ltgFile, ltgOptions); - if (!doc.validate(ltgOptions)) - throw new Exception("Document " + ltgFile + " not valid."); - - org.apache.xmlbeans.impl.xb.ltgfmt.TestCase[] testCases = doc.getTests().getTestArray(); - - Collection result = new ArrayList(); - for (int i = 0; i < testCases.length; i++) - { - TestCase newCase = new TestCase(); - newCase.ltgFile = ltgFile; - newCase.id = testCases[i].getId(); - newCase.origin = testCases[i].getOrigin(); - newCase.description = testCases[i].getDescription(); - FileDesc[] filedescs = testCases[i].getFiles().getFileArray(); - testCases[i].getOrigin(); - for (int j = 0; j < filedescs.length; j++) - { - String dir = filedescs[j].getFolder(); - String filename = filedescs[j].getFileName(); - File theFile = new File(ltgFile.getParentFile(), dir + "/" + filename); - if (!theFile.exists() || !theFile.isFile() || !theFile.canRead()) - { - outerErrors.add(XmlError.forObject("Can't read file " + theFile, filedescs[j]).toString()); - continue; - } - - switch (filedescs[j].getRole().intValue()) - { - case FileDesc.Role.INT_INSTANCE: - if (newCase.instanceFile != null) - outerErrors.add(XmlError.forObject("More than one instance file speicifed - ignoring all but last", filedescs[j]).toString()); - newCase.instanceFile = theFile; - newCase.ivExpected = filedescs[j].getValidity(); - break; - - case FileDesc.Role.INT_SCHEMA: - if (newCase.schemaFile != null) - outerErrors.add(XmlError.forObject("More than one schema file speicifed - ignoring all but last", filedescs[j]).toString()); - newCase.schemaFile = theFile; - newCase.svExpected = filedescs[j].getValidity(); - break; - - case FileDesc.Role.INT_RESOURCE: - if (newCase.resourceFile != null) - outerErrors.add(XmlError.forObject("More than one resource file speicifed - ignoring all but last", filedescs[j]).toString()); - newCase.resourceFile = theFile; - newCase.rvExpected = filedescs[j].getValidity(); - break; - - default: - throw new XmlException(XmlError.forObject("Unexpected file role", filedescs[j])); - } - - if (filedescs[j].getCode() != null) - newCase.errorCode = filedescs[j].getCode().getID(); - } - result.add(newCase); - } - return (TestCase[])result.toArray(new TestCase[result.size()]); - } - catch (Exception e) - { - if (errors.isEmpty()) - outerErrors.add(e.getMessage()); - else for (Iterator i = errors.iterator(); i.hasNext(); ) - outerErrors.add(i.next().toString()); - return null; - } - } - - public static boolean errorReported(String errorCode, Collection set) - { - if (errorCode == null || set == null || set.size() == 0) - return false; - - for (Iterator i = set.iterator(); i.hasNext(); ) - { - if (errorCode.equals(((XmlError)i.next()).getErrorCode())) - return true; - } - - return false; - } - -} diff --git a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java b/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java deleted file mode 100644 index d13ce42..0000000 --- a/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java +++ /dev/null @@ -1,1340 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.tool; - -import java.util.*; -import java.util.zip.ZipFile; -import java.util.zip.ZipEntry; -import java.io.*; -import java.math.BigInteger; - - -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.util.HexBin; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.SchemaLocalAttribute; -import org.apache.xmlbeans.SchemaParticle; -import org.apache.xmlbeans.SchemaProperty; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.soap.SOAPArrayType; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import javax.xml.namespace.QName; - -public class XsbDumper -{ - public static void printUsage() - { - System.out.println("Prints the contents of an XSB file in human-readable form."); - System.out.println("An XSB file contains schema meta information needed to "); - System.out.println("perform tasks such as binding and validation."); - System.out.println("Usage: dumpxsb myfile.xsb"); - System.out.println(" myfile.xsb - Path to an XSB file."); - System.out.println(); - } - - public static void main(String[] args) - { - if (args.length == 0) { - printUsage(); - System.exit(0); - return; - } - - for (int i = 0; i < args.length; i++) - { - dump(new File(args[i]), true); - } - } - - private static void dump(File file, boolean force) - { - if (file.isDirectory()) - { - File[] files = file.listFiles( - new FileFilter() - { - public boolean accept(File file) - { return file.isDirectory() || file.isFile() && file.getName().endsWith(".xsb"); } - } - ); - for (int i = 0; i < files.length; i++) - { - dump(files[i], false); - } - } - else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) - { - dumpZip(file); - } - else if (force || file.getName().endsWith(".xsb")) - { - try - { - System.out.println(file.toString()); - dump(new FileInputStream(file), " "); - System.out.println(); - } - catch (FileNotFoundException e) - { - System.out.println(e.toString()); - } - } - } - - public static void dumpZip(File file) - { - try - { - ZipFile zipFile = new ZipFile(file); - Enumeration e = zipFile.entries(); - while (e.hasMoreElements()) - { - ZipEntry entry = (ZipEntry)e.nextElement(); - if (entry.getName().endsWith(".xsb")) - { - System.out.println(entry.getName()); - dump(zipFile.getInputStream(entry), " "); - System.out.println(); - } - } - } - catch (IOException e) - { - System.out.println(e.toString()); - } - } - - public static void dump(InputStream input) - { - dump(input, "", System.out); - } - - public static void dump(InputStream input, String indent) - { - dump(input, indent, System.out); - } - - public static void dump(InputStream input, String indent, PrintStream output) - { - XsbDumper dumper = new XsbDumper(input, indent, output); - dumper.dumpAll(); - } - - private XsbDumper(InputStream stream, String indent, PrintStream ostream) - { - _input = new DataInputStream(stream); - _indent = indent; - _out = ostream; - } - - void flush() { _out.flush(); } - void emit(String str) { _out.println(_indent + str); flush(); } - void emit() { _out.println(); flush(); } - void error(Exception e) { _out.println(e.toString()); flush(); IllegalStateException e2 = new IllegalStateException( e.getMessage() ); e2.initCause( e ); throw e2; } - void error(String str) { _out.println(str); flush(); IllegalStateException e2 = new IllegalStateException( str ); throw e2; } - private String _indent; - private PrintStream _out; - void indent() { _indent += " "; } - void outdent() { _indent = _indent.substring(0, _indent.length() - 2); } - - public static final int DATA_BABE = 0xDA7ABABE; - public static final int MAJOR_VERSION = 2; - public static final int MINOR_VERSION = 24; - - public static final int FILETYPE_SCHEMAINDEX = 1; - public static final int FILETYPE_SCHEMATYPE = 2; - public static final int FILETYPE_SCHEMAELEMENT = 3; - public static final int FILETYPE_SCHEMAATTRIBUTE = 4; - public static final int FILETYPE_SCHEMAPOINTER = 5; - public static final int FILETYPE_SCHEMAMODELGROUP = 6; - public static final int FILETYPE_SCHEMAATTRIBUTEGROUP = 7; - - static String filetypeString(int code) - { - switch (code) - { - case FILETYPE_SCHEMAINDEX: return "FILETYPE_SCHEMAINDEX"; - case FILETYPE_SCHEMATYPE: return "FILETYPE_SCHEMATYPE"; - case FILETYPE_SCHEMAELEMENT: return "FILETYPE_SCHEMAELEMENT"; - case FILETYPE_SCHEMAATTRIBUTE: return "FILETYPE_SCHEMAATTRIBUTE"; - case FILETYPE_SCHEMAPOINTER: return "FILETYPE_SCHEMAPOINTER"; - case FILETYPE_SCHEMAMODELGROUP: return "FILETYPE_SCHEMAMODELGROUP"; - case FILETYPE_SCHEMAATTRIBUTEGROUP: return "FILETYPE_SCHEMAATTRIBUTEGROUP"; - default: - return "Unknown FILETYPE (" + code + ")"; - } - } - - public static final int FLAG_PART_SKIPPABLE = 1; - public static final int FLAG_PART_FIXED = 4; - public static final int FLAG_PART_NILLABLE = 8; - public static final int FLAG_PART_BLOCKEXT = 16; - public static final int FLAG_PART_BLOCKREST = 32; - public static final int FLAG_PART_BLOCKSUBST = 64; - public static final int FLAG_PART_ABSTRACT = 128; - public static final int FLAG_PART_FINALEXT = 256; - public static final int FLAG_PART_FINALREST = 512; - - static String particleflagsString(int flags) - { - StringBuffer result = new StringBuffer(); - if ((flags & FLAG_PART_SKIPPABLE) != 0) result.append("FLAG_PART_SKIPPABLE | "); - if ((flags & FLAG_PART_FIXED) != 0) result.append("FLAG_PART_FIXED | "); - if ((flags & FLAG_PART_NILLABLE) != 0) result.append("FLAG_PART_NILLABLE | "); - if ((flags & FLAG_PART_BLOCKEXT) != 0) result.append("FLAG_PART_BLOCKEXT | "); - if ((flags & FLAG_PART_BLOCKREST) != 0) result.append("FLAG_PART_BLOCKREST | "); - if ((flags & FLAG_PART_BLOCKSUBST) != 0) result.append("FLAG_PART_BLOCKSUBST | "); - if ((flags & FLAG_PART_ABSTRACT) != 0) result.append("FLAG_PART_ABSTRACT | "); - if ((flags & FLAG_PART_FINALEXT) != 0) result.append("FLAG_PART_FINALEXT | "); - if ((flags & FLAG_PART_FINALREST) != 0) result.append("FLAG_PART_FINALREST | "); - if (result.length() == 0) result.append("0 | "); - return result.substring(0, result.length() - 3); - } - - public static final int FLAG_PROP_ISATTR = 1; - public static final int FLAG_PROP_JAVASINGLETON = 2; - public static final int FLAG_PROP_JAVAOPTIONAL = 4; - public static final int FLAG_PROP_JAVAARRAY = 8; - - static String propertyflagsString(int flags) - { - StringBuffer result = new StringBuffer(); - if ((flags & FLAG_PROP_ISATTR) != 0) result.append("FLAG_PROP_ISATTR | "); - if ((flags & FLAG_PROP_JAVASINGLETON) != 0) result.append("FLAG_PROP_JAVASINGLETON | "); - if ((flags & FLAG_PROP_JAVAOPTIONAL) != 0) result.append("FLAG_PROP_JAVAOPTIONAL | "); - if ((flags & FLAG_PROP_JAVAARRAY) != 0) result.append("FLAG_PROP_JAVAARRAY | "); - if (result.length() == 0) result.append("0 | "); - return result.substring(0, result.length() - 3); - } - - public static final int FIELD_NONE = 0; - public static final int FIELD_GLOBAL = 1; - public static final int FIELD_LOCALATTR = 2; - public static final int FIELD_LOCALELT = 3; - - static String containerfieldTypeString(int code) - { - switch (code) - { - case FIELD_NONE: return "FIELD_NONE"; - case FIELD_GLOBAL: return "FIELD_GLOBAL"; - case FIELD_LOCALATTR: return "FIELD_LOCALATTR"; - case FIELD_LOCALELT: return "FIELD_LOCALELT"; - default: - return "Unknown container field type (" + code + ")"; - } - } - - // type flags - static final int FLAG_SIMPLE_TYPE = 0x1; - static final int FLAG_DOCUMENT_TYPE = 0x2; - static final int FLAG_ORDERED = 0x4; - static final int FLAG_BOUNDED = 0x8; - static final int FLAG_FINITE = 0x10; - static final int FLAG_NUMERIC = 0x20; - static final int FLAG_STRINGENUM = 0x40; - static final int FLAG_UNION_OF_LISTS = 0x80; - static final int FLAG_HAS_PATTERN = 0x100; - static final int FLAG_ORDER_SENSITIVE = 0x200; - static final int FLAG_TOTAL_ORDER = 0x400; - static final int FLAG_COMPILED = 0x800; - static final int FLAG_BLOCK_EXT = 0x1000; - static final int FLAG_BLOCK_REST = 0x2000; - static final int FLAG_FINAL_EXT = 0x4000; - static final int FLAG_FINAL_REST = 0x8000; - static final int FLAG_FINAL_UNION = 0x10000; - static final int FLAG_FINAL_LIST = 0x20000; - static final int FLAG_ABSTRACT = 0x40000; - static final int FLAG_ATTRIBUTE_TYPE = 0x80000; - - static String typeflagsString(int flags) - { - StringBuffer result = new StringBuffer(); - if ((flags & FLAG_SIMPLE_TYPE) != 0) result.append("FLAG_SIMPLE_TYPE | "); - if ((flags & FLAG_DOCUMENT_TYPE) != 0) result.append("FLAG_DOCUMENT_TYPE | "); - if ((flags & FLAG_ATTRIBUTE_TYPE) != 0) result.append("FLAG_ATTRIBUTE_TYPE | "); - if ((flags & FLAG_ORDERED) != 0) result.append("FLAG_ORDERED | "); - if ((flags & FLAG_BOUNDED) != 0) result.append("FLAG_BOUNDED | "); - if ((flags & FLAG_FINITE) != 0) result.append("FLAG_FINITE | "); - if ((flags & FLAG_NUMERIC) != 0) result.append("FLAG_NUMERIC | "); - if ((flags & FLAG_STRINGENUM) != 0) result.append("FLAG_STRINGENUM | "); - if ((flags & FLAG_UNION_OF_LISTS) != 0) result.append("FLAG_UNION_OF_LISTS | "); - if ((flags & FLAG_HAS_PATTERN) != 0) result.append("FLAG_HAS_PATTERN | "); - if ((flags & FLAG_TOTAL_ORDER) != 0) result.append("FLAG_TOTAL_ORDER | "); - if ((flags & FLAG_COMPILED) != 0) result.append("FLAG_COMPILED | "); - if ((flags & FLAG_BLOCK_EXT) != 0) result.append("FLAG_BLOCK_EXT | "); - if ((flags & FLAG_BLOCK_REST) != 0) result.append("FLAG_BLOCK_REST | "); - if ((flags & FLAG_FINAL_EXT) != 0) result.append("FLAG_FINAL_EXT | "); - if ((flags & FLAG_FINAL_REST) != 0) result.append("FLAG_FINAL_REST | "); - if ((flags & FLAG_FINAL_UNION) != 0) result.append("FLAG_FINAL_UNION | "); - if ((flags & FLAG_FINAL_LIST) != 0) result.append("FLAG_FINAL_LIST | "); - if ((flags & FLAG_ABSTRACT) != 0) result.append("FLAG_ABSTRACT | "); - if (result.length() == 0) result.append("0 | "); - return result.substring(0, result.length() - 3); - } - - void dumpAll() - { - int filetype = dumpHeader(); - switch (filetype) - { - case FILETYPE_SCHEMAINDEX: - dumpIndexData(); - return; - case FILETYPE_SCHEMATYPE: - dumpTypeFileData(); - break; - case FILETYPE_SCHEMAELEMENT: - dumpParticleData(true); - break; - case FILETYPE_SCHEMAATTRIBUTE: - dumpAttributeData(true); - break; - case FILETYPE_SCHEMAPOINTER: - dumpPointerData(); - break; - case FILETYPE_SCHEMAMODELGROUP: - dumpModelGroupData(); - break; - case FILETYPE_SCHEMAATTRIBUTEGROUP: - dumpAttributeGroupData(); - break; - } - readEnd(); - } - - static String hex32String(int i) - { - return Integer.toHexString(i); - } - - protected int dumpHeader() - { - int magic = readInt(); - emit("Magic cookie: " + hex32String(magic)); - - if (magic != DATA_BABE) - { - emit("Wrong magic cookie."); - return 0; - } - - _majorver = readShort(); - _minorver = readShort(); - if (atLeast(2, 18, 0)) - _releaseno = readShort(); - - emit("Major version: " + _majorver); - emit("Minor version: " + _minorver); - emit("Release number: " + _releaseno); - - if (_majorver != MAJOR_VERSION || _minorver > MINOR_VERSION) - { - emit("Incompatible version."); - return 0; - } - - int actualfiletype = readShort(); - emit("Filetype: " + filetypeString(actualfiletype)); - - _stringPool = new StringPool(); - _stringPool.readFrom(_input); - - return actualfiletype; - } - - void dumpPointerData() - { - emit("Type system: " + readString()); - } - - protected void dumpIndexData() - { - // has a handle pool (count, handle/type, handle/type...) - int size = readShort(); - emit("Handle pool (" + size + "):"); - indent(); - for (int i = 0; i < size; i++) - { - String handle = readString(); - int code = readShort(); - emit(handle + " (" + filetypeString(code) + ")"); - } - outdent(); - - dumpQNameMap("Global elements"); - - // qname map of global attributes - dumpQNameMap("Global attributes"); - - // attr groups and model groups - dumpQNameMap("Model groups"); - dumpQNameMap("Attribute groups"); - - dumpQNameMap("Identity constraints"); - - // qname map of global types - dumpQNameMap("Global types"); - - // qname map of document types, by the qname of the contained element - dumpQNameMap("Document types"); - - // qname map of attribute types, by the qname of the contained attribute - dumpQNameMap("Attribute types"); - - // all the types indexed by classname - dumpClassnameIndex("All types by classname"); - - // all the namespaces - dumpStringArray("Defined namespaces"); - - // version 15 stuff for redefines - if (atLeast(2, 15, 0)) - { - dumpQNameMap("Redefined global types"); - dumpQNameMap("Redfined model groups"); - dumpQNameMap("Redfined attribute groups"); - } - - // version 19 annotations - if (atLeast(2, 19, 0)) - dumpAnnotations(); - - readEnd(); - } - - - class StringPool - { - private List intsToStrings = new ArrayList(); - private Map stringsToInts = new HashMap(); - - StringPool() - { - intsToStrings.add(null); - } - - String stringForCode(int code) - { - if (code == 0) - return null; - return (String)intsToStrings.get(code); - } - - int codeForString(String str) - { - if (str == null) - return 0; - Integer result = (Integer)stringsToInts.get(str); - if (result == null) - { - result = new Integer(intsToStrings.size()); - intsToStrings.add(str); - stringsToInts.put(str, result); - } - return result.intValue(); - } - - void readFrom(DataInputStream input) - { - if (intsToStrings.size() != 1 || stringsToInts.size() != 0) - throw new IllegalStateException(); - - try - { - int size = input.readShort(); - emit("String pool (" + size + "):"); - indent(); - for (int i = 1; i < size; i++) - { - String str = input.readUTF(); - int code = codeForString(str); - if (code != i) - throw new IllegalStateException(); - emit(code + " = \"" + str + "\""); - } - outdent(); - } - catch (IOException e) - { - emit(e.toString()); - } - } - } - - // active while loading one type. - DataInputStream _input; - StringPool _stringPool; - - int readShort() - { - try - { - return _input.readUnsignedShort(); - } - catch (IOException e) - { - error(e); - return 0; - } - } - - int readInt() - { - try - { - return _input.readInt(); - } - catch (IOException e) - { - error(e); - return 0; - } - } - - String readString() - { - return _stringPool.stringForCode(readShort()); - } - - QName readQName() - { - String namespace = readString(); - String localname = readString(); - if (localname == null) - return null; - return new QName(namespace, localname); - } - - String readHandle() - { - return readString(); - } - - String readType() - { - return readHandle(); - } - - static String qnameString(QName qname) - { - if (qname == null) - return "(null)"; - if (qname.getNamespaceURI() != null) - return qname.getLocalPart() + "@" + qname.getNamespaceURI(); - else - return qname.getLocalPart(); - } - - static String qnameSetString(QNameSet set) - { - return set.toString(); - } - - void dumpQNameMap(String fieldname) - { - int size = readShort(); - emit(fieldname + " (" + size + "):"); - indent(); - for (int i = 0; i < size; i++) - { - emit(qnameString(readQName()) + " = " + readHandle()); - } - outdent(); - } - - void dumpTypeArray(String fieldname) - { - int size = readShort(); - emit(fieldname + " (" + size + "):"); - indent(); - for (int i = 0; i < size; i++) - { - emit(i + " = " + readType()); - } - outdent(); - } - - void dumpClassnameIndex(String fieldname) - { - int size = readShort(); - emit(fieldname + " (" + size + "):"); - indent(); - for (int i = 0; i < size; i++) - { - emit(readString() + " = " + readType()); - } - outdent(); - } - - void dumpStringArray(String fieldname) - { - int size = readShort(); - emit(fieldname + " (" + size + "):"); - indent(); - for (int i = 0; i < size; i++) - { - emit(readString()); - } - outdent(); - } - - void readEnd() - { - try - { - _input.close(); - } - catch (IOException e) - { - // oh, well. - } - _input = null; - _stringPool = null; - } - - static String particleTypeString(int spt) - { - switch (spt) - { - case SchemaParticle.ALL: return "ALL"; - case SchemaParticle.CHOICE: return "CHOICE"; - case SchemaParticle.ELEMENT: return "ELEMENT"; - case SchemaParticle.SEQUENCE: return "SEQUENCE"; - case SchemaParticle.WILDCARD: return "WILDCARD"; - default: - return "Unknown particle type (" + spt + ")"; - } - } - - static String bigIntegerString(BigInteger bigint) - { - if (bigint == null) - return "(null)"; - return bigint.toString(); - } - - static String wcprocessString(int code) - { - switch (code) - { - case SchemaParticle.STRICT: return "STRICT"; - case SchemaParticle.SKIP: return "SKIP"; - case SchemaParticle.LAX: return "LAX"; - case 0: return "NOT_WILDCARD"; - default: - return "Unknown process type (" + code + ")"; - } - } - - void dumpAnnotation() - { - if (!atLeast(2, 19, 0)) - return; // no annotations in this version of the file - - int n = readInt(); - if (n == -1) - return; // no annotation present - emit("Annotation"); - boolean empty = true; - indent(); - if (n > 0) - { - emit("Attributes (" + n + "):"); - indent(); - for (int i = 0; i < n; i++) - { - if (atLeast(2, 24, 0)) - emit("Name: " + qnameString(readQName()) + - ", Value: " + readString() + - ", ValueURI: " + readString()); - else - emit("Name: " + qnameString(readQName()) + - ", Value: " + readString()); - } - outdent(); - empty = false; - } - - n = readInt(); - if (n > 0) - { - emit("Documentation elements (" + n + "):"); - indent(); - for (int i = 0; i < n; i++) - emit(readString()); - outdent(); - empty = false; - } - - n = readInt(); - if (n > 0) - { - emit("Appinfo elements (" + n + "):"); - indent(); - for (int i = 0; i < n; i++) - emit(readString()); - outdent(); - empty = false; - } - if (empty) - emit(""); - outdent(); - } - - void dumpAnnotations() - { - int n = readInt(); - if (n > 0) - { - emit("Top-level annotations (" + n + "):"); - indent(); - for (int i = 0; i < n; i++) - dumpAnnotation(); - outdent(); - } - } - - void dumpParticleData(boolean global) - { - int particleType = readShort(); - emit(particleTypeString(particleType) + ":"); - indent(); - int particleFlags = readShort(); - emit("Flags: " + particleflagsString(particleFlags)); - - emit("MinOccurs: " + bigIntegerString(readBigInteger())); - emit("MaxOccurs: " + bigIntegerString(readBigInteger())); - - emit("Transition: " + qnameSetString(readQNameSet())); - - switch (particleType) - { - case SchemaParticle.WILDCARD: - emit("Wildcard set: " + qnameSetString(readQNameSet())); - emit("Wildcard process: " + wcprocessString(readShort())); - break; - - case SchemaParticle.ELEMENT: - emit("Name: " + qnameString(readQName())); - emit("Type: " + readType()); - emit("Default: " + readString()); - if (atLeast(2, 16, 0)) - emit("Default value: " + readXmlValueObject()); - emit("WsdlArrayType: " + SOAPArrayTypeString(readSOAPArrayType())); - dumpAnnotation(); - if (global) - { - if (atLeast(2, 17, 0)) - emit("Substitution group ref: " + readHandle()); - int substGroupCount = readShort(); - emit("Substitution group members (" + substGroupCount + ")"); - indent(); - for (int i = 0; i < substGroupCount; i++) - { - emit(qnameString(readQName())); - } - outdent(); - } - int count = readShort(); - emit("Identity constraints (" + count + "):"); - indent(); - for (int i = 0; i < count; i++) - { - emit(readHandle()); - } - outdent(); - if (global) - emit("Filename: " + readString()); - break; - - case SchemaParticle.ALL: - case SchemaParticle.SEQUENCE: - case SchemaParticle.CHOICE: - dumpParticleArray("Particle children"); - break; - - default: - error("Unrecognized schema particle type"); - } - outdent(); - } - - void dumpParticleArray(String fieldname) - { - int count = readShort(); - emit(fieldname + "(" + count + "):"); - indent(); - for (int i = 0; i < count; i++) - dumpParticleData(false); - outdent(); - } - - static String complexVarietyString(int code) - { - switch (code) - { - case SchemaType.EMPTY_CONTENT: return "EMPTY_CONTENT"; - case SchemaType.SIMPLE_CONTENT: return "SIMPLE_CONTENT"; - case SchemaType.ELEMENT_CONTENT: return "ELEMENT_CONTENT"; - case SchemaType.MIXED_CONTENT: return "MIXED_CONTENT"; - default: - return "Unknown complex variety (" + code + ")"; - } - } - - static String simpleVarietyString(int code) - { - switch (code) - { - case SchemaType.ATOMIC: return "ATOMIC"; - case SchemaType.LIST: return "LIST"; - case SchemaType.UNION: return "UNION"; - default: - return "Unknown simple variety (" + code + ")"; - } - } - - String facetCodeString(int code) - { - switch (code) - { - case SchemaType.FACET_LENGTH: return "FACET_LENGTH"; - case SchemaType.FACET_MIN_LENGTH: return "FACET_MIN_LENGTH"; - case SchemaType.FACET_MAX_LENGTH: return "FACET_MAX_LENGTH"; - case SchemaType.FACET_MIN_EXCLUSIVE: return "FACET_MIN_EXCLUSIVE"; - case SchemaType.FACET_MIN_INCLUSIVE: return "FACET_MIN_INCLUSIVE"; - case SchemaType.FACET_MAX_INCLUSIVE: return "FACET_MAX_INCLUSIVE"; - case SchemaType.FACET_MAX_EXCLUSIVE: return "FACET_MAX_EXCLUSIVE"; - case SchemaType.FACET_TOTAL_DIGITS: return "FACET_TOTAL_DIGITS"; - case SchemaType.FACET_FRACTION_DIGITS: return "FACET_FRACTION_DIGITS"; - default: - return "Unknown facet code (" + code + ")"; - } - } - - String whitespaceCodeString(int code) - { - switch (code) - { - case SchemaType.WS_COLLAPSE: return "WS_COLLAPSE"; - case SchemaType.WS_PRESERVE: return "WS_PRESERVE"; - case SchemaType.WS_REPLACE: return "WS_REPLACE"; - case SchemaType.WS_UNSPECIFIED: return "WS_UNSPECIFIED"; - default: - return "Unknown whitespace code (" + code + ")"; - } - } - - String derivationTypeString(int code) - { - switch (code) - { - case SchemaType.DT_NOT_DERIVED: return "DT_NOT_DERIVED"; - case SchemaType.DT_RESTRICTION: return "DT_RESTRICTION"; - case SchemaType.DT_EXTENSION: return "DT_EXTENSION"; - default: - return "Unknown derivation code (" + code + ")"; - } - } - - void dumpTypeFileData() - { - emit("Name: " + qnameString(readQName())); - emit("Outer type: " + readType()); - emit("Depth: " + readShort()); - emit("Base type: " + readType()); - emit("Derivation type: " + derivationTypeString(readShort())); - dumpAnnotation(); - - emit("Container field:"); - indent(); - int containerfieldtype = readShort(); - emit("Reftype: " + containerfieldTypeString(containerfieldtype)); - switch (containerfieldtype) - { - case FIELD_GLOBAL: - emit("Handle: " + readHandle()); - break; - case FIELD_LOCALATTR: - emit("Index: " + readShort()); - break; - case FIELD_LOCALELT: - emit("Index: " + readShort()); - break; - } - outdent(); - emit("Java class name: " + readString()); - emit("Java impl class name: " + readString()); - - dumpTypeArray("Anonymous types"); - - emit("Anonymous union member ordinal: " + readShort()); - - int flags; - flags = readInt(); - emit("Flags: " + typeflagsString(flags)); - boolean isComplexType = ((flags & FLAG_SIMPLE_TYPE) == 0); - - int complexVariety = SchemaType.NOT_COMPLEX_TYPE; - if (isComplexType) - { - complexVariety = readShort(); - emit("Complex variety: " + complexVarietyString(complexVariety)); - - if (atLeast(2, 23, 0)) - emit("Content based on type: " + readType()); - - int attrCount = readShort(); - emit("Attribute model (" + attrCount + "):"); - indent(); - for (int i = 0; i < attrCount; i++) - dumpAttributeData(false); - - emit("Wildcard set: " + qnameSetString(readQNameSet())); - emit("Wildcard process: " + wcprocessString(readShort())); - outdent(); - - // Attribute Property Table - int attrPropCount = readShort(); - emit("Attribute properties (" + attrPropCount + "):"); - indent(); - for (int i = 0; i < attrPropCount; i++) - { - dumpPropertyData(); - } - outdent(); - - if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT) - { - emit("IsAll: " + readShort()); - - // Content model tree - dumpParticleArray("Content model"); - - // Element Property Table - int elemPropCount = readShort(); - emit("Element properties (" + elemPropCount + "):"); - indent(); - for (int i = 0; i < elemPropCount; i++) - { - dumpPropertyData(); - } - outdent(); - } - } - - if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT) - { - int simpleVariety = readShort(); - emit("Simple type variety: " + simpleVarietyString(simpleVariety)); - - boolean isStringEnum = ((flags & FLAG_STRINGENUM) != 0); - - int facetCount = readShort(); - emit("Facets (" + facetCount + "):"); - indent(); - for (int i = 0; i < facetCount; i++) - { - emit(facetCodeString(readShort())); - emit("Value: " + readXmlValueObject()); - emit("Fixed: " + readShort()); - } - outdent(); - - emit("Whitespace rule: " + whitespaceCodeString(readShort())); - - int patternCount = readShort(); - emit("Patterns (" + patternCount + "):"); - indent(); - for (int i = 0; i < patternCount; i++) - { - emit(readString()); - } - outdent(); - - int enumCount = readShort(); - emit("Enumeration values (" + enumCount + "):"); - indent(); - for (int i = 0; i < enumCount; i++) - { - emit(readXmlValueObject()); - } - outdent(); - - emit("Base enum type: " + readType()); - if (isStringEnum) - { - int seCount = readShort(); - emit("String enum entries (" + seCount + "):"); - indent(); - for (int i = 0; i < seCount; i++) - { - emit("\"" + readString() + "\" -> " + readShort() + " = " + readString()); - } - outdent(); - } - - switch (simpleVariety) - { - case SchemaType.ATOMIC: - emit("Primitive type: " + readType()); - emit("Decimal size: " + readInt()); - break; - - case SchemaType.LIST: - emit("List item type: " + readType()); - break; - - case SchemaType.UNION: - dumpTypeArray("Union members"); - break; - - default: - error("Unknown simple type variety"); - } - } - - emit("Filename: " + readString()); - } - - static String attruseCodeString(int code) - { - switch (code) - { - case SchemaLocalAttribute.OPTIONAL: return "OPTIONAL"; - case SchemaLocalAttribute.REQUIRED: return "REQUIRED"; - case SchemaLocalAttribute.PROHIBITED: return "PROHIBITED"; - default: - return "Unknown use code (" + code + ")"; - } - } - - void dumpAttributeData(boolean global) - { - emit("Name: " + qnameString(readQName())); - emit("Type: " + readType()); - emit("Use: " + attruseCodeString(readShort())); - emit("Default: " + readString()); - if (atLeast(2, 16, 0)) - emit("Default value: " + readXmlValueObject()); - emit("Fixed: " + readShort()); - emit("WsdlArrayType: " + SOAPArrayTypeString(readSOAPArrayType())); - dumpAnnotation(); - if (global) - emit("Filename: " + readString()); - } - - private static final XmlOptions prettyOptions = - new XmlOptions().setSavePrettyPrint(); - - void dumpXml() - { - String xml = readString(); - try - { - emit( XmlObject.Factory.parse( xml ).xmlText( prettyOptions ) ); - } - catch ( XmlException x ) - { - emit( "!!!!!! BAD XML !!!!!" ); - emit( xml ); - } - } - - void dumpModelGroupData() - { - emit("Name: " + qnameString(readQName())); - emit("Target namespace: " + readString()); - emit("Chameleon: " + readShort()); - if (atLeast(2, 22, 0)) - emit("Element form default: " + readString()); - if (atLeast(2, 22, 0)) - emit("Attribute form default: " + readString()); - if (atLeast(2, 15, 0)) - emit("Redefine: " + readShort()); - emit("Model Group Xml: "); - dumpXml(); - dumpAnnotation(); - if (atLeast(2, 21, 0)) - emit("Filename: " + readString()); - } - - void dumpAttributeGroupData() - { - emit("Name: " + qnameString(readQName())); - emit("Target namespace: " + readString()); - emit("Chameleon: " + readShort()); - if (atLeast(2, 22, 0)) - emit("Form default: " + readString()); - if (atLeast(2, 15, 0)) - emit("Redefine: " + readShort()); - emit("Attribute Group Xml: "); - dumpXml(); - dumpAnnotation(); - if (atLeast(2, 21, 0)) - emit("Filename: " + readString()); - } - - static String alwaysString(int code) - { - switch (code) - { - case SchemaProperty.CONSISTENTLY: return "CONSISTENTLY"; - case SchemaProperty.NEVER: return "NEVER"; - case SchemaProperty.VARIABLE: return "VARIABLE"; - default: - return "Unknown frequency code (" + code + ")"; - } - } - - static String jtcString(int code) - { - switch (code) - { - case SchemaProperty.XML_OBJECT: return "XML_OBJECT"; - case SchemaProperty.JAVA_BOOLEAN: return "JAVA_BOOLEAN"; - case SchemaProperty.JAVA_FLOAT: return "JAVA_FLOAT"; - case SchemaProperty.JAVA_DOUBLE: return "JAVA_DOUBLE"; - case SchemaProperty.JAVA_BYTE: return "JAVA_BYTE"; - case SchemaProperty.JAVA_SHORT: return "JAVA_SHORT"; - case SchemaProperty.JAVA_INT: return "JAVA_INT"; - case SchemaProperty.JAVA_LONG: return "JAVA_LONG"; - - case SchemaProperty.JAVA_BIG_DECIMAL: return "JAVA_BIG_DECIMAL"; - case SchemaProperty.JAVA_BIG_INTEGER: return "JAVA_BIG_INTEGER"; - case SchemaProperty.JAVA_STRING: return "JAVA_STRING"; - case SchemaProperty.JAVA_BYTE_ARRAY: return "JAVA_BYTE_ARRAY"; - case SchemaProperty.JAVA_GDATE: return "JAVA_GDATE"; - case SchemaProperty.JAVA_GDURATION: return "JAVA_GDURATION"; - case SchemaProperty.JAVA_DATE: return "JAVA_DATE"; - case SchemaProperty.JAVA_QNAME: return "JAVA_QNAME"; - case SchemaProperty.JAVA_CALENDAR: return "JAVA_CALENDAR"; - case SchemaProperty.JAVA_LIST: return "JAVA_LIST"; - - case SchemaProperty.JAVA_ENUM: return "JAVA_ENUM"; - case SchemaProperty.JAVA_OBJECT: return "JAVA_OBJECT"; - - default: - return "Unknown java type code (" + code + ")"; - } - } - - void dumpPropertyData() - { - emit("Property"); - indent(); - emit("Name: " + qnameString(readQName())); - emit("Type: " + readType()); - int propflags = readShort(); - emit("Flags: " + propertyflagsString(propflags)); - emit("Container type: " + readType()); - emit("Min occurances: " + bigIntegerString(readBigInteger())); - emit("Max occurances: " + bigIntegerString(readBigInteger())); - emit("Nillable: " + alwaysString(readShort())); - emit("Default: " + alwaysString(readShort())); - emit("Fixed: " + alwaysString(readShort())); - emit("Default text: " + readString()); - emit("Java prop name: " + readString()); - emit("Java type code: " + jtcString(readShort())); - emit("Type for java signature: " + readType()); - if (atMost(2, 19, 0)) - emit("Java setter delimiter: " + qnameSetString(readQNameSet())); - if (atLeast(2, 16, 0)) - emit("Default value: " + readXmlValueObject()); - if (((propflags & FLAG_PROP_ISATTR) == 0) && atLeast(2, 17, 0)) - { - int size = readShort(); - emit("Accepted substitutions (" + size + "):"); - for (int i = 0 ; i < size ; i++) - emit(" Accepted name " + readQName()); - } - outdent(); - } - - String readXmlValueObject() - { - String type = readType(); - if (type == null) - return "null"; - - int btc = readShort(); - String value; - switch (btc) - { - default: - assert(false); - case 0: - value = "nil"; - break; - - case SchemaType.BTC_ANY_SIMPLE: - case SchemaType.BTC_ANY_URI: - case SchemaType.BTC_STRING: - case SchemaType.BTC_DURATION: - case SchemaType.BTC_DATE_TIME: - case SchemaType.BTC_TIME: - case SchemaType.BTC_DATE: - case SchemaType.BTC_G_YEAR_MONTH: - case SchemaType.BTC_G_YEAR: - case SchemaType.BTC_G_MONTH_DAY: - case SchemaType.BTC_G_DAY: - case SchemaType.BTC_G_MONTH: - case SchemaType.BTC_DECIMAL: - case SchemaType.BTC_BOOLEAN: - value = readString(); - break; - - case SchemaType.BTC_BASE_64_BINARY: - case SchemaType.BTC_HEX_BINARY: - { - value = new String(HexBin.encode(readByteArray())); - if (value.length() > 19) - value = value.subSequence(0, 16) + "..."; - break; - } - - case SchemaType.BTC_QNAME: - case SchemaType.BTC_NOTATION: - value = QNameHelper.pretty(readQName()); - break; - - case SchemaType.BTC_FLOAT: - case SchemaType.BTC_DOUBLE: - value = Double.toString(readDouble()); - break; - } - return value + " (" + type + ": " + btc +")"; - } - - double readDouble() - { - try - { - return _input.readDouble(); - } - catch (IOException e) - { - error(e); - return 0.0; - } - } - - String SOAPArrayTypeString(SOAPArrayType t) - { - if (t == null) - return "null"; - return QNameHelper.pretty(t.getQName()) + t.soap11DimensionString(); - } - - SOAPArrayType readSOAPArrayType() - { - QName qName = readQName(); - String dimensions = readString(); - if (qName == null) - return null; - return new SOAPArrayType(qName, dimensions); - } - - QNameSet readQNameSet() - { - int flag = readShort(); - - Set uriSet = new HashSet(); - int uriCount = readShort(); - for (int i = 0; i < uriCount; i++) - uriSet.add(readString()); - - Set qnameSet1 = new HashSet(); - int qncount1 = readShort(); - for (int i = 0; i < qncount1; i++) - qnameSet1.add(readQName()); - - Set qnameSet2 = new HashSet(); - int qncount2 = readShort(); - for (int i = 0; i < qncount2; i++) - qnameSet2.add(readQName()); - - if (flag == 1) - return QNameSet.forSets(uriSet, null, qnameSet1, qnameSet2); - else - return QNameSet.forSets(null, uriSet, qnameSet2, qnameSet1); - } - - byte[] readByteArray() - { - try - { - int len = _input.readShort(); - byte[] result = new byte[len]; - _input.readFully(result); - return result; - } - catch (IOException e) - { - error(e); - return null; - } - } - - BigInteger readBigInteger() - { - byte[] result = readByteArray(); - if (result.length == 0) - return null; - if (result.length == 1 && result[0] == 0) - return BigInteger.ZERO; - if (result.length == 1 && result[0] == 1) - return BigInteger.ONE; - return new BigInteger(result); - } - - static final byte[] SINGLE_ZERO_BYTE = new byte[] { (byte)0 }; - - private int _majorver; - private int _minorver; - private int _releaseno; - - - protected boolean atLeast(int majorver, int minorver, int releaseno) - { - if (_majorver > majorver) - return true; - if (_majorver < majorver) - return false; - if (_minorver > minorver) - return true; - if (_minorver < minorver) - return false; - return (_releaseno >= releaseno); - } - - protected boolean atMost(int majorver, int minorver, int releaseno) - { - if (_majorver > majorver) - return false; - if (_majorver < majorver) - return true; - if (_minorver > minorver) - return false; - if (_minorver < minorver) - return true; - return (_releaseno <= releaseno); - } - -} diff --git a/src/xmlconfig/org/apache/xmlbeans/impl/config/BindingConfigImpl.java b/src/xmlconfig/org/apache/xmlbeans/impl/config/BindingConfigImpl.java deleted file mode 100755 index 956cbed..0000000 --- a/src/xmlconfig/org/apache/xmlbeans/impl/config/BindingConfigImpl.java +++ /dev/null @@ -1,480 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.config; - -import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument.Config; -import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; -import org.apache.xmlbeans.impl.xb.xmlconfig.Nsconfig; -import org.apache.xmlbeans.impl.xb.xmlconfig.Qnameconfig; -import org.apache.xmlbeans.impl.xb.xmlconfig.Qnametargetenum; -import org.apache.xmlbeans.impl.xb.xmlconfig.Usertypeconfig; -import org.apache.xmlbeans.BindingConfig; -import org.apache.xmlbeans.UserType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.InterfaceExtension; -import org.apache.xmlbeans.PrePostExtension; -import org.apache.xmlbeans.impl.jam.JamClassLoader; -import org.apache.xmlbeans.impl.jam.JamService; -import org.apache.xmlbeans.impl.jam.JamServiceFactory; -import org.apache.xmlbeans.impl.jam.JamServiceParams; -import org.apache.xmlbeans.impl.schema.StscState; - -import javax.xml.namespace.QName; -import java.io.File; -import java.io.IOException; -import java.util.*; - -/** - * An implementation of BindingConfig - */ -public class BindingConfigImpl extends BindingConfig -{ - private Map _packageMap; - private Map _prefixMap; - private Map _suffixMap; - private Map _packageMapByUriPrefix; // uri prefix -> package - private Map _prefixMapByUriPrefix; // uri prefix -> name prefix - private Map _suffixMapByUriPrefix; // uri prefix -> name suffix - private Map _qnameTypeMap; - private Map _qnameDocTypeMap; - private Map _qnameElemMap; - private Map _qnameAttMap; - - private List _interfaceExtensions; - private List _prePostExtensions; - private Map _userTypes; - - private BindingConfigImpl() - { - _packageMap = Collections.EMPTY_MAP; - _prefixMap = Collections.EMPTY_MAP; - _suffixMap = Collections.EMPTY_MAP; - _packageMapByUriPrefix = Collections.EMPTY_MAP; - _prefixMapByUriPrefix = Collections.EMPTY_MAP; - _suffixMapByUriPrefix = Collections.EMPTY_MAP; - _qnameTypeMap = Collections.EMPTY_MAP; - _qnameDocTypeMap = Collections.EMPTY_MAP; - _qnameElemMap = Collections.EMPTY_MAP; - _qnameAttMap = Collections.EMPTY_MAP; - _interfaceExtensions = new ArrayList(); - _prePostExtensions = new ArrayList(); - _userTypes = Collections.EMPTY_MAP; - } - - public static BindingConfig forConfigDocuments(Config[] configs, File[] javaFiles, File[] classpath) - { - return new BindingConfigImpl(configs, javaFiles, classpath); - } - - private BindingConfigImpl(Config[] configs, File[] javaFiles, File[] classpath) - { - _packageMap = new LinkedHashMap(); - _prefixMap = new LinkedHashMap(); - _suffixMap = new LinkedHashMap(); - _packageMapByUriPrefix = new LinkedHashMap(); - _prefixMapByUriPrefix = new LinkedHashMap(); - _suffixMapByUriPrefix = new LinkedHashMap(); - _qnameTypeMap = new LinkedHashMap(); - _qnameDocTypeMap = new LinkedHashMap(); - _qnameElemMap = new LinkedHashMap(); - _qnameAttMap = new LinkedHashMap(); - _interfaceExtensions = new ArrayList(); - _prePostExtensions = new ArrayList(); - _userTypes = new LinkedHashMap(); - - for (int i = 0; i < configs.length; i++) - { - Config config = configs[i]; - Nsconfig[] nsa = config.getNamespaceArray(); - for (int j = 0; j < nsa.length; j++) - { - recordNamespaceSetting(nsa[j].getUri(), nsa[j].getPackage(), _packageMap); - recordNamespaceSetting(nsa[j].getUri(), nsa[j].getPrefix(), _prefixMap); - recordNamespaceSetting(nsa[j].getUri(), nsa[j].getSuffix(), _suffixMap); - recordNamespacePrefixSetting(nsa[j].getUriprefix(), nsa[j].getPackage(), _packageMapByUriPrefix); - recordNamespacePrefixSetting(nsa[j].getUriprefix(), nsa[j].getPrefix(), _prefixMapByUriPrefix); - recordNamespacePrefixSetting(nsa[j].getUriprefix(), nsa[j].getSuffix(), _suffixMapByUriPrefix); - } - - Qnameconfig[] qnc = config.getQnameArray(); - for (int j = 0; j < qnc.length; j++) - { - List applyto = qnc[j].xgetTarget().xgetListValue(); - QName name = qnc[j].getName(); - String javaname = qnc[j].getJavaname(); - for (int k = 0; k < applyto.size(); k++) - { - Qnametargetenum a = (Qnametargetenum) applyto.get(k); - switch (a.enumValue().intValue()) - { - case Qnametargetenum.INT_TYPE: - _qnameTypeMap.put(name, javaname); - break; - case Qnametargetenum.INT_DOCUMENT_TYPE: - _qnameDocTypeMap.put(name, javaname); - break; - case Qnametargetenum.INT_ACCESSOR_ELEMENT: - _qnameElemMap.put(name, javaname); - break; - case Qnametargetenum.INT_ACCESSOR_ATTRIBUTE: - _qnameAttMap.put(name, javaname); - break; - } - } - } - - Extensionconfig[] ext = config.getExtensionArray(); - for (int j = 0; j < ext.length; j++) - { - recordExtensionSetting(javaFiles, classpath, ext[j]); - } - - Usertypeconfig[] utypes = config.getUsertypeArray(); - for (int j = 0; j < utypes.length; j++) - { - recordUserTypeSetting(javaFiles, classpath, utypes[j]); - } - } - - secondPhaseValidation(); - //todo normalize(); - } - - void addInterfaceExtension(InterfaceExtensionImpl ext) - { - if (ext==null) - return; - - _interfaceExtensions.add(ext); - } - - void addPrePostExtension(PrePostExtensionImpl ext) - { - if (ext==null) - return; - - _prePostExtensions.add(ext); - } - - void secondPhaseValidation() - { - // validate interface methods collisions - Map methodSignatures = new HashMap(); - - for (int i = 0; i < _interfaceExtensions.size(); i++) - { - InterfaceExtensionImpl interfaceExtension = (InterfaceExtensionImpl) _interfaceExtensions.get(i); - - InterfaceExtensionImpl.MethodSignatureImpl[] methods = (InterfaceExtensionImpl.MethodSignatureImpl[])interfaceExtension.getMethods(); - for (int j = 0; j < methods.length; j++) - { - InterfaceExtensionImpl.MethodSignatureImpl ms = methods[j]; - - if (methodSignatures.containsKey(methods[j])) - { - - InterfaceExtensionImpl.MethodSignatureImpl ms2 = (InterfaceExtensionImpl.MethodSignatureImpl) methodSignatures.get(methods[j]); - if (!ms.getReturnType().equals(ms2.getReturnType())) - { - BindingConfigImpl.error("Colliding methods '" + ms.getSignature() + "' in interfaces " + - ms.getInterfaceName() + " and " + ms2.getInterfaceName() + ".", null); - } - - return; - } - - // store it into hashmap - methodSignatures.put(methods[j], methods[j]); - } - } - - // validate that PrePostExtension-s do not intersect - for (int i = 0; i < _prePostExtensions.size() - 1; i++) - { - PrePostExtensionImpl a = (PrePostExtensionImpl) _prePostExtensions.get(i); - for (int j = 1; j < _prePostExtensions.size(); j++) - { - PrePostExtensionImpl b = (PrePostExtensionImpl) _prePostExtensions.get(j); - if (a.hasNameSetIntersection(b)) - BindingConfigImpl.error("The applicable domain for handler '" + a.getHandlerNameForJavaSource() + - "' intersects with the one for '" + b.getHandlerNameForJavaSource() + "'.", null); - } - } - } - - private static void recordNamespaceSetting(Object key, String value, Map result) - { - if (value == null) - return; - else if (key == null) - result.put("", value); - else if (key instanceof String && "##any".equals(key)) - result.put(key, value); - else if (key instanceof List) - { - for (Iterator i = ((List)key).iterator(); i.hasNext(); ) - { - String uri = (String)i.next(); - if ("##local".equals(uri)) - uri = ""; - result.put(uri, value); - } - } - } - - private static void recordNamespacePrefixSetting(List list, String value, Map result) - { - if (value == null) - return; - else if (list == null) - return; - for (Iterator i = list.iterator(); i.hasNext(); ) - { - result.put(i.next(), value); - } - } - - private void recordExtensionSetting(File[] javaFiles, File[] classpath, Extensionconfig ext) - { - NameSet xbeanSet = null; - Object key = ext.getFor(); - - - if (key instanceof String && "*".equals(key)) - xbeanSet = NameSet.EVERYTHING; - else if (key instanceof List) - { - NameSetBuilder xbeanSetBuilder = new NameSetBuilder(); - for (Iterator i = ((List) key).iterator(); i.hasNext();) - { - String xbeanName = (String) i.next(); - xbeanSetBuilder.add(xbeanName); - } - xbeanSet = xbeanSetBuilder.toNameSet(); - } - - if (xbeanSet == null) - error("Invalid value of attribute 'for' : '" + key + "'.", ext); - - Extensionconfig.Interface[] intfXO = ext.getInterfaceArray(); - Extensionconfig.PrePostSet ppXO = ext.getPrePostSet(); - - if (intfXO.length > 0 || ppXO != null) - { - JamClassLoader jamLoader = getJamLoader(javaFiles, classpath); - for (int i = 0; i < intfXO.length; i++) - { - addInterfaceExtension(InterfaceExtensionImpl.newInstance(jamLoader, xbeanSet, intfXO[i])); - } - - addPrePostExtension(PrePostExtensionImpl.newInstance(jamLoader, xbeanSet, ppXO)); - } - } - - private void recordUserTypeSetting(File[] javaFiles, File[] classpath, - Usertypeconfig usertypeconfig) - { - JamClassLoader jamLoader = getJamLoader(javaFiles, classpath); - UserTypeImpl userType = UserTypeImpl.newInstance(jamLoader, usertypeconfig); - _userTypes.put(userType.getName(), userType); - } - - - private String lookup(Map map, Map mapByUriPrefix, String uri) - { - if (uri == null) - uri = ""; - String result = (String)map.get(uri); - if (result != null) - return result; - if (mapByUriPrefix != null) - { - result = lookupByUriPrefix(mapByUriPrefix, uri); - if (result != null) - return result; - } - - return (String)map.get("##any"); - } - - private String lookupByUriPrefix(Map mapByUriPrefix, String uri) - { - if (uri == null) - return null; - if (!mapByUriPrefix.isEmpty()) - { - String uriprefix = null; - Iterator i = mapByUriPrefix.keySet().iterator(); - while (i.hasNext()) - { - String nextprefix = (String)i.next(); - if (uriprefix != null && nextprefix.length() < uriprefix.length()) - continue; - if (uri.startsWith(nextprefix)) - uriprefix = nextprefix; - } - - if (uriprefix != null) - return (String)mapByUriPrefix.get(uriprefix); - } - return null; - } - - //package methods - static void warning(String s, XmlObject xo) - { - StscState.get().error(s, XmlError.SEVERITY_WARNING, xo); - } - - static void error(String s, XmlObject xo) - { - StscState.get().error(s, XmlError.SEVERITY_ERROR, xo); - } - - //public methods - - public String lookupPackageForNamespace(String uri) - { - return lookup(_packageMap, _packageMapByUriPrefix, uri); - } - - public String lookupPrefixForNamespace(String uri) - { - return lookup(_prefixMap, _prefixMapByUriPrefix, uri); - } - - public String lookupSuffixForNamespace(String uri) - { - return lookup(_suffixMap, _suffixMapByUriPrefix, uri); - } - - /** @deprecated replaced with {@link #lookupJavanameForQName(QName, int)} */ - public String lookupJavanameForQName(QName qname) - { - String result = (String)_qnameTypeMap.get(qname); - if (result != null) - return result; - return (String)_qnameDocTypeMap.get(qname); - } - - public String lookupJavanameForQName(QName qname, int kind) - { - switch (kind) - { - case QNAME_TYPE: - return (String)_qnameTypeMap.get(qname); - case QNAME_DOCUMENT_TYPE: - return (String)_qnameDocTypeMap.get(qname); - case QNAME_ACCESSOR_ELEMENT: - return (String)_qnameElemMap.get(qname); - case QNAME_ACCESSOR_ATTRIBUTE: - return (String)_qnameAttMap.get(qname); - } - return null; - } - - public UserType lookupUserTypeForQName(QName qname) - { - if (qname == null) - return null; - - return (UserType) _userTypes.get(qname); - } - - public InterfaceExtension[] getInterfaceExtensions() - { - return (InterfaceExtension[])_interfaceExtensions.toArray(new InterfaceExtension[_interfaceExtensions.size()]); - } - - public InterfaceExtension[] getInterfaceExtensions(String fullJavaName) - { - List result = new ArrayList(); - for (int i = 0; i < _interfaceExtensions.size(); i++) - { - InterfaceExtensionImpl intfExt = (InterfaceExtensionImpl) _interfaceExtensions.get(i); - if (intfExt.contains(fullJavaName)) - result.add(intfExt); - } - - return (InterfaceExtension[])result.toArray(new InterfaceExtension[result.size()]); - } - - public PrePostExtension[] getPrePostExtensions() - { - return (PrePostExtension[])_prePostExtensions.toArray(new PrePostExtension[_prePostExtensions.size()]); - } - - public PrePostExtension getPrePostExtension(String fullJavaName) - { - for (int i = 0; i < _prePostExtensions.size(); i++) - { - PrePostExtensionImpl prePostExt = (PrePostExtensionImpl) _prePostExtensions.get(i); - if (prePostExt.contains(fullJavaName)) - return prePostExt; - } - return null; - } - - private JamClassLoader getJamLoader(File[] javaFiles, File[] classpath) - { - JamServiceFactory jf = JamServiceFactory.getInstance(); - JamServiceParams params = jf.createServiceParams(); - params.set14WarningsEnabled(false); - // BUGBUG(radup) This is here because the above doesn't do the trick - params.setShowWarnings(false); - - // process the included sources - if (javaFiles!=null) - for (int i = 0; i < javaFiles.length; i++) - params.includeSourceFile(javaFiles[i]); - - //params.setVerbose(DirectoryScanner.class); - - // add the sourcepath and classpath, if specified - params.addClassLoader(this.getClass().getClassLoader()); - if (classpath != null) - for (int i = 0; i < classpath.length; i++) - params.addClasspath(classpath[i]); - - // create service, get classes, return compiler - JamService service; - try - { - service = jf.createService(params); - } - catch (IOException ioe) - { - error("Error when accessing .java files.", null); - return null; - } - -// JClass[] cls = service.getAllClasses(); -// for (int i = 0; i < cls.length; i++) -// { -// JClass cl = cls[i]; -// System.out.println("CL: " + cl + " " + cl.getQualifiedName()); -// JMethod[] methods = cl.getMethods(); -// for (int j = 0; j < methods.length; j++) -// { -// JMethod method = methods[j]; -// System.out.println(" " + method.getQualifiedName()); -// } -// } - - return service.getClassLoader(); - } -} diff --git a/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtensionImpl.java b/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtensionImpl.java deleted file mode 100755 index caefa33..0000000 --- a/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtensionImpl.java +++ /dev/null @@ -1,411 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.config; - -import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; -import org.apache.xmlbeans.InterfaceExtension; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.jam.JMethod; -import org.apache.xmlbeans.impl.jam.JClass; -import org.apache.xmlbeans.impl.jam.JParameter; -import org.apache.xmlbeans.impl.jam.JamClassLoader; - -public class InterfaceExtensionImpl implements InterfaceExtension -{ - private NameSet _xbeanSet; - private String _interfaceClassName; - private String _delegateToClassName; - private MethodSignatureImpl[] _methods; - - static InterfaceExtensionImpl newInstance(JamClassLoader loader, NameSet xbeanSet, Extensionconfig.Interface intfXO) - { - InterfaceExtensionImpl result = new InterfaceExtensionImpl(); - - result._xbeanSet = xbeanSet; - JClass interfaceJClass = validateInterface(loader, intfXO.getName(), intfXO); - - - if (interfaceJClass == null) - { - BindingConfigImpl.error("Interface '" + intfXO.getStaticHandler() + "' not found.", intfXO); - return null; - } - - result._interfaceClassName = interfaceJClass.getQualifiedName(); - - result._delegateToClassName = intfXO.getStaticHandler(); - JClass delegateJClass = validateClass(loader, result._delegateToClassName, intfXO); - - if (delegateJClass == null) // no HandlerClass - { - BindingConfigImpl.warning("Handler class '" + intfXO.getStaticHandler() + "' not found on classpath, skip validation.", intfXO); - return result; - } - - if (!result.validateMethods(interfaceJClass, delegateJClass, intfXO)) - return null; - - return result; - } - - private static JClass validateInterface(JamClassLoader loader, String intfStr, XmlObject loc) - { - return validateJava(loader, intfStr, true, loc); - } - - static JClass validateClass(JamClassLoader loader, String clsStr, XmlObject loc) - { - return validateJava(loader, clsStr, false, loc); - } - - static JClass validateJava(JamClassLoader loader, String clsStr, boolean isInterface, XmlObject loc) - { - if (loader==null) - return null; - - final String ent = isInterface ? "Interface" : "Class"; - JClass cls = loader.loadClass(clsStr); - - if (cls==null || cls.isUnresolvedType()) - { - BindingConfigImpl.error(ent + " '" + clsStr + "' not found.", loc); - return null; - } - - if ( (isInterface && !cls.isInterface()) || - (!isInterface && cls.isInterface())) - { - BindingConfigImpl.error("'" + clsStr + "' must be " + - (isInterface ? "an interface" : "a class") + ".", loc); - } - - if (!cls.isPublic()) - { - BindingConfigImpl.error(ent + " '" + clsStr + "' is not public.", loc); - } - - return cls; - } - - private boolean validateMethods(JClass interfaceJClass, JClass delegateJClass, XmlObject loc) - { - //assert _delegateToClass != null : "Delegate to class handler expected."; - boolean valid = true; - - JMethod[] interfaceMethods = interfaceJClass.getMethods(); - _methods = new MethodSignatureImpl[interfaceMethods.length]; - - for (int i = 0; i < interfaceMethods.length; i++) - { - JMethod method = validateMethod(interfaceJClass, delegateJClass, interfaceMethods[i], loc); - if (method != null) - _methods[i] = new MethodSignatureImpl(getStaticHandler(), method); - else - valid = false; - } - - - return valid; - } - - private JMethod validateMethod(JClass interfaceJClass, JClass delegateJClass, JMethod method, XmlObject loc) - { - String methodName = method.getSimpleName(); - JParameter[] params = method.getParameters(); - JClass returnType = method.getReturnType(); - - JClass[] delegateParams = new JClass[params.length+1]; - delegateParams[0] = returnType.forName("org.apache.xmlbeans.XmlObject"); - for (int i = 1; i < delegateParams.length; i++) - { - delegateParams[i] = params[i-1].getType(); - } - - JMethod handlerMethod = null; - handlerMethod = getMethod(delegateJClass, methodName, delegateParams); - if (handlerMethod==null) - { - BindingConfigImpl.error("Handler class '" + delegateJClass.getQualifiedName() + "' does not contain method " + methodName + "(" + listTypes(delegateParams) + ")", loc); - return null; - } - - // check for throws exceptions - JClass[] intfExceptions = method.getExceptionTypes(); - JClass[] delegateExceptions = handlerMethod.getExceptionTypes(); - if ( delegateExceptions.length!=intfExceptions.length ) - { - BindingConfigImpl.error("Handler method '" + delegateJClass.getQualifiedName() + "." + methodName + "(" + listTypes(delegateParams) + - ")' must declare the same exceptions as the interface method '" + interfaceJClass.getQualifiedName() + "." + methodName + "(" + listTypes(params), loc); - return null; - } - - for (int i = 0; i < delegateExceptions.length; i++) - { - if ( delegateExceptions[i]!=intfExceptions[i] ) - { - BindingConfigImpl.error("Handler method '" + delegateJClass.getQualifiedName() + "." + methodName + "(" + listTypes(delegateParams) + - ")' must declare the same exceptions as the interface method '" + interfaceJClass.getQualifiedName() + "." + methodName + "(" + listTypes(params), loc); - return null; - } - } - - if (!handlerMethod.isPublic() || !handlerMethod.isStatic()) - { - BindingConfigImpl.error("Method '" + delegateJClass.getQualifiedName() + "." + methodName + "(" + listTypes(delegateParams) + ")' must be declared public and static.", loc); - return null; - } - - if (!returnType.equals(handlerMethod.getReturnType())) - { - BindingConfigImpl.error("Return type for method '" + handlerMethod.getReturnType() + " " + delegateJClass.getQualifiedName() + - "." + methodName + "(" + listTypes(delegateParams) + ")' does not match the return type of the interface method :'" + returnType + "'.", loc); - return null; - } - - return method; - } - - static JMethod getMethod(JClass cls, String name, JClass[] paramTypes) - { - JMethod[] methods = cls.getMethods(); - for (int i = 0; i < methods.length; i++) - { - JMethod method = methods[i]; - if (!name.equals(method.getSimpleName())) - continue; - - JParameter[] mParams = method.getParameters(); - - // can have methods with same name but different # of params - if (mParams.length != paramTypes.length) - continue; - - for (int j = 0; j < mParams.length; j++) - { - JParameter mParam = mParams[j]; - if (!mParam.getType().equals(paramTypes[j])) - continue; - } - - return method; - } - return null; - } - - private static String listTypes(JClass[] types) - { - StringBuffer result = new StringBuffer(); - for (int i = 0; i < types.length; i++) - { - JClass type = types[i]; - if (i>0) - result.append(", "); - result.append(emitType(type)); - } - return result.toString(); - } - - private static String listTypes(JParameter[] params) - { - StringBuffer result = new StringBuffer(); - for (int i = 0; i < params.length; i++) - { - JClass type = params[i].getType(); - if (i>0) - result.append(", "); - result.append(emitType(type)); - } - return result.toString(); - } - - public static String emitType(JClass cls) - { - if (cls.isArrayType()) - return emitType(cls.getArrayComponentType()) + "[]"; - else - return cls.getQualifiedName().replace('$', '.'); - } - - /* public getters */ - public boolean contains(String fullJavaName) - { - return _xbeanSet.contains(fullJavaName); - } - - public String getStaticHandler() - { - return _delegateToClassName; - } - - public String getInterface() - { - return _interfaceClassName; - } - - public InterfaceExtension.MethodSignature[] getMethods() - { - return _methods; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - buf.append(" static handler: ").append(_delegateToClassName).append("\n"); - buf.append(" interface: ").append(_interfaceClassName).append("\n"); - buf.append(" name set: ").append(_xbeanSet).append("\n"); - - for (int i = 0; i < _methods.length; i++) - buf.append(" method[").append(i).append("]=").append(_methods[i]).append("\n"); - - return buf.toString(); - } - - // this is used only for detecting method colisions of extending interfaces - static class MethodSignatureImpl implements InterfaceExtension.MethodSignature - { - private String _intfName; - private final int NOTINITIALIZED = -1; - private int _hashCode = NOTINITIALIZED; - private String _signature; - - private String _name; - private String _return; - private String[] _params; - private String[] _exceptions; - - MethodSignatureImpl(String intfName, JMethod method) - { - if (intfName==null || method==null) - throw new IllegalArgumentException("Interface: " + intfName + " method: " + method); - - _intfName = intfName; - _hashCode = NOTINITIALIZED; - _signature = null; - - _name = method.getSimpleName(); - _return = method.getReturnType().getQualifiedName().replace('$', '.'); - - JParameter[] paramTypes = method.getParameters(); - _params = new String[paramTypes.length]; - for (int i = 0; i < paramTypes.length; i++) - _params[i] = paramTypes[i].getType().getQualifiedName().replace('$', '.');; - - JClass[] exceptionTypes = method.getExceptionTypes(); - _exceptions = new String[exceptionTypes.length]; - for (int i = 0; i < exceptionTypes.length; i++) - _exceptions[i] = exceptionTypes[i].getQualifiedName().replace('$', '.'); - } - - String getInterfaceName() - { - return _intfName; - } - - public String getName() - { - return _name; - } - - public String getReturnType() - { - return _return; - } - - public String[] getParameterTypes() - { - return _params; - } - - public String[] getExceptionTypes() - { - return _exceptions; - } - - public boolean equals(Object o) - { - if ( !(o instanceof MethodSignatureImpl)) - return false; - - MethodSignatureImpl ms = (MethodSignatureImpl)o; - - if (!ms.getName().equals(getName()) ) - return false; - - String[] params = getParameterTypes(); - String[] msParams = ms.getParameterTypes(); - - if (msParams.length != params.length ) - return false; - - for (int i = 0; i < params.length; i++) - { - if (!msParams[i].equals(params[i])) - return false; - } - - if (!_intfName.equals(ms._intfName)) - return false; - - return true; - } - - public int hashCode() - { - if (_hashCode!=NOTINITIALIZED) - return _hashCode; - - int hash = getName().hashCode(); - - String[] params = getParameterTypes(); - - for (int i = 0; i < params.length; i++) - { - hash *= 19; - hash += params[i].hashCode(); - } - - hash += 21 * _intfName.hashCode(); - - _hashCode = hash; - return _hashCode; - } - - String getSignature() - { - if (_signature!=null) - return _signature; - - StringBuffer sb = new StringBuffer(60); - sb.append(_name).append("("); - for (int i = 0; i < _params.length; i++) - sb.append((i == 0 ? "" : " ,")).append(_params[i]); - sb.append(")"); - - _signature = sb.toString(); - - return _signature; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - - buf.append(getReturnType()).append(" ").append(getSignature()); - - return buf.toString(); - } - } -} diff --git a/src/xmlconfig/org/apache/xmlbeans/impl/config/NameSet.java b/src/xmlconfig/org/apache/xmlbeans/impl/config/NameSet.java deleted file mode 100644 index 2b0b8d0..0000000 --- a/src/xmlconfig/org/apache/xmlbeans/impl/config/NameSet.java +++ /dev/null @@ -1,224 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Author: Cezar Andrei ( cezar.andrei at bea.com ) - * Date: Apr 25, 2004 - */ -package org.apache.xmlbeans.impl.config; - -import java.util.Set; -import java.util.Collections; -import java.util.HashSet; - -/** - * Reprezents a non finite set of names. - * @see NameSetBuilder - */ -public class NameSet -{ - /** - * An empty NameSet, it doesn't contain any name - */ - public static NameSet EMPTY = new NameSet(true, Collections.EMPTY_SET); - /** - * The NameSet that contains any name - */ - public static NameSet EVERYTHING = new NameSet(false, Collections.EMPTY_SET); - - /* - There are two big cases: - 1) - it reprezents "*", ie all except a finite set of names: _isFinite==false - 2) - if reprezents only a finite set of names: _isFinite==true - */ - private boolean _isFinite; - private Set _finiteSet; - - private NameSet(boolean isFinite, Set finiteSet) - { - _isFinite = isFinite; - _finiteSet = finiteSet; - } - - static NameSet newInstance(boolean isFinite, Set finiteSet) - { - if ( finiteSet.size()==0 ) - if ( isFinite ) - return NameSet.EMPTY; - else - return NameSet.EVERYTHING; - else - { - Set fs = new HashSet(); - fs.addAll(finiteSet); - return new NameSet(isFinite, fs); - } - } - - private static Set intersectFiniteSets(Set a, Set b) - { - Set intersection = new HashSet(); - //compute the intersection of _finiteSet with withSet - while (a.iterator().hasNext()) - { - String name = (String) a.iterator().next(); - if (b.contains(name)) - intersection.add(name); - } - return intersection; - } - - /** - * Returns the union of this NameSet with the 'with' NameSet. - */ - public NameSet union(NameSet with) - { - if (_isFinite) - { - if (with._isFinite) - { - Set union = new HashSet(); - union.addAll(_finiteSet); - union.addAll(with._finiteSet); - return newInstance(true, union); - } - else - { - Set subst = new HashSet(); - subst.addAll(with._finiteSet); - subst.removeAll(_finiteSet); - return newInstance(false, subst); - } - } - else - { - if (with._isFinite) - { - Set subst = new HashSet(); - subst.addAll(_finiteSet); - subst.removeAll(with._finiteSet); - return newInstance(false, subst); - } - else - { - return newInstance(false, intersectFiniteSets(_finiteSet, with._finiteSet)); - } - } - } - - /** - * Returns the intersection of this NameSet with the 'with' NameSet - */ - public NameSet intersect(NameSet with) - { - if (_isFinite) - { - if (with._isFinite) - { - return newInstance(true, intersectFiniteSets(_finiteSet, with._finiteSet)); - } - else - { - Set subst = new HashSet(); - subst.addAll(_finiteSet); - subst.removeAll(with._finiteSet); - return newInstance(false, subst); - } - } - else - { - if (with._isFinite) - { - Set subst = new HashSet(); - subst.addAll(with._finiteSet); - subst.removeAll(_finiteSet); - return newInstance(true, subst); - } - else - { - Set union = new HashSet(); - union.addAll(_finiteSet); - union.addAll(with._finiteSet); - return newInstance(false, union); - } - } - } - - /** - * Returns the result of substracting this NameSet from 'from' NameSet - * @see NameSet#substract - */ - public NameSet substractFrom(NameSet from) - { - return from.substract(this); - } - - /** - * Returns the result of substracting 'what' NameSet from this NameSet - * @see NameSet#substractFrom - */ - public NameSet substract(NameSet what) - { - if (_isFinite) - { - if ( what._isFinite ) - { - // it's the subst of _finiteSet with what._finiteSet - Set subst = new HashSet(); - subst.addAll(_finiteSet); - subst.removeAll(what._finiteSet); - return newInstance(true, subst); - } - else - { - return newInstance(true, intersectFiniteSets(_finiteSet, what._finiteSet)); - } - } - else - { - if ( what._isFinite ) - { - // it's the union of _finiteSet with what._finiteSet - Set union = new HashSet(); - union.addAll(_finiteSet); - union.addAll(what._finiteSet); - return newInstance(false, union); - } - else - { - // what's in thisSet and it's not in whatSet - Set subst = new HashSet(); - subst.addAll(what._finiteSet); - subst.removeAll(_finiteSet); - return newInstance(true, subst); - } - } - } - - /** - * Returns an inversion of this NameSet - */ - public NameSet invert() - { - return newInstance(!_isFinite, _finiteSet); - } - - public boolean contains(String name) - { - if (_isFinite) - return _finiteSet.contains(name); - else - return !_finiteSet.contains(name); - } -} diff --git a/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtensionImpl.java b/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtensionImpl.java deleted file mode 100755 index bbf7415..0000000 --- a/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtensionImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.xmlbeans.impl.config; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.PrePostExtension; -import org.apache.xmlbeans.impl.jam.JamClassLoader; -import org.apache.xmlbeans.impl.jam.JClass; -import org.apache.xmlbeans.impl.jam.JMethod; -import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; - - -public class PrePostExtensionImpl implements PrePostExtension -{ - - private static JClass[] PARAMTYPES_PREPOST = null; //new JClass[]{int.class, XmlObject.class, QName.class, boolean.class, int.class}; - private static final String[] PARAMTYPES_STRING = new String[] {"int", "org.apache.xmlbeans.XmlObject", - "javax.xml.namespace.QName", "boolean", "int"}; - private static final String SIGNATURE; - static - { - String sig = "("; - for (int i = 0; i < PARAMTYPES_STRING.length; i++) - { - String t = PARAMTYPES_STRING[i]; - if (i!=0) - sig += ", "; - sig += t; - } - SIGNATURE = sig + ")"; - } - - private NameSet _xbeanSet; - private JClass _delegateToClass; - private String _delegateToClassName; - private JMethod _preSet; - private JMethod _postSet; - - static PrePostExtensionImpl newInstance(JamClassLoader jamLoader, NameSet xbeanSet, Extensionconfig.PrePostSet prePostXO) - { - if (prePostXO==null) - return null; - - PrePostExtensionImpl result = new PrePostExtensionImpl(); - - result._xbeanSet = xbeanSet; - result._delegateToClassName = prePostXO.getStaticHandler(); - result._delegateToClass = InterfaceExtensionImpl.validateClass(jamLoader, result._delegateToClassName, prePostXO); - - if ( result._delegateToClass==null ) // no HandlerClass - { - BindingConfigImpl.warning("Handler class '" + prePostXO.getStaticHandler() + "' not found on classpath, skip validation.", prePostXO); - return result; - } - - if (!result.lookAfterPreAndPost(jamLoader, prePostXO)) - return null; - - return result; - } - - private boolean lookAfterPreAndPost(JamClassLoader jamLoader, XmlObject loc) - { - assert _delegateToClass!=null : "Delegate to class handler expected."; - boolean valid = true; - - initParamPrePost(jamLoader); - - _preSet = InterfaceExtensionImpl.getMethod(_delegateToClass, "preSet", PARAMTYPES_PREPOST); - if (_preSet==null) - {} // not available is ok, _preSet will be null - - if (_preSet!=null && !_preSet.getReturnType().equals(jamLoader.loadClass("boolean"))) - { - // just emit an warning and don't remember as a preSet - BindingConfigImpl.warning("Method '" + _delegateToClass.getSimpleName() + - ".preSet" + SIGNATURE + "' " + - "should return boolean to be considered for a preSet handler.", loc); - _preSet = null; - } - - _postSet = InterfaceExtensionImpl.getMethod(_delegateToClass, "postSet", PARAMTYPES_PREPOST); - if (_postSet==null) - {} // not available is ok, _postSet will be null - - if (_preSet==null && _postSet==null) - { - BindingConfigImpl.error("prePostSet handler specified '" + _delegateToClass.getSimpleName() + - "' but no preSet" + SIGNATURE + " or " + - "postSet" + SIGNATURE + " methods found.", loc); - valid = false; - } - - return valid; - } - - private void initParamPrePost(JamClassLoader jamLoader) - { - if (PARAMTYPES_PREPOST==null) - { - PARAMTYPES_PREPOST = new JClass[PARAMTYPES_STRING.length]; - for (int i = 0; i < PARAMTYPES_PREPOST.length; i++) - { - PARAMTYPES_PREPOST[i] = jamLoader.loadClass(PARAMTYPES_STRING[i]); - if (PARAMTYPES_PREPOST[i]==null) - { - throw new IllegalStateException("JAM should have access to the following types " + SIGNATURE); - } - } - } - } - - // public methods - public NameSet getNameSet() - { - return _xbeanSet; - } - - public boolean contains(String fullJavaName) - { - return _xbeanSet.contains(fullJavaName); - } - - public boolean hasPreCall() - { - return _preSet!=null; - } - - public boolean hasPostCall() - { - return _postSet!=null; - } - - public String getStaticHandler() - { - return _delegateToClassName; - } - - /** - * Returns the name of the handler in a form that can be put in a java source. - */ - public String getHandlerNameForJavaSource() - { - // used only in validation - if (_delegateToClass==null) - return null; - - return InterfaceExtensionImpl.emitType(_delegateToClass); - } - - boolean hasNameSetIntersection(PrePostExtensionImpl ext) - { - return !NameSet.EMPTY.equals(_xbeanSet.intersect(ext._xbeanSet)); - } - -} diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/BufferedXMLInputStream.java b/src/xmlinputstream/org/apache/xmlbeans/xml/stream/BufferedXMLInputStream.java deleted file mode 100755 index 3b5cc82..0000000 --- a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/BufferedXMLInputStream.java +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.xml.stream; - -import java.io.IOException; -/** - * Extends the XMLInputStream to allow marking and reseting of the stream. - * - * @since XMLInputStream 1.0 - * @version 1.0 - * @see org.apache.xmlbeans.xml.stream.CharacterData - * @see org.apache.xmlbeans.xml.stream.ProcessingInstruction - * @see org.apache.xmlbeans.xml.stream.StartElement - * @see org.apache.xmlbeans.xml.stream.EndElement - * @see org.apache.xmlbeans.xml.stream.CharacterData - * @see org.apache.xmlbeans.xml.stream.XMLName - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ -public interface BufferedXMLInputStream extends XMLInputStream { - /** - * Sets the marks a point to return to in the stream, - * throws an exception if the stream does not support mark. - * This is only supported in BufferedStreams - */ - public void mark() throws XMLStreamException; - /** - * Resets the stream to the previous mark. - * throws an exception if the stream does not support mark; - */ - public void reset() throws XMLStreamException; -} - - - - - diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/ReferenceResolver.java b/src/xmlinputstream/org/apache/xmlbeans/xml/stream/ReferenceResolver.java deleted file mode 100755 index ac5c886..0000000 --- a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/ReferenceResolver.java +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.xml.stream; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -/** - * This interface can be implemented to allow resolution of references - * on a stream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ -public interface ReferenceResolver { - /** - * Returns the xml pointed to by this idref as an XMLInputStream - * @param idref - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - XMLInputStream resolve(String idref) - throws XMLStreamException; - - /** - * Returns the id that corresponds to this idref - * @param idref - */ - String getId(String idref); -} diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartElement.java b/src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartElement.java deleted file mode 100755 index 14d904d..0000000 --- a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/StartElement.java +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.xml.stream; - -import java.util.Map; -/** - * The StartElement interface provides access to information about - * start elements - * - * @since Weblogic XML Input Stream 1.0 - * @version 1.0 - * @see org.apache.xmlbeans.xml.stream.AttributeIterator - */ - -public interface StartElement extends XMLEvent { - /** - * Returns an AttributeIterator of non-namespace declared attributes - */ - public AttributeIterator getAttributes(); - /** - * Returns an AttributeIterator of namespaces declared in this element - */ - public AttributeIterator getNamespaces(); - /** - * Returns the union of declared attributes and namespaces - */ - public AttributeIterator getAttributesAndNamespaces(); - /** - * Returns the attribute referred to by this name - */ - public Attribute getAttributeByName(XMLName name); - /** - * Gets the value that the prefix is bound to in the - * context of this element. Returns null if - * the prefix is not bound in this context - */ - public String getNamespaceUri(String prefix); - /** - * Gets a java.util.Map from prefixes to URIs in scope for this - * element. - */ - public Map getNamespaceMap(); -} diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLInputStream.java b/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLInputStream.java deleted file mode 100755 index 1d69110..0000000 --- a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLInputStream.java +++ /dev/null @@ -1,142 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.xml.stream; - -/** - * - * This is the top level interface for iterating over XML Events - * in an XML document. - * - *

      Difference from SAX

      - *

      An event stream can be thought of encapsulating SAX - * events. It applies an iterator/pull metaphor to the parser - * allowing procedural, stream-based, handling of input XML rather than - * having to write chained event handlers to handle complex XML - * documents. - *

      Difference from DOM

      - *

      The pull metaphor allows single-pass, stream-based parsing of the document rather - * than tree based manipulation.

      - * - * @since XMLInputStream 1.0 - * @version 1.0 - * @see org.apache.xmlbeans.xml.stream.XMLEvent - * @see org.apache.xmlbeans.xml.stream.CharacterData - * @see org.apache.xmlbeans.xml.stream.ProcessingInstruction - * @see org.apache.xmlbeans.xml.stream.StartElement - * @see org.apache.xmlbeans.xml.stream.EndElement - * @see org.apache.xmlbeans.xml.stream.CharacterData - * @see org.apache.xmlbeans.xml.stream.XMLName - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - -// REVIEW pdapkus@bea.com 2002-Sep-13 -- while I like the convenience -// of many of these methods, it strikes me that many of these methods -// could implemented as static methods in a utility class. the down -// side to having them in this base interface is that it makes the -// contract for implementers unnecessarily steap and results in -// duplicated code in methods that can't extend one of the common base -// classes. - -public interface XMLInputStream { - /** - * Get the next XMLEvent on the stream - * @see org.apache.xmlbeans.xml.stream.XMLEvent - */ - public XMLEvent next() throws XMLStreamException; - /** - * Check if there are more events to pull of the stream - * @see org.apache.xmlbeans.xml.stream.XMLEvent - */ - public boolean hasNext() throws XMLStreamException; - /** - * Skip the next stream event - */ - public void skip() throws XMLStreamException; - /** - * Skips the entire next start tag / end tag pair. - */ - public void skipElement() throws XMLStreamException; - /** - * Check the next XMLEvent without reading it from the stream. - * Returns null if the stream is at EOF or has no more XMLEvents. - * @see org.apache.xmlbeans.xml.stream.XMLEvent - */ - public XMLEvent peek() throws XMLStreamException; - /** - * Position the stream at the next XMLEvent of this type. The method - * returns true if the stream contains another XMLEvent of this type - * and false otherwise. - * @param eventType An integer code that indicates the element type. - * @see org.apache.xmlbeans.xml.stream.XMLEvent - */ - public boolean skip(int eventType) throws XMLStreamException; - /** - * Position the stream at the next element of this name. The method - * returns true if the stream contains another element with this name - * and false otherwise. Skip is a forward operator only. It does - * not look backward in the stream. - * @param name An object that defines an XML name. - * If the XMLName.getNameSpaceName() method on the XMLName argument returns - * null the XMLName will match just the local name. Prefixes are - * not checked for equality. - * @see org.apache.xmlbeans.xml.stream.XMLName - */ - public boolean skip(XMLName name) throws XMLStreamException; - /** - * Position the stream at the next element of this name and this type. - * The method returns true if the stream contains another element - * with this name of this type and false otherwise. - * @param name An object that defines an XML name. - * If the XMLName.getNameSpaceName() method on the XMLName argument returns - * null the XMLName will match just the local name. Prefixes are - * not checked for equality. - * @param eventType An integer code that indicates the element type. - * @see org.apache.xmlbeans.xml.stream.XMLEvent - * @see org.apache.xmlbeans.xml.stream.XMLName - */ - public boolean skip(XMLName name, int eventType) throws XMLStreamException; - /** - * getSubStream() returns a stream which points to the entire next element in the - * current stream. For example: take a document that has a root node A, where the children - * of A are B, C, and D. If the stream is pointing to the start element of A, getSubStream() will return - * A, B, C and D including the start element of A and the end element of A. The position of the parent - * stream is not changed and the events read by the substream are written back to its parent. - */ - public XMLInputStream getSubStream() throws XMLStreamException; - /** - * Closes this input stream and releases any system resources associated with the stream. - */ - public void close() throws XMLStreamException; - - /** - * Returns the reference resolver that was set for this stream, - * returns null if no ReferenceResolver has been set. - * @see org.apache.xmlbeans.xml.stream.ReferenceResolver - */ - public ReferenceResolver getReferenceResolver(); - /** - * Provides a way to set the ReferenceResolver of the stream, - * this is mostly needed for handle references to other parts of the - * document. - * @see org.apache.xmlbeans.xml.stream.ReferenceResolver - */ - public void setReferenceResolver(ReferenceResolver resolver); -} - - - - - diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLStreamException.java b/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLStreamException.java deleted file mode 100755 index 32c6f25..0000000 --- a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/XMLStreamException.java +++ /dev/null @@ -1,141 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.xml.stream; - -import java.io.IOException; -import java.io.PrintStream; -import java.io.PrintWriter; - -import org.apache.xmlbeans.xml.stream.utils.NestedThrowable; - -/** - * The base exception for unexpected input during XML handling - * - * @since Weblogic XML Input Stream 1.0 - * @version 1.0 - */ - -public class XMLStreamException - extends IOException - implements NestedThrowable -{ - protected Throwable th; - - public XMLStreamException() {} - - public XMLStreamException(String msg) { - super(msg); - } - - public XMLStreamException(Throwable th) { - this.th = th; - - } - - public XMLStreamException(String msg, Throwable th) { - super(msg); - this.th = th; - } - - /** - * Gets the nested exception. - * - * @return Nested exception - */ - public Throwable getNestedException() { - return getNested(); - } - - //try to do someting useful - public String getMessage() { - String msg = super.getMessage(); - - if (msg == null && th != null) { - return th.getMessage(); - } else { - return msg; - } - } - - - // ================================================================= - // NestedThrowable implementation. - - /** - * Gets the nested Throwable. - * - * @return Nested exception - */ - public Throwable getNested() { - return th; - } - - public String superToString() { - return super.toString(); - } - - public void superPrintStackTrace(PrintStream ps) { - super.printStackTrace(ps); - } - - public void superPrintStackTrace(PrintWriter pw) { - super.printStackTrace(pw); - } - - // End NestedThrowable implementation. - // ================================================================= - - /** - * Prints the exception message and its nested exception message. - * - * @return String representation of the exception - */ - public String toString() { - return NestedThrowable.Util.toString(this); - } - - /** - * Prints the stack trace associated with this exception and - * its nested exception. - * - * @param s PrintStream - */ - public void printStackTrace(PrintStream s) { - NestedThrowable.Util.printStackTrace(this, s); - } - - /** - * Prints the stack trace associated with this exception and - * its nested exception. - * - * @param s PrintStream - */ - public void printStackTrace(PrintWriter w) { - NestedThrowable.Util.printStackTrace(this, w); - } - - /** - * Prints the stack trace associated with this exception and - * its nested exception to System.err. - * - * @param s PrintStream - */ - public void printStackTrace() { - printStackTrace(System.err); - } -} - - diff --git a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/utils/NestedThrowable.java b/src/xmlinputstream/org/apache/xmlbeans/xml/stream/utils/NestedThrowable.java deleted file mode 100755 index 2ca73d2..0000000 --- a/src/xmlinputstream/org/apache/xmlbeans/xml/stream/utils/NestedThrowable.java +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.xml.stream.utils; - -/** - * The interface implemented by NestedException, NestedError, and - * NestedRuntimeException largely so Util can provide a standard - * implementation of toString() and printStackTrace() - * - * @deprecated use JDK 1.4 style nested throwables where possible. - * - */ - -import java.io.PrintWriter; -import java.io.PrintStream; -import java.lang.reflect.InvocationTargetException; - -public interface NestedThrowable { - - /** Get the nested Throwable. */ - Throwable getNested(); - - /** Call super.toString(). [Kludge but necessary.] */ - String superToString(); - - /** Call super.printStackTrace(). [Kludge but necessary.] */ - void superPrintStackTrace(PrintStream ps); - - /** Call super.printStackTrace(). [Kludge but necessary.] */ - void superPrintStackTrace(PrintWriter po); - - static class Util { - - private static String EOL = System.getProperty("line.separator"); - - /** - * Prints the exception message and its nested exception message. - * - * @return String representation of the exception - */ - public static String toString(NestedThrowable nt) { - Throwable nested = nt.getNested(); - if (nested == null) { - return nt.superToString(); - } else { - return nt.superToString() + " - with nested exception:" + - EOL + "[" + nestedToString(nested) + "]"; - } - } - - private static String nestedToString(Throwable nested) { - if (nested instanceof InvocationTargetException) { - InvocationTargetException ite = (InvocationTargetException) nested; - return nested.toString() + " - with target exception:" + - EOL + "[" + ite.getTargetException().toString() + - "]"; - } - return nested.toString(); - } - - /** - * Prints the stack trace associated with this exception and - * its nested exception. - * - * @param s PrintStream - */ - public static void printStackTrace(NestedThrowable nt, PrintStream s) { - Throwable nested = nt.getNested(); - if (nested != null) { - nested.printStackTrace(s); - s.println("--------------- nested within: ------------------"); - } - nt.superPrintStackTrace(s); - } - - /** - * Prints the stack trace associated with this exception and - * its nested exception. - * - * @param w PrintWriter - */ - public static void printStackTrace(NestedThrowable nt, PrintWriter w) { - Throwable nested = nt.getNested(); - if (nested != null) { - nested.printStackTrace(w); - w.println("--------------- nested within: ------------------"); - } - nt.superPrintStackTrace(w); - } - } - -} diff --git a/src/xmlpublic/org/apache/xmlbeans/BindingConfig.java b/src/xmlpublic/org/apache/xmlbeans/BindingConfig.java deleted file mode 100755 index 85efd0e..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/BindingConfig.java +++ /dev/null @@ -1,106 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; - -/** - * The BindingConfig class is used during compilation to control the generation of java source files. - * The default BindingConfig does nothing, but sub-classes should provide more interesting behavior. - * - * @see XmlBeans#compileXmlBeans(String, SchemaTypeSystem, XmlObject[], BindingConfig, SchemaTypeLoader, Filer, XmlOptions) XmlBeans.compileXmlBeans() - */ -public class BindingConfig -{ - private static final InterfaceExtension[] EMPTY_INTERFACE_EXT_ARRAY = new InterfaceExtension[0]; - private static final PrePostExtension[] EMPTY_PREPOST_EXT_ARRAY = new PrePostExtension[0]; - private static final UserType[] EMPTY_USER_TYPE_ARRY = new UserType[0]; - - public static final int QNAME_TYPE = 1; - public static final int QNAME_DOCUMENT_TYPE = 2; - public static final int QNAME_ACCESSOR_ELEMENT = 3; - public static final int QNAME_ACCESSOR_ATTRIBUTE = 4; - - /** - * @param uri the namespace uri - * @return the package name for a namespace or null. - */ - public String lookupPackageForNamespace(String uri) { return null; } - - /** - * @param uri the namespace uri - * @return the prefix applied to each java name for a namespace or null. - */ - public String lookupPrefixForNamespace(String uri) { return null; } - - /** - * @param uri the namespace uri - * @return Get the suffix applied to each java name for a namespace or null. - */ - public String lookupSuffixForNamespace(String uri) { return null; } - - /** - * @param qname the qname of the java name - * @return the java name for a QName or null. - * @deprecated replaced with {@link #lookupJavanameForQName(QName, int)} - */ - public String lookupJavanameForQName(QName qname) { return null; } - - /** - * @param qname the qname of the java name - * @param kind the type of the qname, which one of {@link #QNAME_TYPE}, {@link #QNAME_DOCUMENT_TYPE}, - * {@link #QNAME_ACCESSOR_ELEMENT}, {@link #QNAME_ACCESSOR_ATTRIBUTE} - * - * @return Get the java name for a QName of a specific component kind, or null. - */ - public String lookupJavanameForQName(QName qname, int kind) { return null; } - - /** - * @return all configured InterfaceExtensions or an empty array. - */ - public InterfaceExtension[] getInterfaceExtensions() { return EMPTY_INTERFACE_EXT_ARRAY; } - - /** - * @param fullJavaName the fully qualified java type name - * @return all InterfaceExtensions defined for the fully qualified java - * type generated from schema compilation or an empty array. - */ - public InterfaceExtension[] getInterfaceExtensions(String fullJavaName) { return EMPTY_INTERFACE_EXT_ARRAY; } - - /** - * @return all configued PrePostExtensions or an empty array. - */ - public PrePostExtension[] getPrePostExtensions() { return EMPTY_PREPOST_EXT_ARRAY; } - - /** - * @param fullJavaName the fully qualified java type name - * @return the PrePostExtension defined for the fully qualified java - * type generated from schema compilation or null. - */ - public PrePostExtension getPrePostExtension(String fullJavaName) { return null; } - - /** - * @return all defined user types. - */ - public UserType[] getUserTypes() { return EMPTY_USER_TYPE_ARRY; } - - /** - * @param qname the qname of the user type - * @return a user defined Java type for a given QName. - */ - public UserType lookupUserTypeForQName(QName qname) { return null; } - -} diff --git a/src/xmlpublic/org/apache/xmlbeans/FilterXmlObject.java b/src/xmlpublic/org/apache/xmlbeans/FilterXmlObject.java deleted file mode 100644 index 7f2b667..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/FilterXmlObject.java +++ /dev/null @@ -1,812 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -import java.io.InputStream; -import java.io.Reader; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.math.BigInteger; -import java.math.BigDecimal; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.w3c.dom.Node; -import org.xml.sax.ContentHandler; -import org.xml.sax.SAXException; -import org.xml.sax.ext.LexicalHandler; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamReader; - -/** - * A FilterXmlObject delegates to some other XmlObject, which it can use as - * its basic source of data, possibly transforming the data along the way or - * providing additional functionality. The class FilterXmlObject itself - * simply overrides all methods of XmlObject with versions that pass all - * requests to the underlying XmlObject. Subclasses of FilterXmlObject may - * further override some of these methods and may also provide additional - * methods and fields. - *

      - * Note: it is important that FilterXmlObject has no storage (i.e., no - * non-transient fields), because subclasses may be serializable and - * adding storage would break the serialization format. - */ -public abstract class FilterXmlObject implements XmlObject, SimpleValue, DelegateXmlObject -{ - public SchemaType schemaType() - { - return underlyingXmlObject().schemaType(); - } - - public boolean validate() - { - return underlyingXmlObject().validate(); - } - - public boolean validate(XmlOptions options) - { - return underlyingXmlObject().validate(options); - } - - public XmlObject[] selectPath(String path) - { - return underlyingXmlObject().selectPath(path); - } - - public XmlObject[] selectPath(String path, XmlOptions options) - { - return underlyingXmlObject().selectPath(path, options); - } - - public XmlObject[] execQuery(String query) - { - return underlyingXmlObject().execQuery(query); - } - - public XmlObject[] execQuery(String query, XmlOptions options) - { - return underlyingXmlObject().execQuery(query, options); - } - - public XmlObject changeType(SchemaType newType) - { - return underlyingXmlObject().changeType(newType); - } - - public boolean isNil() - { - return underlyingXmlObject().isNil(); - } - - public void setNil() - { - underlyingXmlObject().setNil(); - } - - public boolean isImmutable() - { - return underlyingXmlObject().isImmutable(); - } - - public XmlObject set(XmlObject srcObj) - { - return underlyingXmlObject().set(srcObj); - } - - public XmlObject copy() - { - return underlyingXmlObject().copy(); - } - - public XmlObject copy(XmlOptions options) - { - return underlyingXmlObject().copy(options); - } - - public boolean valueEquals(XmlObject obj) - { - return underlyingXmlObject().valueEquals(obj); - } - - public int valueHashCode() - { - return underlyingXmlObject().valueHashCode(); - } - - public int compareTo(Object obj) - { - return underlyingXmlObject().compareTo(obj); - } - - public int compareValue(XmlObject obj) - { - return underlyingXmlObject().compareValue(obj); - } - - public Object monitor() - { - return underlyingXmlObject().monitor(); - } - - public XmlDocumentProperties documentProperties() - { - return underlyingXmlObject().documentProperties(); - } - - public XmlCursor newCursor() - { - return underlyingXmlObject().newCursor(); - } - - /** - * @deprecated Deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newXMLInputStream() - { - return underlyingXmlObject().newXMLInputStream(); - } - - public XMLStreamReader newXMLStreamReader() - { - return underlyingXmlObject().newXMLStreamReader(); - } - - public String xmlText() - { - return underlyingXmlObject().xmlText(); - } - - public InputStream newInputStream() - { - return underlyingXmlObject().newInputStream(); - } - - public Reader newReader() - { - return underlyingXmlObject().newReader(); - } - - public Node newDomNode() - { - return underlyingXmlObject().newDomNode(); - } - - public Node getDomNode() - { - return underlyingXmlObject().getDomNode(); - } - - public void save(ContentHandler ch, LexicalHandler lh) throws SAXException - { - underlyingXmlObject().save(ch, lh); - } - - public void save(File file) throws IOException - { - underlyingXmlObject().save(file); - } - - public void save(OutputStream os) throws IOException - { - underlyingXmlObject().save(os); - } - - public void save(Writer w) throws IOException - { - underlyingXmlObject().save(w); - } - - /** - * @deprecated Deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newXMLInputStream(XmlOptions options) - { - return underlyingXmlObject().newXMLInputStream(options); - } - - public XMLStreamReader newXMLStreamReader(XmlOptions options) - { - return underlyingXmlObject().newXMLStreamReader(options); - } - - public String xmlText(XmlOptions options) - { - return underlyingXmlObject().xmlText(options); - } - - public InputStream newInputStream(XmlOptions options) - { - return underlyingXmlObject().newInputStream(options); - } - - public Reader newReader(XmlOptions options) - { - return underlyingXmlObject().newReader(options); - } - - public Node newDomNode(XmlOptions options) - { - return underlyingXmlObject().newDomNode(options); - } - - public void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException - { - underlyingXmlObject().save(ch, lh, options); - } - - public void save(File file, XmlOptions options) throws IOException - { - underlyingXmlObject().save(file, options); - } - - public void save(OutputStream os, XmlOptions options) throws IOException - { - underlyingXmlObject().save(os, options); - } - - public void save(Writer w, XmlOptions options) throws IOException - { - underlyingXmlObject().save(w, options); - } - - public SchemaType instanceType() - { - return ((SimpleValue)underlyingXmlObject()).instanceType(); - } - - /** - * @deprecated replaced with {@link #getStringValue} - */ - public String stringValue() - { - return ((SimpleValue)underlyingXmlObject()).stringValue(); - } - - /** - * @deprecated replaced with {@link #getBooleanValue} - */ - public boolean booleanValue() - { - return ((SimpleValue)underlyingXmlObject()).booleanValue(); - } - - /** - * @deprecated replaced with {@link #getByteValue} - */ - public byte byteValue() - { - return ((SimpleValue)underlyingXmlObject()).byteValue(); - } - - /** - * @deprecated replaced with {@link #getShortValue} - */ - public short shortValue() - { - return ((SimpleValue)underlyingXmlObject()).shortValue(); - } - - /** - * @deprecated replaced with {@link #getIntValue} - */ - public int intValue() - { - return ((SimpleValue)underlyingXmlObject()).intValue(); - } - - /** - * @deprecated replaced with {@link #getLongValue} - */ - public long longValue() - { - return ((SimpleValue)underlyingXmlObject()).longValue(); - } - - /** - * @deprecated replaced with {@link #getBigIntegerValue} - */ - public BigInteger bigIntegerValue() - { - return ((SimpleValue)underlyingXmlObject()).bigIntegerValue(); - } - - /** - * @deprecated replaced with {@link #getBigDecimalValue} - */ - public BigDecimal bigDecimalValue() - { - return ((SimpleValue)underlyingXmlObject()).bigDecimalValue(); - } - - /** - * @deprecated replaced with {@link #getFloatValue} - */ - public float floatValue() - { - return ((SimpleValue)underlyingXmlObject()).floatValue(); - } - - /** - * @deprecated replaced with {@link #getDoubleValue} - */ - public double doubleValue() - { - return ((SimpleValue)underlyingXmlObject()).doubleValue(); - } - - /** - * @deprecated replaced with {@link #getByteArrayValue} - */ - public byte[] byteArrayValue() - { - return ((SimpleValue)underlyingXmlObject()).byteArrayValue(); - } - - /** - * @deprecated replaced with {@link #getEnumValue} - */ - public StringEnumAbstractBase enumValue() - { - return ((SimpleValue)underlyingXmlObject()).enumValue(); - } - - /** - * @deprecated replaced with {@link #getCalendarValue} - */ - public Calendar calendarValue() - { - return ((SimpleValue)underlyingXmlObject()).calendarValue(); - } - - /** - * @deprecated replaced with {@link #getDateValue} - */ - public Date dateValue() - { - return ((SimpleValue)underlyingXmlObject()).dateValue(); - } - - /** - * @deprecated replaced with {@link #getGDateValue} - */ - public GDate gDateValue() - { - return ((SimpleValue)underlyingXmlObject()).gDateValue(); - } - - /** - * @deprecated replaced with {@link #getGDurationValue} - */ - public GDuration gDurationValue() - { - return ((SimpleValue)underlyingXmlObject()).gDurationValue(); - } - - /** - * @deprecated replaced with {@link #getQNameValue} - */ - public QName qNameValue() - { - return ((SimpleValue)underlyingXmlObject()).qNameValue(); - } - - /** - * @deprecated replaced with {@link #getListValue} - */ - public List listValue() - { - return ((SimpleValue)underlyingXmlObject()).listValue(); - } - - /** - * @deprecated replaced with {@link #getListValue} - */ - public List xlistValue() - { - return ((SimpleValue)underlyingXmlObject()).xlistValue(); - } - - /** - * @deprecated replaced with {@link #getObjectValue} - */ - public Object objectValue() - { - return ((SimpleValue)underlyingXmlObject()).objectValue(); - } - - /** - * @deprecated replaced with {@link #setStringValue} - */ - public void set(String obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setBooleanValue} - */ - public void set(boolean v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setByteValue} - */ - public void set(byte v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setShortValue} - */ - public void set(short v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setIntValue} - */ - public void set(int v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setLongValue} - */ - public void set(long v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setBigIntegerValue} - */ - public void set(BigInteger obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setBigDecimalValue} - */ - public void set(BigDecimal obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setFloatValue} - */ - public void set(float v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setDoubleValue} - */ - public void set(double v) - { - ((SimpleValue)underlyingXmlObject()).set(v); - } - - /** - * @deprecated replaced with {@link #setByteArrayValue} - */ - public void set(byte[] obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setEnumValue} - */ - public void set(StringEnumAbstractBase obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setCalendarValue} - */ - public void set(Calendar obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setDateValue} - */ - public void set(Date obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setGDateValue} - */ - public void set(GDateSpecification obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setGDurationValue} - */ - public void set(GDurationSpecification obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setQNameValue} - */ - public void set(QName obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - /** - * @deprecated replaced with {@link #setListValue} - */ - public void set(List obj) - { - ((SimpleValue)underlyingXmlObject()).set(obj); - } - - public String getStringValue() - { - return ((SimpleValue)underlyingXmlObject()).getStringValue(); - } - - public boolean getBooleanValue() - { - return ((SimpleValue)underlyingXmlObject()).getBooleanValue(); - } - - public byte getByteValue() - { - return ((SimpleValue)underlyingXmlObject()).getByteValue(); - } - - public short getShortValue() - { - return ((SimpleValue)underlyingXmlObject()).getShortValue(); - } - - public int getIntValue() - { - return ((SimpleValue)underlyingXmlObject()).getIntValue(); - } - - public long getLongValue() - { - return ((SimpleValue)underlyingXmlObject()).getLongValue(); - } - - public BigInteger getBigIntegerValue() - { - return ((SimpleValue)underlyingXmlObject()).getBigIntegerValue(); - } - - public BigDecimal getBigDecimalValue() - { - return ((SimpleValue)underlyingXmlObject()).getBigDecimalValue(); - } - - public float getFloatValue() - { - return ((SimpleValue)underlyingXmlObject()).getFloatValue(); - } - - public double getDoubleValue() - { - return ((SimpleValue)underlyingXmlObject()).getDoubleValue(); - } - - public byte[] getByteArrayValue() - { - return ((SimpleValue)underlyingXmlObject()).getByteArrayValue(); - } - - public StringEnumAbstractBase getEnumValue() - { - return ((SimpleValue)underlyingXmlObject()).getEnumValue(); - } - - public Calendar getCalendarValue() - { - return ((SimpleValue)underlyingXmlObject()).getCalendarValue(); - } - - public Date getDateValue() - { - return ((SimpleValue)underlyingXmlObject()).getDateValue(); - } - - public GDate getGDateValue() - { - return ((SimpleValue)underlyingXmlObject()).getGDateValue(); - } - - public GDuration getGDurationValue() - { - return ((SimpleValue)underlyingXmlObject()).getGDurationValue(); - } - - public QName getQNameValue() - { - return ((SimpleValue)underlyingXmlObject()).getQNameValue(); - } - - public List getListValue() - { - return ((SimpleValue)underlyingXmlObject()).getListValue(); - } - - public List xgetListValue() - { - return ((SimpleValue)underlyingXmlObject()).xgetListValue(); - } - - public Object getObjectValue() - { - return ((SimpleValue)underlyingXmlObject()).getObjectValue(); - } - - public void setStringValue(String obj) - { - ((SimpleValue)underlyingXmlObject()).setStringValue(obj); - } - - public void setBooleanValue(boolean v) - { - ((SimpleValue)underlyingXmlObject()).setBooleanValue(v); - } - - public void setByteValue(byte v) - { - ((SimpleValue)underlyingXmlObject()).setByteValue(v); - } - - public void setShortValue(short v) - { - ((SimpleValue)underlyingXmlObject()).setShortValue(v); - } - - public void setIntValue(int v) - { - ((SimpleValue)underlyingXmlObject()).setIntValue(v); - } - - public void setLongValue(long v) - { - ((SimpleValue)underlyingXmlObject()).setLongValue(v); - } - - public void setBigIntegerValue(BigInteger obj) - { - ((SimpleValue)underlyingXmlObject()).setBigIntegerValue(obj); - } - - public void setBigDecimalValue(BigDecimal obj) - { - ((SimpleValue)underlyingXmlObject()).setBigDecimalValue(obj); - } - - public void setFloatValue(float v) - { - ((SimpleValue)underlyingXmlObject()).setFloatValue(v); - } - - public void setDoubleValue(double v) - { - ((SimpleValue)underlyingXmlObject()).setDoubleValue(v); - } - - public void setByteArrayValue(byte[] obj) - { - ((SimpleValue)underlyingXmlObject()).setByteArrayValue(obj); - } - - public void setEnumValue(StringEnumAbstractBase obj) - { - ((SimpleValue)underlyingXmlObject()).setEnumValue(obj); - } - - public void setCalendarValue(Calendar obj) - { - ((SimpleValue)underlyingXmlObject()).setCalendarValue(obj); - } - - public void setDateValue(Date obj) - { - ((SimpleValue)underlyingXmlObject()).setDateValue(obj); - } - - public void setGDateValue(GDate obj) - { - ((SimpleValue)underlyingXmlObject()).setGDateValue(obj); - } - - public void setGDurationValue(GDuration obj) - { - ((SimpleValue)underlyingXmlObject()).setGDurationValue(obj); - } - - public void setQNameValue(QName obj) - { - ((SimpleValue)underlyingXmlObject()).setQNameValue(obj); - } - - public void setListValue(List obj) - { - ((SimpleValue)underlyingXmlObject()).setListValue(obj); - } - - public void setObjectValue(Object obj) - { - ((SimpleValue)underlyingXmlObject()).setObjectValue(obj); - } - - /** - * @deprecated replaced with {@link #setObjectValue} - **/ - public void objectSet(Object obj) - { - ((SimpleValue)underlyingXmlObject()).objectSet(obj); - } - - public XmlObject[] selectChildren(QName elementName) - { - return underlyingXmlObject().selectChildren(elementName); - } - - public XmlObject[] selectChildren(String elementUri, String elementLocalName) - { - return underlyingXmlObject().selectChildren(elementUri, elementLocalName); - } - - public XmlObject[] selectChildren(QNameSet elementNameSet) - { - return underlyingXmlObject().selectChildren(elementNameSet); - } - - public XmlObject selectAttribute(QName attributeName) - { - return underlyingXmlObject().selectAttribute(attributeName); - } - - public XmlObject selectAttribute(String attributeUri, String attributeLocalName) - { - return underlyingXmlObject().selectAttribute(attributeUri, attributeLocalName); - } - - public XmlObject[] selectAttributes(QNameSet attributeNameSet) - { - return underlyingXmlObject().selectAttributes(attributeNameSet); - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/GDate.java b/src/xmlpublic/org/apache/xmlbeans/GDate.java deleted file mode 100644 index 805967e..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/GDate.java +++ /dev/null @@ -1,1105 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * Represents an XML Schema-compatible Gregorian date. - *

      - * There are many date types in XML Schema, and this type - * represents the natural union of all those types. A GDate - * can hold any subset of date fields (Year, Month, Day, Time, - * Timezone, or some combination). Wherever the specification - * provides guidance, the guidelines in the - * XML Schema 1.0 specification - * (plus published errata) are followed. - *

      - * Instances may separately have values or no values for - * the year, month, day-of-month, and time-of-day. Not all - * operations are meaningful on all combinations. - */ -public final class GDate implements GDateSpecification, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - // XMLSchema spec requires support only for years 1 to 9999, but XMLBeans covers more up to the following limitations - // to avoid losing precision when transforming to a java.util.Date - static final int MAX_YEAR = 292277265; // is Long.MAX_VALUE ms in years - 1 (for the 11month, 31days, 23h, 59m, 59sec case). - static final int MIN_YEAR = -292275295; // is Long.MIN_VALUE ms in years + 1970 + 1 - - // for fast equality comparison, hashing, and serialization - private transient String _canonicalString; - private transient String _string; - - private int _bits; - private int _CY; - private int _M; - private int _D; - private int _h; - private int _m; - private int _s; - private BigDecimal _fs; - private int _tzsign; - private int _tzh; - private int _tzm; - - - /* package */ static final BigDecimal _zero = BigDecimal.valueOf(0); - /* package */ static final BigDecimal _one = BigDecimal.valueOf(1); - - /** - * Constructs a GDate based on a lexical representation. - */ - public GDate(CharSequence string) - { - // first trim XML whitespace - int len = string.length(); - int start = 0; - while (len > 0 && isSpace(string.charAt(len - 1))) - len -= 1; - while (start < len && isSpace(string.charAt(start))) - start += 1; - - // pick optional timezone off the end - if (len - start >= 1 && string.charAt(len - 1) == 'Z') - { - _bits |= HAS_TIMEZONE; - len -= 1; - } - else if (len - start >= 6) - timezone: { - int tzsign; - int tzhour; - int tzminute; - - if (string.charAt(len - 3) != ':') - break timezone; - - switch (string.charAt(len - 6)) - { - case '-': - tzsign = -1; break; - case '+': - tzsign = 1; break; - default: - break timezone; - } - - tzhour = twoDigit(string, len - 5); - tzminute = twoDigit(string, len - 2); - if (tzhour > 14) - throw new IllegalArgumentException("time zone hour must be two digits between -14 and +14"); - if (tzminute > 59) - throw new IllegalArgumentException("time zone minute must be two digits between 00 and 59"); - _bits |= HAS_TIMEZONE; - _tzsign = tzsign; - _tzh = tzhour; - _tzm = tzminute; - len -= 6; - } - - // pick date fields off the beginning if it doesn't look like a time - if (start < len && (start + 2 >= len || string.charAt(start + 2) != ':')) - scandate: - { - // parse year sign - boolean negyear = false; - if (start < len && string.charAt(start) == '-') - { - negyear = true; - start += 1; - } - - // scan year digits - int value = 0; - int digits = -start; - char ch; - boolean startsWithZero = start < len && digitVal(string.charAt(start))==0; - - for (;;) - { - ch = start < len ? string.charAt(start) : '\0'; - if (!isDigit(ch)) - break; - - if ( startsWithZero && start+digits>=4 ) - throw new IllegalArgumentException("year value starting with zero must be 4 or less digits: " + string); - - value = value * 10 + digitVal(ch); - start += 1; - } - digits += start; - if (digits > 9) - throw new IllegalArgumentException("year too long (up to 9 digits)"); - else if (digits >= 4) - { - _bits |= HAS_YEAR; - _CY = negyear ? -value : value; - if (_CY == 0) throw new IllegalArgumentException("year must not be zero"); - } - else if (digits > 0) - throw new IllegalArgumentException("year must be four digits (may pad with zeroes, e.g., 0560)"); - - if ( _CY > MAX_YEAR ) - throw new IllegalArgumentException("year value not supported: too big, must be less than " + MAX_YEAR); - - if ( _CY < MIN_YEAR ) - throw new IllegalArgumentException("year values not supported: too small, must be bigger than " + MIN_YEAR); - - // hyphen introduces a month - if (ch != '-') - { - if (negyear && !hasYear()) - throw new IllegalArgumentException(); // a single minus - else - break scandate; - } - start += 1; - - // two-digit month - if (len - start >= 2) - { - value = twoDigit(string, start); - if (value >= 1 && value <= 12) - { - _bits |= HAS_MONTH; - _M = value; - start += 2; - } - } - - // hyphen introduces a day - ch = start < len ? string.charAt(start) : '\0'; - if (ch != '-') - { - if (!hasMonth()) - throw new IllegalArgumentException(); // minus after a year - else - break scandate; - } - start += 1; - - // two-digit day - if (len - start >= 2) - { - value = twoDigit(string, start); - if (value >= 1 && value <= 31) - { - _bits |= HAS_DAY; - _D = value; - start += 2; - } - } - - if (!hasDay()) - { - // error in the original schema spec permits an extra '-' here - if (hasMonth() && !hasYear()) - { - ch = start < len ? string.charAt(start) : '\0'; - if (ch == '-') - { - start += 1; - break scandate; - } - } - throw new IllegalArgumentException(); // minus after a month - } - } - - // time - if (start < len) - { - if (hasYear() || hasMonth() || hasDay()) - { - if (string.charAt(start) != 'T') - throw new IllegalArgumentException("date and time must be separated by 'T'"); - start += 1; - } - - if (len < start + 8 || string.charAt(start + 2) != ':' || string.charAt(start + 5) != ':') - throw new IllegalArgumentException(); - - int h = twoDigit(string, start); - if (h > 24) - throw new IllegalArgumentException("hour must be between 00 and 23"); - int m = twoDigit(string, start + 3); - if (m >= 60) - throw new IllegalArgumentException("minute must be between 00 and 59"); - int s = twoDigit(string, start + 6); - if (s >= 60) - throw new IllegalArgumentException("second must be between 00 and 59"); - - start += 8; - - BigDecimal fs = _zero; - if (start < len) - { - if (string.charAt(start) != '.') - throw new IllegalArgumentException(); - if (start + 1 < len) - { - for (int i = start + 1; i < len; i++) - { - if (!isDigit(string.charAt(i))) - throw new IllegalArgumentException(); - } - try - { - fs = new BigDecimal(string.subSequence(start, len).toString()); - } - catch (Throwable e) - { - throw new IllegalArgumentException(); - } - } - } - - _bits |= HAS_TIME; - _h = h; - _m = m; - _s = s; - _fs = fs; - } - - if ( hasTime() && _h == 24 ) - { - if ( _m != 0 || _s != 0 || _fs.compareTo(_zero) != 0 ) - throw new IllegalArgumentException("if hour is 24, minutes, seconds and fraction must be 0"); - else - { // normalize to next day if it has date or at least has day - if ( hasDate() ) - { - GDateBuilder gdb = new GDateBuilder(_CY, _M, _D, _h, _m, _s, _fs, _tzsign, _tzh, _tzm); - gdb.normalize24h(); - - _D = gdb.getDay(); - _M = gdb.getMonth(); - _CY = gdb.getYear(); - _h = 0; - } - else if ( hasDay() ) // if no date only days increment - { - _D++; - _h = 0; - } - } - } - - if (!isValid()) - throw new IllegalArgumentException("invalid date"); - } - - /** - * Constructs a GDate with the specified year, month, day, - * hours, minutes, seconds, and optional fractional seconds, in - * an unspecified timezone. - *

      - * Note that by not specifying the timezone the GDate - * becomes partially unordered with respect to times that - * do have a specified timezone. - */ - public GDate( - int year, - int month, - int day, - int hour, - int minute, - int second, - BigDecimal fraction) - { - _bits = HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; - - _CY = year; - _M = month; - _D = day; - _h = hour; - _m = minute; - _s = second; - _fs = fraction == null ? _zero : fraction; - - if (!isValid()) - throw new IllegalArgumentException(); - } - - /** - * Constructs an absolute GDate with the specified year, - * month, day, hours, minutes, seconds, and optional fractional - * seconds, and in the timezone specified. - *

      - * If you wish to have a time or date that isn't in a specified timezone, - * then use the constructor that does not include the timezone arguments. - */ - public GDate( - int year, - int month, - int day, - int hour, - int minute, - int second, - BigDecimal fraction, - int tzSign, - int tzHour, - int tzMinute) - { - _bits = HAS_TIMEZONE | HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; - - _CY = year; - _M = month; - _D = day; - _h = hour; - _m = minute; - _s = second; - _fs = fraction == null ? _zero : fraction; - _tzsign = tzSign; - _tzh = tzHour; - _tzm = tzMinute; - - if (!isValid()) - throw new IllegalArgumentException(); - } - - /** - * Constructs a GDate based on a java.util.Date. - *

      - * The current offset of the default timezone is used as the timezone. - *

      - * For example, if eastern daylight time is in effect at the given - * date, the timezone on the east coast of the united states - * translates to GMT-05:00 (EST) + 1:00 (DT offset) == GMT-04:00. - */ - public GDate(Date date) - { - // requires some date math, so ctor lives on GDateBuilder - this(new GDateBuilder(date)); - } - - /** - * Constructs a GDate based on a java.util.Calendar. - *

      - * If the calendar does not have some fields set, the same absence - * of information is reflected in the GDate. Note that - * java.util.GregorianCalendar fills in all fields as soon as any - * are fetched, so constructing a GDate with the same calendar object - * twice may result in a different GDate because of a changed calendar. - * Note that org.apache.xmlbeans.XmlCalendar is stable if you re-get a set field, - * so it does not have the same problem. - */ - public GDate(Calendar calendar) - { - // we must scrape the "isSet" information out before accessing anything - boolean isSetYear = calendar.isSet(Calendar.YEAR); - boolean isSetEra = calendar.isSet(Calendar.ERA); - boolean isSetMonth = calendar.isSet(Calendar.MONTH); - boolean isSetDay = calendar.isSet(Calendar.DAY_OF_MONTH); - boolean isSetHourOfDay = calendar.isSet(Calendar.HOUR_OF_DAY); - boolean isSetHour = calendar.isSet(Calendar.HOUR); - boolean isSetAmPm = calendar.isSet(Calendar.AM_PM); - boolean isSetMinute = calendar.isSet(Calendar.MINUTE); - boolean isSetSecond = calendar.isSet(Calendar.SECOND); - boolean isSetMillis = calendar.isSet(Calendar.MILLISECOND); - boolean isSetZone = calendar.isSet(Calendar.ZONE_OFFSET); - boolean isSetDst = calendar.isSet(Calendar.DST_OFFSET); - - if (isSetYear) - { - int y = calendar.get(Calendar.YEAR); - if (isSetEra && calendar instanceof GregorianCalendar) - if (calendar.get(Calendar.ERA) == GregorianCalendar.BC) - y = -y; //1 - y; - _bits |= HAS_YEAR; - _CY = y; - } - if (isSetMonth) - { - _bits |= HAS_MONTH; - _M = calendar.get(Calendar.MONTH) + 1; // !!note - } - if (isSetDay) - { - _bits |= HAS_DAY; - _D = calendar.get(Calendar.DAY_OF_MONTH); - } - boolean gotTime = false; - - int h = 0; - int m = 0; - int s = 0; - BigDecimal fs = _zero; - - if (isSetHourOfDay) - { - h = calendar.get(Calendar.HOUR_OF_DAY); - gotTime = true; - } - else if (isSetHour && isSetAmPm) - { - h = calendar.get(Calendar.HOUR) + calendar.get(Calendar.AM_PM) * 12; - gotTime = true; - } - - if (isSetMinute) - { - m = calendar.get(Calendar.MINUTE); - gotTime = true; - } - - if (isSetSecond) - { - s = calendar.get(Calendar.SECOND); - gotTime = true; - } - - if (isSetMillis) - { - fs = BigDecimal.valueOf(calendar.get(Calendar.MILLISECOND), 3); - gotTime = true; - } - - if (gotTime) - { - _bits |= HAS_TIME; - _h = h; - _m = m; - _s = s; - _fs = fs; - } - - if (isSetZone) - { - int zoneOffsetInMilliseconds = calendar.get(Calendar.ZONE_OFFSET); - if (isSetDst) - zoneOffsetInMilliseconds += calendar.get(Calendar.DST_OFFSET); - - _bits |= HAS_TIMEZONE; - if (zoneOffsetInMilliseconds == 0) - { - _tzsign = 0; - _tzh = 0; - _tzm = 0; - TimeZone zone = calendar.getTimeZone(); - String id = zone.getID(); - if (id != null && id.length() > 3) switch (id.charAt(3)) - { - case '+': _tzsign = 1; break; // GMT+00:00 - case '-': _tzsign = -1; break; // GMT-00:00 - } - } - else - { - _tzsign = (zoneOffsetInMilliseconds < 0 ? -1 : +1); - zoneOffsetInMilliseconds = zoneOffsetInMilliseconds * _tzsign; - _tzh = zoneOffsetInMilliseconds / 3600000; - _tzm = (zoneOffsetInMilliseconds - _tzh * 3600000) / 60000; - } - } - } - - /** - * Constructs a GDate based on another GDateSpecification. - */ - public GDate(GDateSpecification gdate) - { - if (gdate.hasTimeZone()) - { - _bits |= HAS_TIMEZONE; - _tzsign = gdate.getTimeZoneSign(); - _tzh = gdate.getTimeZoneHour(); - _tzm = gdate.getTimeZoneMinute(); - } - - if (gdate.hasTime()) - { - _bits |= HAS_TIME; - _h = gdate.getHour(); - _m = gdate.getMinute(); - _s = gdate.getSecond(); - _fs = gdate.getFraction(); - } - - if (gdate.hasDay()) - { - _bits |= HAS_DAY; - _D = gdate.getDay(); - } - - if (gdate.hasMonth()) - { - _bits |= HAS_MONTH; - _M = gdate.getMonth(); - } - - if (gdate.hasYear()) - { - _bits |= HAS_YEAR; - _CY = gdate.getYear(); - } - } - - /* package */ static final boolean isDigit(char ch) - { - return ((char)(ch - '0') <= '9' - '0'); // char is unsigned - } - - /* package */ static final boolean isSpace(char ch) - { - switch (ch) - { - case ' ': - case '\t': - case '\r': - case '\n': - return true; - default: - return false; - } - } - - /* package */ static final int digitVal(char ch) - { - return (ch - '0'); - } - - private static final int twoDigit(CharSequence str, int index) - { - char ch1 = str.charAt(index); - char ch2 = str.charAt(index + 1); - if (!isDigit(ch1) || !isDigit(ch2)) - return 100; // not two digits - return digitVal(ch1) * 10 + digitVal(ch2); - } - - /** - * Returns true: all GDate instances are immutable. - */ - public final boolean isImmutable() - { - return true; - } - - /** - * Returns a combination of flags indicating the information - * contained by this GDate. The five flags are - * HAS_TIMEZONE, HAS_YEAR, HAS_MONTH, HAS_DAY, and HAS_TIME. - */ - public int getFlags() - { - return _bits; - } - - /** - * True if this date/time specification specifies a timezone. - */ - public final boolean hasTimeZone() - { return ((_bits & HAS_TIMEZONE) != 0); } - - /** - * True if this date/time specification specifies a year. - */ - public final boolean hasYear() - { return ((_bits & HAS_YEAR) != 0); } - - /** - * True if this date/time specification specifies a month-of-year. - */ - public final boolean hasMonth() - { return ((_bits & HAS_MONTH) != 0); } - - /** - * True if this date/time specification specifies a day-of-month. - */ - public final boolean hasDay() - { return ((_bits & HAS_DAY) != 0); } - - /** - * True if this date/time specification specifies a time-of-day. - */ - public final boolean hasTime() - { return ((_bits & HAS_TIME) != 0); } - - /** - * True if this date/time specification specifies a full date (year, month, day) - */ - public final boolean hasDate() - { return ((_bits & (HAS_DAY | HAS_MONTH | HAS_YEAR)) == (HAS_DAY | HAS_MONTH | HAS_YEAR)); } - - /** - * Gets the year. Should be a four-digit year specification. - */ - public final int getYear() - { return _CY; } - - /** - * Gets the month-of-year. January is 1. - */ - public final int getMonth() - { return _M; } - - /** - * Gets the day-of-month. The first day of each month is 1. - */ - public final int getDay() - { return _D; } - - /** - * Gets the hour-of-day. Midnight is 0, and 11PM is 23. - */ - public final int getHour() - { return _h; } - - /** - * Gets the minute-of-hour. Range from 0 to 59. - */ - public final int getMinute() - { return _m; } - - /** - * Gets the second-of-minute. Range from 0 to 59. - */ - public final int getSecond() - { return _s; } - - /** - * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). - */ - public final BigDecimal getFraction() - { return _fs; } - - /** - * Gets the time zone sign. For time zones east of GMT, - * this is positive; for time zones west, this is negative. - */ - public final int getTimeZoneSign() - { return _tzsign; } - - /** - * Gets the time zone hour. - * - * This is always positive: for the sign, look at - * getTimeZoneSign(). - */ - public final int getTimeZoneHour() - { return _tzh; } - - /** - * Gets the time zone minutes. - * - * This is always positive: for the sign, look at - * getTimeZoneSign(). - */ - public final int getTimeZoneMinute() - { return _tzm; } - - /** - * Gets the rounded millisecond value. Range from 0 to 999 - */ - public int getMillisecond() - { - if (_fs == null) - return 0; - return _fs.setScale(3, BigDecimal.ROUND_DOWN).unscaledValue().intValue(); - } - - /** - * The canonical string representation. Specific moments or - * times-of-day in a specified timezone are normalized to - * UTC time to produce a canonical string form for them. - * Other recurring time specifications keep their timezone - * information. - */ - public String canonicalString() - { - ensureCanonicalString(); - return _canonicalString; - } - - /** - * True if this GDate corresponds to a valid gregorian date value - * in XML schema. - */ - public boolean isValid() - { - return GDateBuilder.isValidGDate(this); - } - - /** - * Returns the Julian date corresponding to this Gregorian date. - * The Julian date (JD) is a continuous count of days from - * 1 January 4713 BC. - */ - public int getJulianDate() - { - return GDateBuilder.julianDateForGDate(this); - } - - /** - * Retrieves the value of the current time as an {@link XmlCalendar}. - *

      - * {@link XmlCalendar} is a subclass of {@link java.util.GregorianCalendar} - * which is slightly customized to match XML schema date rules. - *

      - * The returned {@link XmlCalendar} has only those time and date fields - * set that are reflected in the GDate object. Because of the way the - * {@link java.util.Calendar} contract works, any information in the isSet() vanishes - * as soon as you view any unset field using get() methods. - * This means that if it is important to understand which date fields - * are set, you must call isSet() first before get(). - */ - public XmlCalendar getCalendar() - { - return new XmlCalendar(this); - } - - - /** - * Retrieves the value of the current time as a java.util.Date - * instance. - */ - public Date getDate() - { - return GDateBuilder.dateForGDate(this); - } - - /** - * Comparison to another GDate. - *

        - *
      • Returns -1 if this < date. (less-than) - *
      • Returns 0 if this == date. (equal) - *
      • Returns 1 if this > date. (greater-than) - *
      • Returns 2 if this <> date. (incomparable) - *
      - * Two instances are incomparable if they have different amounts - * of information. - */ - public int compareToGDate(GDateSpecification datespec) - { - return GDateBuilder.compareGDate(this, datespec); - } - - /** - * Returns the builtin type code for the shape of the information - * contained in this instance, or 0 if the - * instance doesn't contain information corresponding to a - * Schema type. - *

      - * Value will be equal to - * {@link SchemaType#BTC_NOT_BUILTIN}, - * {@link SchemaType#BTC_G_YEAR}, - * {@link SchemaType#BTC_G_YEAR_MONTH}, - * {@link SchemaType#BTC_G_MONTH}, - * {@link SchemaType#BTC_G_MONTH_DAY}, - * {@link SchemaType#BTC_G_DAY}, - * {@link SchemaType#BTC_DATE}, - * {@link SchemaType#BTC_DATE_TIME}, or - * {@link SchemaType#BTC_TIME}. - */ - public int getBuiltinTypeCode() - { - return GDateBuilder.btcForFlags(_bits); - } - - /** - * Adds a duration to this GDate, and returns a new GDate. - */ - public GDate add(GDurationSpecification duration) - { - GDateBuilder builder = new GDateBuilder(this); - builder.addGDuration(duration); - return builder.toGDate(); - } - - /** - * Adds a duration to this GDate, and returns a new GDate. - */ - public GDate subtract(GDurationSpecification duration) - { - GDateBuilder builder = new GDateBuilder(this); - builder.subtractGDuration(duration); - return builder.toGDate(); - } - - /** - * GDate is an immutable class, and equality is computed based - * on its canonical value. - */ - public boolean equals(Object obj) - { - if (obj == this) - return true; - if (!(obj instanceof GDate)) - return false; - - ensureCanonicalString(); - return _canonicalString.equals(((GDate)obj).canonicalString()); - } - - /** - * Returns a hash code for this GDate. - */ - public int hashCode() - { - ensureCanonicalString(); - return _canonicalString.hashCode(); - } - - /** - * The canonical string representation. Specific moments or - * times-of-day in a specified timezone are normalized to - * UTC time to produce a canonical string form for them. - * Other recurring time specifications keep their timezone - * information. - */ - private void ensureCanonicalString() - { - if (_canonicalString != null) - return; - - boolean needNormalize = - (hasTimeZone() && getTimeZoneSign() != 0 && hasTime() && - ((hasDay() == hasMonth() && hasDay() == hasYear()))); - - if (!needNormalize && getFraction() != null && getFraction().scale() > 0) - { - BigInteger bi = getFraction().unscaledValue(); - needNormalize = (bi.mod(GDateBuilder.TEN).signum() == 0); - } - - if (!needNormalize) - _canonicalString = toString(); - else - { - GDateBuilder gdb = new GDateBuilder(this); - gdb.normalize(); - _canonicalString = gdb.toString(); - } - } - - /** - * The natural string representation. This represents the information - * that is available, including timezone. For types that correspond - * to defined schema types (schemaBuiltinTypeCode() > 0), - * this provides the natural lexical representation. - *

      - * When both time and timezone are specified, this string is not - * the canonical representation unless the timezone is UTC (Z) - * (since the same moment in time can be expressed in different - * timezones). To get a canonical string, use the canonicalString() - * method. - */ - public String toString() - { - if (_string == null) - _string = formatGDate(this); - return _string; - } - - private final static char[] _tensDigit = - { - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', - '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', - '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', - '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', - '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', - '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', - '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', - '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', - '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', - }; - private final static char[] _onesDigit = - { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - }; - - private static final int _padTwoAppend(char[] b, int i, int n) - { - assert(n >= 0 && n < 100); - b[i] = _tensDigit[n]; - b[i + 1] = _onesDigit[n]; - return i + 2; - } - - private static final int _padFourAppend(char[] b, int i, int n) - { - if (n < 0) - { - b[i++] = '-'; - n = -n; - } - if (n >= 10000) - { - String s = Integer.toString(n); - s.getChars(0, s.length(), b, i); - return i + s.length(); - } - int q = n / 100; - int r = n - q * 100; - b[i] = _tensDigit[q]; - b[i + 1] = _onesDigit[q]; - b[i + 2] = _tensDigit[r]; - b[i + 3] = _onesDigit[r]; - return i + 4; - } - - private static final TimeZone GMTZONE = TimeZone.getTimeZone("GMT"); - private static final TimeZone[] MINUSZONE = - { - TimeZone.getTimeZone("GMT-00:00"), - TimeZone.getTimeZone("GMT-01:00"), - TimeZone.getTimeZone("GMT-02:00"), - TimeZone.getTimeZone("GMT-03:00"), - TimeZone.getTimeZone("GMT-04:00"), - TimeZone.getTimeZone("GMT-05:00"), - TimeZone.getTimeZone("GMT-06:00"), - TimeZone.getTimeZone("GMT-07:00"), - TimeZone.getTimeZone("GMT-08:00"), - TimeZone.getTimeZone("GMT-09:00"), - TimeZone.getTimeZone("GMT-10:00"), - TimeZone.getTimeZone("GMT-11:00"), - TimeZone.getTimeZone("GMT-12:00"), - TimeZone.getTimeZone("GMT-13:00"), - TimeZone.getTimeZone("GMT-14:00"), - }; - private static final TimeZone[] PLUSZONE = - { - TimeZone.getTimeZone("GMT+00:00"), - TimeZone.getTimeZone("GMT+01:00"), - TimeZone.getTimeZone("GMT+02:00"), - TimeZone.getTimeZone("GMT+03:00"), - TimeZone.getTimeZone("GMT+04:00"), - TimeZone.getTimeZone("GMT+05:00"), - TimeZone.getTimeZone("GMT+06:00"), - TimeZone.getTimeZone("GMT+07:00"), - TimeZone.getTimeZone("GMT+08:00"), - TimeZone.getTimeZone("GMT+09:00"), - TimeZone.getTimeZone("GMT+10:00"), - TimeZone.getTimeZone("GMT+11:00"), - TimeZone.getTimeZone("GMT+12:00"), - TimeZone.getTimeZone("GMT+13:00"), - TimeZone.getTimeZone("GMT+14:00"), - }; - - /* package */ static final TimeZone timeZoneForGDate(GDateSpecification date) - { - // use a cached timezone if integral; otherwise make a new one. - if (!date.hasTimeZone()) - return TimeZone.getDefault(); - if (date.getTimeZoneSign() == 0) - return GMTZONE; - if (date.getTimeZoneMinute() == 0 && date.getTimeZoneHour() <= 14 && date.getTimeZoneHour() >= 0) - return date.getTimeZoneSign() < 0 ? MINUSZONE[date.getTimeZoneHour()] : PLUSZONE[date.getTimeZoneHour()]; - - char[] zb = new char[9]; - zb[0] = 'G'; - zb[1] = 'M'; - zb[2] = 'T'; - zb[3] = (date.getTimeZoneSign() < 0) ? '-' : '+'; - GDate._padTwoAppend(zb, 4, date.getTimeZoneHour()); - zb[6] = ':'; - GDate._padTwoAppend(zb, 7, date.getTimeZoneMinute()); - return TimeZone.getTimeZone(new String(zb)); - } - - /* package */ static String formatGDate(GDateSpecification spec) - { - // We've used a char[] rather than a StringBuffer for a 4x speedup - // -YY(10)YY-MM-DDTHH:MM:SS.FFFFFF+ZH:ZM - // 1 + 10 + 3+ 3+ 3+ 3+ 3+1 + s + 3+ 3 = 33 + s - BigDecimal fs = spec.getFraction(); - char[] message = new char[33 + (fs == null ? 0 : fs.scale())]; - int i = 0; - - if (spec.hasYear() || spec.hasMonth() || spec.hasDay()) - { - dmy: { - if (spec.hasYear()) - i = _padFourAppend(message, 0, spec.getYear()); - else - message[i++] = '-'; - - if (!(spec.hasMonth() || spec.hasDay())) - break dmy; - - message[i++] = '-'; - if (spec.hasMonth()) - i = _padTwoAppend(message, i, spec.getMonth()); - - if (!spec.hasDay()) - break dmy; - - message[i++] = '-'; - i = _padTwoAppend(message, i, spec.getDay()); - break dmy; - } - if (spec.hasTime()) - message[i++] = 'T'; - } - - if (spec.hasTime()) - { - i = _padTwoAppend(message, i, spec.getHour()); - message[i++] = ':'; - i = _padTwoAppend(message, i, spec.getMinute()); - message[i++] = ':'; - i = _padTwoAppend(message, i, spec.getSecond()); - if (fs != _zero) // (optimization ~3%) - { - String frac = fs.toString(); - int point = frac.indexOf('.'); - if (point >= 0) - { - frac.getChars(point, frac.length(), message, i); - i += frac.length() - point; - } - } - } - - if (spec.hasTimeZone()) - { - if (spec.getTimeZoneSign() == 0) - { - message[i++] = 'Z'; - } - else - { - message[i++] = spec.getTimeZoneSign() > 0 ? '+' : '-'; - i = _padTwoAppend(message, i, spec.getTimeZoneHour()); - message[i++] = ':'; - i = _padTwoAppend(message, i, spec.getTimeZoneMinute()); - } - } - - // it would be nice to use (0, i, message) ctor instead - return new String(message, 0, i); - } - -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java b/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java deleted file mode 100644 index 53fdcbe..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java +++ /dev/null @@ -1,1503 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -/** - * Used to build {@link GDate GDates}. - *

      - * Like GDate, a GDateBuilder represents an Gregorian Date, Time, - * and Timezone, or subset of information (Year, Month, Day, - * Time, Timezone, or some combination). Wherever it provides - * guidance, the XML Schema 1.0 specification (plus published - * errata) is followed. - *

      - * Instances may separately set or clear the year, month, - * day-of-month, and time-of-day. Not all operations are - * meaningful on all combinations. In particular, timezone - * normalization is only possible if there is a time, or - * a time together with a full date. - */ -public final class GDateBuilder implements GDateSpecification, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private int _bits; - private int _CY; - private int _M; - private int _D; - private int _h; - private int _m; - private int _s; - private BigDecimal _fs; - private int _tzsign; - private int _tzh; - private int _tzm; - - /** - * Constructs a GDateBuilder specifying no date or time - */ - public GDateBuilder() - { - } - - /** - * Builds another GDateBuilder with the same value - * as this one. - */ - public Object clone() - { - return new GDateBuilder(this); - } - - /** - * Builds a GDate from this GDateBuilder. - */ - public GDate toGDate() - { - return new GDate(this); - } - - /** - * Construts a GDateBuilder by copying another GDateSpecificaiton. - */ - public GDateBuilder(GDateSpecification gdate) - { - if (gdate.hasTimeZone()) - setTimeZone(gdate.getTimeZoneSign(), gdate.getTimeZoneHour(), gdate.getTimeZoneMinute()); - - if (gdate.hasTime()) - setTime(gdate.getHour(), gdate.getMinute(), gdate.getSecond(), gdate.getFraction()); - - if (gdate.hasDay()) - setDay(gdate.getDay()); - - if (gdate.hasMonth()) - setMonth(gdate.getMonth()); - - if (gdate.hasYear()) - setYear(gdate.getYear()); - } - - // Forms: - - // Date part: - // Year: (-?\d{4,}) - // YearMonth: (-?\d{4,})-(\d{2}) - // Date: (-?\d{4,})-(\d{2})-(\d{2}) - // Month: --(\d{2})(--)? //errata R-48 - // MonthDay: --(\d{2})-(\d{2}) - // Day: ---(\d{2}) - - // Time part: - // Time: (\d{2}):(\d{2}):(\d{2})(.\d*)? - - // Timezone part: - // TZ: (Z)|([+-]\d{2}):(\d{2}) - - /** - * Constructs a GDateBuilder from a lexical - * representation. The lexical space contains the - * union of the lexical spaces of all the schema - * date/time types (except for duration). - */ - public GDateBuilder(CharSequence string) - { - this(new GDate(string)); - } - - - public GDateBuilder(Calendar calendar) - { - this(new GDate(calendar)); - } - - /** - * Constructs a GDateBuilder with the specified year, month, day, - * hours, minutes, seconds, and optional fractional seconds, in - * an unspecified timezone. - *

      - * Note that by not specifying the timezone the GDateBuilder - * becomes partially unordered with respect to timesthat do have a - * specified timezone. - * - * @param year The year - * @param month The month, from 1-12 - * @param day The day of month, from 1-31 - * @param hour The hour of day, from 0-23 - * @param minute The minute of hour, from 0-59 - * @param second The second of minute, from 0-59 - * @param fraction The fraction of second, 0.0 to 0.999... (may be null) - */ - public GDateBuilder( - int year, - int month, - int day, - int hour, - int minute, - int second, - BigDecimal fraction) - { - _bits = HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; - - if (year == 0) - throw new IllegalArgumentException(); - - _CY = (year > 0 ? year : year + 1); - _M = month; - _D = day; - _h = hour; - _m = minute; - _s = second; - _fs = fraction == null ? GDate._zero : fraction; - - if (!isValid()) - throw new IllegalArgumentException(); - } - - /** - * Constructs an absolute GDateBuilder with the specified year, - * month, day, hours, minutes, seconds, and optional fractional - * seconds, and in the timezone specified. - *

      - * Note that you can reexpress the GDateBuilder in any timezone using - * normalizeToTimeZone(). The normalize() method normalizes to UTC. - *

      - * If you wish to have a time or date that isn't in a specified timezone, - * then use the constructor that does not include the timezone arguments. - * - * @param year the year - * @param month the month, from 1-12 - * @param day the day of month, from 1-31 - * @param hour the hour of day, from 0-23 - * @param minute the minute of hour, from 0-59 - * @param second the second of minute, from 0-59 - * @param fraction the fraction of second, 0.0 to 0.999... (may be null) - * @param tzSign the timezone offset sign, either +1, 0, or -1 - * @param tzHour the timezone offset hour - * @param tzMinute the timezone offset minute - */ - public GDateBuilder( - int year, - int month, - int day, - int hour, - int minute, - int second, - BigDecimal fraction, - int tzSign, - int tzHour, - int tzMinute) - { - _bits = HAS_TIMEZONE | HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME; - - if (year == 0) - throw new IllegalArgumentException(); - - _CY = (year > 0 ? year : year + 1); - _M = month; - _D = day; - _h = hour; - _m = minute; - _s = second; - _fs = fraction == null ? GDate._zero : fraction; - _tzsign = tzSign; - _tzh = tzHour; - _tzm = tzMinute; - - if (!isValid()) - throw new IllegalArgumentException(); - } - - /** - * Constructs a GDateBuilder based on a java.util.Date. - *

      - * The current offset of the default timezone is used as the timezone. - *

      - * For example, if eastern daylight time is in effect at the given - * date, the timezone on the east coast of the united states - * translates to GMT-05:00 (EST) + 1:00 (DT offset) == GMT-04:00. - * - * @param date the date object to copy - */ - public GDateBuilder(Date date) - { - setDate(date); - } - - /** - * True if the instance is immutable. - */ - public boolean isImmutable() - { - return false; - } - - /** - * Returns a combination of flags indicating the information - * contained by this GDate. The five flags are - * HAS_TIMEZONE, HAS_YEAR, HAS_MONTH, HAS_DAY, and HAS_TIME. - */ - public int getFlags() - { - return _bits; - } - - /** - * True if this date/time specification specifies a timezone. - */ - public final boolean hasTimeZone() - { return ((_bits & HAS_TIMEZONE) != 0); } - - /** - * True if this date/time specification specifies a year. - */ - public final boolean hasYear() - { return ((_bits & HAS_YEAR) != 0); } - - /** - * True if this date/time specification specifies a month-of-year. - */ - public final boolean hasMonth() - { return ((_bits & HAS_MONTH) != 0); } - - /** - * True if this date/time specification specifies a day-of-month. - */ - public final boolean hasDay() - { return ((_bits & HAS_DAY) != 0); } - - /** - * True if this date/time specification specifies a time-of-day. - */ - public final boolean hasTime() - { return ((_bits & HAS_TIME) != 0); } - - /** - * True if this date/time specification specifies a full date (year, month, day) - */ - public final boolean hasDate() - { return ((_bits & (HAS_DAY | HAS_MONTH | HAS_YEAR)) == (HAS_DAY | HAS_MONTH | HAS_YEAR)); } - - /** - * Gets the year. Should be a four-digit year specification. - */ - public final int getYear() - { return (_CY > 0 ? _CY : _CY - 1); } - - /** - * Gets the month-of-year. January is 1. - */ - public final int getMonth() - { return _M; } - - /** - * Gets the day-of-month. The first day of each month is 1. - */ - public final int getDay() - { return _D; } - - /** - * Gets the hour-of-day. Midnight is 0, and 11PM is 23. - */ - public final int getHour() - { return _h; } - - /** - * Gets the minute-of-hour. Range from 0 to 59. - */ - public final int getMinute() - { return _m; } - - /** - * Gets the second-of-minute. Range from 0 to 59. - */ - public final int getSecond() - { return _s; } - - - /** - * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). - */ - public final BigDecimal getFraction() - { return _fs; } - - - /** - * Gets the rounded millisecond value. Range from 0 to 999 - */ - public final int getMillisecond() - { - if (_fs == null || _fs == GDate._zero) - return 0; - return _fs.setScale(3, BigDecimal.ROUND_HALF_UP).unscaledValue().intValue(); - } - - /** - * Gets the time zone sign. For time zones east of GMT, - * this is positive; for time zones west, this is negative. - */ - public final int getTimeZoneSign() - { return _tzsign; } - - /** - * Gets the time zone hour. - * This is always positive: for the sign, look at - * getTimeZoneSign(). - */ - public final int getTimeZoneHour() - { return _tzh; } - - /** - * Gets the time zone minutes. - * This is always positive: for the sign, look at - * getTimeZoneSign(). - */ - public final int getTimeZoneMinute() - { return _tzm; } - - - - /** - * Sets the year. Should be a four-digit year specification. - * @param year the year - */ - public void setYear(int year) - { - if (year < GDate.MIN_YEAR || year > GDate.MAX_YEAR) - throw new IllegalArgumentException("year out of range"); - if (year == 0) - throw new IllegalArgumentException("year cannot be 0"); - _bits |= HAS_YEAR; _CY = (year > 0 ? year : year + 1); - } - - /** - * Sets the month-of-year. January is 1. - * @param month the month, from 1-12 - */ - public void setMonth(int month) - { - if (month < 1 || month > 12) - throw new IllegalArgumentException("month out of range"); - _bits |= HAS_MONTH; _M = month; - } - - /** - * Sets the day-of-month. The first day of each month is 1. - * @param day the day of month, from 1-31 - */ - public void setDay(int day) - { - if (day < 1 || day > 31) - throw new IllegalArgumentException("day out of range"); - _bits |= HAS_DAY; _D = day; - } - - /** - * Sets the time. Hours in the day range from 0 to 23; - * minutes and seconds range from 0 to 59; and fractional - * seconds range from 0 (inclusive) to 1 (exclusive). - * The fraction can be null and is assumed to be zero. - * @param hour the hour of day, from 0-23 or 24 only if min, sec and fraction are 0 - * @param minute the minute of hour, from 0-59 - * @param second the second of minute, from 0-59 - * @param fraction the fraction of second, 0.0 to 0.999... (may be null) - */ - public void setTime(int hour, int minute, int second, BigDecimal fraction) - { - if (hour < 0 || hour > 24 ) - throw new IllegalArgumentException("hour out of range"); - if (minute < 0 || minute > 59) - throw new IllegalArgumentException("minute out of range"); - if (second < 0 || second > 59) - throw new IllegalArgumentException("second out of range"); - if (fraction != null && (fraction.signum() < 0 || fraction.compareTo(GDate._one) > 1)) - throw new IllegalArgumentException("fraction out of range"); - if ( hour == 24 && (minute!=0 || second!=0 || (fraction!=null && (GDate._zero.compareTo(fraction)!=0)) )) - throw new IllegalArgumentException("when hour is 24, min sec and fracton must be 0"); - - _bits |= HAS_TIME; - _h = hour; - _m = minute; - _s = second; - _fs = fraction == null ? GDate._zero : fraction; - } - - /** - * Sets the time zone without changing the other time - * fields. If you with to adjust other time fields to express - * the same actual moment in time in a different time zone, - * use normalizeToTimeZone. - *

      - * Timezones must be between -14:00 and +14:00. Sign - * must be -1 or 1 (or 0 for UTC only), and the offset hours - * and minute arguments must be nonnegative. - * - * @param tzSign the timezone offset sign, either +1, 0, or -1 - * @param tzHour the timezone offset hour - * @param tzMinute the timezone offset minute - */ - public void setTimeZone(int tzSign, int tzHour, int tzMinute) - { - if (!((tzSign == 0 && tzHour == 0 && tzMinute == 0) || - ((tzSign == -1 || tzSign == 1) && - (tzHour >= 0 && tzMinute >= 0) && - (tzHour == 14 && tzMinute == 0 || tzHour < 14 && tzMinute < 60)))) - throw new IllegalArgumentException("time zone out of range (-14:00 to +14:00). (" + - (tzSign<0 ? "-" : "+") + tzHour + ":" + tzMinute + ")"); - - _bits |= HAS_TIMEZONE; - _tzsign = tzSign; - _tzh = tzHour; - _tzm = tzMinute; - } - - /** - * Sets the time zone based on a number of offset minutes rather - * than sign/hour/minute; for example, setTimeZone(-60) is the - * same as setTimeZone(-1, 1, 0). - */ - public void setTimeZone(int tzTotalMinutes) - { - if (tzTotalMinutes < -14 * 60 || tzTotalMinutes > 14 * 60) - throw new IllegalArgumentException("time zone out of range (-840 to 840 minutes). (" + tzTotalMinutes + ")"); - - int tzSign = tzTotalMinutes < 0 ? -1 : tzTotalMinutes > 0 ? 1 : 0; - tzTotalMinutes *= tzSign; - int tzH = tzTotalMinutes / 60; - int tzM = tzTotalMinutes - tzH * 60; - - setTimeZone(tzSign, tzH, tzM); - } - - /** - * Clears the year. After clearing, hasYear returns false and the - * value of getYear is undefined. - */ - public void clearYear() - { _bits &= ~HAS_YEAR; _CY = 0; } - - /** - * Clears the month-of-year. After clearing. hasMonth returns false and - * the value of getMonth is undefined. - */ - public void clearMonth() - { _bits &= ~HAS_MONTH; _M = 0; } - - /** - * Clears the day-of-month. After clearing. hasDay returns false and - * the value of getDay is undefined. - */ - public void clearDay() - { _bits &= ~HAS_DAY; _D = 0; } - - /** - * Clears the time-of-day. - * After clearing. hasTime returns false and - * the value of getTime is undefined. - */ - public void clearTime() - { - _bits &= ~HAS_TIME; - _h = 0; - _m = 0; - _s = 0; - _fs = null; - } - - /** - * Clears the timezone. After clearing. hasTimeZone returns false and - * the value of getTimeZoneHour and getTimeZoneMinute are undefined. - * Does not change the other time fields. - */ - public void clearTimeZone() - { - _bits &= ~HAS_TIMEZONE; - _tzsign = 0; - _tzh = 0; - _tzm = 0; - } - - /** - * True if all date fields lie within their legal ranges. A GDateBuilder - * can be invalid, for example, if you change the month to February - * and the day-of-month is 31. - */ - public boolean isValid() - { - return isValidGDate(this); - } - - /* package */ static final boolean isValidGDate(GDateSpecification date) - { - if (date.hasYear() && date.getYear() == 0) - return false; - - if (date.hasMonth() && (date.getMonth() < 1 || date.getMonth() > 12)) - return false; - - if (date.hasDay() && - (date.getDay() < 1 || date.getDay() > 31 || - date.getDay() > 28 && - date.hasMonth() && - (date.hasYear() ? - date.getDay() > _maxDayInMonthFor((date.getYear() > 0 ? - date.getYear() : - date.getYear() + 1), - date.getMonth()) : - date.getDay() > _maxDayInMonth(date.getMonth())))) - return false; - - if (date.hasTime() && ((date.getHour() < 0 || date.getHour() > 23 || - date.getMinute() < 0 || date.getMinute() > 59 || - date.getSecond() < 0 || date.getSecond() > 59 || - date.getFraction().signum() < 0 || date.getFraction().compareTo(GDate._one) >= 0) ) && - // check for 24:00:00 valid format - !(date.getHour() == 24 && date.getMinute() == 0 && date.getSecond() == 0 && - date.getFraction().compareTo(GDate._zero) == 0 ) ) - return false; - - if (date.hasTimeZone() && - (!((date.getTimeZoneSign() == 0 && date.getTimeZoneHour() == 0 && date.getTimeZoneMinute() == 0) || - ((date.getTimeZoneSign() == -1 || date.getTimeZoneSign() == +1) && - // NB: allow +00:00 and -00:00 - // (date.getTimeZoneHour() == 0 && date.getTimeZoneMinute() > 0 || date.getTimeZoneHour() > 0 && date.getTimeZoneMinute() >= 0) && - (date.getTimeZoneHour() >= 0 && date.getTimeZoneMinute() >= 0) && - (date.getTimeZoneHour() == 14 && date.getTimeZoneMinute() == 0 || date.getTimeZoneHour() < 14 && date.getTimeZoneMinute() < 60))))) - return false; - - // everyting looks kosher - return true; - } - - - /** - * Normalizes the instance, ensuring date and time fields are within - * their normal ranges. - *

      - * If no timezone or no time is specified, or if a partial date is specified, this - * method does nothing, and leaves the timezone information as-is. - *

      - * If a time or time and date is specified, this method normalizes the timezone - * to UTC. - */ - public void normalize() - { - // DateTime or Time, with TimeZone: normalize to UTC. - // In the process all the fields will be normalized. - if (hasDay() == hasMonth() && hasDay() == hasYear() && - hasTimeZone() && hasTime() ) - { - normalizeToTimeZone(0, 0, 0); - } - else - { - // No timezone, or incomplete date. - _normalizeTimeAndDate(); - } - - // remove trailing zeros from fractional seconds - if (hasTime() && _fs != null && _fs.scale() > 0) - { - if (_fs.signum() == 0) - _fs = GDate._zero; - else - { - BigInteger bi = _fs.unscaledValue(); - String str = bi.toString(); - int lastzero; - for (lastzero = str.length(); lastzero > 0; lastzero -= 1) - if (str.charAt(lastzero - 1) != '0') - break; - if (lastzero < str.length()) - _fs = _fs.setScale(_fs.scale() - str.length() + lastzero); - } - } - } - - /** - * Normalizes the instance when hour is 24. If day is present, hour 24 is equivalent to hour 00 next day. - */ - void normalize24h() - { - if ( !hasTime() || getHour()!=24 ) - return; - - _normalizeTimeAndDate(); - } - - - private void _normalizeTimeAndDate() - { - long carry = 0; - - if (hasTime()) - carry = _normalizeTime(); - - if (hasDay()) - _D += carry; - - if (hasDate()) - { - _normalizeDate(); - } - else if (hasMonth()) - { - // with incomplete dates, just months can be normalized: - // days stay denormalized. - if (_M < 1 || _M > 12) - { - int temp = _M; - _M = _modulo(temp, 1, 13); - if (hasYear()) - _CY = _CY + (int)_fQuotient(temp, 1, 13); - } - } - } - - /** - * If the time and timezone are known, this method changes the timezone to the - * specified UTC offset, altering minutes, hours, day, month, and year as - * necessary to ensure that the actual described moment in time is the same. - *

      - * It is an error to operate on instances without a time or timezone, or - * with a partially specified date. - * - * @param tzSign the timezone offset sign, either +1, 0, or -1 - * @param tzHour the timezone offset hour - * @param tzMinute the timezone offset minute - */ - public void normalizeToTimeZone(int tzSign, int tzHour, int tzMinute) - { - if (!((tzSign == 0 && tzHour == 0 && tzMinute == 0) || - ((tzSign == -1 || tzSign == 1) && - (tzHour >= 0 && tzMinute >= 0) && - (tzHour == 14 && tzMinute == 0 || tzHour < 14 && tzMinute < 60)))) - throw new IllegalArgumentException("time zone must be between -14:00 and +14:00"); - - if (!hasTimeZone() || !hasTime()) - throw new IllegalStateException("cannot normalize time zone without both time and timezone"); - - if (!(hasDay() == hasMonth() && hasDay() == hasYear())) - throw new IllegalStateException("cannot do date math without a complete date"); - - int hshift = tzSign * tzHour - _tzsign * _tzh; - int mshift = tzSign * tzMinute - _tzsign * _tzm; - - _tzsign = tzSign; - _tzh = tzHour; - _tzm = tzMinute; - addDuration(1, 0, 0, 0, hshift, mshift, 0, null); - } - - /** - * Normalizes to a time zone specified by a number of offset minutes rather - * than sign/hour/minute; for example, normalizeToTimeZone(-60) is the - * same as normalizeToTimeZone(-1, 1, 0). - */ - public void normalizeToTimeZone(int tzTotalMinutes) - { - if (tzTotalMinutes < -14 * 60 || tzTotalMinutes > 14 * 60) - throw new IllegalArgumentException("time zone out of range (-840 to 840 minutes). (" + tzTotalMinutes + ")"); - - int tzSign = tzTotalMinutes < 0 ? -1 : tzTotalMinutes > 0 ? 1 : 0; - tzTotalMinutes *= tzSign; - int tzH = tzTotalMinutes / 60; - int tzM = tzTotalMinutes - tzH * 60; - - normalizeToTimeZone(tzSign, tzH, tzM); - } - - - /** - * Adds a given duration to the date/time. - * - * @param duration the duration to add - */ - public void addGDuration(GDurationSpecification duration) - { - addDuration(duration.getSign(), duration.getYear(), duration.getMonth(), duration.getDay(), - duration.getHour(), duration.getMinute(), duration.getSecond(), duration.getFraction()); - } - - /** - * Subtracts a given duration from the date/time. - * - * @param duration the duration to subtract - */ - public void subtractGDuration(GDurationSpecification duration) - { - addDuration(-duration.getSign(), duration.getYear(), duration.getMonth(), duration.getDay(), - duration.getHour(), duration.getMinute(), duration.getSecond(), duration.getFraction()); - } - - - /** - * Normalizes the date by carrying over to the year any months outside 1..12 - * and carrying over to the month any days outside 1..(days-in-month). - */ - private void _normalizeDate() - { - if (_M < 1 || _M > 12 || _D < 1 || _D > _maxDayInMonthFor(_CY, _M)) - { - // fix months first - int temp = _M; - _M = _modulo(temp, 1, 13); - _CY = _CY + (int)_fQuotient(temp, 1, 13); - - // then pull days out - int extradays = _D - 1; - _D = 1; - - // then use the julian date function to fix - setJulianDate(getJulianDate() + extradays); - } - } - - /** - * Normalizes time so that fractions are 0..1(exc), seconds/minutes 0..59, - * and hours 0..24. Returns the number of days to carry over from normalizing - * away more than 24 hours. - */ - private long _normalizeTime() - { - long carry = 0; - long temp; - - // fractions - if (_fs != null && (_fs.signum() < 0 || _fs.compareTo(GDate._one) >= 0)) - { - BigDecimal bdcarry = _fs.setScale(0, BigDecimal.ROUND_FLOOR); - _fs = _fs.subtract(bdcarry); - carry = bdcarry.longValue(); - } - - if (carry != 0 || _s < 0 || _s > 59 || _m < 0 || _m > 50 || _h < 0 || _h > 23) - { - // seconds - temp = _s + carry; - carry = _fQuotient(temp, 60); - _s = _mod(temp, 60, carry); - - // minutes - temp = _m + carry; - carry = _fQuotient(temp, 60); - _m = _mod(temp, 60, carry); - - // hours - temp = _h + carry; - carry = _fQuotient(temp, 24); - _h = _mod(temp, 24, carry); - } - - return carry; - } - - /** - * Adds a given duration to the date/time. - * - * @param sign +1 to add, -1 to subtract - * @param year the number of years to add - * @param month the number of months to add - * @param day the number of days to add - * @param hour the number of hours to add - * @param minute the number of minutes to add - * @param second the number of seconds to add - * @param fraction the number of fractional seconds to add (may be null) - */ - public void addDuration(int sign, int year, int month, int day, - int hour, int minute, int second, BigDecimal fraction) - { - boolean timemath = hour != 0 || minute != 0 || second != 0 || fraction != null && fraction.signum() != 0; - if (timemath && !hasTime()) - throw new IllegalStateException("cannot do time math without a complete time"); - boolean datemath = hasDay() && (day != 0 || timemath); - if (datemath && !hasDate()) - throw new IllegalStateException("cannot do date math without a complete date"); - - int temp; - - // months + years are easy - if (month != 0 || year != 0) - { - // Prepare the _D to be pegged before changing month - if (hasDay()) - _normalizeDate(); - - // Add months and years - temp = _M + sign * month; - _M = _modulo(temp, 1, 13); - _CY = _CY + sign * year + (int)_fQuotient(temp, 1, 13); - - // In new month, day may need to be pegged before proceeding - if (hasDay()) - { - assert(_D >= 1); - temp = _maxDayInMonthFor(_CY, _M); - if (_D > temp) - _D = temp; - } - } - - long carry = 0; - - if (timemath) - { - // fractions - if (fraction != null && fraction.signum() != 0) - { - if (_fs.signum() == 0 && sign == 1) - _fs = fraction; - else - _fs = (sign == 1) ? _fs.add(fraction) : _fs.subtract(fraction); - } - - // seconds, minutes, hours - _s += sign * second; - _m += sign * minute; - _h += sign * hour; - - // normalize time - carry = _normalizeTime(); - } - - if (datemath) - { - // days: may require renormalization - _D += sign * day + carry; - _normalizeDate(); - } - } - - /** - * Given {year,month} computes maximum - * number of days for given month - */ - private static int _maxDayInMonthFor(int year, int month) - { - if (month == 4 || month == 6 || month == 9 || month == 11) - return 30; - - if (month == 2) - return (_isLeapYear(year) ? 29 : 28); - - return 31; - } - - /** - * Given {year,month} computes maximum - * number of days for given month - */ - private static int _maxDayInMonth(int month) - { - if (month == 4 || month == 6 || month == 9 || month == 11) - return 30; - - if (month == 2) - return 29; - - return 31; - } - - /** - * Returns the Julian date corresponding to this Gregorian date. - * The Julian date (JD) is a continuous count of days from - * 1 January 4713 BC. - */ - public final int getJulianDate() - { - return julianDateForGDate(this); - } - - - /** - * Sets the Gregorian date based on the given Julian date. - * The Julian date (JD) is a continuous count of days from - * 1 January 4713 BC. - * - * @param julianday the julian day number - */ - public void setJulianDate(int julianday) - { - if (julianday < 0) - throw new IllegalArgumentException("date before year -4713"); - - int temp; - int qepoc; - - // from http://aa.usno.navy.mil/faq/docs/JD_Formula.html - temp = julianday + 68569; - qepoc = 4 * temp / 146097; - temp = temp - (146097 * qepoc + 3) / 4; - _CY = 4000 * (temp + 1) / 1461001; - temp = temp - 1461 * _CY / 4 + 31; - _M = 80 * temp / 2447; - _D = temp - 2447 * _M / 80; - temp = _M / 11; - _M = _M + 2 - 12 * temp; - _CY = 100 * (qepoc - 49) + _CY + temp; - - _bits |= HAS_DAY | HAS_MONTH | HAS_YEAR; - } - - - /** - * Sets the current time and date based on a java.util.Date instance. - *

      - * The timezone offset used is based on the default TimeZone. (The - * default TimeZone is consulted to incorporate daylight savings offsets - * if applicable for the current date as well as the base timezone offset.) - *

      - * If you wish to normalize the timezone, e.g., to UTC, follow this with - * a call to normalizeToTimeZone. - * - * @param date the Date object to copy - */ - public void setDate(Date date) - { - // Default timezone - TimeZone dtz = TimeZone.getDefault(); - int offset = dtz.getOffset(date.getTime()); - int offsetsign = 1; - if (offset < 0) - { - offsetsign = -1; - offset = -offset; - } - int offsetmin = offset / (1000 * 60); - int offsethr = offsetmin / 60; - offsetmin = offsetmin - offsethr * 60; - - setTimeZone(offsetsign, offsethr, offsetmin); - - // paranoia: tz.getOffset can return fractions of minutes, but we must round - int roundedoffset = offsetsign * (offsethr * 60 + offsetmin) * 60 * 1000; - - // midnight - setTime(0, 0, 0, GDate._zero); - - // Set to January 1, 1970. - // setJulianDate(2440588); - _bits |= HAS_DAY | HAS_MONTH | HAS_YEAR; - _CY = 1970; - _M = 1; - _D = 1; - - // Add a duration representing the number of milliseconds - addGDuration(new GDuration(1, 0, 0, 0, 0, 0, 0, - BigDecimal.valueOf(date.getTime() + roundedoffset, 3))); - - // special case: ss.000 -> ss - if (_fs.signum() == 0) - _fs = GDate._zero; - } - - /** - * Copies a GDateSpecification, completely replacing the current - * information in this GDateBuilder. - * - * @param gdate the GDateSpecification to copy - */ - public void setGDate(GDateSpecification gdate) - { - _bits = gdate.getFlags() & (HAS_TIMEZONE | HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME); - int year = gdate.getYear(); - _CY = (year > 0 ? year : year + 1); - _M = gdate.getMonth(); - _D = gdate.getDay(); - _h = gdate.getHour(); - _m = gdate.getMinute(); - _s = gdate.getSecond(); - _fs = gdate.getFraction(); - _tzsign = gdate.getTimeZoneSign(); - _tzh = gdate.getTimeZoneHour(); - _tzm = gdate.getTimeZoneMinute(); - } - - - /** - * Retrieves the value of the current time as an {@link XmlCalendar}. - *

      - * {@link XmlCalendar} is a subclass of {@link java.util.GregorianCalendar} - * which is slightly customized to match XML schema date rules. - *

      - * The returned {@link XmlCalendar} has only those time and date fields - * set that are reflected in the GDate object. Because of the way the - * {@link java.util.Calendar} contract works, any information in the isSet() vanishes - * as soon as you view any unset field using get() methods. - * This means that if it is important to understand which date fields - * are set, you must call isSet() first before get(). - */ - public XmlCalendar getCalendar() - { - return new XmlCalendar(this); - } - - /** - * Retrieves the value of the current time as a java.util.Date - * instance. - */ - public Date getDate() - { - return dateForGDate(this); - } - - /* package */ static int julianDateForGDate(GDateSpecification date) - { - if (!date.hasDate()) - throw new IllegalStateException("cannot do date math without a complete date"); - - // from http://aa.usno.navy.mil/faq/docs/JD_Formula.html - int day = date.getDay(); - int month = date.getMonth(); - int year = date.getYear(); - year = (year > 0 ? year : year + 1); - int result = day-32075+1461*(year+4800+(month-14)/12)/4+ - 367*(month-2-(month-14)/12*12)/12-3*((year+4900+(month-14)/12)/100)/4; - - if (result < 0) - throw new IllegalStateException("date too far in the past (year allowed to -4713)"); - - return result; - } - - /* package */ static Date dateForGDate(GDateSpecification date) - { - long jDate = julianDateForGDate(date); - long to1970Date = jDate - 2440588; - long to1970Ms = 1000 * 60 * 60 * 24 * to1970Date; - - to1970Ms += date.getMillisecond(); - to1970Ms += date.getSecond() * 1000; - to1970Ms += date.getMinute() * 60 * 1000; - to1970Ms += date.getHour() * 60 * 60 * 1000; - if (date.hasTimeZone()) - { - to1970Ms -= (date.getTimeZoneMinute() * date.getTimeZoneSign()) * 60 * 1000; - to1970Ms -= (date.getTimeZoneHour() * date.getTimeZoneSign()) * 60 * 60 * 1000; - } - else - { - TimeZone def = TimeZone.getDefault(); - int offset = def.getOffset(to1970Ms); - to1970Ms -= offset; - } - - return new Date(to1970Ms); - } - - /** - * True for leap years. - */ - private static boolean _isLeapYear(int year) - { - // BUGBUG: Julian calendar? - return ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))); - } - - /** - * fQuotient(a, b) = the greatest integer less than or equal to a/b - */ - private static final long _fQuotient(long a, int b) - { - if ((a < 0) == (b < 0)) - return a / b; - - return -((b - a - 1) / b); - } - - /** - * modulo(a, b) = a - fQuotient(a,b)*b - */ - private static int _mod(long a, int b, long quotient) - { - return (int)(a - quotient*b) ; - } - - /** - * modulo(a - low, high - low) + low - */ - private static final int _modulo(long temp, int low, int high) - { - long a = temp - low; - int b = high - low; - return (_mod(a, b, _fQuotient(a, b)) + low) ; - } - - /** - * Quotient(a - low, high - low) - */ - private static final long _fQuotient(long temp, int low, int high) - { - return _fQuotient(temp - low, high - low); - } - - /** - * Sets to the first possible moment that matches the given - * specification. - */ - private void _setToFirstMoment() - { - // 1584 was the first leap year during which the Gregorian - // calendar was in use: seems like the most reasonable "first" - // year to use in absence of a year. - - if (!hasYear()) - setYear(1584); - - if (!hasMonth()) - setMonth(1); - - if (!hasDay()) - setDay(1); - - if (!hasTime()) - setTime(0, 0, 0, GDate._zero); - } - - /** - * Comparison to another GDate. - *

        - *
      • Returns -1 if this < date. (less-than) - *
      • Returns 0 if this == date. (equal) - *
      • Returns 1 if this > date. (greater-than) - *
      • Returns 2 if this <> date. (incomparable) - *
      - * Two instances are incomparable if they have different amounts - * of information. - * - * @param datespec the date to compare against - */ - public final int compareToGDate(GDateSpecification datespec) - { - return compareGDate(this, datespec); - } - - - /* package */ static final int compareGDate(GDateSpecification tdate, GDateSpecification datespec) - { - // same amount of information: looks good - int bitdiff = tdate.getFlags() ^ datespec.getFlags(); - - easy: if ((bitdiff & (HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME | HAS_TIMEZONE)) == 0) - { - // If the other date needs to be normalized to - // our timezone, make a clone and do so if possible - if (tdate.hasTimeZone() && - (datespec.getTimeZoneHour() != tdate.getTimeZoneHour() || - datespec.getTimeZoneMinute() != tdate.getTimeZoneMinute() || - datespec.getTimeZoneSign() != tdate.getTimeZoneSign())) - { - datespec = new GDateBuilder(datespec); - - int flags = tdate.getFlags() & (HAS_YEAR | HAS_MONTH | HAS_DAY); - if (flags != 0 && flags != (HAS_YEAR | HAS_MONTH | HAS_DAY) || !tdate.hasTime()) - { - // in these cases we'll need to fill in fields - ((GDateBuilder)datespec)._setToFirstMoment(); - tdate = new GDateBuilder(tdate); - ((GDateBuilder)tdate)._setToFirstMoment(); - } - - ((GDateBuilder)datespec).normalizeToTimeZone(tdate.getTimeZoneSign(), tdate.getTimeZoneHour(), tdate.getTimeZoneMinute()); - } - - // compare by field - return fieldwiseCompare(tdate, datespec); - } - - // different amounts of information (except timezone): not comparable - if ((bitdiff & (HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME)) != 0) - return 2; - - // The schema spec says we should try to compare with-timezone and - // without-timezone specifications... Well, OK, sure, if they say so. - - // We don't have a timezone but the other does: reverse the call - if (!tdate.hasTimeZone()) - { - int result = compareGDate(datespec, tdate); - return result == 2 ? 2 : -result; - } - - // Now tdate is guaranteed to have a timezone and datespec not. - - // To muck with the times, make clones - GDateBuilder pdate = new GDateBuilder(tdate); - - // To cover the one uncovered case: if one date is 02/28 and the - // other date is 03/01, shift days closer by one to simulate being - // the last day of the month within a leap year - if ((tdate.getFlags() & (HAS_YEAR | HAS_MONTH | HAS_DAY)) == (HAS_MONTH | HAS_DAY)) - { - if (tdate.getDay() == 28 && tdate.getMonth() == 2) - { - if (datespec.getDay() == 01 && datespec.getMonth() == 3) - { - pdate.setDay(29); - } - } - else if (datespec.getDay() == 28 && datespec.getMonth() == 2) - { - if (tdate.getDay() == 01 && tdate.getMonth() == 3) - { - pdate.setMonth(02); - pdate.setDay(29); - } - } - } - - // For timespans, compare by first instant of time - // possible. Therefore, fill in Midnight, January 1, 1584 (a leap year) - // in absence of other information. - pdate._setToFirstMoment(); - - // P < Q if P < (Q with time zone +14:00) - GDateBuilder qplusdate = new GDateBuilder(datespec); - qplusdate._setToFirstMoment(); - qplusdate.setTimeZone(1, 14, 0); - qplusdate.normalizeToTimeZone(tdate.getTimeZoneSign(), tdate.getTimeZoneHour(), tdate.getTimeZoneMinute()); - if (fieldwiseCompare(pdate, qplusdate) == -1) - return -1; - - // P > Q if P > (Q with time zone -14:00) - GDateBuilder qminusdate = qplusdate; - qminusdate.setGDate(datespec); - qminusdate._setToFirstMoment(); - qminusdate.setTimeZone(-1, 14, 0); - qminusdate.normalizeToTimeZone(tdate.getTimeZoneSign(), tdate.getTimeZoneHour(), tdate.getTimeZoneMinute()); - if (fieldwiseCompare(pdate, qminusdate) == 1) - return 1; - - // P <> Q otherwise - return 2; - } - - /** - * Does a simple most-significant-digit-first comparison, - * ignoring any timezone or has/doesn't have issues. - * The data must have been digested first. - */ - private static int fieldwiseCompare(GDateSpecification tdate, GDateSpecification date) - { - if (tdate.hasYear()) - { - int CY = date.getYear(); - int TCY = tdate.getYear(); - if (TCY < CY) return -1; - if (TCY > CY) return 1; - } - if (tdate.hasMonth()) - { - int M = date.getMonth(); - int TM = tdate.getMonth(); - if (TM < M) return -1; - if (TM > M) return 1; - } - if (tdate.hasDay()) - { - int D = date.getDay(); - int TD = tdate.getDay(); - if (TD < D) return -1; - if (TD > D) return 1; - } - if (tdate.hasTime()) - { - int h = date.getHour(); - int th = tdate.getHour(); - if (th < h) return -1; - if (th > h) return 1; - int m = date.getMinute(); - int tm = tdate.getMinute(); - if (tm < m) return -1; - if (tm > m) return 1; - int s = date.getSecond(); - int ts = tdate.getSecond(); - if (ts < s) return -1; - if (ts > s) return 1; - BigDecimal fs = date.getFraction(); - BigDecimal tfs = tdate.getFraction(); - if (tfs == null && fs == null) return 0; - return (tfs == null ? GDate._zero : tfs).compareTo(fs == null ? GDate._zero : fs); - } - - return 0; - } - - /** - * Returns the builtin type code for the shape of the information - * contained in this instance, or 0 if the - * instance doesn't contain information corresponding to a - * Schema type. - *

      - * Value will be equal to - * {@link SchemaType#BTC_NOT_BUILTIN}, - * {@link SchemaType#BTC_G_YEAR}, - * {@link SchemaType#BTC_G_YEAR_MONTH}, - * {@link SchemaType#BTC_G_MONTH}, - * {@link SchemaType#BTC_G_MONTH_DAY}, - * {@link SchemaType#BTC_G_DAY}, - * {@link SchemaType#BTC_DATE}, - * {@link SchemaType#BTC_DATE_TIME}, or - * {@link SchemaType#BTC_TIME}. - */ - public final int getBuiltinTypeCode() - { - return btcForFlags(_bits); - } - - /* package */ static int btcForFlags(int flags) - { - switch (flags & (HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME)) - { - case HAS_YEAR: - return SchemaType.BTC_G_YEAR; - case HAS_YEAR | HAS_MONTH: - return SchemaType.BTC_G_YEAR_MONTH; - case HAS_MONTH: - return SchemaType.BTC_G_MONTH; - case HAS_MONTH | HAS_DAY: - return SchemaType.BTC_G_MONTH_DAY; - case HAS_DAY: - return SchemaType.BTC_G_DAY; - case HAS_YEAR | HAS_MONTH | HAS_DAY: - return SchemaType.BTC_DATE; - case HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME: - return SchemaType.BTC_DATE_TIME; - case HAS_TIME: - return SchemaType.BTC_TIME; - default: - return SchemaType.BTC_NOT_BUILTIN; - } - } - - /** - * Clears the fields in this GDateBuilder that are not applicable - * for the given SchemaType date code. The code should be - * {@link SchemaType#BTC_G_YEAR}, - * {@link SchemaType#BTC_G_YEAR_MONTH}, - * {@link SchemaType#BTC_G_MONTH}, - * {@link SchemaType#BTC_G_MONTH_DAY}, - * {@link SchemaType#BTC_G_DAY}, - * {@link SchemaType#BTC_DATE}, - * {@link SchemaType#BTC_DATE_TIME}, or - * {@link SchemaType#BTC_TIME}. - * - * @param typeCode the type code to apply - */ - public void setBuiltinTypeCode(int typeCode) - { - switch (typeCode) - { - case SchemaType.BTC_G_YEAR: - //HAS_YEAR - clearMonth(); - clearDay(); - clearTime(); - return; - case SchemaType.BTC_G_YEAR_MONTH: - //HAS_YEAR | HAS_MONTH - clearDay(); - clearTime(); - return; - case SchemaType.BTC_G_MONTH: - //HAS_MONTH - clearYear(); - clearDay(); - clearTime(); - return; - case SchemaType.BTC_G_MONTH_DAY: - //HAS_MONTH | HAS_DAY - clearYear(); - clearTime(); - return; - case SchemaType.BTC_G_DAY: - //HAS_DAY - clearYear(); - clearMonth(); - clearTime(); - return; - case SchemaType.BTC_DATE: - //HAS_YEAR | HAS_MONTH | HAS_DAY - clearTime(); - return; - case SchemaType.BTC_DATE_TIME: - //HAS_YEAR | HAS_MONTH | HAS_DAY | HAS_TIME - return; - case SchemaType.BTC_TIME: - //HAS_TIME - clearYear(); - clearMonth(); - clearDay(); - return; - default: - throw new IllegalArgumentException("codeType must be one of SchemaType BTC_ DATE TIME related types."); - } - } - - - /* package */ static final BigInteger TEN = BigInteger.valueOf(10); - - /** - * The canonical string representation. Specific moments or - * times-of-day in a specified timezone are normalized to - * UTC time to produce a canonical string form for them. - * Other recurring time specifications keep their timezone - * information. - */ - public String canonicalString() - { - boolean needNormalize = - (hasTimeZone() && getTimeZoneSign() != 0 && hasTime() && - ((hasDay() == hasMonth() && hasDay() == hasYear()))); - - if (!needNormalize && getFraction()!=null && getFraction().scale() > 0) - { - BigInteger bi = getFraction().unscaledValue(); - needNormalize = (bi.mod(TEN).signum() == 0); - } - - if (!needNormalize) - return toString(); - - GDateBuilder cdate = new GDateBuilder(this); - cdate.normalize(); - return cdate.toString(); - } - - /** - * The natural string representation. This represents the information - * that is available, including timezone. For types that correspond - * to defined schema types (schemaBuiltinTypeCode() > 0), - * this provides the natural lexical representation. - *

      - * When both time and timezone are specified, this string is not - * the canonical representation unless the timezone is UTC (Z) - * (since the same moment in time can be expressed in different - * timezones). To get a canonical string, use the canonicalString() - * method. - */ - public final String toString() - { - return GDate.formatGDate(this); - } - -} diff --git a/src/xmlpublic/org/apache/xmlbeans/GDurationBuilder.java b/src/xmlpublic/org/apache/xmlbeans/GDurationBuilder.java deleted file mode 100644 index 23b8caf..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/GDurationBuilder.java +++ /dev/null @@ -1,668 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.math.BigDecimal; -import java.math.BigInteger; - -/** - * Used to build {@link GDuration GDurations}. - */ -public class GDurationBuilder implements GDurationSpecification, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private int _sign; - private int _CY; - private int _M; - private int _D; - private int _h; - private int _m; - private int _s; - private BigDecimal _fs; - - /** - * Constructs an empty GDurationBuilder representing zero seconds. - */ - public GDurationBuilder() - { - _sign = +1; - _fs = GDate._zero; - } - - /** - * Constructs a GDuration from a lexical - * representation. - */ - public GDurationBuilder(String s) - { - this(new GDuration(s)); - } - - /** - * Constructs a GDurationBuilder with the specified sign, - * year, month, day, hours, minutes, seconds, and optional - * fractional seconds. - * @param sign +1 for a positive duration, -1 for a negative duration - * @throws java.lang.IllegalArgumentException if the sign is not 1 or -1 - */ - public GDurationBuilder( - int sign, - int year, - int month, - int day, - int hour, - int minute, - int second, - BigDecimal fraction) - { - if (sign != 1 && sign != -1) - throw new IllegalArgumentException(); - _sign = sign; - _CY = year; - _M = month; - _D = day; - _h = hour; - _m = minute; - _s = second; - _fs = fraction == null ? GDate._zero : fraction; - } - - /** - * Constructs a GDurationBuilder from another GDurationBuilderSpecification. - */ - public GDurationBuilder(GDurationSpecification gDuration) - { - _sign = gDuration.getSign(); - _CY = gDuration.getYear(); - _M = gDuration.getMonth(); - _D = gDuration.getDay(); - _h = gDuration.getHour(); - _m = gDuration.getMinute(); - _s = gDuration.getSecond(); - _fs = gDuration.getFraction(); - } - - /** - * Builds another GDurationBuilder with the same value - * as this one. - */ - public Object clone() - { - return new GDurationBuilder(this); - } - - /** - * Builds a GDuration from this GDurationBuilder. - */ - public GDuration toGDuration() - { - return new GDuration(this); - } - - /** - * Adds to this duration. Does a fieldwise add, with no - * normalization. - */ - public void addGDuration(GDurationSpecification duration) - { - int sign = _sign * duration.getSign(); - _add(duration, sign); - } - - /** - * Subtracts from this duration. Does a fieldwise subtraction, - * with no normalization. - */ - public void subtractGDuration(GDurationSpecification duration) - { - int sign = -_sign * duration.getSign(); - _add(duration, sign); - } - - private void _add(GDurationSpecification duration, int sign) - { - _CY += sign * duration.getYear(); - _M += sign * duration.getMonth(); - _D += sign * duration.getDay(); - _h += sign * duration.getHour(); - _m += sign * duration.getMinute(); - _s += sign * duration.getSecond(); - - if (duration.getFraction().signum() == 0) - return; - - if (_fs.signum() == 0 && sign == 1) - _fs = duration.getFraction(); - else - _fs = sign > 0 ? - _fs.add(duration.getFraction()) : - _fs.subtract(duration.getFraction()); - } - - /** - * Sets the sign. - */ - public final void setSign(int sign) - { - if (sign != 1 && sign != -1) - throw new IllegalArgumentException(); - _sign = sign; - } - - /** - * Sets the year component. - */ - public void setYear(int year) - { _CY = year; } - - /** - * Sets the month component. - */ - public void setMonth(int month) - { _M = month; } - - /** - * Sets the day component. - */ - public void setDay(int day) - { _D = day; } - - /** - * Sets the hour component. - */ - public void setHour(int hour) - { _h = hour; } - - /** - * Sets the minute component. - */ - public void setMinute(int minute) - { _m = minute; } - - /** - * Sets the second component. - */ - public void setSecond(int second) - { _s = second; } - - /** - * Sets the fraction-of-second component. - */ - public void setFraction(BigDecimal fraction) - { _fs = fraction == null ? GDate._zero : fraction; } - - /** - * All GDuration instances return true. - */ - public final boolean isImmutable() - { - return true; - } - - /** - * Returns the sign of the duration: +1 is forwards - * and -1 is backwards in time. - * This value does not necessarily reflect the - * true direction of the duration if the duration - * is not normalized or not normalizable. - */ - public final int getSign() - { return _sign; } - - /** - * Gets the year component. - */ - public final int getYear() - { return _CY; } - - /** - * Gets the month-of-year component. - */ - public final int getMonth() - { return _M; } - - /** - * Gets the day-of-month component. - */ - public final int getDay() - { return _D; } - - /** - * Gets the hour-of-day component. - */ - public final int getHour() - { return _h; } - - /** - * Gets the minute-of-hour component. - */ - public final int getMinute() - { return _m; } - - /** - * Gets the second-of-minute component. - */ - public final int getSecond() - { return _s; } - - - /** - * Gets the fraction-of-second. Range from 0 (inclusive) to 1 (exclusive). - */ - public BigDecimal getFraction() - { return _fs; } - - /** - * Returns true if all of the individual components - * of the duration are nonnegative. - */ - public boolean isValid() - { - return GDurationBuilder.isValidDuration(this); - } - - - /** - * Normalize a duration value. This ensures that months, - * hours, minutes, seconds, and fractions are positive and - * within the ranges 0..11, 0..23, 0..59, etc. Negative - * durations are indicated by a negative sign rather - * than negative components. - *

      - * Most duration specifications can be normalized to - * valid durations with all positive components, but - * not all of them can. - *

      - * The only situations which cannot be normalized are - * where the year/month and the day/hour/minute/second - * offsets are of opposite sign. Days cannot be carried - * into months since the length of a Gregorian month is - * variable depending on when the duration is applied. - * In these cases, this method normalizes the components - * so that "day" is the only negative component. - */ - public void normalize() - { - _normalizeImpl(true); - } - - /** - * fQuotient(a, b) = the greatest integer less than or equal to a/b - */ - private static final long _fQuotient(long a, int b) - { - if ((a < 0) == (b < 0)) - return a / b; - - return -((b - a - 1) / b); - } - - /** - * modulo(a, b) = a - fQuotient(a,b)*b - */ - private static final int _mod(long a, int b, long quotient) - { - return (int)(a - quotient*b) ; - } - - - /** - * Private implemenation of normalize. The flag is - * to facilitate this method calling itself without - * danger of infinite recursion. - */ - private void _normalizeImpl(boolean adjustSign) - { - long temp; - - // months to years - if (_M < 0 || _M > 11) - { - temp = _M; - long ycarry = _fQuotient(temp, 12); - _M = _mod(temp, 12, ycarry); - _CY += ycarry; - } - - long carry = 0; - - // fractions to seconds - if (_fs != null && (_fs.signum() < 0 || _fs.compareTo(GDate._one) >= 0)) - { - BigDecimal bdcarry = _fs.setScale(0, BigDecimal.ROUND_FLOOR); - _fs = _fs.subtract(bdcarry); - carry = bdcarry.intValue(); - } - - if (carry != 0 || _s < 0 || _s > 59 || _m < 0 || _m > 50 || _h < 0 || _h > 23) - { - // seconds - temp = _s + carry; - carry = _fQuotient(temp, 60); - _s = _mod(temp, 60, carry); - - // minutes - temp = _m + carry; - carry = _fQuotient(temp, 60); - _m = _mod(temp, 60, carry); - - // hours - temp = _h + carry; - carry = _fQuotient(temp, 24); - _h = _mod(temp, 24, carry); - _D += carry; - } - - if (_CY == 0 && _M == 0 && _D == 0 && _h == 0 && _m == 0 && _s == 0 && (_fs == null || _fs.signum() == 0)) - _sign = 1; - - if (adjustSign && (_D < 0 || _CY < 0)) - { - int sign = (_D <= 0 && (_CY < 0 || _CY == 0 && _M == 0)) ? -_sign : _getTotalSignSlowly(); - if (sign == 2) - sign = (_CY < 0) ? -_sign : _sign; - if (sign == 0) - sign = 1; - if (sign != _sign) - { - _sign = sign; - _CY = -_CY; - _M = -_M; - _D = -_D; - _h = -_h; - _m = -_m; - _s = -_s; - if (_fs != null) - _fs = _fs.negate(); - } - _normalizeImpl(false); - } - } - - - /* package */ static boolean isValidDuration(GDurationSpecification spec) - { - if (!(spec.getSign() == 1 || spec.getSign() == -1)) - return false; - - return (spec.getYear() >= 0 && spec.getMonth() >= 0 && spec.getDay() >= 0 && - spec.getHour() >= 0 && spec.getMinute() >= 0 && spec.getSecond() >= 0 && - spec.getFraction().signum() >= 0); - } - - /** - * Comparison to another GDuration. - *

        - *
      • Returns -1 if this < duration. (less-than) - *
      • Returns 0 if this == duration. (equal) - *
      • Returns 1 if this > duration. (greater-than) - *
      • Returns 2 if this <> duration. (incomparable) - *
      - * Two instances are incomparable if they have different amounts - * of information. - */ - public final int compareToGDuration(GDurationSpecification duration) - { - return GDurationBuilder.compareDurations(this, duration); - } - - /** - * The natural string representation of the duration. - *

      - * Any components that are zero are omitted. Note that if the duration - * is invalid, i.e., it has negative components, those negative - * components are serialized out here. To check for validity, use - * the isValid() method; and to normalize most durations to a valid - * form use the normalize() method. - */ - public String toString() - { - return GDurationBuilder.formatDuration(this); - } - - /* package */ static int compareDurations(GDurationSpecification d1, GDurationSpecification d2) - { - // first do an all-fields check - if (d1.getFraction().signum() == 0 && d2.getFraction().signum() == 0) - { - int s1 = d1.getSign(); - int s2 = d2.getSign(); - long month1 = s1 * ((long)d1.getYear() * 12 + d1.getMonth()); - long month2 = s2 * ((long)d2.getYear() * 12 + d2.getMonth()); - long sec1 = s1 * ((((long)d1.getDay() * 24 + d1.getHour()) * 60 + d1.getMinute()) * 60 + d1.getSecond()); - long sec2 = s2 * ((((long)d2.getDay() * 24 + d2.getHour()) * 60 + d2.getMinute()) * 60 + d2.getSecond()); - if (month1 == month2) - { - if (sec1 == sec2) - return 0; - if (sec1 < sec2) - return -1; - if (sec1 > sec2) - return 1; - } - if (month1 < month2 && sec1 - sec2 < 28 * 24 * 60 * 60) - return -1; - if (month1 > month2 && sec2 - sec1 < 28 * 24 * 60 * 60) - return 1; - } - - // the answer isn't obvious, so then do a total-sign check - GDurationBuilder diff = new GDurationBuilder(d1); - diff.subtractGDuration(d2); - return diff._getTotalSignSlowly(); - } - - /** - * Per schema spec, comparison of durations is simply done - * by calculating adding the duration to these four dates and - * comparing the results. If the results are ambiguous, the - * answer is "incomparable". - */ - private static final GDate[] _compDate = new GDate[] - { - new GDate(1696, 9, 1, 0, 0, 0, null, 0, 0, 0), - new GDate(1697, 2, 1, 0, 0, 0, null, 0, 0, 0), - new GDate(1903, 3, 1, 0, 0, 0, null, 0, 0, 0), - new GDate(1903, 7, 1, 0, 0, 0, null, 0, 0, 0) - }; - - - /** - * This returns the total sign of the duration, +1 - * if the duration moves forward in time, -1 if the - * duration moves backwards in time, 0 if the duration - * is zero-length, and 2 if the duration may be positive - * or negative depending on the date. - * - * (For example, one month minus 30 days is indeterminate). - */ - private int _getTotalSignSlowly() - { - int pos = 0; - int neg = 0; - int zer = 0; - - GDateBuilder enddate = new GDateBuilder(); - for (int i = 0; i < _compDate.length; i++) - { - enddate.setGDate(_compDate[i]); - enddate.addGDuration(this); - switch (enddate.compareToGDate(_compDate[i])) - { - case -1: - neg++; break; - case 0: - zer++; break; - case 1: - pos++; break; - } - } - - if (pos == _compDate.length) - return +1; - if (neg == _compDate.length) - return -1; - if (zer == _compDate.length) - return 0; - return 2; - } - - /* package */ static String formatDuration(GDurationSpecification duration) - { - // Sign+P: (-)?P - // Year: (?:(\d+)Y)? - // Month: (?:(\d+)M)? - // Day: (?:(\d+)D)? - // Time: (?:(T) - // Hours: (?:(\d+)H)? - // Minutes: (?:(\d+)M)? - // Seconds: (?:(\d+(?:\.\d*)?|(?:.\d+)S)? - - StringBuffer message = new StringBuffer(30); - - if (duration.getSign() < 0) - message.append('-'); - - message.append('P'); - - if (duration.getYear() != 0) - { - message.append(duration.getYear()); - message.append('Y'); - } - - if (duration.getMonth() != 0) - { - message.append(duration.getMonth()); - message.append('M'); - } - - if (duration.getDay() != 0) - { - message.append(duration.getDay()); - message.append('D'); - } - - if (duration.getHour() != 0 || duration.getMinute() != 0 || duration.getSecond() != 0 || - (duration.getFraction().signum() != 0)) - { - message.append('T'); - } - - if (duration.getHour() != 0) - { - message.append(duration.getHour()); - message.append('H'); - } - - if (duration.getMinute() != 0) - { - message.append(duration.getMinute()); - message.append('M'); - } - - if (duration.getFraction().signum() != 0) - { - BigDecimal s = duration.getFraction(); - if (duration.getSecond() != 0) - s = s.add(BigDecimal.valueOf(duration.getSecond())); - // todo when upgrade to 1.5 message.append(s.stripTrailingZeros().toPlainString()); - message.append(stripTrailingZeros(toPlainString(s))); - message.append('S'); - } - else if (duration.getSecond() != 0) - { - message.append(duration.getSecond()); - message.append('S'); - } - else if (message.length() <= 2) - // Specify zero seconds if everything was 0 - message.append("T0S"); - - return message.toString(); - } - - public static String toPlainString(BigDecimal bd) - { - BigInteger intVal = bd.unscaledValue(); - int scale = bd.scale(); - String intValStr = intVal.toString(); - if (scale == 0) - return intValStr; - - boolean isNegative = (intValStr.charAt(0) == '-'); - - int point = intValStr.length() - scale - (isNegative ? 1 : 0); - - StringBuffer sb = new StringBuffer(intValStr.length() + 2 + (point <= 0 ? (-point + 1) : 0)); - if (point <= 0) - { - // prepend zeros and a decimal point. - if (isNegative) sb.append('-'); - sb.append('0').append('.'); - while (point < 0) - { - sb.append('0'); - point++; - } - sb.append(intValStr.substring(isNegative ? 1 : 0)); - } - else if (point < intValStr.length()) - { - // No zeros needed - sb.append(intValStr); - sb.insert(point + (isNegative ? 1 : 0), '.'); - } - else - { - // append zeros if not 0 - sb.append(intValStr); - if (!intVal.equals(BigInteger.ZERO)) - for (int i = intValStr.length(); i < point; i++) - sb.append('0'); - } - return sb.toString(); - } - - public static String stripTrailingZeros(String s) - { - boolean seenDot = false; - int i = s.length() - 1; - int zeroIndex = i; - - while(i>=0) - { - if (s.charAt(i)!='0') - break; - i--; - zeroIndex--; - } - while(i>=0) - { - if (s.charAt(i)=='E') - return s; - if (s.charAt(i)=='.') - { - seenDot = true; - break; - } - i--; - } - - return seenDot? s.substring(0, zeroIndex+1) : s; - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/QNameSet.java b/src/xmlpublic/org/apache/xmlbeans/QNameSet.java deleted file mode 100644 index 246e874..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/QNameSet.java +++ /dev/null @@ -1,447 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; - -import java.util.Set; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Collections; -import java.util.Arrays; - -/** - * This interface represents a lattice of finite and infinite sets of QNames. - * The lattice the minimal one that is closed under union, intersection, and - * inverse, and contains individual QNames as well as entire namespaces. - * Here is a summary of the two kinds of QNameSets: - *

        - *
      • A QNameSet can cover a finite set of namespaces, additionally including a finite - * set of QNames outside those namespaces, and with the exception of - * a finite set of QNames excluded from those namespaes: - *
          - *
        • excludedQNamesInIncludedURIs == the set of excluded QNames from coveredURIs namespaces - *
        • excludedURIs == null - *
        • includedURIs == the set of covered namespace URIs - *
        • includedQNamesInExcludedURIs == set of additional QNames outside coveredURIs namespaces - *
        - *
      • - *
      • A QNameSet can cover all namespaces except for a finite number of excluded ones, - * additionally including a finite set of QNames within the excluded namespaces, - * and with the exception of a finite set of QNames outside the excluded namespaces: - *
          - *
        • excludedQNamesInIncludedURIs == the set of excluded QNames outside uncoveredURIs namespaces - *
        • excludedURIs == the set of uncovered namespace URIs - *
        • includedURIs == null - *
        • includedQNamesInExcludedURIs == set of additional QNames from uncoveredURIs namespaces - *
        - *
      • - *
      - *

      - * Notice that a finite set of QNames is a degenerate case of the first - * category outlined above: - *

        - *
      • A QnameSet can contain a finite number of QNames: - *
          - *
        • excludedQNamesInIncludedURIs == empty set - *
        • excludedURIs == null - *
        • includedURIs == empty set - *
        • includedQNamesInExcludedURIs == set of included QNames - *
        - *
      • - *
      - * - * @see QNameSetBuilder - */ -public final class QNameSet implements QNameSetSpecification, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private final boolean _inverted; - private final Set _includedURIs; - private final Set _excludedQNames; - private final Set _includedQNames; - - /** - * The empty QNameSet. - */ - public static final QNameSet EMPTY = new QNameSet(null, Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.EMPTY_SET); - - /** - * The QNameSet containing all QNames. - */ - public static final QNameSet ALL = new QNameSet(Collections.EMPTY_SET, null, Collections.EMPTY_SET, Collections.EMPTY_SET); - - /** - * The QNameSet containing all QNames in the local (no-)namespace. - */ - public static final QNameSet LOCAL = new QNameSet(null, Collections.singleton(""), Collections.EMPTY_SET, Collections.EMPTY_SET); - - /** - * The QNameSet containing all QNames except for those in the local (no-)namespace. - */ - public static final QNameSet NONLOCAL = new QNameSet(Collections.singleton(""), null, Collections.EMPTY_SET, Collections.EMPTY_SET); - - /** - * Private function to minimize object creation when copying sets. - */ - private static Set minSetCopy(Set original) - { - if (original == null) - return null; - if (original.isEmpty()) - return Collections.EMPTY_SET; - if (original.size() == 1) - return Collections.singleton(original.iterator().next()); - return new HashSet(original); - } - - /** - * Returns a QNameSet based on the given sets of excluded URIs, - * included URIs, excluded QNames in included namespaces, and included - * QNames in excluded namespaces. - * - * @param excludedURIs the finite set of namespace URI strings to exclude from the set, or null if this set is infinite - * @param includedURIs the finite set of namespace URI strings to include in the set, or null if this set is infinite - * @param excludedQNamesInIncludedURIs the finite set of exceptional QNames to exclude from the included namespaces - * @param excludedQNamesInIncludedURIs the finite set of exceptional QNames to include that are in the excluded namespaces - * - * @return the constructed QNameSet - */ - public static QNameSet forSets(Set excludedURIs, Set includedURIs, Set excludedQNamesInIncludedURIs, Set includedQNamesInExcludedURIs) - { - if ((excludedURIs != null) == (includedURIs != null)) - throw new IllegalArgumentException("Exactly one of excludedURIs and includedURIs must be null"); - - if (excludedURIs == null && includedURIs.isEmpty() && includedQNamesInExcludedURIs.isEmpty()) - return EMPTY; - if (includedURIs == null && excludedURIs.isEmpty() && excludedQNamesInIncludedURIs.isEmpty()) - return ALL; - if (excludedURIs == null && includedURIs.size() == 1 && includedURIs.contains("") && - includedQNamesInExcludedURIs.isEmpty() && excludedQNamesInIncludedURIs.isEmpty()) - return LOCAL; - if (includedURIs == null && excludedURIs.size() == 1 && excludedURIs.contains("") && - excludedQNamesInIncludedURIs.isEmpty() && includedQNamesInExcludedURIs.isEmpty()) - return NONLOCAL; - - return new QNameSet( - minSetCopy(excludedURIs), - minSetCopy(includedURIs), - minSetCopy(excludedQNamesInIncludedURIs), - minSetCopy(includedQNamesInExcludedURIs)); - } - - /** - * Returns a QNameSet based on the given array of included QNames - * - * @param includedQNames the array of included QNames - */ - public static QNameSet forArray(QName[] includedQNames) - { - if (includedQNames == null) - throw new IllegalArgumentException("includedQNames cannot be null"); - - return new QNameSet(null, Collections.EMPTY_SET, Collections.EMPTY_SET, new HashSet(Arrays.asList(includedQNames))); - } - - /** - * Returns a QNameSet with the same contents as the given - * QNameSetSpecification. - * @return the copied QNameSet - */ - public static QNameSet forSpecification(QNameSetSpecification spec) - { - if (spec instanceof QNameSet) - return (QNameSet)spec; - return QNameSet.forSets(spec.excludedURIs(), spec.includedURIs(), spec.excludedQNamesInIncludedURIs(), spec.includedQNamesInExcludedURIs()); - } - - /** - * Returns a QNameSet corresponding to the given wildcard namespace string. - * This is a space-separated list of URIs, plus special tokens as specified - * in the XML Schema specification (##any, ##other, ##targetNamespace, ##local). - * @return the constructed QNameSet - */ - public static QNameSet forWildcardNamespaceString(String wildcard, String targetURI) - { - return QNameSet.forSpecification(new QNameSetBuilder(wildcard, targetURI)); - } - - /** - * Returns a QNameSet containing only the given QName. - * @return the constructed QNameSet - */ - public static QNameSet singleton(QName name) - { - return new QNameSet(null, Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.singleton(name)); - } - - /** - * Constructs a QNameSetBuilder whose contents are given by - * the four sets. - * - * This constuctor is PRIVATE because it uses the given - * sets directly, and it trusts its callers to set only immutable values. - * This constructor is is only called by the static builder methods on - * QNameSet: those methods are all careful assign only unchanging sets. - */ - private QNameSet(Set excludedURIs, Set includedURIs, Set excludedQNamesInIncludedURIs, Set includedQNamesInExcludedURIs) - { - if (includedURIs != null && excludedURIs == null) - { - _inverted = false; - _includedURIs = includedURIs; - _excludedQNames = excludedQNamesInIncludedURIs; - _includedQNames = includedQNamesInExcludedURIs; - } - else if (excludedURIs != null && includedURIs == null) - { - _inverted = true; - _includedURIs = excludedURIs; - _excludedQNames = includedQNamesInExcludedURIs; - _includedQNames = excludedQNamesInIncludedURIs; - } - else - throw new IllegalArgumentException("Exactly one of excludedURIs and includedURIs must be null"); - } - - /** - * Local xml names are hased using "" as the namespace. - */ - private static String nsFromName(QName xmlName) - { - String ns = xmlName.getNamespaceURI(); - return ns == null ? "" : ns; - } - - /** - * True if this ModelTransitionSet contains the given qname. - */ - public boolean contains(QName name) - { - boolean in = _includedURIs.contains(nsFromName(name)) ? - !_excludedQNames.contains(name) : - _includedQNames.contains(name); - return _inverted ^ in; - } - - /** - * True if this ModelTransitionSet contains all QNames. - */ - public boolean isAll() - { - return _inverted && _includedURIs.isEmpty() && _includedQNames.isEmpty(); - } - - /** - * True if this ModelTransitionSet contains no QNames. - */ - public boolean isEmpty() - { - return !_inverted && _includedURIs.isEmpty() && _includedQNames.isEmpty(); - } - - /** - * Returns a new QNameSet that is the intersection of this one and another. - * @param set the set to insersect with - * @return the intersection - */ - public QNameSet intersect(QNameSetSpecification set) - { - QNameSetBuilder result = new QNameSetBuilder(this); - result.restrict(set); - return result.toQNameSet(); - } - - /** - * Returns a new QNameSet that is the union of this one and another. - * @param set the set to union with - * @return the union - */ - public QNameSet union(QNameSetSpecification set) - { - QNameSetBuilder result = new QNameSetBuilder(this); - result.addAll(set); - return result.toQNameSet(); - } - - /** - * Returns a new QNameSet that is the inverse of this one. - */ - public QNameSet inverse() - { - if (this == EMPTY) - return ALL; - if (this == ALL) - return EMPTY; - if (this == LOCAL) - return NONLOCAL; - if (this == NONLOCAL) - return LOCAL; - return new QNameSet(includedURIs(), excludedURIs(), includedQNamesInExcludedURIs(), excludedQNamesInIncludedURIs()); - } - - /** - * True if the given set is a subset of this one. - * @param set the set to test - * @return true if this contains all QNames contained by the given set - */ - public boolean containsAll(QNameSetSpecification set) - { - // a.contains(b) == a.inverse.isDisjoint(b) - if (!_inverted && set.excludedURIs() != null) - return false; - - return inverse().isDisjoint(set); - } - - /** - * True if the given set is disjoint from this one. - * @param set the set to test - * @return true if the set is disjoint from this set - */ - public boolean isDisjoint(QNameSetSpecification set) - { - if (_inverted && set.excludedURIs() != null) - return false; - - if (_inverted) - return isDisjointImpl(set, this); - else - return isDisjointImpl(this, set); - } - - private boolean isDisjointImpl(QNameSetSpecification set1, QNameSetSpecification set2) - { - Set includeURIs = set1.includedURIs(); - Set otherIncludeURIs = set2.includedURIs(); - if (otherIncludeURIs != null) - { - for (Iterator i = includeURIs.iterator(); i.hasNext(); ) - { - if (otherIncludeURIs.contains(i.next())) - return false; - } - } - else - { - Set otherExcludeURIs = set2.excludedURIs(); - for (Iterator i = includeURIs.iterator(); i.hasNext(); ) - { - if (!otherExcludeURIs.contains(i.next())) - return false; - } - } - - for (Iterator i = set1.includedQNamesInExcludedURIs().iterator(); i.hasNext(); ) - { - if (set2.contains((QName)i.next())) - return false; - } - - if (includeURIs.size() > 0) - for (Iterator i = set2.includedQNamesInExcludedURIs().iterator(); i.hasNext(); ) - { - if (set1.contains((QName)i.next())) - return false; - } - - return true; - } - - - /** - * Namespaces that are fully excluded from the set except for a finite - * number of individual QName exceptions. Returns null if this set is infinite. - * @return the set of excluded namespace URI strings - */ - public Set excludedURIs() - { - if (_inverted) return Collections.unmodifiableSet(_includedURIs); - return null; - } - - /** - * Namespaces that are fully included in set except for a finite - * number of individual QName exceptions. Returns null if this set is infinite. - * @return the set of included namespace URI strings - */ - public Set includedURIs() - { - if (!_inverted) return _includedURIs; - return null; - } - - /** - * The set of QNames excluded from the set even though they are within - * a namespace that is otherwise fully included in the set. - * @return the set of excluded QNames from within includedURI namespaces - */ - public Set excludedQNamesInIncludedURIs() - { - return Collections.unmodifiableSet(_inverted ? _includedQNames : _excludedQNames); - } - - /** - * The set of QNames included in the set even though they are within - * a namespace that is otherwise fully included in the set. - * @return the set of included QNames from within excludedURI namespaces - */ - public Set includedQNamesInExcludedURIs() - { - return Collections.unmodifiableSet(_inverted ? _excludedQNames : _includedQNames); - } - - private String prettyQName(QName name) - { - if (name.getNamespaceURI() == null) - return name.getLocalPart(); - return name.getLocalPart() + "@" + name.getNamespaceURI(); - } - - /** - * Returns a string representation useful for debugging, subject to change. - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("QNameSet"); - sb.append(_inverted ? "-(" : "+("); - for (Iterator i = _includedURIs.iterator(); i.hasNext(); ) - { - sb.append("+*@"); - sb.append(i.next()); - sb.append(", "); - } - for (Iterator i = _excludedQNames.iterator(); i.hasNext(); ) - { - sb.append("-"); - sb.append(prettyQName((QName)i.next())); - sb.append(", "); - } - for (Iterator i = _includedQNames.iterator(); i.hasNext(); ) - { - sb.append("+"); - sb.append(prettyQName((QName)i.next())); - sb.append(", "); - } - int index = sb.lastIndexOf(", "); - if (index > 0) - sb.setLength(index); - sb.append(')'); - return sb.toString(); - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaCodePrinter.java b/src/xmlpublic/org/apache/xmlbeans/SchemaCodePrinter.java deleted file mode 100755 index 8b65366..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/SchemaCodePrinter.java +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.io.Writer; -import java.io.IOException; - -/** - * This class is used to provide alternate implementations of the - * schema Java code generation. - */ - -public interface SchemaCodePrinter -{ - public void printTypeImpl(Writer writer, SchemaType sType) - throws IOException; - - public void printType(Writer writer, SchemaType sType) - throws IOException; - - /** - * @deprecated Obsoleted by functionality in {@link SchemaTypeSystem.save()} - */ - public void printLoader(Writer writer, SchemaTypeSystem system) - throws IOException; -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaIdentityConstraint.java b/src/xmlpublic/org/apache/xmlbeans/SchemaIdentityConstraint.java deleted file mode 100644 index cf5933a..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/SchemaIdentityConstraint.java +++ /dev/null @@ -1,97 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; -import java.util.Map; - -/** - * Represents an identity constraint definition. - */ -public interface SchemaIdentityConstraint extends SchemaComponent, SchemaAnnotated -{ - /** - * Return the selector xpath as a string. - */ - String getSelector(); - - /** - * Return a compiled xpath object for the selector. - */ - Object getSelectorPath(); - - /** - * Return (a copy of) the xpaths for all the fields. - */ - String[] getFields(); - - /** - * Return a compiled xpath object for the field. - */ - Object getFieldPath(int index); - - /** - * Return a read-only copy of the namespace map. This is the - * set of prefix to URI mappings that were in scope in the - * schema at the point at which this constraint was declared - */ - Map getNSMap(); - - /** A xs:key constraint. See {@link #getConstraintCategory}. */ - public static final int CC_KEY = 1; - /** A xs:keyRef constraint. See {@link #getConstraintCategory}. */ - public static final int CC_KEYREF = 2; - /** A xs:unique constraint. See {@link #getConstraintCategory}. */ - public static final int CC_UNIQUE = 3; - - /** - * Return the constraint category. Either {@link #CC_KEY}, {@link #CC_KEYREF}, - * or {@link #CC_UNIQUE}. - */ - int getConstraintCategory(); - - /** - * Returns the key that a key ref refers to. Only valid for - * keyrefs. - */ - SchemaIdentityConstraint getReferencedKey(); - - /** - * Used to allow on-demand loading of identity constraints. - * - * @exclude - */ - public static final class Ref extends SchemaComponent.Ref - { - public Ref(SchemaIdentityConstraint idc) - { super(idc); } - - public Ref(SchemaTypeSystem system, String handle) - { super(system, handle); } - - public final int getComponentType() - { return SchemaComponent.IDENTITY_CONSTRAINT; } - - public final SchemaIdentityConstraint get() - { return (SchemaIdentityConstraint)getComponent(); } - } - - /** - * Returns user-specific information. - * @see SchemaBookmark - */ - Object getUserData(); -} diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaType.java b/src/xmlpublic/org/apache/xmlbeans/SchemaType.java deleted file mode 100644 index fc10375..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/SchemaType.java +++ /dev/null @@ -1,908 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; - -/** - * Represents a schema type. - *

      - * SchemaType is the metadata "type" class for {@link XmlObject}, and it plays the - * analogous role for {@link XmlObject} that {@link java.lang.Class} plays for - * {@link java.lang.Object}. - *

      - * Every XML Bean class corresponds to a singleton SchemaType object - * obtainable by ClassName.type (e.g., {@link XmlNonPositiveInteger#type}), and - * every XML Bean instance has an actual SchemaType, obtainable by - * {@link XmlObject#schemaType}. The ClassName.type and schemaType() mechanisms are - * analogous to the ordinary Java ClassName.class and obj.getClass() mechanisms. - *

      - * All schema types are represented by a SchemaType, this includes all types - * regardless of whether they are built-in or user-defined, compiled or - * uncompiled, simple or complex. - *

      - * In addition, a compiled XML Bean type system includes special "document" schema types - * each representing a document containing nothing but a single element for each - * global element, and special "attribute" schema types each representing - * a fragment containing nothing but a single global attribute for global - * attribute. - *

      - * Do not confuse Schema Types with other types of Schema Components such as - * {@link SchemaGlobalElement Global Elements}, {@link SchemaGlobalAttribute Global Attributes}, - * {@link SchemaModelGroup Named Model Groups}, or {@link SchemaAttributeGroup Attribute Groups}. - * SchemaType represents a Type component, not any of the other kinds of components. - * There are different kinds of metadata objects for the different Schema components. - *

      - * The space of SchemaTypes is divided as follows: - * - *

        - *
      • First, there is the universal base type and the universal - * subtype. These are {@link XmlObject#type} - * (corresponding to xs:anyType) and {@link XmlBeans#NO_TYPE}, - * respectively. The first type is a base type of all other - * types. The other type indicates the absence of type information - * and, at least in set-theoretic terms, is a subtype of all other types. - *
      • There is another universal base type that is the base type - * for all simple types. This is the {@link XmlAnySimpleType#type}, - * corresponding to xs:anySimpleType. Only XmlObject.type and - * XmlAnySimpleType.type return true for {@link #isURType}, and - * only XmlBeans.NO_TYPE returns true for {@link #isNoType}. - *
      • The two "special" kinds of types that are generated that - * do not formally exist in the actual Schema specification are - * document types and global attribute types (corresponding to - * documents that contain a global element, or fragments that - * contain a global attribute). They can be detected using - * {@link #isDocumentType} and {@link #isAttributeType}. Other - * than their anonymity (lack of a type name) and their appearance - * only at the root of an instance, they are otherwise just like - * ordinary complex types. - *
      • Simple types can be detected using {@link #isSimpleType}. - * Complex types are consdered to be all the types that are - * not simple. - *
      • Simple types are divided into three varieties: atomic types, - * list types, and union types. Which variety of simple type - * you have can be discoverd using {@link #getSimpleVariety}. - * It will return either {@link #ATOMIC}, {@link #LIST}, or - * {@link #UNION}. - *
      • An {@link #ATOMIC} simple type is always based on one of the - * 20 built-in primitive schema types. You can determine - * the underlying primitive type for an atomic simple type - * by calling {@link #getPrimitiveType}. An atomic type - * may add facet restrictions on top of the primitive type, - * and these facets can be explored using {@link #getFacet}, - * {@link #getWhiteSpaceRule}, {@link #matchPatternFacet}, - * {@link #getEnumerationValues}, and related methods. - *
      • A {@link #LIST} simple type is always based on another non-list - * simple type. The underlying list item type can be obtained - * by using {@link #getListItemType}. - *
      • A {@link #UNION} simple type is always composed out of a number of - * other simple types. The direct members of the union can - * be obtained by {@link #getUnionMemberTypes}. When unions - * consist of other unions, it is useful to know useful to know - * the "leaves of the union tree", so the - * set of non-union types making up the union can be obtained - * by {@link #getUnionConstituentTypes}. The closure of the - * entire "union tree" is {@link #getUnionSubTypes} (this includes - * the type itself). For - * simple unions that do not consist of other unions, all three - * of these sets are the same. - *
      • Complex types have nested structure. They are divided into - * four content types: empty content, simple content, element-only - * content, and mixed content. All kinds of complex types may - * have attributes. The content type for a complex type can - * be dermined using {@link #getContentType}. This will return - * {@link #EMPTY_CONTENT}, {@link #SIMPLE_CONTENT}, - * {@link #ELEMENT_CONTENT}, or {@link #MIXED_CONTENT}. - *
      • If a complex type has {@link #EMPTY_CONTENT}, the content model will be null. - *
      • If a complex type has {@link #SIMPLE_CONTENT}, then it will extend the - * simple type that describes the content. In addition, the type - * may impose additional simple type facet restrictions; these can - * be determined in the same way they are for a simple type. - *
      • If a complex type has {@link #ELEMENT_CONTENT} or {@link #MIXED_CONTENT}, then - * the detailed content model can be determined by examining - * the particle tree (which may be null for MIXED_CONTENT). - * The particle tree can be obtained via {@link #getContentModel}. - *
      • When working with a complex type, most users will find it - * sufficient to discover the summarized shape of the content model - * and attribute model using {@link #getElementProperties}, - * {@link #getAttributeProperties}, and related methods rather than - * examining the particle tree and attribute model directly. - *
      - * - * @see SchemaTypeLoader - * @see XmlObject#schemaType - * @see SimpleValue#instanceType - */ -public interface SchemaType extends SchemaComponent, SchemaAnnotated -{ - /** - * The name used to describe the type in the schema. - * Null if the type is anonymous (nested), or if it is a document type. - */ - public abstract QName getName(); - - /** - * The parent schema element. - * Null for top-level (named) types and document types. - */ - public abstract SchemaField getContainerField(); - - /** - * True if this is a document type. - *

      - * Document types are generated for every global element. A document - * type is an unnamed complex type that contains exactly one element: - * we define these types, because they are the types of the "documents" - * which contain the defined global elements, and they all turn into - * Java types. (Named ElementnameDocument.) - */ - public boolean isDocumentType(); - - /** - * True if this is a attribute type. - *

      - * Attribute types are generated for every global attribute. An attribute - * type is an unnamed complex type that contains exactly one attribute: - * we define these types, because they are the types of the "attribute documents" - * which contain the defined global attribute, and they all turn into - * Java types. (Named AttributenameAttribute.) - */ - public boolean isAttributeType(); - - - /** - * Returns the document element name if this is a document type, - * or null otherwise. - */ - public QName getDocumentElementName(); - - /** - * Returns the attribute qname if this is a attribute type, - * or null otherwise. - */ - public QName getAttributeTypeAttributeName(); - - /** - * The outer schema type. - * Null for top-level (named) types. - */ - public abstract SchemaType getOuterType(); - - /** - * True if this anonymous type has no corresponding Java type. True for - * anonymous types nested within simple type restrictions. - */ - public abstract boolean isSkippedAnonymousType(); - - /** - * True if this schema type was compiled to have a corresponding - * Java class. - */ - public abstract boolean isCompiled(); - - /** - * The fully-qualified Java type name of the class. - */ - public abstract String getFullJavaName(); - - /** - * The short unqualfiied Java name for the class. - */ - public abstract String getShortJavaName(); - - /** - * The fully-qualified Java type name of the implementation class. - */ - public abstract String getFullJavaImplName(); - - /** - * The short unqualfiied Java name for the implementation class. - */ - public abstract String getShortJavaImplName(); - - /** - * The Java class corresponding to this schema type. - */ - public abstract Class getJavaClass(); - - /** - * The Java class corresponding to the enumeration type for this schema type, - * if applicable (or null if not an enumeration). - */ - public abstract Class getEnumJavaClass(); - - /** - * Returns user-specific information. - * @see SchemaBookmark - */ - public Object getUserData(); - - /** - * True if the Xsd type is anonymous (i.e., not top-level). - */ - public abstract boolean isAnonymousType(); - - /** - * True for any of the 40+ built-in types. - */ - public abstract boolean isBuiltinType(); - - /** - * True for the anySimpleType and any restrictions/unions/lists. - */ - public abstract boolean isSimpleType(); - - /** - * Returns base restriction or extension type. Unions and lists - * return the anySimpleType. - */ - public abstract SchemaType getBaseType(); - - /** - * Returns common base type with the given type. The returned - * type is the most specific declared base type of both types. - */ - public abstract SchemaType getCommonBaseType(SchemaType type); - - /** - * True if the specified type derives from this type (or if - * it is the same type). - * - * Note that XmlObject.type (the anyType) is assignable - * from all type, and the XmlBeans.noType (the absence of - * a type) is assignable to all types. - */ - public abstract boolean isAssignableFrom(SchemaType type); - - /** - * Returns an integer for the derivation type, either - * {@link #DT_EXTENSION}, {@link #DT_RESTRICTION}, {@link #DT_NOT_DERIVED}. - */ - public int getDerivationType(); - - /** Not derived. True for XmlObject.type only. See {@link #getDerivationType}. */ - public static final int DT_NOT_DERIVED = 0; - /** Derived by restriction. See {@link #getDerivationType}. */ - public static final int DT_RESTRICTION = 1; - /** Derived by extension. See {@link #getDerivationType}. */ - public static final int DT_EXTENSION = 2; - - /** - * Returns an integer for builtin types that can be used - * for quick comparison. - */ - public abstract int getBuiltinTypeCode(); - - /** Not a builtin type */ - public static final int BTC_NOT_BUILTIN = 0; - /** xs:anyType, aka {@link XmlObject#type} */ - public static final int BTC_ANY_TYPE = 1; - - /** The primitive types have codes between BTC_FIRST_PRIMITIVE and BTC_LAST_PRIMITIVE inclusive */ - public static final int BTC_FIRST_PRIMITIVE = 2; - - /** xs:anySimpleType, aka {@link XmlAnySimpleType#type} */ - public static final int BTC_ANY_SIMPLE = 2; - - /** xs:boolean, aka {@link XmlBoolean#type} */ - public static final int BTC_BOOLEAN = 3; - /** xs:base64Binary, aka {@link XmlBase64Binary#type} */ - public static final int BTC_BASE_64_BINARY = 4; - /** xs:hexBinary, aka {@link XmlBase64Binary#type} */ - public static final int BTC_HEX_BINARY = 5; - /** xs:anyURI, aka {@link XmlAnyURI#type} */ - public static final int BTC_ANY_URI = 6; - /** xs:QName, aka {@link XmlQName#type} */ - public static final int BTC_QNAME = 7; - /** xs:NOTATION, aka {@link XmlNOTATION#type} */ - public static final int BTC_NOTATION = 8; - /** xs:float, aka {@link XmlFloat#type} */ - public static final int BTC_FLOAT = 9; - /** xs:double, aka {@link XmlDouble#type} */ - public static final int BTC_DOUBLE = 10; - /** xs:decimal, aka {@link XmlDecimal#type} */ - public static final int BTC_DECIMAL = 11; - /** xs:string, aka {@link XmlString#type} */ - public static final int BTC_STRING = 12; - - /** xs:duration, aka {@link XmlDuration#type} */ - public static final int BTC_DURATION = 13; - /** xs:dateTime, aka {@link XmlDateTime#type} */ - public static final int BTC_DATE_TIME = 14; - /** xs:time, aka {@link XmlTime#type} */ - public static final int BTC_TIME = 15; - /** xs:date, aka {@link XmlDate#type} */ - public static final int BTC_DATE = 16; - /** xs:gYearMonth, aka {@link XmlGYearMonth#type} */ - public static final int BTC_G_YEAR_MONTH = 17; - /** xs:gYear, aka {@link XmlGYear#type} */ - public static final int BTC_G_YEAR = 18; - /** xs:gMonthDay, aka {@link XmlGMonthDay#type} */ - public static final int BTC_G_MONTH_DAY = 19; - /** xs:gDay, aka {@link XmlGDay#type} */ - public static final int BTC_G_DAY = 20; - /** xs:gMonth, aka {@link XmlGMonth#type} */ - public static final int BTC_G_MONTH = 21; - - /** The primitive types have codes between BTC_FIRST_PRIMITIVE and BTC_LAST_PRIMITIVE inclusive */ - public static final int BTC_LAST_PRIMITIVE = 21; - - // derived numerics - /** xs:integer, aka {@link XmlInteger#type} */ - public static final int BTC_INTEGER = 22; - /** xs:long, aka {@link XmlLong#type} */ - public static final int BTC_LONG = 23; - /** xs:int, aka {@link XmlInt#type} */ - public static final int BTC_INT = 24; - /** xs:short, aka {@link XmlShort#type} */ - public static final int BTC_SHORT = 25; - /** xs:byte, aka {@link XmlByte#type} */ - public static final int BTC_BYTE = 26; - /** xs:nonPositiveInteger, aka {@link XmlNonPositiveInteger#type} */ - public static final int BTC_NON_POSITIVE_INTEGER = 27; - /** xs:NegativeInteger, aka {@link XmlNegativeInteger#type} */ - public static final int BTC_NEGATIVE_INTEGER = 28; - /** xs:nonNegativeInteger, aka {@link XmlNonNegativeInteger#type} */ - public static final int BTC_NON_NEGATIVE_INTEGER = 29; - /** xs:positiveInteger, aka {@link XmlPositiveInteger#type} */ - public static final int BTC_POSITIVE_INTEGER = 30; - /** xs:unsignedLong, aka {@link XmlUnsignedLong#type} */ - public static final int BTC_UNSIGNED_LONG = 31; - /** xs:unsignedInt, aka {@link XmlUnsignedInt#type} */ - public static final int BTC_UNSIGNED_INT = 32; - /** xs:unsignedShort, aka {@link XmlUnsignedShort#type} */ - public static final int BTC_UNSIGNED_SHORT = 33; - /** xs:unsignedByte, aka {@link XmlUnsignedByte#type} */ - public static final int BTC_UNSIGNED_BYTE = 34; - - // derived strings - /** xs:normalizedString, aka {@link XmlNormalizedString#type} */ - public static final int BTC_NORMALIZED_STRING = 35; - /** xs:token, aka {@link XmlToken#type} */ - public static final int BTC_TOKEN = 36; - /** xs:Name, aka {@link XmlName#type} */ - public static final int BTC_NAME = 37; - /** xs:NCName, aka {@link XmlNCName#type} */ - public static final int BTC_NCNAME = 38; - /** xs:language, aka {@link XmlLanguage#type} */ - public static final int BTC_LANGUAGE = 39; - /** xs:ID, aka {@link XmlID#type} */ - public static final int BTC_ID = 40; - /** xs:IDREF, aka {@link XmlIDREF#type} */ - public static final int BTC_IDREF = 41; - /** xs:IDREFS, aka {@link XmlIDREFS#type} */ - public static final int BTC_IDREFS = 42; - /** xs:ENTITY, aka {@link XmlENTITY#type} */ - public static final int BTC_ENTITY = 43; - /** xs:ENTITIES, aka {@link XmlENTITIES#type} */ - public static final int BTC_ENTITIES = 44; - /** xs:NMTOKEN, aka {@link XmlNMTOKEN#type} */ - public static final int BTC_NMTOKEN = 45; - /** xs:NMTOKENS, aka {@link XmlNMTOKENS#type} */ - public static final int BTC_NMTOKENS = 46; - - public static final int BTC_LAST_BUILTIN = 46; - - /** - * True for anyType and anySimpleType. - */ - public boolean isURType(); - - /** - * True for the type object that represents a the absence of a determined type. - * XML Objects whose type isNoType() are never valid. - */ - public boolean isNoType(); - - /** - * Returns the SchemaTypeLoader in which this type was defined. - * Complex types are defined and used in exactly one schema type - * system, but simple types are defined in one type system and can - * be used in any number of type systems. The most common case is - * the builtin types, which are defined in the builtin type system - * and used elsewhere. - */ - public SchemaTypeSystem getTypeSystem(); - - /** True if this type cannot be used directly in instances */ - public boolean isAbstract(); - - /** True if other types cannot extend this type (only for complex types) */ - public boolean finalExtension(); - - /** True if other types cannot restrict this type */ - public boolean finalRestriction(); - - /** True if list derivation of this type is prohibited (only for simple types) */ - public boolean finalList(); - - /** True if union derivation of this type is prohibited (only for simple types) */ - public boolean finalUnion(); - - /** True if extensions of this type cannot be substituted for this type */ - public boolean blockExtension(); - - /** True if restrictions of this type cannot be substituted for this type */ - public boolean blockRestriction(); - - /** - * Returns {@link #EMPTY_CONTENT}, {@link #SIMPLE_CONTENT}, {@link #ELEMENT_CONTENT}, or - * {@link #MIXED_CONTENT} for complex types. For noncomplex types, returns - * {@link #NOT_COMPLEX_TYPE}. - */ - public abstract int getContentType(); - - /** Not a complex type. See {@link #getContentType()}. */ - public static final int NOT_COMPLEX_TYPE = 0; - /** Empty content. See {@link #getContentType()}. */ - public static final int EMPTY_CONTENT = 1; - /** Simple content. See {@link #getContentType()}. */ - public static final int SIMPLE_CONTENT = 2; - /** Element-only content. See {@link #getContentType()}. */ - public static final int ELEMENT_CONTENT = 3; - /** Mixed content. See {@link #getContentType()}. */ - public static final int MIXED_CONTENT = 4; - - - /** - * For complex types with simple content returns the base type for this - * type's content. In most cases, this is the same as the base type, but - * it can also be an anonymous type. - */ - SchemaType getContentBasedOnType(); - - /** - * Returns a {@link SchemaTypeElementSequencer} object, which can then - * be used to validate complex content inside this element. This is useful - * for example for trying out different names and see which one would be - * valid as a child of this element. - */ - SchemaTypeElementSequencer getElementSequencer(); - - /** - * The array of inner (anonymous) types defined - * within this type. - */ - public abstract SchemaType[] getAnonymousTypes(); - - /** - * Returns a SchemaProperty corresponding to an element within this - * complex type by looking up the element name. - */ - public abstract SchemaProperty getElementProperty(QName eltName); - - /** - * Returns all the SchemaProperties corresponding to elements. - */ - public abstract SchemaProperty[] getElementProperties(); - - /** - * Returns a SchemaProperty corresponding to an attribute within this - * complex type by looking up the attribute name. - */ - public abstract SchemaProperty getAttributeProperty(QName attrName); - - /** - * Returns all the SchemaProperties corresponding to attributes. - */ - public abstract SchemaProperty[] getAttributeProperties(); - - /** - * Returns all the SchemaProperties within this complex type, - * elements followed by attributes. - */ - public abstract SchemaProperty[] getProperties(); - - /** - * Returns the SchemaProperties defined by this complex type, - * exclusive of the base type (if any). - */ - SchemaProperty[] getDerivedProperties(); - - /** - * Returns the attribute model for this complex type (with simple or complex content). - */ - public abstract SchemaAttributeModel getAttributeModel(); - - /** - * True if this type permits wildcard attributes. See the attribute model for - * more information about which wildcards are allowed. - */ - public abstract boolean hasAttributeWildcards(); - - /** - * Returns the complex content model for this complex type (with complex content). - */ - public abstract SchemaParticle getContentModel(); - - /** - * True if this type permits element wildcards. See the content model for - * more information about which wildcards are allowed, and where. - */ - public abstract boolean hasElementWildcards(); - - /** - * For document types, true if the given name can be substituted for the - * document element name. - */ - public boolean isValidSubstitution(QName name); - - /** - * True if the complex content model for this complex type is an "all" group. - */ - public abstract boolean hasAllContent(); - - /** - * True if particles have same defaults, nillability, etc, that are - * invariant when order changes. Computed only for Javaized types. - */ - public abstract boolean isOrderSensitive(); - - /** - * Returns the type of a child element based on the element name and - * an xsi:type attribute (and the type system within which names are - * resolved). - */ - public abstract SchemaType getElementType(QName eltName, QName xsiType, SchemaTypeLoader wildcardTypeLoader); - - /** - * Returns the type of an attribute based on the attribute name and - * the type system within which (wildcard) names are resolved. - */ - public abstract SchemaType getAttributeType(QName eltName, SchemaTypeLoader wildcardTypeLoader); - - /*************************************************************/ - /* SIMPLE TYPE MODEL BELOW */ - /*************************************************************/ - - /** xs:length facet */ - public static final int FACET_LENGTH = 0; - /** xs:minLength facet */ - public static final int FACET_MIN_LENGTH = 1; - /** xs:maxLength facet */ - public static final int FACET_MAX_LENGTH = 2; - /** xs:minExclusive facet */ - public static final int FACET_MIN_EXCLUSIVE = 3; - /** xs:minInclusive facet */ - public static final int FACET_MIN_INCLUSIVE = 4; - /** xs:maxInclusive facet */ - public static final int FACET_MAX_INCLUSIVE = 5; - /** xs:maxExclusive facet */ - public static final int FACET_MAX_EXCLUSIVE = 6; - /** xs:totalDigits facet */ - public static final int FACET_TOTAL_DIGITS = 7; - /** xs:fractionDigits facet */ - public static final int FACET_FRACTION_DIGITS = 8; - - public static final int LAST_BASIC_FACET = 8; - - /** xs:whiteSpace facet - use {@link #getWhiteSpaceRule} instead */ - public static final int FACET_WHITE_SPACE = 9; - /** xs:pattern facet - use {@link #matchPatternFacet} instead */ - public static final int FACET_PATTERN = 10; - /** xs:enumeration facet - use {@link #getEnumerationValues} instead */ - public static final int FACET_ENUMERATION = 11; - - /** The last ordinary facet code */ - public static final int LAST_FACET = 11; - - /** @see #ordered */ - public static final int PROPERTY_ORDERED = 12; - /** @see #isBounded */ - public static final int PROPERTY_BOUNDED = 13; - /** @see #isFinite */ - public static final int PROPERTY_CARDINALITY = 14; - /** @see #isNumeric */ - public static final int PROPERTY_NUMERIC = 15; - - /** The last property code */ - public static final int LAST_PROPERTY = 15; - - - /** - * Returns the value of the given facet, or null if - * none is set. - */ - public abstract XmlAnySimpleType getFacet(int facetCode); - - /** - * True if the given facet is fixed. - */ - public abstract boolean isFacetFixed(int facetCode); - - /** - * True if ordered. Returns either {@link #UNORDERED}, - * {@link #PARTIAL_ORDER}, or {@link #TOTAL_ORDER}. - */ - public abstract int ordered(); - - /** Unordered. See {@link #ordered}. */ - public static int UNORDERED = 0; - /** Partially ordered. See {@link #ordered}. */ - public static int PARTIAL_ORDER = 1; - /** Totally ordered. See {@link #ordered}. */ - public static int TOTAL_ORDER = 2; - - /** - * True if bounded. - */ - public abstract boolean isBounded(); - - /** - * True if finite. - */ - public abstract boolean isFinite(); - - /** - * True if numeric. - */ - public abstract boolean isNumeric(); - - /** - * True if there are regex pattern facents - */ - public abstract boolean hasPatternFacet(); - - /** - * True - */ - public abstract String[] getPatterns(); - - /** - * True if the given string matches the pattern facets. - * Always true if there are no pattern facets. - */ - public abstract boolean matchPatternFacet(String s); - - /** - * Returns the array of valid objects from the - * enumeration facet, null if no enumeration defined. - */ - public abstract XmlAnySimpleType[] getEnumerationValues(); - - /** - * True if this is a string enum where an integer - * is assigned to each enumerated value. - */ - public abstract boolean hasStringEnumValues(); - - /** - * If this is a string enumeration, returns the most basic base schema - * type that this enuemration is based on. Otherwise returns null. - */ - public abstract SchemaType getBaseEnumType(); - - /** - * Returns the array of SchemaStringEnumEntries for this type: this - * array includes information about the java constant names used for - * each string enum entry. - */ - public SchemaStringEnumEntry[] getStringEnumEntries(); - - /** - * Returns the string enum entry corresponding to the given enumerated - * string, or null if there is no match or this type is not - * a string enumeration. - */ - public SchemaStringEnumEntry enumEntryForString(String s); - - /** - * Returns the string enum value corresponding to the given enumerated - * string, or null if there is no match or this type is not - * a string enumeration. - */ - public abstract StringEnumAbstractBase enumForString(String s); - - /** - * Returns the string enum value corresponding to the given enumerated - * string, or null if there is no match or this type is not - * a string enumeration. - */ - public abstract StringEnumAbstractBase enumForInt(int i); - - /** - * True for any of the 20 primitive types (plus anySimpleType) - */ - public abstract boolean isPrimitiveType(); - - /** - * Returns whether the simple type is ATOMIC, UNION, or LIST. - * Returns {@link #NOT_SIMPLE}, {@link #ATOMIC}, {@link #UNION}, - * or {@link #LIST}. - */ - public abstract int getSimpleVariety(); - - /** Not a simple type or simple content. See {@link #getSimpleVariety}. */ - public static final int NOT_SIMPLE = 0; - /** Atomic type. See {@link #getSimpleVariety} */ - public static final int ATOMIC = 1; - /** Union type. See {@link #getSimpleVariety} */ - public static final int UNION = 2; - /** Simple list type. See {@link #getSimpleVariety} */ - public static final int LIST = 3; - - - /** - * For atomic types only: get the primitive type underlying this one. - *

      - * Returns null if this is not an atomic type. - */ - public abstract SchemaType getPrimitiveType(); - - /** - * For atomic numeric restrictions of decimal only: the - * numeric size category. Takes into account min and max - * restrictions as well as totalDigits and fractionDigits - * facets. - *

      - * Returns either {@link #NOT_DECIMAL}, - * {@link #SIZE_BYTE}, {@link #SIZE_SHORT}, {@link #SIZE_INT}, - * {@link #SIZE_LONG}, {@link #SIZE_BIG_INTEGER}, or - * {@link #SIZE_BIG_DECIMAL}. - */ - public abstract int getDecimalSize(); - - /** Not a decimal restriction. See {@link #getDecimalSize}. */ - public static final int NOT_DECIMAL = 0; - /** Fits in a byte. See {@link #getDecimalSize}. */ - public static final int SIZE_BYTE = 8; - /** Fits in a short. See {@link #getDecimalSize}. */ - public static final int SIZE_SHORT = 16; - /** Fits in an int. See {@link #getDecimalSize}. */ - public static final int SIZE_INT = 32; - /** Fits in a long. See {@link #getDecimalSize}. */ - public static final int SIZE_LONG = 64; - /** Fits in a {@link java.math.BigInteger}. See {@link #getDecimalSize}. */ - public static final int SIZE_BIG_INTEGER = 1000000; // "millions" - /** Fits in a {@link java.math.BigDecimal}. See {@link #getDecimalSize}. */ - public static final int SIZE_BIG_DECIMAL = 1000001; // "even more" - - /** - * For union types only: get the shallow member types. This - * returns the declared member types of the union, so, for - * example if the type contains another union, the nested - * members of that union are NOT returned here. - *

      - * Returns null if this type is not a union. - */ - public abstract SchemaType[] getUnionMemberTypes(); - - /** - * For union types only: gets the full tree of member types. - * This computes the closure of the set returned by - * getUnionMemberTypes(), so, for example, it returns - * all the types nested within unions of unions as well - * as the top-level members; the set also includes the - * type itself. If you are seeking only the basic - * non-union consituents, use getUnionConstituentTypes. - *

      - * Returns null if this type is not a union. - */ - public abstract SchemaType[] getUnionSubTypes(); - - /** - * For union types only: get the constituent member types. This - * returns only non-union types, so, for example, for unions of - * unions, this returns the flattened list of individual member - * types within the innermost unions. - *

      - * Returns null if this type is not a union. - */ - public abstract SchemaType[] getUnionConstituentTypes(); - - /** - * For union types only: get the most specific common base - * type of the constituent member types. May return a UR type. - *

      - * Returns null if this type is not a union. - */ - public abstract SchemaType getUnionCommonBaseType(); - - /** - * For anonymous types defined inside a union only: gets - * the integer indicating the declaration order of this - * type within the outer union type, or zero if this is - * not applicable. The first anonymous union member within - * a union type is numbered "1". Used to differentiate - * between different anonymous types. - */ - public abstract int getAnonymousUnionMemberOrdinal(); - - /** - * For list types only: get the item type. This is the atomic - * or union type that is the type of every entry in the list. - *

      - * Returns null if this type is not a list. - */ - public abstract SchemaType getListItemType(); - - /** - * For nonunion simple types: get the whitespace rule. This is - * either {@link #WS_PRESERVE}, {@link #WS_REPLACE}, or - * {@link #WS_COLLAPSE}. Returns {@link #WS_UNSPECIFIED} - * for unions and complex types. - */ - public abstract int getWhiteSpaceRule(); - - /** Whitespace rule unspecified. See {@link #getWhiteSpaceRule}. */ - public static final int WS_UNSPECIFIED = 0; - /** Whitespace preserved. See {@link #getWhiteSpaceRule}. */ - public static final int WS_PRESERVE = 1; - /** Whitespace replaced by ordinary space. See {@link #getWhiteSpaceRule}. */ - public static final int WS_REPLACE = 2; - /** Whitespace collapsed and trimmed. See {@link #getWhiteSpaceRule}. */ - public static final int WS_COLLAPSE = 3; - - /** - * Creates an immutable simple type value that does not reside in a tree. - */ - public abstract XmlAnySimpleType newValue(Object v); - - - /** - * Used to allow on-demand loading of types. - * - * @exclude - */ - public final static class Ref extends SchemaComponent.Ref - { - public Ref(SchemaType type) - { super(type); } - - public Ref(SchemaTypeSystem system, String handle) - { super(system, handle); } - - public final int getComponentType() - { return SchemaComponent.TYPE; } - - public final SchemaType get() - { return (SchemaType)getComponent(); } - } - - /** - * Retruns a SchemaType.Ref pointing to this schema type itself. - */ - public Ref getRef(); - - /** - * Returns a QNameSet of elements that may exist in wildcard - * buchets and are not explicitly defined in this schema type. - * Note: In this example: - * - * - * - * - * - * - * the returned QNameSet will not contain the qname of 'someElement'. - * @return the constructed QNameSet - */ - public QNameSet qnameSetForWildcardElements(); - - /** - * Returns a QNameSet of attributes that may exist in wildcard - * buchets and are not explicitly defined in this schema type. - * Note: In this example: - * - * ... - * - * - * - * the returned QNameSet will not contain the qname of 'someAttribute'. - * @return the constructed QNameSet - */ - public QNameSet qnameSetForWildcardAttributes(); -} diff --git a/src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoader.java b/src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoader.java deleted file mode 100644 index abd2ae6..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/SchemaTypeLoader.java +++ /dev/null @@ -1,165 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLStreamException; - -import java.io.File; -import java.io.InputStream; -import java.io.IOException; -import java.io.Reader; -import java.net.URL; - -import javax.xml.stream.XMLStreamReader; - -import org.w3c.dom.Node; -import org.w3c.dom.DOMImplementation; - -/** - * Represents a searchable set of XML Schema component definitions. - *

      - * SchemaTypeLoader is somewhat analogous to {@link java.lang.ClassLoader}, - * because it is responsible for finding {@link SchemaComponent} definitions - * by name, yet it is not responsible for being able to enumerate all the - * component definitons available. (If you wish to enumerate component - * definitions, see {@link SchemaTypeSystem}.) There are some ways in which - * SchemaTypeSystems are dissimilar from ClassLoaders, however. - * Since XML Schema has a number of instance-oriented typing mechanisms - * (such as wildcards) that do not exist in Java, a SchemaTypeLoader is - * not associated with a type; instead, a SchemaTypeLoader is associated - * with each XML instance. - *

      - * Every XML instance is loaded within the context of a SchemaTypeLoader; - * the SchemaTypeLoader for an instance is used to resolve all type definitions - * within the instance and for applying type-sensitive methods such as - * {@link XmlObject#validate}. - *

      - * Normally the SchemaTypeLoader being used for all instances is the - * context type loader (that is, the SchemaTypeLoader returned from - * {@link XmlBeans#getContextTypeLoader()}). The context type loader - * consults the thread's context ClassLoader (see {@link Thread#getContextClassLoader()}) - * to find schema type defintions that are available on the classpath. - * The net result is that you can use schema types simply by putting - * their compiled schema JARs on your classpath. - * If you wish to load instances using a different SchemaTypeLoader, then you must - * call {@link #parse} methods on the SchemaTypeLoader instance explicitly - * rather than using the normal convenient Factory methods. - *

      - * A SchemaTypeLoader can be obtained by dynamically loading XSD files - * using {@link XmlBeans#loadXsd}, or by assembling other SchemaTypeLoaders - * or SchemaTypeSystems on a path using {@link XmlBeans#typeLoaderUnion}. - * - * @see XmlBeans#loadXsd - * @see XmlBeans#getContextTypeLoader - * @see XmlBeans#typeLoaderUnion - * @see SchemaTypeSystem - */ -public interface SchemaTypeLoader -{ - /** Returns the type with the given name, or null if none. */ - public SchemaType findType(QName name); - - /** Returns the document type rooted at the given element name, or null if none. */ - public SchemaType findDocumentType(QName name); - - /** Returns the attribute type containing the given attribute name, or null if none. */ - public SchemaType findAttributeType(QName name); - - /** Returns the global element defintion with the given name, or null if none. */ - public SchemaGlobalElement findElement(QName name); - - /** Returns the global attribute defintion with the given name, or null if none. */ - public SchemaGlobalAttribute findAttribute(QName name); - - /** Returns the model group defintion with the given name, or null if none. */ - public SchemaModelGroup findModelGroup(QName name); - - /** Returns the attribute group defintion with the given name, or null if none. */ - public SchemaAttributeGroup findAttributeGroup(QName name); - - /** True if the typeloader contains any definitions in the given namespace. */ - public boolean isNamespaceDefined(String namespace); - - /** Used for on-demand loading. */ - public SchemaType.Ref findTypeRef(QName name); - - /** Used for on-demand loading. */ - public SchemaType.Ref findDocumentTypeRef(QName name); - - /** Used for on-demand loading. */ - public SchemaType.Ref findAttributeTypeRef(QName name); - - /** Used for on-demand loading. */ - public SchemaGlobalElement.Ref findElementRef(QName name); - - /** Used for on-demand loading. */ - public SchemaGlobalAttribute.Ref findAttributeRef(QName name); - - /** Used for on-demand loading. */ - public SchemaModelGroup.Ref findModelGroupRef(QName name); - - /** Used for on-demand loading. */ - public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name); - - /** Used for on-demand loading. */ - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name); - - /** Finds a type for a given signature string */ - public SchemaType typeForSignature(String signature); - - /** Finds a type for a given fully-qualified XML Bean classname */ - public SchemaType typeForClassname(String classname); - - /** Loads original XSD source as a stream. See {@link SchemaType#getSourceName}. */ - public InputStream getSourceAsStream(String sourceName); - - /** Compiles an XPath */ - public String compilePath(String pathExpr, XmlOptions options) throws XmlException; - - /** Compiles an XQuery */ - public String compileQuery(String queryExpr, XmlOptions options) throws XmlException; - - /** Creates an instance of the given type. */ - public XmlObject newInstance ( SchemaType type, XmlOptions options ); - /** Parses an instance of the given type. */ - public XmlObject parse ( String xmlText, SchemaType type, XmlOptions options ) throws XmlException; - /** Parses an instance of the given type. */ - public XmlObject parse ( File file, SchemaType type, XmlOptions options ) throws XmlException, IOException; - /** Parses an instance of the given type. */ - public XmlObject parse ( URL file, SchemaType type, XmlOptions options ) throws XmlException, IOException; - /** Parses an instance of the given type. */ - public XmlObject parse ( InputStream jiois, SchemaType type, XmlOptions options ) throws XmlException, IOException; - /** Parses an instance of the given type. */ - public XmlObject parse ( XMLStreamReader xsr, SchemaType type, XmlOptions options ) throws XmlException; - /** Parses an instance of the given type. */ - public XmlObject parse ( Reader jior, SchemaType type, XmlOptions options ) throws XmlException, IOException; - /** Parses an instance of the given type. */ - public XmlObject parse ( Node node, SchemaType type, XmlOptions options ) throws XmlException; - /** Parses an instance of the given type. - * @deprecated Deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XmlObject parse ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException; - /** Returns an XmlSaxHandler that can parse an instance of the given type. */ - public XmlSaxHandler newXmlSaxHandler ( SchemaType type, XmlOptions options ); - /** Returns a DOMImplementation. */ - public DOMImplementation newDomImplementation ( XmlOptions options ); - /** Returns a validating XMLInputStream that will throw an exception if the XML is not valid - * @deprecated Deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException; -} diff --git a/src/xmlpublic/org/apache/xmlbeans/SimpleValue.java b/src/xmlpublic/org/apache/xmlbeans/SimpleValue.java deleted file mode 100644 index 3d86aac..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/SimpleValue.java +++ /dev/null @@ -1,333 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; -import java.util.List; -import java.util.Date; -import java.util.Calendar; -import java.math.BigInteger; -import java.math.BigDecimal; - -/** - * All XmlObject implementations can be coerced to SimpleValue. - * For any given schema type, only a subset of the conversion - * methods will work. Others will throw an exception. - *

      - * SimpleValue is useful for declaring variables which can hold - * more than one similar schema type that may not happen to - * have a common XML base type, for example, two list types, - * or two unrelated integer restrictions that happen to fit - * into an int. - */ -public interface SimpleValue extends XmlObject -{ - /** - * The same as getSchemaType unless this is a union instance - * or nil value. - *

      - * For unions, this returns the non-union consituent type of - * this instance. This type may change if setters are called - * that cause the instance to change to another constituent - * type of the union. - *

      - * For nil values, this returns null. - */ - SchemaType instanceType(); - - /** Returns the value as a {@link String}. */ - String getStringValue(); - /** Returns the value as a boolean. */ - boolean getBooleanValue(); - /** Returns the value as a byte. */ - public byte getByteValue(); - /** Returns the value as a short. */ - public short getShortValue(); - /** Returns the value as an int. */ - public int getIntValue(); - /** Returns the value as a long. */ - public long getLongValue(); - /** Returns the value as a {@link BigInteger}. */ - public BigInteger getBigIntegerValue(); - /** Returns the value as a {@link BigDecimal}. */ - public BigDecimal getBigDecimalValue(); - /** Returns the value as a float. */ - public float getFloatValue(); - /** Returns the value as a double. */ - public double getDoubleValue(); - /** Returns the value as a byte array. */ - byte[] getByteArrayValue(); - /** Returns the value as a {@link StringEnumAbstractBase}. */ - StringEnumAbstractBase getEnumValue(); - /** Returns the value as a {@link Calendar}. */ - Calendar getCalendarValue(); - /** Returns the value as a {@link Date}. */ - Date getDateValue(); - /** Returns the value as a {@link GDate}. */ - GDate getGDateValue(); - /** Returns the value as a {@link GDuration}. */ - GDuration getGDurationValue(); - /** Returns the value as a {@link QName}. */ - QName getQNameValue(); - /** Returns the value as a {@link List} of friendly Java objects (String, Integer, Byte, Short, Long, BigInteger, Decimal, Float, Double, byte[], Calendar, GDuration). */ - List getListValue(); - /** Returns the value as a {@link List} of XmlAnySimpleType objects. */ - List xgetListValue(); - - /** Returns a union value as a its natural friendly Java object (String, Integer, Byte, Short, Long, BigInteger, Decimal, Float, Double, byte[], Calendar, GDuration). */ - Object getObjectValue(); - - // following are simple type value setters - - /** Sets the value as a {@link String}. */ - void setStringValue(String obj); - /** Sets the value as a boolean. */ - void setBooleanValue(boolean v); - /** Sets the value as a byte. */ - void setByteValue(byte v); - /** Sets the value as a short. */ - void setShortValue(short v); - /** Sets the value as an int. */ - void setIntValue(int v); - /** Sets the value as a long. */ - void setLongValue(long v); - /** Sets the value as a {@link BigInteger}. */ - void setBigIntegerValue(BigInteger obj); - /** Sets the value as a {@link BigDecimal}. */ - void setBigDecimalValue(BigDecimal obj); - /** Sets the value as a float. */ - void setFloatValue(float v); - /** Sets the value as a double. */ - void setDoubleValue(double v); - /** Sets the value as a byte array. */ - void setByteArrayValue(byte[] obj); - /** Sets the value as a {@link StringEnumAbstractBase}. */ - void setEnumValue(StringEnumAbstractBase obj); - /** Sets the value as a {@link Calendar}. */ - void setCalendarValue(Calendar obj); - /** Sets the value as a {@link Date}. */ - void setDateValue(Date obj); - /** Sets the value as a {@link GDate}. */ - void setGDateValue(GDate obj); - /** Sets the value as a {@link GDuration}. */ - void setGDurationValue(GDuration obj); - /** Sets the value as a {@link QName}. */ - void setQNameValue(QName obj); - /** Sets the value as a {@link List}. */ - void setListValue(List obj); - /** Sets the value as an arbitrary {@link Object}. */ - void setObjectValue(Object obj); - - /** - * Returns the value as a {@link String}. * - * @deprecated replaced with {@link #getStringValue} - */ - String stringValue(); - /** - * Returns the value as a boolean. * - * @deprecated replaced with {@link #getBooleanValue} - */ - boolean booleanValue(); - /** - * Returns the value as a byte. * - * @deprecated replaced with {@link #getByteValue} - */ - public byte byteValue(); - /** - * Returns the value as a short. * - * @deprecated replaced with {@link #getShortValue} - */ - public short shortValue(); - /** - * Returns the value as an int. * - * @deprecated replaced with {@link #getIntValue} - */ - public int intValue(); - /** - * Returns the value as a long. * - * @deprecated replaced with {@link #getLongValue} - */ - public long longValue(); - /** - * Returns the value as a {@link BigInteger}. * - * @deprecated replaced with {@link #getBigIntegerValue} - */ - public BigInteger bigIntegerValue(); - /** - * Returns the value as a {@link BigDecimal}. * - * @deprecated replaced with {@link #getBigDecimalValue} - */ - public BigDecimal bigDecimalValue(); - /** - * Returns the value as a float. * - * @deprecated replaced with {@link #getFloatValue} - */ - public float floatValue(); - /** - * Returns the value as a double. * - * @deprecated replaced with {@link #getDoubleValue} - */ - public double doubleValue(); - /** - * Returns the value as a byte array. * - * @deprecated replaced with {@link #getByteArrayValue} - */ - byte[] byteArrayValue(); - /** - * Returns the value as a {@link StringEnumAbstractBase}. * - * @deprecated replaced with {@link #getEnumValue} - */ - StringEnumAbstractBase enumValue(); - /** - * Returns the value as a {@link Calendar}. * - * @deprecated replaced with {@link #getCalendarValue} - */ - Calendar calendarValue(); - /** - * Returns the value as a {@link Date}. * - * @deprecated replaced with {@link #getDateValue} - */ - Date dateValue(); - /** - * Returns the value as a {@link GDate}. * - * @deprecated replaced with {@link #getGDateValue} - */ - GDate gDateValue(); - /** - * Returns the value as a {@link GDuration}. * - * @deprecated replaced with {@link #getGDurationValue} - */ - GDuration gDurationValue(); - /** - * Returns the value as a {@link QName}. * - * @deprecated replaced with {@link #getQNameValue} - */ - QName qNameValue(); - /** - * Returns the value as a {@link List} of friendly Java objects (String, Integer, Byte, Short, Long, BigInteger, Decimal, Float, Double, byte[], Calendar, GDuration). * - * @deprecated replaced with {@link #getListValue} - */ - List listValue(); - /** - * Returns the value as a {@link List} of XmlAnySimpleType objects. * - * @deprecated replaced with {@link #xgetListValue} - */ - List xlistValue(); - - /** - * Returns a union value as a its natural friendly Java object (String, Integer, Byte, Short, Long, BigInteger, Decimal, Float, Double, byte[], Calendar, GDuration). * - * @deprecated replaced with {@link #getObjectValue} - */ - Object objectValue(); - - // following are simple type value setters - - /** - * Sets the value as a {@link String}. * - * @deprecated replaced with {@link #setStringValue} - */ - void set(String obj); - /** - * Sets the value as a boolean. * - * @deprecated replaced with {@link #setBooleanValue} - */ - void set(boolean v); - /** - * Sets the value as a byte. - * @deprecated replaced with {@link #setByteValue} - **/ - void set(byte v); - /** - * Sets the value as a short. - * @deprecated replaced with {@link #setShortValue} - **/ - void set(short v); - /** - * Sets the value as an int. - * @deprecated replaced with {@link #setIntValue} - **/ - void set(int v); - /** - * Sets the value as a long. - * @deprecated replaced with {@link #setLongValue} - **/ - void set(long v); - /** - * Sets the value as a {@link BigInteger}. - * @deprecated replaced with {@link #setBigIntegerValue} - **/ - void set(BigInteger obj); - /** - * Sets the value as a {@link BigDecimal} - * @deprecated replaced with {@link #setBigDecimalValue} - **/ - void set(BigDecimal obj); - /** - * Sets the value as a float. - * @deprecated replaced with {@link #setFloatValue} - **/ - void set(float v); - /** - * Sets the value as a double. - * @deprecated replaced with {@link #setDoubleValue} - **/ - void set(double v); - /** - * Sets the value as a byte array. - * @deprecated replaced with {@link #setByteArrayValue} - **/ - void set(byte[] obj); - /** - * Sets the value as a {@link StringEnumAbstractBase}. - * @deprecated replaced with {@link #setEnumValue} - **/ - void set(StringEnumAbstractBase obj); - /** - * Sets the value as a {@link Calendar}. - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar obj); - /** - * Sets the value as a {@link Date}. - * @deprecated replaced with {@link #setDateValue} - **/ - void set(Date obj); - /** - * Sets the value as a {@link GDate}. - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification obj); - /** - * Sets the value as a {@link GDuration}. - * @deprecated replaced with {@link #setGDurationValue} - **/ - void set(GDurationSpecification obj); - /** - * Sets the value as a {@link QName}. - * @deprecated replaced with {@link #setQNameValue} - **/ - void set(QName obj); - /** - * Sets the value as a {@link List}. - * @deprecated replaced with {@link #setListValue} - **/ - void set(List obj); - /** - * Sets the value as an arbitrary {@link Object}. - * @deprecated replaced with {@link #setObjectValue} - **/ - void objectSet(Object obj); -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XMLStreamValidationException.java b/src/xmlpublic/org/apache/xmlbeans/XMLStreamValidationException.java deleted file mode 100644 index 9ec0b0e..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XMLStreamValidationException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import org.apache.xmlbeans.xml.stream.XMLStreamException; - -/** - * An exception thrown from a validating XMLInputStream. - * - * @see XmlObject.Factory#newValidatingXMLInputStream - * @see SchemaTypeLoader#newValidatingXMLInputStream - */ -public class XMLStreamValidationException extends XMLStreamException -{ - public XMLStreamValidationException ( XmlError xmlError ) - { - super( xmlError.toString() ); - - _xmlError = xmlError; - } - - public XmlError getXmlError ( ) - { - return _xmlError; - } - - private XmlError _xmlError; -} \ No newline at end of file diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlAnySimpleType.java b/src/xmlpublic/org/apache/xmlbeans/XmlAnySimpleType.java deleted file mode 100644 index acc6fd6..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlAnySimpleType.java +++ /dev/null @@ -1,154 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:anySimpleType type. - *

      - * All simple types are convertible to {@link String}. - */ -public interface XmlAnySimpleType extends XmlObject -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_anySimpleType"); - - /** - * Returns the value as a {@link String} - * @deprecated replaced by {@link #getStringValue} - **/ - String stringValue(); - /** - * Sets the value as a {@link String} - * @deprecated replaced by {@link #setStringValue} - **/ - void set(String s); - - /** - * Returns the value as a {@link String} - **/ - String getStringValue(); - - /** - * Sets the value as a {@link String} - **/ - void setStringValue(String s); - - /** - * A class with methods for creating instances - * of {@link XmlAnySimpleType}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlAnySimpleType} */ - public static XmlAnySimpleType newInstance() { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlAnySimpleType} */ - public static XmlAnySimpleType newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlAnySimpleType} value */ - public static XmlAnySimpleType newValue(Object obj) { - return type.newValue( obj ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a String. For example: "<xml-fragment>anything</xml-fragment>". */ - public static XmlAnySimpleType parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a String. For example: "<xml-fragment>anything</xml-fragment>". */ - public static XmlAnySimpleType parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a File. */ - public static XmlAnySimpleType parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a File. */ - public static XmlAnySimpleType parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a URL. */ - public static XmlAnySimpleType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a URL. */ - public static XmlAnySimpleType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from an InputStream. */ - public static XmlAnySimpleType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from an InputStream. */ - public static XmlAnySimpleType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a Reader. */ - public static XmlAnySimpleType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a Reader. */ - public static XmlAnySimpleType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a DOM Node. */ - public static XmlAnySimpleType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from a DOM Node. */ - public static XmlAnySimpleType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from an XMLInputStream. - * @deprecated Deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlAnySimpleType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlAnySimpleType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlAnySimpleType} fragment from an XMLStreamReader. */ - public static XmlAnySimpleType parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlAnySimpleType} fragment from an XMLStreamReader. */ - public static XmlAnySimpleType parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlAnySimpleType) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlAnyURI.java b/src/xmlpublic/org/apache/xmlbeans/XmlAnyURI.java deleted file mode 100644 index 4246e72..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlAnyURI.java +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:anyURI type. - *

      - * Convertible to {@link String}. - */ -public interface XmlAnyURI extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_anyURI"); - - /** - * A class with methods for creating instances - * of {@link XmlAnyURI}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlAnyURI} */ - public static XmlAnyURI newInstance() { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlAnyURI} */ - public static XmlAnyURI newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlAnyURI} value */ - public static XmlAnyURI newValue(Object obj) { - return (XmlAnyURI) type.newValue( obj ); } - - /** Parses a {@link XmlAnyURI} fragment from a String. For example: "<xml-fragment>http://www.w3.org/</xml-fragment>". */ - public static XmlAnyURI parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from a String. For example: "<xml-fragment>http://www.w3.org/</xml-fragment>". */ - public static XmlAnyURI parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from a File. */ - public static XmlAnyURI parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from a File. */ - public static XmlAnyURI parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from a URL. */ - public static XmlAnyURI parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from a URL. */ - public static XmlAnyURI parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from an InputStream. */ - public static XmlAnyURI parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from an InputStream. */ - public static XmlAnyURI parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from a Reader. */ - public static XmlAnyURI parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from a Reader. */ - public static XmlAnyURI parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from a DOM Node. */ - public static XmlAnyURI parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from a DOM Node. */ - public static XmlAnyURI parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlAnyURI parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlAnyURI parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlAnyURI} fragment from an XMLStreamReader. */ - public static XmlAnyURI parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlAnyURI} fragment from an XMLStreamReader. */ - public static XmlAnyURI parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlAnyURI) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlBase64Binary.java b/src/xmlpublic/org/apache/xmlbeans/XmlBase64Binary.java deleted file mode 100644 index ba8bbd6..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlBase64Binary.java +++ /dev/null @@ -1,151 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:base64Binary type. - *

      - * Convertible to a byte array. - */ -public interface XmlBase64Binary extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_base64Binary"); - - /** - * Returns this value as a byte array. - * @deprecated replaced by {@link #getByteArrayValue} - **/ - byte[] byteArrayValue(); - - /** - * Sets this value as a byte array. - * @deprecated replaced by {@link #setByteArrayValue} - **/ - void set(byte[] ba); - - /** Returns this value as a byte array. **/ - byte[] getByteArrayValue(); - /** Sets this value as a byte array. */ - void setByteArrayValue(byte[] ba); - - - /** - * A class with methods for creating instances - * of {@link XmlBase64Binary}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlBase64Binary} */ - public static XmlBase64Binary newInstance() { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlBase64Binary} */ - public static XmlBase64Binary newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlBase64Binary} value */ - public static XmlBase64Binary newValue(Object obj) { - return (XmlBase64Binary) type.newValue( obj ); } - - /** Parses a {@link XmlBase64Binary} fragment from a String. For example: "<xml-fragment>VGhpcyBzdHJp</xml-fragment>". */ - public static XmlBase64Binary parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from a String. For example: "<xml-fragment>VGhpcyBzdHJp</xml-fragment>". */ - public static XmlBase64Binary parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from a File. */ - public static XmlBase64Binary parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from a File. */ - public static XmlBase64Binary parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from a URL. */ - public static XmlBase64Binary parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from a URL. */ - public static XmlBase64Binary parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from an InputStream. */ - public static XmlBase64Binary parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from an InputStream. */ - public static XmlBase64Binary parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from a Reader. */ - public static XmlBase64Binary parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from a Reader. */ - public static XmlBase64Binary parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from a DOM Node. */ - public static XmlBase64Binary parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from a DOM Node. */ - public static XmlBase64Binary parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlBase64Binary parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlBase64Binary parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlBase64Binary} fragment from an XMLStreamReader. */ - public static XmlBase64Binary parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlBase64Binary} fragment from an XMLStreamReader. */ - public static XmlBase64Binary parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlBase64Binary) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java b/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java deleted file mode 100644 index f44b623..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java +++ /dev/null @@ -1,885 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.namespace.QName; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Constructor; -import java.lang.ref.SoftReference; -import java.io.File; - -import javax.xml.stream.XMLStreamReader; - -import org.w3c.dom.Node; - -/** - * Provides an assortment of utilities - * for managing XML Bean types, type systems, QNames, paths, - * and queries. - */ -public final class XmlBeans -{ - private static String XMLBEANS_TITLE = "org.apache.xmlbeans"; - private static String XMLBEANS_VERSION = "3.0.2"; - private static String XMLBEANS_VENDOR = "Apache Software Foundation"; - - static - { - Package pkg = XmlBeans.class.getPackage(); - if (pkg != null) - { - XMLBEANS_TITLE = pkg.getImplementationTitle(); - XMLBEANS_VERSION = pkg.getImplementationVersion(); - XMLBEANS_VENDOR = pkg.getImplementationVendor(); - } - } - - /** - * Returns the XmlBeans Package title, "org.apache.xmlbeans", - * the value of - * {@link Package#getImplementationTitle() XmlBeans.class.getPackage().getImplementationTitle()}. - */ - public static final String getTitle() - { - return XMLBEANS_TITLE; - } - - /** - * Returns the XmlBeans vendor, "Apache Software Foundation", - * the value of - * {@link Package#getImplementationVendor() XmlBeans.class.getPackage().getImplementationVendor()}. - */ - public static final String getVendor() - { - return XMLBEANS_VENDOR; - } - - /** - * Returns the XmlBeans version, - * the value of - * {@link Package#getImplementationVersion() XmlBeans.class.getPackage().getImplementationVersion()}. - */ - public static final String getVersion() - { - return XMLBEANS_VERSION; - } - - /** - * Thread local QName cache for general use - */ - private static final ThreadLocal _threadLocalLoaderQNameCache = - new ThreadLocal() - { - protected Object initialValue() - { - return new SoftReference(new QNameCache( 32 )); - } - }; - - /** - * Returns a thread local QNameCache - */ - public static QNameCache getQNameCache ( ) - { - SoftReference softRef = (SoftReference)_threadLocalLoaderQNameCache.get(); - QNameCache qnameCache = (QNameCache) (softRef).get(); - if (qnameCache==null) - { - qnameCache = new QNameCache( 32 ); - _threadLocalLoaderQNameCache.set(new SoftReference(qnameCache)); - } - return qnameCache; - } - - /** - * Obtains a name from the thread local QNameCache - */ - public static QName getQName ( String localPart ) - { - return getQNameCache().getName( "", localPart ); - } - - /** - * Obtains a name from the thread local QNameCache - */ - - public static QName getQName ( String namespaceUri, String localPart ) - { - return getQNameCache().getName( namespaceUri, localPart ); - } - - private static final Method _getContextTypeLoaderMethod = buildGetContextTypeLoaderMethod(); - private static final Method _getBuiltinSchemaTypeSystemMethod = buildGetBuiltinSchemaTypeSystemMethod(); - private static final Method _getNoTypeMethod = buildGetNoTypeMethod(); - private static final Method _typeLoaderBuilderMethod = buildTypeLoaderBuilderMethod(); - private static final Method _compilationMethod = buildCompilationMethod(); - private static final Method _nodeToCursorMethod = buildNodeToCursorMethod(); - private static final Method _nodeToXmlObjectMethod = buildNodeToXmlObjectMethod(); - private static final Method _nodeToXmlStreamMethod = buildNodeToXmlStreamMethod(); - private static final Method _streamToNodeMethod = buildStreamToNodeMethod(); - private static final Constructor _pathResourceLoaderConstructor = buildPathResourceLoaderConstructor(); - - private static RuntimeException causedException ( RuntimeException e, Throwable cause ) - { - e.initCause( cause ); - - return e; - } - - private static XmlException wrappedException(Throwable e) - { - if (e instanceof XmlException) - return (XmlException) e; - - return new XmlException( e.getMessage(), e ); - } - - private static final Constructor buildConstructor ( String className, Class[] args ) - { - try - { - return - Class.forName( - className, false, XmlBeans.class.getClassLoader() ). - getConstructor( args ); - } - catch ( Exception e ) - { - throw causedException( - new IllegalStateException( - "Cannot load constructor for " + className + - ": verify that xbean.jar is on the classpath" ), e ); - } - } - - private static final Method buildMethod ( String className, String methodName, Class[] args ) - { - try - { - return - Class.forName( - className, false, XmlBeans.class.getClassLoader() ). - getMethod( methodName, args ); - } - catch ( Exception e ) - { - throw causedException( - new IllegalStateException( - "Cannot load " + methodName + - ": verify that xbean.jar is on the classpath" ), e ); - } - } - - private static final Method buildNoArgMethod ( String className, String methodName ) - { - return buildMethod( className, methodName, new Class[ 0 ] ); - } - - private static final Method buildNodeMethod ( String className, String methodName ) - { - return buildMethod( className, methodName, new Class[] { Node.class } ); - } - - private static Method buildGetContextTypeLoaderMethod() - { - return buildNoArgMethod( "org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl", "getContextTypeLoader" ); - } - - - private static final Method buildGetBuiltinSchemaTypeSystemMethod() - { - return buildNoArgMethod( "org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem", "get" ); - } - - private static final Method buildGetNoTypeMethod() - { - return buildNoArgMethod( "org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem", "getNoType" ); - } - - private static final Method buildTypeLoaderBuilderMethod ( ) - { - return - buildMethod( - "org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl", "build", - new Class[] { SchemaTypeLoader[].class, ResourceLoader.class, ClassLoader.class } ); - } - - private static final Method buildCompilationMethod() - { - return - buildMethod( - "org.apache.xmlbeans.impl.schema.SchemaTypeSystemCompiler", "compile", - new Class[] { String.class, SchemaTypeSystem.class, XmlObject[].class, BindingConfig.class, SchemaTypeLoader.class, Filer.class, XmlOptions.class } ); - } - - private static final Method buildNodeToCursorMethod() - { - return buildNodeMethod( "org.apache.xmlbeans.impl.store.Locale", "nodeToCursor" ); - } - - private static final Method buildNodeToXmlObjectMethod() - { - return buildNodeMethod( "org.apache.xmlbeans.impl.store.Locale", "nodeToXmlObject" ); - } - - private static final Method buildNodeToXmlStreamMethod() - { - return buildNodeMethod( "org.apache.xmlbeans.impl.store.Locale", "nodeToXmlStream" ); - } - - private static final Method buildStreamToNodeMethod() - { - return - buildMethod( - "org.apache.xmlbeans.impl.store.Locale", "streamToNode", - new Class[] { XMLStreamReader.class } ); - } - - private static final Constructor buildPathResourceLoaderConstructor() - { - return - buildConstructor( - "org.apache.xmlbeans.impl.schema.PathResourceLoader", - new Class[] { File[].class } ); - } - - /** - * Compiles an XPath, returning a String equal to that which was passed, - * but whose identity is that of one which has been precompiled and cached. - */ - public static String compilePath ( String pathExpr ) throws XmlException - { - return compilePath( pathExpr, null ); - } - - /** - * Compiles an XPath, returning a String equal to that which was passed, - * but whose identity is that of one which has been precompiled and cached; - * takes an option for specifying text that indicates the name of context node. - * The default is "this", as in "$this". - * - * @param options Options for the path. For example, you can call - * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} - * method to specify a particular name for the expression - * variable that indicates the context node. - */ - public static String compilePath ( String pathExpr, XmlOptions options ) - throws XmlException - { - return getContextTypeLoader().compilePath( pathExpr, options ); - } - - /** - * Compiles an XQuery, returning a String equal to that which was passed, - * but whose identity is that of one which has been precompiled and cached. - */ - public static String compileQuery ( String queryExpr ) throws XmlException - { - return compileQuery( queryExpr, null ); - } - - /** - * Compiles an XQuery, returning a String equal to that which was passed, - * but whose identity is that of one which has been precompiled and cached; - * takes an option for specifying text that indicates the context node. - * - * @param options Options for the query. For example, you can call - * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} - * method to specify a particular name for the expression - * variable that indicates the context node and the - * {@link XmlOptions#setXqueryVariables(java.util.Map) XmlOptions.setXqueryVariables(Map)} - * method to map external variable names to values. - */ - public static String compileQuery ( String queryExpr, XmlOptions options ) - throws XmlException - { - return getContextTypeLoader().compileQuery( queryExpr, options ); - } - - /** - * Gets the SchemaTypeLoader based on the current thread's context - * ClassLoader. This is the SchemaTypeLoader that is used to assign - * schema types to XML documents by default. The SchemaTypeLoader is - * also consulted to resolve wildcards and xsi:type attributes. - *

      - * The "parse" methods of XmlBeans all delegate to the - * "parseInstance" methods of the context type loader. - */ - public static SchemaTypeLoader getContextTypeLoader() - { - try - { - return (SchemaTypeLoader)_getContextTypeLoaderMethod.invoke(null, null); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl.getContextTypeLoader(): verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Returns the builtin type system. This SchemaTypeSystem contains - * only the 46 builtin types defined by the XML Schema specification. - */ - public static SchemaTypeSystem getBuiltinTypeSystem() - { - try - { - return (SchemaTypeSystem)_getBuiltinSchemaTypeSystemMethod.invoke(null, null); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to BuiltinSchemaTypeSystem.get(): verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Creates an XmlCursor for a DOM node which is implemented by XmlBwans - */ - public static XmlCursor nodeToCursor ( Node n ) - { - try - { - return (XmlCursor) _nodeToCursorMethod.invoke( null, new Object[] { n } ); - } - catch ( IllegalAccessException e ) - { - throw causedException( - new IllegalStateException( - "No access to nodeToCursor verify that version of xbean.jar is correct" ), e ); - } - catch ( InvocationTargetException e ) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Creates an XmlObject for a DOM node which is implemented by XmlBwans - */ - public static XmlObject nodeToXmlObject ( Node n ) - { - try - { - return (XmlObject) _nodeToXmlObjectMethod.invoke( null, new Object[] { n } ); - } - catch ( IllegalAccessException e ) - { - throw causedException( - new IllegalStateException( - "No access to nodeToXmlObject verify that version of xbean.jar is correct" ), e ); - } - catch ( InvocationTargetException e ) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Creates an XmlObject for a DOM node which is implemented by XmlBwans - */ - public static XMLStreamReader nodeToXmlStreamReader ( Node n ) - { - try - { - return (XMLStreamReader) _nodeToXmlStreamMethod.invoke( null, new Object[] { n } ); - } - catch ( IllegalAccessException e ) - { - throw causedException( - new IllegalStateException( - "No access to nodeToXmlStreamReader verify that version of xbean.jar is correct" ), e ); - } - catch ( InvocationTargetException e ) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Returns the XmlObject for a DOM node which is implemented by XmlBwans - */ - public static Node streamToNode ( XMLStreamReader xs ) - { - try - { - return (Node) _streamToNodeMethod.invoke( null, new Object[] { xs } ); - } - catch ( IllegalAccessException e ) - { - throw causedException( - new IllegalStateException( - "No access to streamToNode verify that version of xbean.jar is correct" ), e ); - } - catch ( InvocationTargetException e ) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Returns the SchemaTypeSystem that results from compiling the XML - * schema definitions passed. - *

      - * Just like compileXsd, but uses the context type loader for - * linking, and returns a unioned typeloader that is suitable for - * creating instances. - */ - public static SchemaTypeLoader loadXsd(XmlObject[] schemas) throws XmlException - { - return loadXsd(schemas, null); - } - - /** - *

      Returns the SchemaTypeSystem that results from compiling the XML - * schema definitions passed in schemas.

      - * - *

      This is just like compileXsd, but uses the context type loader for - * linking, and returns a unioned typeloader that is suitable for - * creating instances.

      - * - *

      Use the options parameter to specify one or both of the following:

      - * - *
        - *
      • A collection instance that should be used as an error listener during - * compilation, as described in {@link XmlOptions#setErrorListener}.
      • - *
      • Whether validation should not be done when building the SchemaTypeSystem, - * as described in {@link XmlOptions#setCompileNoValidation}.
      • - *
      - * - * @param schemas The schema definitions from which to build the schema type system. - * @param options Options specifying an error listener and/or validation behavior. - */ - public static SchemaTypeLoader loadXsd(XmlObject[] schemas, XmlOptions options) throws XmlException - { - try - { - SchemaTypeSystem sts = - (SchemaTypeSystem) - _compilationMethod.invoke( - null, new Object[] { null, null, schemas, null, getContextTypeLoader(), null, options }); - - if (sts == null) - return null; - - return - typeLoaderUnion( - new SchemaTypeLoader[] { sts, getContextTypeLoader() } ); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl.forSchemaXml(): verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - throw wrappedException(e.getCause()); - } - } - - /** - *

      Returns the SchemaTypeSystem that results from compiling the XML - * schema definitions passed.

      - * - *

      The XmlObjects passed in should be w3c <schema> elements whose type - * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in - * the XML namespace http://www.w3c.org/2001/XMLSchema.) Also - * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.

      - * - *

      The optional second argument is a SchemaTypeLoader which will be - * consulted for already-compiled schema types which may be linked - * while processing the given schemas.

      - * - *

      The SchemaTypeSystem that is returned should be combined - * (via {@link #typeLoaderUnion}) with the typepath typeloader in order - * to create a typeloader that can be used for creating and validating - * instances.

      - * - *

      Use the options parameter to specify the following:

      - * - *
        - *
      • A collection instance that should be used as an error listener during - * compilation, as described in {@link XmlOptions#setErrorListener}.
      • - *
      • Whether validation should not be done when building the SchemaTypeSystem, - * as described in {@link XmlOptions#setCompileNoValidation}.
      • - *
      - * - * @param schemas The schema definitions from which to build the schema type system. - * @param typepath The path to already-compiled schema types for linking while processing. - * @param options Options specifying an error listener and/or validation behavior. - */ - public static SchemaTypeSystem compileXsd(XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException - { - return compileXmlBeans(null, null, schemas, null, typepath, null, options); - } - - /** - *

      Returns the SchemaTypeSystem that results from augumenting the - * SchemaTypeSystem passed in by incrementally adding the given XML - * schema definitions.

      - * - *

      These could be new definitions (if the Schema document is not recorded into - * the existing SchemaTypeSystem), modifications to the already existing - * definitions (if the Schema document is already recorded in the existing - * SchemaTypeSystem), or deletions (if the Schema document is already recorded - * in the existing SchemaTypeSystem and the new definitions are empty). - * The identity of documents is established using - * {@link XmlDocumentProperties#getSourceName}, so if the caller choses to - * construct the Schema definitions using other methods than parsing an - * XML document, they should make sure that the names returned by that - * method are consistent with the caller's intent (add/modify).

      - * - *

      The XmlObjects passed in should be w3c <schema> elements whose type - * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in - * the XML namespace http://www.w3c.org/2001/XMLSchema.) Also - * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.

      - * - *

      The optional second argument is a SchemaTypeLoader which will be - * consulted for already-compiled schema types which may be linked - * while processing the given schemas.

      - * - *

      The SchemaTypeSystem that is returned should be combined - * (via {@link #typeLoaderUnion}) with the typepath typeloader in order - * to create a typeloader that can be used for creating and validating - * instances.

      - * - *

      Use the options parameter to specify the following:

      - * - *
        - *
      • A collection instance that should be used as an error listener during - * compilation, as described in {@link XmlOptions#setErrorListener}.
      • - *
      • Whether validation should not be done when building the SchemaTypeSystem, - * as described in {@link XmlOptions#setCompileNoValidation}.
      • - *
      - * - * @param schemas The schema definitions from which to build the schema type system. - * @param typepath The path to already-compiled schema types for linking while processing. - * @param options Options specifying an error listener and/or validation behavior. - */ - public static SchemaTypeSystem compileXsd(SchemaTypeSystem system, XmlObject[] schemas, SchemaTypeLoader typepath, XmlOptions options) throws XmlException - { - return compileXmlBeans(null, system, schemas, null, typepath, null, options); - } - - /** - *

      Returns the SchemaTypeSystem that results from augumenting the - * SchemaTypeSystem passed in by incrementally adding the given XML - * schema definitions.

      - * - *

      These could be new definitions (if the Schema document is not recorded into - * the existing SchemaTypeSystem), modifications to the already existing - * definitions (if the Schema document is already recorded in the existing - * SchemaTypeSystem), or deletions (if the Schema document is already recorded - * in the existing SchemaTypeSystem and the new definitions are empty). - * The identity of documents is established using - * {@link XmlDocumentProperties#getSourceName}, so if the caller choses to - * construct the Schema definitions using other methods than parsing an - * XML document, they should make sure that the names returned by that - * method are consistent with the caller's intent (add/modify).

      - * - *

      The XmlObjects passed in should be w3c <schema> elements whose type - * is org.w3c.x2001.xmlSchema.Schema. (That is, schema elements in - * the XML namespace http://www.w3c.org/2001/XMLSchema.) Also - * org.w3c.x2001.xmlSchema.SchemaDocument is permitted.

      - * - *

      The optional name argument is used to name the compiled schema type system. - * A randomly generated name will be used if the name is null.

      - * - *

      The optional {@link BindingConfig} argument is used to control the shape - * of the generated code. A BindingConfig isn't used if Filer - * is null.

      - * - *

      The optional SchemaTypeLoader argument will be - * consulted for already-compiled schema types which may be linked - * while processing the given schemas. If not specified, the context - * typeloader (as returned by {@link #getContextTypeLoader}) will be used.

      - * - *

      The optional {@link Filer} argument is used to create new binary or source - * files which are the product of the compilation. If the Filer is null, the - * schema binaries (.xsb) files and source files won't be generated.

      - * - *

      The SchemaTypeSystem that is returned should be combined - * (via {@link #typeLoaderUnion}) with the typepath typeloader in order - * to create a typeloader that can be used for creating and validating - * instances.

      - * - *

      Use the options parameter to specify the following:

      - * - *
        - *
      • A collection instance that should be used as an error listener during - * compilation, as described in {@link XmlOptions#setErrorListener}.
      • - *
      • Whether validation should not be done when building the SchemaTypeSystem, - * as described in {@link XmlOptions#setCompileNoValidation}.
      • - *
      - * - * @param name The type system name or null to use a randomly generated name. - * @param system A pre-existing SchemaTypeSystem used in incremental compilation. - * @param schemas The schema definitions from which to build the schema type system. - * @param config The configuration controls the code generation shape. - * @param typepath The path to already-compiled schema types for linking while processing. - * @param filer The Filer instance used to create binary binding files and source text files. - * @param options Options specifying an error listener and/or validation behavior. - */ - public static SchemaTypeSystem compileXmlBeans(String name, SchemaTypeSystem system, XmlObject[] schemas, BindingConfig config, SchemaTypeLoader typepath, Filer filer, XmlOptions options) throws XmlException - { - try - { - return (SchemaTypeSystem)_compilationMethod.invoke(null, new Object[] { name, system, schemas, config, typepath != null ? typepath : getContextTypeLoader(), filer, options }); - } - catch (IllegalAccessException e) - { - throw new IllegalStateException("No access to SchemaTypeLoaderImpl.forSchemaXml(): verify that version of xbean.jar is correct"); - } - catch (InvocationTargetException e) - { - throw wrappedException(e.getCause()); - } - } - - - /** - * Returns the union of a list of typeLoaders. The returned - * SchemaTypeLoader searches the given list of SchemaTypeLoaders - * in order from first to last. - */ - public static SchemaTypeLoader typeLoaderUnion(SchemaTypeLoader[] typeLoaders) - { - try - { - if (typeLoaders.length == 1) - return typeLoaders[0]; - - return (SchemaTypeLoader)_typeLoaderBuilderMethod.invoke(null, new Object[] {typeLoaders, null, null}); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Returns a SchemaTypeLoader that searches for compiled schema types - * in the given ClassLoader. - */ - public static SchemaTypeLoader typeLoaderForClassLoader(ClassLoader loader) - { - try - { - return (SchemaTypeLoader)_typeLoaderBuilderMethod.invoke(null, new Object[] {null, null, loader}); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Returns a SchemaTypeLoader that searches for compiled schema types - * in the given ResourceLoader. - * - * @see XmlBeans#resourceLoaderForPath(File[]) - */ - public static SchemaTypeLoader typeLoaderForResource(ResourceLoader resourceLoader) - { - try - { - return (SchemaTypeLoader)_typeLoaderBuilderMethod.invoke(null, new Object[] {null, resourceLoader, null}); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - private static final String HOLDER_CLASS_NAME = "TypeSystemHolder"; - private static final String TYPE_SYSTEM_FIELD = "typeSystem"; - - /** - * Returns the SchemaTypeSystem of the given name (as returned by - * {@link SchemaTypeSystem#getName}) for the given ClassLoader. - *

      - * Note: you will almost always need typeLoaderForClassLoader() - * instead (see {@link XmlBeans#typeLoaderForClassLoader}). - */ - public static SchemaTypeSystem typeSystemForClassLoader(ClassLoader loader, String stsName) - { - try - { - ClassLoader cl = loader == null ? Thread.currentThread().getContextClassLoader() : loader; - Class clazz = cl.loadClass(stsName + "." + HOLDER_CLASS_NAME); - SchemaTypeSystem sts = (SchemaTypeSystem) - (clazz.getDeclaredField(TYPE_SYSTEM_FIELD).get(null)); - if (sts == null) - { - throw new RuntimeException("SchemaTypeSystem is null for field " + - TYPE_SYSTEM_FIELD + " on class with name " + stsName + - "." + HOLDER_CLASS_NAME + - ". Please verify the version of xbean.jar is correct."); - } - return sts; - } - catch (ClassNotFoundException e) - { - throw causedException(new RuntimeException("Cannot load SchemaTypeSystem. " + - "Unable to load class with name " + stsName + "." + HOLDER_CLASS_NAME + - ". Make sure the generated binary files are on the classpath."), e); - } - catch (NoSuchFieldException e) - { - throw causedException(new RuntimeException("Cannot find field " + - TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME + - ". Please verify the version of xbean.jar is correct."), e); - } - catch (IllegalAccessException e) - { - throw causedException(new RuntimeException("Field " + - TYPE_SYSTEM_FIELD + " on class " + stsName + "." + HOLDER_CLASS_NAME + - "is not accessible. Please verify the version of xbean.jar is correct."), e); - } - } - - /** - * Returns a new ResourceLoader for a search path where each component of - * the path is either a directory or a compiled xbean jar. - */ - public static ResourceLoader resourceLoaderForPath(File[] path) - { - try - { - return (ResourceLoader)_pathResourceLoaderConstructor.newInstance(new Object[] {path}); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl: verify that version of xbean.jar is correct"), e); - } - catch (InstantiationException e) - { - throw causedException(new IllegalStateException(e.getMessage()), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * Returns the SchemaType from a corresponding XmlObject subclass, - * or null if none. - */ - public static SchemaType typeForClass(Class c) - { - if (c == null || !XmlObject.class.isAssignableFrom(c)) - return null; - - try - { - Field typeField = c.getField("type"); - - if (typeField == null) - return null; - - return (SchemaType)typeField.get(null); - } - catch (Exception e) - { - return null; - } - } - - private static SchemaType getNoType() - { - try - { - return (SchemaType)_getNoTypeMethod.invoke(null, null); - } - catch (IllegalAccessException e) - { - throw causedException(new IllegalStateException("No access to SchemaTypeLoaderImpl.getContextTypeLoader(): verify that version of xbean.jar is correct"), e); - } - catch (InvocationTargetException e) - { - Throwable t = e.getCause(); - IllegalStateException ise = new IllegalStateException(t.getMessage()); - ise.initCause(t); // use initCause() to support Java 1.4 - throw ise; - } - } - - /** - * The SchemaType object given to an XmlObject instance when - * no type can be determined. - *

      - * The NO_TYPE is the universal derived type. That is, it is - * derived from all other schema types, and no instances of the - * NO_TYPE are valid. (It is not to be confused with the anyType, - * which is the universal base type from which all other types - * can be derived, and of which all instances are valid.) - */ - public static SchemaType NO_TYPE = getNoType(); - - private XmlBeans ( ) { } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlBoolean.java b/src/xmlpublic/org/apache/xmlbeans/XmlBoolean.java deleted file mode 100644 index 579b38d..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlBoolean.java +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:boolean type. - *

      - * Naturally, convertible to Java boolean. - */ -public interface XmlBoolean extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_boolean"); - - /** - * Returns this value as a boolean - * @deprecated replaced by {@link #getBooleanValue} - **/ - boolean booleanValue(); - /** - * Sets this value as a boolean - * @deprecated replaced by {@link #setBooleanValue} - **/ - void set(boolean v); - - /** Returns this value as a boolean */ - boolean getBooleanValue(); - /** Sets this value as a boolean */ - void setBooleanValue(boolean v); - - /** - * A class with methods for creating instances - * of {@link XmlBoolean}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlBoolean} */ - public static XmlBoolean newInstance() { - return (XmlBoolean) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlBoolean} */ - public static XmlBoolean newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlBoolean) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlBoolean} value */ - public static XmlBoolean newValue(Object obj) { - return (XmlBoolean) type.newValue( obj ); } - - /** Parses a {@link XmlBoolean} fragment from a String. For example: "<xml-fragment>true</xml-fragment>". */ - public static XmlBoolean parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from a String. For example: "<xml-fragment>true</xml-fragment>". */ - public static XmlBoolean parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from a File. */ - public static XmlBoolean parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from a File. */ - public static XmlBoolean parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from a URL. */ - public static XmlBoolean parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from a URL. */ - public static XmlBoolean parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from an InputStream. */ - public static XmlBoolean parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from an InputStream. */ - public static XmlBoolean parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from a Reader. */ - public static XmlBoolean parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from a Reader. */ - public static XmlBoolean parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from a DOM Node. */ - public static XmlBoolean parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from a DOM Node. */ - public static XmlBoolean parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlBoolean parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlBoolean parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlBoolean} fragment from an XMLStreamReader. */ - public static XmlBoolean parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlBoolean} fragment from an XMLStreamReader. */ - public static XmlBoolean parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlBoolean) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlByte.java b/src/xmlpublic/org/apache/xmlbeans/XmlByte.java deleted file mode 100644 index b59d3ee..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlByte.java +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:byte type. - *

      - * Naturally, convertible to Java byte. - */ -public interface XmlByte extends XmlShort -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_byte"); - - /** - * Returns this value as a byte - * @deprecated replaced by {@link #getByteValue} - **/ - public byte byteValue(); - /** - * Sets this value as a byte - * @deprecated replaced by {@link #setByteValue} - **/ - public void set(byte s); - - /** Returns this value as a byte */ - public byte getByteValue(); - /** Sets this value as a byte */ - public void setByteValue(byte s); - - /** - * A class with methods for creating instances - * of {@link XmlByte}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlByte} */ - public static XmlByte newInstance() { - return (XmlByte) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlByte} */ - public static XmlByte newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlByte) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlByte} value */ - public static XmlByte newValue(Object obj) { - return (XmlByte) type.newValue( obj ); } - - /** Parses a {@link XmlByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". */ - public static XmlByte parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". */ - public static XmlByte parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlByte} fragment from a File. */ - public static XmlByte parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlByte} fragment from a File. */ - public static XmlByte parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlByte} fragment from a URL. */ - public static XmlByte parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlByte} fragment from a URL. */ - public static XmlByte parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlByte} fragment from an InputStream. */ - public static XmlByte parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlByte} fragment from an InputStream. */ - public static XmlByte parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlByte} fragment from a Reader. */ - public static XmlByte parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlByte} fragment from a Reader. */ - public static XmlByte parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlByte} fragment from a DOM Node. */ - public static XmlByte parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlByte} fragment from a DOM Node. */ - public static XmlByte parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlByte} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlByte parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlByte} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlByte parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlByte} fragment from an XMLStreamReader. */ - public static XmlByte parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlByte) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlByte} fragment from an XMLStreamReader. */ - public static XmlByte parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlByte) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlCursor.java b/src/xmlpublic/org/apache/xmlbeans/XmlCursor.java deleted file mode 100644 index 07fb309..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlCursor.java +++ /dev/null @@ -1,1818 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.util.Collection; -import java.util.Map; -import javax.xml.namespace.QName; - -/** - * Represents a position between two logical tokens in an XML document. - * - * The tokens themselves are not exposed as objects, but their type and properties - * are discoverable through methods on the cursor. In particular, the general - * category of token is represented by a {@link XmlCursor.TokenType TokenType}.

      - * - * You use an XmlCursor instance to navigate through and manipulate an XML - * instance document. - * Once you obtain an XML document, you can create a cursor to represent - * a specific place in the XML. Because you can use a cursor with or - * without a schema corresponding to the XML, cursors are an ideal - * way to handle XML without a schema. You can create a new cursor by - * calling the {@link XmlTokenSource#newCursor() newCursor} method - * exposed by an object representing - * the XML, whether it was parsed into a strong type compiled from - * schema or an {@link XmlObject XmlObject} (as in the no-schema case).

      - * - * With an XmlCursor, you can also:

      - * - *

        - *
      • Execute XQuery and XPath expressions against the XML with the - * execQuery and selectPath methods.
      • - * - *
      • Edit and reshape the document by inserting, moving, copying, and removing - * XML.
      • - * - *
      • Insert bookmarks that "stick" to the XML at the cursor's - * position even if the cursor or XML moves.
      • - - *
      • Get and set values for containers (elements and whole documents), - * attributes, processing instructions, and comments.
      • - *
      - * - * A cursor moves through XML by moving past tokens. A - * token represents a category of XML markup, such as the start of an element, - * its end, an attribute, comment, and so on. XmlCursor methods such as - * toNextToken, toNextSibling, toParent, and so on move the cursor - * among tokens. Each token's category is of a particular type, represented - * by one of the nine types defined by the {@link XmlCursor.TokenType TokenType} class.

      - * - * When you get a new cursor for a whole instance document, the cursor is - * intially located before the STARTDOC token. This token, which has no analogy - * in the XML specification, is present in this logical model of XML - * so that you may distinguish between the document as a whole - * and the content of the document. Terminating the document is an ENDDOC - * token. This token is also not part of the XML specification. A cursor - * located immediately before this token is at the very end of the document. - * It is not possible to position the cursor after the ENDDOC token. - * Thus, the STARTDOC and ENDDOC tokens are effectively "bookends" for the content of - * the document.

      - * - * For example, for the following XML, if you were the navigate a cursor - * through the XML document using toNextToken(), the list of token types that - * follows represents the token sequence you would encounter.

      - * - *
      - * <sample x='y'>
      - *     <value>foo</value>
      - * </sample>
      - * 
      - * - * STARTDOC
      - * START (sample)
      - * ATTR (x='y')
      - * TEXT ("\n ")
      - * START (value)
      - * TEXT ("foo")
      - * END (value)
      - * TEXT ("\n")
      - * END (sample)
      - * ENDDOC

      - * - * When there are no more tokens available, hasNextToken() returns - * false and toNextToken() returns the special token type NONE and does not move - * the cursor. - *

      - * - * The {@link #currentTokenType() currentTokenType()} method - * will return the type of the token that is immediately after the cursor. - * You can also use a number of convenience methods that test for a particular - * token type. These include the methods isStart(), - * isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean - * value indicating whether the token that follows the cursor is the type - * in question. - *

      - * - * A few other methods determine whether the token is of a kind that may include - * multiple token types. The isAnyAttr() method, for example, returns true if - * the token immediately following the cursor is any kind of attribute, - * including those of the ATTR token type and xmlns attributes. - *

      - * - * Legitimate sequences of tokens for an XML document are described - * by the following Backus-Naur Form (BNF):
      - * - *
      - * <doc> ::= STARTDOC <attributes> <content> ENDDOC
      - * <element> ::= START <attributes> <content> END
      - * <attributes> ::= ( ATTR | NAMESPACE ) *
      - * <content> ::= ( COMMENT | PROCINST | TEXT | <element> ) *
      - * 
      - * - * Note that a legitimate sequence is STARTDOC ENDDOC, the result of - * creating a brand new instance of an empty document. Also note that - * attributes may only follow container tokens (STARTDOC or START) - */ -public interface XmlCursor extends XmlTokenSource -{ - /** - * An enumeration that identifies the type of an XML token. - */ - public static final class TokenType - { - public String toString ( ) { return _name; } - - /** - * Returns one of the INT_ values defined in this class. - */ - public int intValue ( ) { return _value; } - - /** No token. See {@link #intValue}. */ - public static final int INT_NONE = 0; - /** The start-document token. See {@link #intValue}. */ - public static final int INT_STARTDOC = 1; - /** The end-document token. See {@link #intValue}. */ - public static final int INT_ENDDOC = 2; - /** The start-element token. See {@link #intValue}. */ - public static final int INT_START = 3; - /** The end-element token. See {@link #intValue}. */ - public static final int INT_END = 4; - /** The text token. See {@link #intValue}. */ - public static final int INT_TEXT = 5; - /** The attribute token. See {@link #intValue}. */ - public static final int INT_ATTR = 6; - /** The namespace declaration token. See {@link #intValue}. */ - public static final int INT_NAMESPACE = 7; - /** The comment token. See {@link #intValue}. */ - public static final int INT_COMMENT = 8; - /** The processing instruction token. See {@link #intValue}. */ - public static final int INT_PROCINST = 9; - - /** True if no token. */ - public boolean isNone ( ) { return this == NONE; } - /** True if is start-document token. */ - public boolean isStartdoc ( ) { return this == STARTDOC; } - /** True if is end-document token. */ - public boolean isEnddoc ( ) { return this == ENDDOC; } - /** True if is start-element token. */ - public boolean isStart ( ) { return this == START; } - /** True if is end-element token. */ - public boolean isEnd ( ) { return this == END; } - /** True if is text token. */ - public boolean isText ( ) { return this == TEXT; } - /** True if is attribute token. */ - public boolean isAttr ( ) { return this == ATTR; } - /** True if is namespace declaration token. */ - public boolean isNamespace ( ) { return this == NAMESPACE; } - /** True if is comment token. */ - public boolean isComment ( ) { return this == COMMENT; } - /** True if is processing instruction token. */ - public boolean isProcinst ( ) { return this == PROCINST; } - - /** True if is start-document or start-element token */ - public boolean isContainer ( ) { return this == STARTDOC || this == START; } - /** True if is end-document or end-element token */ - public boolean isFinish ( ) { return this == ENDDOC || this == END; } - /** True if is attribute or namespace declaration token */ - public boolean isAnyAttr ( ) { return this == NAMESPACE || this == ATTR; } - - /** The singleton no-token type */ - public static final TokenType NONE = new TokenType( "NONE", INT_NONE ); - /** The singleton start-document token type */ - public static final TokenType STARTDOC = new TokenType( "STARTDOC", INT_STARTDOC ); - /** The singleton start-document token type */ - public static final TokenType ENDDOC = new TokenType( "ENDDOC", INT_ENDDOC ); - /** The singleton start-element token type */ - public static final TokenType START = new TokenType( "START", INT_START ); - /** The singleton end-element token type */ - public static final TokenType END = new TokenType( "END", INT_END ); - /** The singleton text token type */ - public static final TokenType TEXT = new TokenType( "TEXT", INT_TEXT ); - /** The singleton attribute token type */ - public static final TokenType ATTR = new TokenType( "ATTR", INT_ATTR ); - /** The singleton namespace declaration token type */ - public static final TokenType NAMESPACE = new TokenType( "NAMESPACE", INT_NAMESPACE ); - /** The singleton comment token type */ - public static final TokenType COMMENT = new TokenType( "COMMENT", INT_COMMENT ); - /** The singleton processing instruction token type */ - public static final TokenType PROCINST = new TokenType( "PROCINST", INT_PROCINST ); - - private TokenType ( String name, int value ) - { - _name = name; - _value = value; - } - - private String _name; - private int _value; - } - - /** - * Deallocates resources needed to manage the cursor, rendering this cursor - * inoperable. Because cursors are managed by a mechanism which stores the - * XML, simply letting a cursor go out of scope and having the garbage collector - * attempt to reclaim it may not produce desirable performance.

      - * - * So, explicitly disposing a cursor allows the underlying implementation - * to release its responsibility of maintaining its position.

      - * - * After a cursor has been disposed, it may not be used again. It can - * throw IllegalStateException or NullPointerException if used after - * disposal.

      - */ - - void dispose ( ); - - /** - * Moves this cursor to the same position as the moveTo cursor. if the - * moveTo cursor is in a different document from this cursor, this cursor - * will not be moved, and false returned. - * - * @param moveTo The cursor at the location to which this cursor - * should be moved. - * @return true if the cursor moved; otherwise, false. - */ - - boolean toCursor ( XmlCursor moveTo ); - - /** - * Saves the current location of this cursor on an internal stack of saved - * positions (independent of selection). This location may be restored - * later by calling the pop() method. - */ - - void push ( ); - - /** - * Restores the cursor location most recently saved with the push() method. - * - * @return true if there was a location to restore; otherwise, false. - */ - - boolean pop ( ); - - /** - * Executes the specified XPath expression against the XML that this - * cursor is in. The cursor's position does not change. To navigate to the - * selections, use {@link #hasNextSelection} and {@link #toNextSelection} (similar to - * {@link java.util.Iterator}).

      - * - * The root referred to by the expression should be given as - * a dot. The following is an example path expression: - *
      -     * cursor.selectPath("./purchase-order/line-item");
      -     * 
      - * - * Note that this method does not support top-level XPath functions. - * - * @param path The path expression to execute. - * @throws XmlRuntimeException If the query expression is invalid. - */ - void selectPath ( String path ); - - /** - * Executes the specified XPath expression against the XML that this - * cursor is in. The cursor's position does not change. To navigate to the - * selections, use hasNextSelection and toNextSelection (similar to - * java.util.Iterator).

      - * - * The root referred to by the expression should be given as - * a dot. The following is an example path expression: - *
      -     * cursor.selectPath("./purchase-order/line-item");
      -     * 
      - * - * Note that this method does not support top-level XPath functions. - * - * @param path The path expression to execute. - * @param options Options for the query. For example, you can call - * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} - * method to specify a particular name for the query expression - * variable that indicates the context node. - * @throws XmlRuntimeException If the query expression is invalid. - */ - void selectPath ( String path, XmlOptions options ); - - /** - * Returns whether or not there is a next selection. - * - * @return true if there is a next selection; otherwise, false. - */ - - boolean hasNextSelection ( ); - - /** - * Moves this cursor to the next location in the selection, - * if any. See the {@link #selectPath} and {@link #addToSelection} methods. - * - * @return true if the cursor moved; otherwise, false. - */ - - boolean toNextSelection ( ); - - /** - * Moves this cursor to the specified location in the selection. - * If i is less than zero or greater than or equal to the selection - * count, this method returns false. - * - * See also the selectPath() and addToSelection() methods. - * - * @param i The index of the desired location. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toSelection ( int i ); - - /** - * Returns the count of the current selection. See also the selectPath() - * and addToSelection() methods. - * - * You may experience better performance if you use the iteration - * model using the toNextSelection method, rather than - * the indexing model using the getSelectionCount and - * toSelection methods. - * - * @return A number indicating the size of the current selection. - */ - - int getSelectionCount ( ); - - - /** - * Appends the current location of the cursor to the selection. - * See also the selectPath() method. You can use this as an - * alternative to calling the selectPath method when you want - * to define your own selection. - */ - - void addToSelection ( ); - - /** - * Clears this cursor's selection, but does not modify the document. - */ - void clearSelections ( ); - - /** - * Moves this cursor to the same position as the bookmark. If the - * bookmark is in a different document from this cursor or if the - * bookmark is orphaned, this cursor - * will not be moved, and false will be returned. - * - * @param bookmark The bookmark at the location to which this - * cursor should be moved. - * @return true if the cursor moved; otherwise, false. - */ - - boolean toBookmark ( XmlBookmark bookmark ); - - /** - * Moves this cursor to the location after its current position - * where a bookmark with the given key exists. Returns false if no - * such bookmark exists. - * - * @param key The key held by the next bookmark at the location to - * which this cursor should be moved. - * @return The next corresponding bookmark, if it exists; null if there - * is no next bookmark with the specified key. - */ - - XmlBookmark toNextBookmark ( Object key ); - - /** - * Moves this cursor to the location before its current position - * where a bookmark with the given key exists. Returns false if no - * such bookmark exists. - * - * @param key The key held by the previous bookmark at the location to - * which this cursor should be moved. - * @return The previous corresponding bookmark, if it exists; null if - * there is no previous bookmark with the specified key. - */ - - XmlBookmark toPrevBookmark ( Object key ); - - /** - * Returns the name of the current token. Names may be associated with - * START, ATTR, NAMESPACE or PROCINST. Returns null if there is no - * name associated with the current token. For START and ATTR, the - * name returned identifies the name of the element or attribute. - * For NAMESPACE, the local part of the name is the prefix, while - * the URI is the namespace defined. For PROCINST, the local part - * is the target and the uri is "". - *

      - * In the following example, xmlObject represents - * an XML instance whose root element is not preceded by any other XML. - * This code prints the root element name (here, the local name, or - * name without URI). - *

      -     * XmlCursor cursor = xmlObject.newCursor();
      -     * cursor.toFirstContentToken();
      -     * String elementName = cursor.getName().getLocalPart();
      -     * System.out.println(elementName);
      -     * 
      - * - * @return The name of the XML at this cursor's location; null if there - * is no name. - */ - - QName getName ( ); - - /** - * Sets the name of the current token. This token can be START, NAMESPACE, - * ATTR or PROCINST. - * - * @param name The new name for the current token. - */ - - void setName ( QName name ); - - /** - * Returns the namespace URI indicated by the given prefix. The current - * context must be at a START or STARTDOC. Namespace prefix mappings - * are queried for the mappings defined at the current container first, - * then parents are queried. The prefix can be "" or null to indicate - * a search for the default namespace. To conform with the - * XML spec, the default namespace will return the no-namespace ("") - * if it is not mapped.

      - * - * Note that this queries the current state of the document. When the - * document is persisted, the saving mechanism may synthesize namespaces - * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are - * only present in the serialized form, and are not reflected back into - * the document being saved. - * - * @param prefix The namespace prefix for the requested namespace. - * @return The URI for corresponding to the specified prefix if it - * exists; otherwise, null. - */ - String namespaceForPrefix ( String prefix ); - - /** - * Returns a prefix that can be used to indicate a namespace URI. The - * current context must be at a START or STARTDOC. If there is an - * existing prefix that indicates the URI in the current context, that - * prefix may be returned. Otherwise, a new prefix for the URI will be - * defined by adding an xmlns attribute to the current container or a - * parent container. - * - * Note that this queries the current state of the document. When the - * document is persisted, the saving mechanism may synthesize namespaces - * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are - * only present in the serialized form, and are not reflected back into - * the document being saved. - * - * @param namespaceURI The namespace URI corresponding to the requested - * prefix. - * @return The prefix corresponding to the specified URI if it exists; - * otherwise, a newly generated prefix. - */ - String prefixForNamespace ( String namespaceURI ); - - /** - * Adds to the specified map, all the namespaces in scope at the container - * where this cursor is positioned. This method is useful for - * container tokens only. - * - * @param addToThis The Map to add the namespaces to. - */ - - void getAllNamespaces ( Map addToThis ); - - /** - * Returns the strongly-typed XmlObject at the current START, - * STARTDOC, or ATTR.

      - * - * The strongly-typed object can be cast to the strongly-typed - * XBean interface corresponding to the XML Schema Type given - * by result.getSchemaType().

      - * - * If a more specific type cannot be determined, an XmlObject - * whose schema type is anyType will be returned. - * - * @return The strongly-typed object at the cursor's current location; - * null if the current location is not a START, STARTDOC, or ATTR. - */ - - XmlObject getObject ( ); - - /** - * Returns the type of the current token. By definition, the current - * token is the token immediately to the right of the cursor. - * If you're in the middle of text, before a character, you get TEXT. - * You can't dive into the text of an ATTR, COMMENT or PROCINST.

      - * - * As an alternative, it may be more convenient for you to use one of the - * methods that test for a particular token type. These include the methods - * isStart(), isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean - * value indicating whether the token that follows the cursor is the type - * in question. - *

      - * - * @return The TokenType instance for the token at the cursor's current - * location. - */ - - TokenType currentTokenType ( ); - - /** - * True if the current token is a STARTDOC token type, meaning - * at the very root of the document. - * - * @return true if this token is a STARTDOC token type; - * otherwise, false. - */ - - boolean isStartdoc ( ); - - /** - * True if this token is an ENDDOC token type, meaning - * at the very end of the document. - * - * @return true if this token is an ENDDOC token type; - * otherwise, false. - */ - - boolean isEnddoc ( ); - - /** - * True if this token is a START token type, meaning - * just before an element's start. - * - * @return true if this token is a START token type; - * otherwise, false. - */ - - boolean isStart ( ); - - /** - * True if this token is an END token type, meaning - * just before an element's end. - * - * @return true if this token is an END token type; - * otherwise, false. - */ - - boolean isEnd ( ); - - /** - * True if the this token is a TEXT token type, meaning - * just before or inside text. - * - * @return true if this token is a TEXT token type; - * otherwise, false. - */ - - boolean isText ( ); - - /** - * True if this token is an ATTR token type, meaning - * just before an attribute. - * - * @return true if this token is an ATTR token type; - * otherwise, false. - */ - - boolean isAttr ( ); - - /** - * True if this token is a NAMESPACE token type, meaning - * just before a namespace declaration. - * - * @return true if this token is a NAMESPACE token type; - * otherwise, false. - */ - - boolean isNamespace ( ); - - /** - * True if this token is a COMMENT token type, meaning - * just before a comment. - * - * @return true if this token is a COMMENT token type; - * otherwise, false. - */ - - boolean isComment ( ); - - /** - * True if this token is a PROCINST token type, meaning - * just before a processing instruction. - * - * @return true if this token is a PROCINST token type; - * otherwise, false. - */ - - boolean isProcinst ( ); - - /** - * True if this token is a container token. The STARTDOC and START - * token types are containers. Containers, including documents and elements, - * have the same content model. In other words, a document and an element - * may have the same contents. For example, a document may contain attributes - * or text, without any child elements. - * - * @return true if this token is a container token; otherwise, false. - */ - - boolean isContainer ( ); - - /** - * True if this token is a finish token. A finish token can be an ENDDOC - * or END token type. - - * @return true if this token is a finish token; otherwise, false. - */ - - boolean isFinish ( ); - - /** - * True if this token is any attribute. This includes an ATTR token type and - * the NAMESPACE token type attribute. - * - * @return true if the current cursor is at any attribute; otherwise, false. - */ - - boolean isAnyAttr ( ); - - /** - * Returns the type of the previous token. By definition, the previous - * token is the token immediately to the left of the cursor.

      - * - * If you're in the middle of text, after a character, you get TEXT. - * - * @return The TokenType instance for the token immediately before the - * token at the cursor's current location. - */ - - TokenType prevTokenType ( ); - - /** - * True if there is a next token. When this is false, as when the cursor is - * at the ENDDOC token, the toNextToken() method returns NONE and does not - * move the cursor. - * - * @return true if there is a next token; otherwise, false. - */ - - boolean hasNextToken ( ); - - - /** - * True if there is a previous token. When this is false, toPrevToken - * returns NONE and does not move the cursor. - * - * @return true if there is a previous token; otherwise, false. - */ - - boolean hasPrevToken ( ); - - /** - * Moves the cursor to the next token. When there are no more tokens - * available, hasNextToken returns false and toNextToken() returns - * NONE and does not move the cursor. Returns the token type - * of the token to the right of the cursor upon a successful move. - * - * @return The token type for the next token if the cursor was moved; - * otherwise, NONE. - */ - - TokenType toNextToken ( ); - - /** - * Moves the cursor to the previous token. When there is no - * previous token, returns NONE, otherwise returns the token - * to the left of the new position of the cursor. - * - * @return The token type for the previous token if the cursor was moved; - * otherwise, NONE. - */ - - TokenType toPrevToken ( ); - - /** - * Moves the cursor to the first token in the content of the current - * START or STARTDOC. That is, the first token after all ATTR and NAMESPACE - * tokens associated with this START.

      - * - * If the current token is not a START or STARTDOC, the cursor is not - * moved and NONE is returned. If the current START or STARTDOC - * has no content, the cursor is moved to the END or ENDDOC token.

      - * - * @return The new current token type. - */ - - TokenType toFirstContentToken ( ); - - - /** - * Moves the cursor to the END or ENDDOC token corresponding to the - * current START or STARTDOC, and returns END or ENDDOC.

      - * - * If the current token is not a START or STARTDOC, the cursor is not - * moved and NONE is returned. - * - * @return The new current token type. - */ - - TokenType toEndToken ( ); - - /** - * Moves the cursor forward by the specified number of characters, and - * stops at the next non-TEXT token. Returns the number of characters - * actually moved across, which is guaranteed to be less than or equal to - * maxCharacterCount. If there is no further text, or if - * there is no text at all, returns zero.

      - * - * Note this does not dive into attribute values, comment contents, - * processing instruction contents, etc., but only content text.

      - * - * You can pass maxCharacterCount < 0 to move over all the text to the - * right. This has the same effect as toNextToken, but returns the amount - * of text moved over. - * - * @param maxCharacterCount The maximum number of characters by which - * the cursor should be moved. - * @return The actual number of characters by which the cursor was moved; - * 0 if the cursor was not moved. - */ - - int toNextChar ( int maxCharacterCount ); - - /** - * Moves the cursor backwards by the number of characters given. Has - * similar characteristics to the {@link #toNextChar(int) toNextChar} method. - * - * @param maxCharacterCount The maximum number of characters by which - * the cursor should be moved. - * @return The actual number of characters by which the cursor was moved; - * 0 if the cursor was not moved. - */ - - int toPrevChar ( int maxCharacterCount ); - - /** - * Moves the cursor to the next sibling element, or returns - * false and does not move the cursor if there is no next sibling - * element. (By definition the position of an element is the same - * as the position of its START token.) - * - * If the current token is not s START, the cursor will be - * moved to the next START without moving out of the scope of the - * current element. - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toNextSibling ( ); - - /** - * Moves the cursor to the previous sibling element, or returns - * false and does not move the cursor if there is no previous sibling - * element. (By definition the position of an element is the same - * as the position of its START token.) - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toPrevSibling ( ); - - /** - * Moves the cursor to the parent element or STARTDOC, or returns - * false and does not move the cursor if there is no parent.

      - * - * Works if you're in attributes or content. Returns false only if at - * STARTDOC. Note that the parent of an END token is the corresponding - * START token. - * - * @return true if the cursor was moved; false if the cursor is at the STARTDOC - * token. - */ - - boolean toParent ( ); - - /** - * Moves the cursor to the first child element, or returns false and - * does not move the cursor if there are no element children.

      - * - * If the cursor is not currently in an element, it moves into the - * first child element of the next element. - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toFirstChild ( ); - - /** - * Moves the cursor to the last element child, or returns false and - * does not move the cursor if there are no element children. - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toLastChild ( ); - - /** - * Moves the cursor to the first child element of the specified name in - * no namespace. - * - * @param name The name of the element to move the cursor to. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toChild ( String name ); - - /** - * Moves the cursor to the first child element of the specified name in the - * specified namespace. - * - * @param namespace The namespace URI for the element to move the cursor - * to. - * @param name The name of the element to move to. - * @return true if the cursor was moved; otherwise, false. - * @throws IllegalArgumentException If the name is not a valid local name. - */ - - boolean toChild ( String namespace, String name ); - - /** - * Moves the cursor to the first child element of the specified qualified name. - * - * @param name The name of the element to move the cursor to. - */ - - boolean toChild ( QName name ); - - /** - * Moves the cursor to the child element specified by index. - * - * @param index The position of the element in the sequence of child - * elements. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toChild ( int index ); - - /** - * Moves the cursor to the specified index child element of the - * specified name, where that element is the . - * - * @param name The name of the child element to move the cursor to. - * @param index The position of the element in the sequence of child - * elements. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toChild ( QName name, int index ); - - /** - * Moves the cursor to the next sibling element of the specified name in no - * namespace. - * - * @param name The name of the element to move the cursor to. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toNextSibling ( String name ); - - /** - * Moves the cursor to the next sibling element of the specified name - * in the specified namespace. - * - * @param namespace The namespace URI for the element to move the cursor - * to. - * @param name The name of the element to move the cursor to. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toNextSibling ( String namespace, String name ); - - - /** - * Moves the cursor to the next sibling element of the specified - * qualified name. - * - * @param name The name of the element to move the cursor to. - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toNextSibling ( QName name ); - - /** - * Moves the cursor to the first attribute of this element, or - * returns false and does not move the cursor if there are no - * attributes. The order of attributes is arbitrary, but stable.

      - * - * If the cursor is on a STARTDOC of a document-fragment, this method will - * move it to the first top level attribute if one exists.

      - * - * xmlns attributes (namespace declarations) are not considered - * attributes by this function.

      - * - * The cursor must be on a START or STARTDOC (in the case of a - * document fragment with top level attributes) for this method to - * succeed. - * - * Example for looping through attributes: - *
      -     *      XmlCursor cursor = ... //cursor on START or STARTDOC
      -     *      if (cursor.toFirstAttribute())
      -     *      {
      -     *          do
      -     *          {
      -     *              // do something using attribute's name and value
      -     *              cursor.getName();
      -     *              cursor.getTextValue();
      -     *          }
      -     *          while (cursor.toNextAttribute());
      -     *      }
      -     * 
      - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toFirstAttribute ( ); - - /** - * Moves the cursor to the last attribute of this element, or - * returns false and does not move the cursor if there are no - * attributes. The order of attributes is arbitrary, but stable.

      - * - * xmlns attributes (namespace declarations) are not considered - * attributes by this function.

      - * - * The cursor must be on a START or STARTDOC for this method - * to succeed. - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toLastAttribute ( ); - - /** - * Moves the cursor to the next sibling attribute, or returns - * false and does not move the cursor if there is no next - * sibling attribute. The order of attributes is arbitrary, but stable.

      - * - * xmlns attributes (namespace declarations) are not considered - * attributes by this function.

      - * - * The cursor must be on an attribute for this method to succeed. - * @see #toFirstAttribute() - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toNextAttribute ( ); - - /** - * Moves the cursor to the previous sibling attribute, or returns - * false and does not move the cursor if there is no previous - * sibling attribute. The order of attributes is arbitrary, but stable.

      - * - * xmlns attributes (namespace declarations) are not considered - * attributes by this function.

      - * - * The cursor must be on an attribute for this method to succeed. - * - * @return true if the cursor was moved; otherwise, false. - */ - - boolean toPrevAttribute ( ); - - /** - * When at a START or STARTDOC, returns the attribute text for the given - * attribute. When not at a START or STARTDOC or the attribute does not - * exist, returns null. - * - * @param attrName The name of the attribute whose value is requested. - * @return The attribute's value if it has one; otherwise, null. - */ - - String getAttributeText ( QName attrName ); - - /** - * When at a START or STARTDOC, sets the attribute text for the given - * attribute. When not at a START or STARTDOC returns false. - * If the attribute does not exist, one is created. - * - * @param attrName The name of the attribute whose value is being set. - * @param value The new value for the attribute. - * @return true if the new value was set; otherwise, false. - */ - - boolean setAttributeText ( QName attrName, String value ); - - /** - * When at a START or STARTDOC, removes the attribute with the given name. - * - * @param attrName The name of the attribute that should be removed. - * @return true if the attribute was removed; otherwise, false. - */ - - boolean removeAttribute ( QName attrName ); - - /** - * Gets the text value of the current document, element, attribute, - * comment, procinst or text token.

      - * - * When getting the text value of an element, non-text content such - * as comments and processing instructions are ignored and text is concatenated. - * For elements that have nested element children, this - * returns the concatenated text of all mixed content and the - * text of all the element children, recursing in first-to-last - * depthfirst order.

      - * - * For attributes, including namespaces, this returns the attribute value.

      - * - * For comments and processing instructions, this returns the text content - * of the comment or PI, not including the delimiting sequences <!-- -->, <? ?>. - * For a PI, the name of the PI is also not included. - *

      - * The value of an empty tag is the empty string.

      - * - * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.

      - * - * @return The text value of the current token if the token's type is - * START, STARTDOC, TEXT, ATTR, COMMENT, PROCINST, or NAMESPACE; null - * if the type is NONE. - */ - - String getTextValue ( ); - - /** - * Copies the text value of the current document, element, attribute, - * comment, processing instruction or text token, counting right from - * this cursor's location up to maxCharacterCount, - * and copies the returned text into returnedChars.

      - * - * When getting the text value of an element, non-text content such - * as comments and processing instructions are ignored and text is concatenated. - * For elements that have nested element children, this - * returns the concatenated text of all mixed content and the - * text of all the element children, recursing in first-to-last - * depthfirst order.

      - * - * For attributes, including namespaces, this returns the attribute value.

      - * - * For comments and processing instructions, this returns the text contents - * of the comment or PI, not including the delimiting sequences <!-- -->, <? ?>. For - * a PI, the text will not include the name of the PI.

      - * - * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.

      - * - * The value of an empty tag is the empty string.

      - * - * @param returnedChars A character array to hold the returned characters. - * @param offset The position within returnedChars to which the first of the - * returned characters should be copied. - * @param maxCharacterCount The maximum number of characters after this cursor's - * location to copy. A negative value specifies that all characters should be copied. - * @return The actual number of characters copied; 0 if no characters - * were copied. - */ - - int getTextValue ( char[] returnedChars, int offset, int maxCharacterCount ); - - /** - * Returns the characters of the current TEXT token. If the current token - * is not TEXT, returns "". If in the middle of a TEXT token, returns - * those chars to the right of the cursor of the TEXT token. - * - * @return The requested text; an empty string if the current token type is - * not TEXT. - */ - - /** - * Sets the text value of the XML at this cursor's location if that XML's - * token type is START, STARTDOC, ATTR, COMMENT or PROCINST.

      - * - * For elements that have nested children this first removes all - * the content of the element and replaces it with the given text. - * - * @param text The text to use as a new value. - * @throws java.lang.IllegalStateException If the token type at this - * cursor's location is not START, STARTDOC, ATTR, COMMENT or - * PROCINST. - */ - void setTextValue ( String text ); - - /** - * Sets the text value of the XML at this cursor's location (if that XML's - * token type is START, STARTDOC, ATTR, COMMENT or PROCINST) to the - * contents of the specified character array.

      - * - * For elements that have nested children this first removes all - * the content of the element and replaces it with the given text. - * - * @param sourceChars A character array containing the XML's new value. - * @param offset The position within sourceChars from which the first of - * the source characters should be copied. - * @param length The maximum number of characters to set as the XML's new - * value. - * @throws java.lang.IllegalArgumentException If the token type at this - * cursor's location is not START, STARTDOC, ATTR, COMMENT or - * PROCINST. - */ - void setTextValue ( char[] sourceChars, int offset, int length ); - - /** - * Returns characters to the right of the cursor up to the next token. - */ - String getChars ( ); - - /** - * Copies characters up to the specified maximum number, counting right from - * this cursor's location to the character at maxCharacterCount. The - * returned characters are added to returnedChars, with the first - * character copied to the offset position. The maxCharacterCount - * parameter should be less than or equal to the length of returnedChars - * minus offset. Copies a number of characters, which is - * either maxCharacterCount or the number of characters up to the next token, - * whichever is less. - * - * @param returnedChars A character array to hold the returned characters. - * @param offset The position within returnedChars at which the first of the - * returned characters should be added. - * @param maxCharacterCount The maximum number of characters after this cursor's - * location to return. - * @return The actual number of characters returned; 0 if no characters - * were returned or if the current token is not TEXT. - */ - - int getChars ( char[] returnedChars, int offset, int maxCharacterCount ); - - /** - * Moves the cursor to the STARTDOC token, which is the - * root of the document. - */ - - void toStartDoc ( ); - - /** - * Moves the cursor to the ENDDOC token, which is the end - * of the document. - */ - - void toEndDoc ( ); - - /** - * Determines if the specified cursor is in the same document as - * this cursor. - * - * @param cursor The cursor that may be in the same document - * as this cursor. - * @return true if the specified cursor is in the same document; - * otherwise, false. - */ - - boolean isInSameDocument ( XmlCursor cursor ); - - /** - * Returns an integer indicating whether this cursor is before, - * after, or at the same position as the specified cursor.

      - * - * a.comparePosition(b) < 0 means a is to the left of b.
      - * a.comparePosition(b) == 0 means a is at the same position as b.
      - * a.comparePosition(b) > 0 means a is to the right of b.

      - * - * The sort order of cursors in the document is the token order. - * For example, if cursor "a" is at a START token and the cursor "b" - * is at a token within the contents of the same element, then - * a.comparePosition(b) will return -1, meaning that the position - * of a is before b. - * - * @param cursor The cursor whose position should be compared - * with this cursor. - * @return 1 if this cursor is after the specified cursor; 0 if - * this cursor is at the same position as the specified cursor; - * -1 if this cursor is before the specified cursor. - * @throws java.lang.IllegalArgumentException If the specified - * cursor is not in the same document as this cursor. - */ - - int comparePosition ( XmlCursor cursor ); - - /** - * Determines if this cursor is to the left of (or before) - * the specified cursor. Note that this is the same as - * a.comparePosition(b) < 0 - * - * @param cursor The cursor whose position should be compared - * with this cursor. - * @return true if this cursor is to the left of the specified - * cursor; otherwise, false. - */ - - boolean isLeftOf ( XmlCursor cursor ); - - /** - * Determines if this cursor is at the same position as - * the specified cursor. Note that this is the same as - * a.comparePosition(b) == 0 - * - * @param cursor The cursor whose position should be compared - * with this cursor. - * @return true if this cursor is at the same position as - * the specified cursor; otherwise, false. - */ - - boolean isAtSamePositionAs ( XmlCursor cursor ); - - /** - * Determines if this cursor is to the right of (or after) - * the specified cursor. Note that this is the same as - * a.comparePosition(b) > 0 - * - * @param cursor The cursor whose position should be compared - * with this cursor. - * @return true if this cursor is to the right of the specified - * cursor; otherwise, false. - */ - - boolean isRightOf ( XmlCursor cursor ); - - /** - * Executes the specified XQuery expression against the XML this - * cursor is in.

      - * - * The query may be a String or a compiled query. You can precompile - * an XQuery expression using the XmlBeans.compileQuery method.

      - * - * The root referred to by the expression should be given as - * a dot. The following is an example path expression: - *
      -     * XmlCursor results = cursor.execQuery("purchase-order/line-item[price <= 20.00]");
      -     * 
      - * - * @param query The XQuery expression to execute. - * @return A cursor containing the results of the query. - * @throws XmlRuntimeException If the query expression is invalid. - */ - - XmlCursor execQuery ( String query ); - - /** - * Executes the specified XQuery expression against the XML this - * cursor is in, and using the specified options.

      - * - * @param query The XQuery expression to execute. - * @param options Options for the query. For example, you can call - * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)} - * method to specify a particular name for the query expression - * variable that indicates the context node. - * @throws XmlRuntimeException If the query expression is invalid. - */ - - XmlCursor execQuery ( String query, XmlOptions options ); - - /** - * Represents the state of a dcoument at a particular point - * in time. It is used to determine if a document has been changed - * since that point in time. - */ - interface ChangeStamp - { - /** - * Returns whether or not the document assoiated with this ChangeStamp - * has been altered since the ChangeStamp had been created. - */ - public boolean hasChanged ( ); - } - - /** - * Returns the current change stamp for the document the current cursor is in. - * This change stamp can be queried at a later point in time to find out - * if the document has changed. - * - * @return The change stamp for the document the current cursor is in. - */ - ChangeStamp getDocChangeStamp ( ); - - /** - * Subclasses of XmlBookmark can be used to annotate an XML document. - * This class is abstract to prevent parties from inadvertently - * interfering with each others' bookmarks without explicitly - * sharing a bookmark class. - */ - - abstract class XmlBookmark - { - /** - * Constructs a strongly-referenced bookmark. - */ - public XmlBookmark ( ) { this( false ); } - - /** - * Constructs a bookmark. - * @param weak true if the document's reference to the bookmark should be a WeakReference - */ - public XmlBookmark ( boolean weak ) - { - _ref = weak ? new WeakReference( this ) : null; - } - - /** - * Call the createCursor method to create a new cursor which is - * positioned at the same splace as the bookmark. It is much more - * efficient to call toBookmark on an existing cursor than it - * is to create a new cursor. However, toBookmark may fail if the - * bookmark is in a different document than the cursor. It is - * under these circumstances where createCursor needs to be called - * on the bookmark. Subsequent navigations to bookmark - * positions should attempt to reuse the last cursor to - * improve performace. - * - * @return the new cursor - */ - public final XmlCursor createCursor ( ) - { - return _currentMark == null ? null : _currentMark.createCursor(); - } - - /** - * @param c the cursor to be moved - * @return the given cursor moved to this bookmark - */ - public final XmlCursor toBookmark ( XmlCursor c ) - { - return c == null || !c.toBookmark( this ) ? createCursor() : c; - } - - /** - * The default key for bookmarks is the class which implements - * them. This way, multiple parties using bookmarks in the - * same instance document will not interfere with eachother. - * One can, however, override getKey() to use a key other than - * the class. - * - * @return default key for bookmarks - */ - public Object getKey ( ) - { - return this.getClass(); - } - - /** - * The mark is set by the host document; it is capable of - * returning an XmlCursor implementation at the location of - * the bookmark. - */ - public XmlMark _currentMark; - - /** - * If non-null, the ref is used by the host document - * to maintain a reference to the bookmark. If it is a weak - * reference, the host document will not prevent the Bookmark - * from being garbage collected. - */ - public final Reference _ref; - } - - /** - * An abstract {@link XmlCursor} factory. - * Implementations of XmlCursor implement XmlMark to be able to - * reconstitute a cursor from a bookmark. When content moves between - * implementations, the XmlMark is set to the implmentation's which - * recieves the new content. - */ - - interface XmlMark - { - XmlCursor createCursor ( ); - } - - /** - * Sets a bookmark to the document at this cursor's location. - * - * The bookmark is attached to the token in the tree immediately - * after the cursor. If the tree is manipulated to move - * that object to a different place, the bookmark moves with it. - * If the tree is manipulated to delete that token from the - * tree, the bookmark is orphaned. Copy operations do not copy - * bookmarks. - * - * @param bookmark The bookmark to set. - */ - - void setBookmark ( XmlBookmark bookmark ); - - /** - * Retrieves the bookmark with the specified key - * at this cursor's location. If there is no bookmark whose key is - * given by the specified key at the current position, null is returned. - * If the {@link XmlCursor.XmlBookmark#getKey() getKey} method is not overridden on - * the bookmark, then the bookmark's class is used as the key. - * - * @param key The key for the bookmark to retrieve. - * @return The requested bookmark; null if there is no bookmark - * corresponding to the specified key. - */ - - XmlBookmark getBookmark ( Object key ); - - /** - * Clears the bookmark whose key is specified, if the bookmark - * exists at this cursor's location. - * - * @param key The for the bookmark to clear. - */ - - void clearBookmark ( Object key ); - - /** - * Retrieves all the bookmarks at this location, adding them to - * the specified collection. Bookmarks held by weak references are - * added to this collection as Weak referenced objects pointing to the - * bookmark. - * - * @param listToFill The collection that will contain bookmarks - * returned by this method. - */ - - void getAllBookmarkRefs ( Collection listToFill ); - - /** - * Removes the XML that is immediately after this cursor. - * - * For the TEXT, ATTR, NAMESPACE, COMMENT and PROCINST tokens, a single - * token is removed. For a START token, the corresponding element and all - * of its contents are removed. For all other tokens, this is a no-op. - * You cannot remove a STARTDOC. - * - * The cursors located in the XML that was removed all collapse to the - * same location. All bookmarks in this XML will be orphaned. - * - * @return true if anything was removed; false only if the cursor is - * just before END or ENDDOC token. - * @throws java.lang.IllegalArgumentException If the cursor is at a - * STARTDOC token. - */ - - boolean removeXml ( ); - - /** - * Moves the XML immediately after this cursor to the location - * specified by the toHere cursor, shifting XML at that location - * to the right to make room. For the TEXT, ATTR, NAMESPACE, - * COMMENT and PROCINST tokens, a single token is moved. For a start token, the - * element and all of its contents are moved. For all other tokens, this - * is a no-op. - * - * The bookmarks located in the XML that was moved also move to the - * new location; the cursors don't move with the content. - * - * @param toHere The cursor at the location to which the XML should - * be moved. - * @return true if anything was moved. This only happens when the XML to be - * moved contains the target of the move. - * @throws java.lang.IllegalArgumentException If the operation is not allowed - * at the cursor's location. This includes attempting to move an end token or the - * document as a whole. Also, moving to a location before the start document or moving - * an attribute to a location other than after another attribute or start token - * will throw. - */ - - boolean moveXml ( XmlCursor toHere ); - - /** - * Copies the XML immediately after this cursor to the location - * specified by the toHere cursor. For the TEXT, ATTR, NAMESPACE, - * COMMENT and PROCINST tokens, a single token is copied. For a start token, - * the element and all of its contents are copied. For all other tokens, this - * is a no-op. - * - * The cursors and bookmarks located in the XML that was copied are also copied - * to the new location. - * - * @param toHere The cursor at the location to which the XML should - * be copied. - * @return true if anything was copied; false if the token supports the operation, - * but nothing was copied. - * @throws java.lang.IllegalArgumentException If the operation is not allowed - * at the cursor's location. - */ - - boolean copyXml ( XmlCursor toHere ); - - /** - * Removes the contents of the container (STARTDOC OR START) immediately after - * this cursor. For all other situations, returns false. Does - * not remove attributes or namspaces. - * - * @return true if anything was copied; otherwise, false. - */ - - boolean removeXmlContents ( ); - - /** - * Moves the contents of the container (STARTDOC OR START) immediately after - * this cursor to the location specified by the toHere cursor. - * For all other situations, returns false. Does not move attributes or - * namespaces. - * - * @param toHere The cursor at the location to which the XML should be moved. - * @return true if anything was moved; otherwise, false. - */ - boolean moveXmlContents ( XmlCursor toHere ); - - /** - * Copies the contents of the container (STARTDOC OR START) immediately to - * the right of the cursor to the location specified by the toHere cursor. - * For all other situations, returns false. Does not copy attributes or - * namespaces. - * - * @param toHere The cursor at the location to which the XML should - * be copied. - * @return true if anything was copied; otherwise, false. - */ - boolean copyXmlContents ( XmlCursor toHere ); - - /** - * Removes characters up to the specified maximum number, counting right from - * this cursor's location to the character at maxCharacterCount. The - * space remaining from removing the characters collapses up to this cursor. - * - * @param maxCharacterCount The maximum number of characters after this cursor's - * location to remove. - * @return The actual number of characters removed. - * @throws java.lang.IllegalArgumentException If the operation is not allowed - * at the cursor's location. - */ - - int removeChars ( int maxCharacterCount ); - - /** - * Moves characters immediately after this cursor to the position immediately - * after the specified cursor. Characters are counted to the right up to the - * specified maximum number. XML after the destination cursor is - * shifted to the right to make room. The space remaining from moving the - * characters collapses up to this cursor. - * - * @param maxCharacterCount The maximum number of characters after this cursor's - * location to move. - * @param toHere The cursor to which the characters should be moved. - * @return The actual number of characters moved. - * @throws java.lang.IllegalArgumentException If the operation is not allowed - * at the cursor's location. - */ - - int moveChars ( int maxCharacterCount, XmlCursor toHere ); - - /** - * Copies characters to the position immediately after the specified cursor. - * Characters are counted to the right up to the specified maximum number. - * XML after the destination cursor is shifted to the right to make room. - * - * @param maxCharacterCount The maximum number of characters after this cursor's - * location to copy. - * @param toHere The cursor to which the characters should be copied. - * @return The actual number of characters copied. - * @throws java.lang.IllegalArgumentException If the operation is not allowed - * at the cursor's location. - */ - - int copyChars ( int maxCharacterCount, XmlCursor toHere ); - - /** - * Inserts the specified text immediately before this cursor's location. - * - * @param text The text to insert. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertChars ( String text ); - - /** - * Inserts an element immediately before this cursor's location, giving - * the element the specified qualified name. - * - * @param name The qualified name for the element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertElement ( QName name ); - - /** - * Inserts an element immediately before this cursor's location, giving - * the element the specified local name. - * - * @param localName The local name for the new element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertElement ( String localName ); - - /** - * Inserts a new element immediately before this cursor's location, giving the - * element the specified local name and associating it with specified namespace - * - * @param localName The local name for the new element. - * @param uri The URI for the new element's namespace. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertElement ( String localName, String uri ); - - /** - * Inserts a new element around this cursor, giving the element the specified - * qualified name. After the element is inserted, this cursor is between its start - * and end. This cursor can then be used to insert additional XML into - * the new element. - * - * @param name The qualified name for the new element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void beginElement ( QName name ); - - /** - * Inserts a new element around this cursor, giving the element the specified - * local name. After the element is inserted, this cursor is between its start - * and end. This cursor can then be used to insert additional XML into - * the new element. - * - * @param localName The local name for the new element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void beginElement ( String localName ); - - /** - * Inserts a new element around this cursor, giving the element the specified - * local name and associating it with the specified namespace. After the element - * is inserted, this cursor is between its start and end. This cursor - * can then be used to insert additional XML into the new element. - * - * @param localName The local name for the new element. - * @param uri The URI for the new element's namespace. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void beginElement ( String localName, String uri ); - - /** - * Inserts a new element immediately before this cursor's location, giving the - * element the specified qualified name and content. - * - * @param name The qualified name for the new element. - * @param text The content for the new element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertElementWithText ( QName name, String text ); - - /** - * Inserts a new element immediately before this cursor's location, giving the - * element the specified local name and content. - * - * @param localName The local name for the new element. - * @param text The content for the new element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertElementWithText ( String localName, String text ); - - /** - * Inserts a new element immediately before this cursor's location, giving the - * element the specified local name, associating it with the specified namespace, - * and giving it the specified content. - * - * @param localName The local name for the new element. - * @param uri The URI for the new element's namespace. - * @param text The content for the new element. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertElementWithText ( String localName, String uri, String text ); - - /** - * Inserts a new attribute immediately before this cursor's location, giving it - * the specified local name. - * - * @param localName The local name for the new attribute. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertAttribute ( String localName ); - - /** - * Inserts a new attribute immediately before this cursor's location, giving it - * the specified local name and associating it with the specified namespace. - * - * @param localName The local name for the new attribute. - * @param uri The URI for the new attribute's namespace. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertAttribute ( String localName, String uri ); - - /** - * Inserts a new attribute immediately before this cursor's location, giving it - * the specified name. - * - * @param name The local name for the new attribute. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertAttribute ( QName name ); - - /** - * Inserts a new attribute immediately before this cursor's location, giving it - * the specified value and name. - * - * @param Name The local name for the new attribute. - * @param value The value for the new attribute. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertAttributeWithValue ( String Name, String value ); - - /** - * Inserts an attribute immediately before the cursor's location, giving it - * the specified name and value, and associating it with the specified namespace. - * - * @param name The name for the new attribute. - * @param uri The URI for the new attribute's namespace. - * @param value The value for the new attribute. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertAttributeWithValue ( String name, String uri, String value ); - - /** - * Inserts an attribute immediately before the cursor's location, giving it - * the specified name and value. - * - * @param name The name for the new attribute. - * @param value The value for the new attribute. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertAttributeWithValue ( QName name, String value ); - - /** - * Inserts a namespace declaration immediately before the cursor's location, - * giving it the specified prefix and URI. - * - * @param prefix The prefix for the namespace. - * @param namespace The URI for the namespace. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertNamespace ( String prefix, String namespace ); - - /** - * Inserts an XML comment immediately before the cursor's location, - * giving it the specified content. - * - * @param text The new comment's content. - * @throws java.lang.IllegalArgumentException If the insertion is not allowed - * at the cursor's location. - */ - - void insertComment ( String text ); - - /** - * Inserts an XML processing instruction immediately before the cursor's location, - * giving it the specified target and text. - * - * @param target The target for the processing instruction. - * @param text The new processing instruction's text. - * @throws java.lang.IllegalStateException If the insertion is not allowed - * at the cursor's location. - */ - - void insertProcInst ( String target, String text ); -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlDate.java b/src/xmlpublic/org/apache/xmlbeans/XmlDate.java deleted file mode 100644 index 7d2fd26..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlDate.java +++ /dev/null @@ -1,185 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Date; -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:date type. - *

      - * Convertible to {@link Calendar}, {@link Date}, and {@link GDate}. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlDate extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_date"); - - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - /** - * Returns this value as a {@link Date} - * @deprecated replaced with {@link #getDateValue} - **/ - Date dateValue(); - /** - * Sets this value as a {@link Date} - * @deprecated replaced with {@link #setDateValue} - **/ - void set(Date d); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - /** Returns this value as a {@link Date} */ - Date getDateValue(); - /** Sets this value as a {@link Date} */ - void setDateValue(Date d); - - /** - * A class with methods for creating instances - * of {@link XmlDate}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlDate} */ - public static XmlDate newInstance() { - return (XmlDate) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlDate} */ - public static XmlDate newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlDate) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlDate} value */ - public static XmlDate newValue(Object obj) { - return (XmlDate) type.newValue( obj ); } - - /** Parses a {@link XmlDate} fragment from a String. For example: "<xml-fragment>2003-06-14</xml-fragment>". */ - public static XmlDate parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlDate} fragment from a String. For example: "<xml-fragment>2003-06-14</xml-fragment>". */ - public static XmlDate parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlDate} fragment from a File. */ - public static XmlDate parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlDate} fragment from a File. */ - public static XmlDate parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlDate} fragment from a URL. */ - public static XmlDate parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlDate} fragment from a URL. */ - public static XmlDate parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlDate} fragment from an InputStream. */ - public static XmlDate parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlDate} fragment from an InputStream. */ - public static XmlDate parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlDate} fragment from a Reader. */ - public static XmlDate parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlDate} fragment from a Reader. */ - public static XmlDate parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlDate} fragment from a DOM Node. */ - public static XmlDate parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlDate} fragment from a DOM Node. */ - public static XmlDate parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlDate} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDate parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlDate} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDate parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlDate} fragment from an XMLStreamReader. */ - public static XmlDate parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlDate) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlDate} fragment from an XMLStreamReader. */ - public static XmlDate parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlDate) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlDateTime.java b/src/xmlpublic/org/apache/xmlbeans/XmlDateTime.java deleted file mode 100644 index 1dabef7..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlDateTime.java +++ /dev/null @@ -1,188 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Date; -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:dateTime type. - *

      - * Convertible to {@link Calendar}, {@link Date}, and {@link GDate}. - * - *

      - * The XmlDateTime class only encapsulates a schema DateTime value, if you need to perform operations - * on dates, see the GDate class - * @see XmlCalendar - * @see GDate - * @see GDuration - */ -public interface XmlDateTime extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_dateTime"); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - /** - * Returns this value as a {@link Date} - * @deprecated replaced with {@link #getDateValue} - **/ - Date dateValue(); - /** - * Sets this value as a {@link Date} - * @deprecated replaced with {@link #setDateValue} - **/ - void set(Date d); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - /** Returns this value as a {@link Date} */ - Date getDateValue(); - /** Sets this value as a {@link Date} */ - void setDateValue(Date d); - - /** - * A class with methods for creating instances - * of {@link XmlDateTime}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlDateTime} */ - public static XmlDateTime newInstance() { - return (XmlDateTime) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlDateTime} */ - public static XmlDateTime newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlDateTime) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlDateTime} value */ - public static XmlDateTime newValue(Object obj) { - return (XmlDateTime) type.newValue( obj ); } - - /** Parses a {@link XmlDateTime} fragment from a String. For example: "<xml-fragment>2003-06-14T12:00:00</xml-fragment>". */ - public static XmlDateTime parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from a String. For example: "<xml-fragment>2003-06-14T12:00:00</xml-fragment>". */ - public static XmlDateTime parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from a File. */ - public static XmlDateTime parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from a File. */ - public static XmlDateTime parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from a URL. */ - public static XmlDateTime parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from a URL. */ - public static XmlDateTime parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from an InputStream. */ - public static XmlDateTime parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from an InputStream. */ - public static XmlDateTime parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from a Reader. */ - public static XmlDateTime parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from a Reader. */ - public static XmlDateTime parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from a DOM Node. */ - public static XmlDateTime parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from a DOM Node. */ - public static XmlDateTime parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDateTime parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDateTime parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlDateTime} fragment from an XMLStreamReader. */ - public static XmlDateTime parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlDateTime} fragment from an XMLStreamReader. */ - public static XmlDateTime parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlDateTime) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlDecimal.java b/src/xmlpublic/org/apache/xmlbeans/XmlDecimal.java deleted file mode 100644 index ad8c3ed..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlDecimal.java +++ /dev/null @@ -1,151 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.math.BigDecimal; - -/** - * Corresponds to the XML Schema - * xs:decimal type. - *

      - * Convertible to {@link BigDecimal}. - */ -public interface XmlDecimal extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_decimal"); - - /** Returns this value as a {@link BigDecimal} */ - BigDecimal getBigDecimalValue(); - /** Sets this value as a {@link BigDecimal} */ - void setBigDecimalValue(BigDecimal bd); - - /** - * Returns this value as a {@link BigDecimal} - * @deprecated replaced with {@link #getBigDecimalValue} - **/ - BigDecimal bigDecimalValue(); - /** - * Sets this value as a {@link BigDecimal} - * @deprecated replaced with {@link #setBigDecimalValue} - **/ - void set(BigDecimal bd); - - /** - * A class with methods for creating instances - * of {@link XmlDecimal}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlDecimal} */ - public static XmlDecimal newInstance() { - return (XmlDecimal) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlDecimal} */ - public static XmlDecimal newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlDecimal) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlDecimal} value */ - public static XmlDecimal newValue(Object obj) { - return (XmlDecimal) type.newValue( obj ); } - - /** Parses a {@link XmlDecimal} fragment from a String. For example: "<xml-fragment>1234.56789</xml-fragment>". */ - public static XmlDecimal parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from a String. For example: "<xml-fragment>1234.56789</xml-fragment>". */ - public static XmlDecimal parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from a File. */ - public static XmlDecimal parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from a File. */ - public static XmlDecimal parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from a URL. */ - public static XmlDecimal parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from a URL. */ - public static XmlDecimal parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from an InputStream. */ - public static XmlDecimal parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from an InputStream. */ - public static XmlDecimal parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from a Reader. */ - public static XmlDecimal parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from a Reader. */ - public static XmlDecimal parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from a DOM Node. */ - public static XmlDecimal parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from a DOM Node. */ - public static XmlDecimal parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDecimal parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDecimal parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlDecimal} fragment from an XMLStreamReader. */ - public static XmlDecimal parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlDecimal} fragment from an XMLStreamReader. */ - public static XmlDecimal parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlDecimal) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlDouble.java b/src/xmlpublic/org/apache/xmlbeans/XmlDouble.java deleted file mode 100644 index 77d1ff0..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlDouble.java +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:double type. - *

      - * Naturally, convertible to a Java double. - */ -public interface XmlDouble extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_double"); - - /** Returns this value as a double */ - double getDoubleValue(); - /** Sets this value as a double */ - void setDoubleValue(double v); - - /** - * Returns this value as a double - * @deprecated replaced with {@link #getDoubleValue} - **/ - double doubleValue(); - /** - * Sets this value as a double - * @deprecated replaced with {@link #setDoubleValue} - **/ - void set(double v); - - /** - * A class with methods for creating instances - * of {@link XmlDouble}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlDouble} */ - public static XmlDouble newInstance() { - return (XmlDouble) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlDouble} */ - public static XmlDouble newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlDouble) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlDouble} value */ - public static XmlDouble newValue(Object obj) { - return (XmlDouble) type.newValue( obj ); } - - /** Parses a {@link XmlDouble} fragment from a String. For example: "<xml-fragment>123.34e+57</xml-fragment>". */ - public static XmlDouble parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlDouble} fragment from a String. For example: "<xml-fragment>123.34e+57</xml-fragment>". */ - public static XmlDouble parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlDouble} fragment from a File. */ - public static XmlDouble parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlDouble} fragment from a File. */ - public static XmlDouble parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlDouble} fragment from a URL. */ - public static XmlDouble parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlDouble} fragment from a URL. */ - public static XmlDouble parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlDouble} fragment from an InputStream. */ - public static XmlDouble parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlDouble} fragment from an InputStream. */ - public static XmlDouble parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlDouble} fragment from a Reader. */ - public static XmlDouble parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlDouble} fragment from a Reader. */ - public static XmlDouble parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlDouble} fragment from a DOM Node. */ - public static XmlDouble parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlDouble} fragment from a DOM Node. */ - public static XmlDouble parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlDouble} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDouble parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlDouble} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDouble parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlDouble} fragment from an XMLStreamReader. */ - public static XmlDouble parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlDouble} fragment from an XMLStreamReader. */ - public static XmlDouble parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlDouble) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlDuration.java b/src/xmlpublic/org/apache/xmlbeans/XmlDuration.java deleted file mode 100644 index f1debb2..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlDuration.java +++ /dev/null @@ -1,151 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:duration type. - *

      - * Convertible to a {@link GDuration}. - * - * @see GDuration - */ -public interface XmlDuration extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_duration"); - - /** Returns this value as a {@link GDuration} */ - GDuration getGDurationValue(); - /** Sets this value as a {@link GDuration} */ - void setGDurationValue(GDuration gd); - - /** - * Returns this value as a {@link GDuration} - * @deprecated replaced with {@link #getGDurationValue} - **/ - GDuration gDurationValue(); - /** - * Sets this value as a {@link GDuration} - * @deprecated replaced with {@link #setGDurationValue} - **/ - void set(GDurationSpecification gd); - - /** - * A class with methods for creating instances - * of {@link XmlDuration}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlDuration} */ - public static XmlDuration newInstance() { - return (XmlDuration) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlDuration} */ - public static XmlDuration newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlDuration) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlDuration} value */ - public static XmlDuration newValue(Object obj) { - return (XmlDuration) type.newValue( obj ); } - - /** Parses a {@link XmlDuration} fragment from a String. For example: "<xml-fragment>P1Y2MT2H</xml-fragment>". */ - public static XmlDuration parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlDuration} fragment from a String. For example: "<xml-fragment>P1Y2MT2H</xml-fragment>". */ - public static XmlDuration parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlDuration} fragment from a File. */ - public static XmlDuration parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlDuration} fragment from a File. */ - public static XmlDuration parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlDuration} fragment from a URL. */ - public static XmlDuration parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlDuration} fragment from a URL. */ - public static XmlDuration parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlDuration} fragment from an InputStream. */ - public static XmlDuration parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlDuration} fragment from an InputStream. */ - public static XmlDuration parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlDuration} fragment from a Reader. */ - public static XmlDuration parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlDuration} fragment from a Reader. */ - public static XmlDuration parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlDuration} fragment from a DOM Node. */ - public static XmlDuration parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlDuration} fragment from a DOM Node. */ - public static XmlDuration parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlDuration} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDuration parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlDuration} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlDuration parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlDuration} fragment from an XMLStreamReader. */ - public static XmlDuration parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlDuration} fragment from an XMLStreamReader. */ - public static XmlDuration parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlDuration) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlENTITIES.java b/src/xmlpublic/org/apache/xmlbeans/XmlENTITIES.java deleted file mode 100644 index 6481db4..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlENTITIES.java +++ /dev/null @@ -1,160 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.List; - - -/** - * Corresponds to the XML Schema - * xs:ENTITIES type, - * a list type. - *

      - * A list type. - */ -public interface XmlENTITIES extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_ENTITIES"); - - /** Returns the value as a {@link List} of {@link String} values */ - List getListValue(); - /** Returns the value as a {@link List} of {@link XmlENTITY} values **/ - List xgetListValue(); - /** Sets the value as a {@link List} */ - void setListValue(List l); - - /** - * Returns the value as a {@link List} of {@link String} values - * @deprecated replaced by {@link #getListValue} - **/ - List listValue(); - /** - * Returns the value as a {@link List} of {@link XmlENTITY} values - * @deprecated replaced by {@link #getListValue} - **/ - List xlistValue(); - /** - * Sets the value as a {@link List} - * @deprecated replaced by {@link #getListValue} - **/ - void set(List l); - - /** - * A class with methods for creating instances - * of {@link XmlENTITIES}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlENTITIES} */ - public static XmlENTITIES newInstance() { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlENTITIES} */ - public static XmlENTITIES newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlENTITIES} value */ - public static XmlENTITIES newValue(Object obj) { - return (XmlENTITIES) type.newValue( obj ); } - - /** Parses a {@link XmlENTITIES} fragment from a String. */ - public static XmlENTITIES parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from a String. */ - public static XmlENTITIES parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from a File. */ - public static XmlENTITIES parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from a File. */ - public static XmlENTITIES parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from a URL. */ - public static XmlENTITIES parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from a URL. */ - public static XmlENTITIES parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from an InputStream. */ - public static XmlENTITIES parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from an InputStream. */ - public static XmlENTITIES parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from a Reader. */ - public static XmlENTITIES parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from a Reader. */ - public static XmlENTITIES parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from a DOM Node. */ - public static XmlENTITIES parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from a DOM Node. */ - public static XmlENTITIES parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlENTITIES parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlENTITIES parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlENTITIES} fragment from an XMLStreamReader. */ - public static XmlENTITIES parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlENTITIES} fragment from an XMLStreamReader. */ - public static XmlENTITIES parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlENTITIES) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlENTITY.java b/src/xmlpublic/org/apache/xmlbeans/XmlENTITY.java deleted file mode 100644 index d5ed9f0..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlENTITY.java +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:ENTITY type. - *

      - * Convertible to {@link String}. - */ -public interface XmlENTITY extends XmlNCName -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_ENTITY"); - - /** - * A class with methods for creating instances - * of {@link XmlENTITY}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlENTITY} */ - public static XmlENTITY newInstance() { - return (XmlENTITY) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlENTITY} */ - public static XmlENTITY newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlENTITY) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlENTITY} value */ - public static XmlENTITY newValue(Object obj) { - return (XmlENTITY) type.newValue( obj ); } - - /** Parses a {@link XmlENTITY} fragment from a String. */ - public static XmlENTITY parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from a String. */ - public static XmlENTITY parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from a File. */ - public static XmlENTITY parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from a File. */ - public static XmlENTITY parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from a URL. */ - public static XmlENTITY parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from a URL. */ - public static XmlENTITY parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from an InputStream. */ - public static XmlENTITY parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from an InputStream. */ - public static XmlENTITY parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from a Reader. */ - public static XmlENTITY parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from a Reader. */ - public static XmlENTITY parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from a DOM Node. */ - public static XmlENTITY parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from a DOM Node. */ - public static XmlENTITY parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlENTITY parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlENTITY parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlENTITY} fragment from an XMLStreamReader. */ - public static XmlENTITY parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlENTITY} fragment from an XMLStreamReader. */ - public static XmlENTITY parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlENTITY) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlError.java b/src/xmlpublic/org/apache/xmlbeans/XmlError.java deleted file mode 100644 index 72b1f7a..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlError.java +++ /dev/null @@ -1,641 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.net.URI; -import java.net.URISyntaxException; -import java.io.File; -import java.util.ResourceBundle; -import java.util.PropertyResourceBundle; -import java.text.MessageFormat; -import javax.xml.stream.Location; - -/** - * Represents a message at a specific XML location. - *

      - * The message can be an error, warning, or simple information, and - * it may optionally be associated with a specific location in - * an XML document. The class includes methods for extracting - * the location as a line number, XmlCursor, or XmlObject, as - * well as for obtaining and message and severity of the - * error. - * - * @see XmlOptions#setErrorListener - * @see XmlException - */ -public class XmlError implements java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private static final ResourceBundle _bundle = PropertyResourceBundle.getBundle("org.apache.xmlbeans.message"); - - private String _message; - private String _code; - private String _source; - private int _severity = SEVERITY_ERROR; - private int _line = -1; - private int _column = -1; - private int _offset = -1; - - private transient XmlCursor _cursor; - - /** - * Copy constructor. - * @param src The original XmlError to copy. - */ - public XmlError(XmlError src) - { - _message = src.getMessage(); - _code = src.getErrorCode(); - _severity = src.getSeverity(); - _source = src.getSourceName(); - _line = src.getLine(); - _column = src.getColumn(); - _offset = src.getOffset(); - _cursor = src.getCursorLocation(); - } - - /** - * The static factory methods should be used instead of - * this constructor. - */ - private XmlError(String message, String code, int severity, - String source, int line, int column, int offset, XmlCursor cursor) - { - _message = message; - _code = code; - _severity = severity; - _source = source; - _line = line; - _column = column; - _offset = offset; - _cursor = cursor; - } - - private XmlError(String code, Object[] args, int severity, - String source, int line, int column, int offset, XmlCursor cursor) - { - this(XmlError.formattedMessage(code, args), code, severity, source, line, column, offset, cursor); - } - - /** - * The static factory methods should be used instead of - * this constructor. - */ - protected XmlError(String message, String code, int severity, XmlCursor cursor) - { - String source = null; - int line = -1; - int column = -1; - int offset = -1; - - if (cursor != null) - { - // Hunt down the line/column/offset - source = cursor.documentProperties().getSourceName(); - - XmlCursor c = cursor.newCursor(); - - XmlLineNumber ln = - (XmlLineNumber) c.getBookmark( XmlLineNumber.class ); - - if (ln == null) - ln = (XmlLineNumber) c.toPrevBookmark( XmlLineNumber.class ); - - if (ln != null) - { - line = ln.getLine(); - column = ln.getColumn(); - offset = ln.getOffset(); - } - - c.dispose(); - } - - _message = message; - _code = code; - _severity = severity; - _source = source; - _line = line; - _column = column; - _offset = offset; - _cursor = cursor; - } - - protected XmlError(String code, Object[] args, int severity, XmlCursor cursor) - { - this(XmlError.formattedMessage(code, args), code, severity, cursor); - } - - /** - * The static factory methods should be used instead of - * this constructor. - */ - protected XmlError(String message, String code, int severity, Location loc) - { - String source = null; - int line = -1; - int column = -1; - - if (loc != null) - { - line = loc.getLineNumber(); - column = loc.getColumnNumber(); - source = loc.getPublicId(); - if (source==null) - source = loc.getSystemId(); - } - - _message = message; - _code = code; - _severity = severity; - _source = source; - _line = line; - _column = column; - } - - protected XmlError(String code, Object[] args, int severity, Location loc) - { - this(XmlError.formattedMessage(code, args), code, severity, loc); - } - - /** - * Returns an XmlError for the given message, with no location and {@link #SEVERITY_ERROR}. - * @param message the error message - */ - public static XmlError forMessage(String message) - { - return forMessage(message, SEVERITY_ERROR); - } - - /** - * Returns an XmlError for the given message, with no location and the given severity. - * @param message the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - */ - public static XmlError forMessage(String message, int severity) - { - return forSource(message, severity, null); - } - - /** - * Returns an XmlError for the given message, with no location and the given severity. - * @param code the error code - * @param args the arguments to use in formatting the error message - */ - public static XmlError forMessage(String code, Object[] args) - { - return forSource(code, args, SEVERITY_ERROR, null); - } - - /** - * Returns an XmlError for the given message, with no location and the given severity. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - */ - public static XmlError forMessage(String code, Object[] args, int severity) - { - return forSource(code, args, severity, null); - } - - /** - * Returns an XmlError for the given message, located in the given file and {@link #SEVERITY_ERROR}. - * @param message the error message - * @param sourceName the URL or other name for the file - */ - public static XmlError forSource(String message, String sourceName) - { - return forLocation(message, SEVERITY_ERROR, sourceName, -1, -1, -1); - } - - /** - * Returns an XmlError for the given message, with the given severity, located in the given file. - * @param message the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param sourceName the URL or other name for the file - */ - public static XmlError forSource(String message, int severity, String sourceName) - { - return forLocation(message, severity, sourceName, -1, -1, -1); - } - - /** - * Returns an XmlError for the given message, with the given severity, located in the given file. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param sourceName the URL or other name for the file - */ - public static XmlError forSource(String code, Object[] args, int severity, String sourceName) - { - return forLocation(code, args, severity, sourceName, -1, -1, -1); - } - - /** - * Returns an XmlError for the given message, located at a specific point in the given file and {@link #SEVERITY_ERROR}. - * @param message the error message - * @param sourceName the URL or other name for the file - * @param location the location from an xml stream - */ - public static XmlError forLocation(String message, String sourceName, Location location) - { - return new XmlError(message, (String)null, SEVERITY_ERROR, sourceName, - location.getLineNumber(), location.getColumnNumber(), -1, null); - } - - /** - * Returns an XmlError for the given message, located at a specific point in the given file and {@link #SEVERITY_ERROR}. - * @param message the error message - * @param sourceName the URL or other name for the file - * @param line the 1-based line number, or -1 if not known - * @param column the 1-based column number, or -1 if not known - * @param offset the 0-base file character offset, or -1 if not known - */ - public static XmlError forLocation(String message, String sourceName, int line, int column, int offset) - { - return new XmlError(message, (String)null, SEVERITY_ERROR, sourceName, line, column, offset, null); - } - - /** - * Returns an XmlError for the given message, with the given severity, located at a specific point in the given file. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param sourceName the URL or other name for the file - * @param line the 1-based line number, or -1 if not known - * @param column the 1-based column number, or -1 if not known - * @param offset the 0-base file character offset, or -1 if not known - */ - public static XmlError forLocation(String code, Object[] args, int severity, String sourceName, int line, int column, int offset) - { - return new XmlError(code, args, severity, sourceName, line, column, offset, null); - } - - /** - * Returns an XmlError for the given message, with the given severity, located at a specific point in the given file. - * @param message the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param sourceName the URL or other name for the file - * @param line the 1-based line number, or -1 if not known - * @param column the 1-based column number, or -1 if not known - * @param offset the 0-base file character offset, or -1 if not known - */ - public static XmlError forLocation(String message, int severity, String sourceName, int line, int column, int offset) - { - return new XmlError(message, (String)null, severity, sourceName, line, column, offset, null); - } - - /** - * Returns an XmlError for the given message, with the given severity, located at the given physcial location and XmlCursor. - * @param message the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param sourceName the URL or other name for the file - * @param line the 1-based line number, or -1 if not known - * @param column the 1-based column number, or -1 if not known - * @param offset the 0-base file character offset, or -1 if not known - * @param cursor the XmlCursor representing the location of the error - */ - public static XmlError forLocationAndCursor(String message, int severity, String sourceName, int line, int column, int offset, XmlCursor cursor) - { - return new XmlError(message, (String)null, severity, sourceName, line, column, offset, cursor); - } - - /** - * Returns an XmlError for the given message, located at the XmlObject, with {@link #SEVERITY_ERROR}. - * @param message the error message - * @param xobj the XmlObject representing the location of the error - */ - public static XmlError forObject(String message, XmlObject xobj) - { - return forObject(message, SEVERITY_ERROR, xobj); - } - - /** - * Returns an XmlError for the given message, located at the XmlObject, with {@link #SEVERITY_ERROR}. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param xobj the XmlObject representing the location of the error - */ - public static XmlError forObject(String code, Object[] args, XmlObject xobj) - { - return forObject(code, args, SEVERITY_ERROR, xobj); - } - - /** - * Returns an XmlError for the given message, with the given severity, located at the XmlObject. - * @param message the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param xobj the XmlObject representing the location of the error - */ - public static XmlError forObject(String message, int severity, XmlObject xobj) - { - if (xobj == null) - return forMessage(message, severity); - - XmlCursor cur = xobj.newCursor(); - XmlError result = forCursor(message, severity, cur); - return result; - } - - /** - * Returns an XmlError for the given message, with the given severity, located at the XmlObject. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param xobj the XmlObject representing the location of the error - */ - public static XmlError forObject(String code, Object[] args, int severity, XmlObject xobj) - { - if (xobj == null) - return forMessage(code, args, severity); - - XmlCursor cur = xobj.newCursor(); - XmlError result = forCursor(code, args, severity, cur); - return result; - } - - /** - * Returns an XmlError for the given message, located at the XmlCursor, with {@link #SEVERITY_ERROR}. - * @param message the error message - * @param cursor the XmlCursor representing the location of the error - */ - public static XmlError forCursor(String message, XmlCursor cursor) - { - return forCursor(message, SEVERITY_ERROR, cursor); - } - - /** - * Returns an XmlError for the given message, located at the XmlCursor, with {@link #SEVERITY_ERROR}. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param cursor the XmlCursor representing the location of the error - */ - public static XmlError forCursor(String code, Object[] args, XmlCursor cursor) - { - return forCursor(code, args, SEVERITY_ERROR, cursor); - } - - /** - * Returns an XmlError for the given message, with the given severity, located at the XmlCursor. - * @param message the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param cursor the XmlCursor representing the location of the error - */ - public static XmlError forCursor(String message, int severity, XmlCursor cursor) - { - return new XmlError(message, (String)null, severity, cursor); - } - - /** - * Returns an XmlError for the given message, with the given severity, located at the XmlCursor. - * @param code the error code - * @param args the arguments to use in formatting the error message - * @param severity the severity ({@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}) - * @param cursor the XmlCursor representing the location of the error - */ - public static XmlError forCursor(String code, Object[] args, int severity, XmlCursor cursor) - { - return new XmlError(code, args, severity, cursor); - } - - /** - * Tries to produce a nicely formatted filename from the given string. - */ - protected static String formattedFileName(String rawString, URI base) - { - if (rawString == null) - return null; - - URI uri = null; - - try - { - // if it looks like an absolute URI, treat it as such - uri = new URI(rawString); - - // otherwise, treat it like a filename - if (!uri.isAbsolute()) - uri = null; - } - catch (URISyntaxException e) - { - uri = null; - } - - // looks like a filename; convert it to uri for relativization - if (uri == null) - uri = new File(rawString).toURI(); - - if (base != null) - uri = base.relativize(uri); - - // filenames get their file: stripped off and their /'s turned into \'s (MSDOS) - if (uri.isAbsolute() ? uri.getScheme().compareToIgnoreCase("file") == 0 : - base != null && base.isAbsolute() && base.getScheme().compareToIgnoreCase("file") == 0) - { - try - { - return (new File(uri)).toString(); - } - catch (Exception e) {}; - } - - return uri.toString(); - } - - /** - * Tries to format a message using the error code. - */ - public static String formattedMessage(String code, Object[] args) - { - if (code == null) - return null; - - String message; - - try - { - message = MessageFormat.format(_bundle.getString(code), args); - } - catch (java.util.MissingResourceException e) - { - return MessageFormat.format(_bundle.getString("message.missing.resource"), - new Object[] { e.getMessage() }); - } - catch (IllegalArgumentException e) - { - return MessageFormat.format(_bundle.getString("message.pattern.invalid"), - new Object[] { e.getMessage() }); - } - - return message; - } - - /** - * An error. See {@link #getSeverity}. - */ - public static final int SEVERITY_ERROR = 0; - /** - * A warning. See {@link #getSeverity}. - */ - public static final int SEVERITY_WARNING = 1; - /** - * An informational message. See {@link #getSeverity}. - */ - public static final int SEVERITY_INFO = 2; - - /** - * Returns the severity. Either {@link #SEVERITY_ERROR}, {@link #SEVERITY_WARNING}, or {@link #SEVERITY_INFO}. - */ - public int getSeverity ( ) { return _severity; } - - /** - * Returns the error message without location information. - */ - public String getMessage ( ) { return _message; } - - /** - * Returns the error code or null. See {@link XmlErrorCodes}. - */ - public String getErrorCode ( ) { return _code; } - - /** - * Returns the URL (or other name) of the file with the error, if available. - */ - public String getSourceName ( ) { return _source; } - - /** - * Returns the line number of the error, if available, -1 if not. - */ - public int getLine ( ) { return _line; } - - /** - * Returns the column number of the error, if available, -1 if not. - */ - public int getColumn ( ) { return _column; } - - /** - * Returns the file character offset of the error, if available, -1 if not. - */ - public int getOffset ( ) { return _offset; } - - /** - * Returns a location object of the given type. XmlCursor.class and - * XmlObject.class can be passed, for example. Null if not available. - */ - public Object getLocation ( Object type ) - { - if (type == XmlCursor.class) - return _cursor; - if (type == XmlObject.class && _cursor != null) - return _cursor.getObject(); - return null; - } - - /** - * Returns a location of the error as an {@link XmlCursor}, null if - * not available. - */ - public XmlCursor getCursorLocation ( ) - { - return (XmlCursor) getLocation( XmlCursor.class ); - } - - /** - * Returns a location of the error as an {@link XmlObject}, null if - * not available. - */ - public XmlObject getObjectLocation ( ) - { - return (XmlObject) getLocation( XmlObject.class ); - } - - /** - * Produces a standard string for the error message, complete with - * filename and location offsets if available. - */ - public String toString ( ) - { - return toString( null ); - } - - /** - * Produces a standard string with the error message. If a non-null - * URI is supplied, source names are relativized against the given - * URI. - */ - public String toString ( URI base ) - { - // modified to carefully match the IDE's - // workshop.workspace.ant.AntLogger regex - // which also matches javac (davidbau) - - StringBuffer sb = new StringBuffer(); - - String source = formattedFileName(getSourceName(), base); - - if ( source != null ) - { - sb.append( source ); - int line = getLine(); - if ( line < 0 ) - line = 0; - - sb.append( ':' ); - sb.append( line ); - sb.append( ':' ); - if (getColumn() > 0) - { - sb.append( getColumn() ); - sb.append( ':' ); - } - sb.append(" "); - } - - switch ( getSeverity() ) - { - case SEVERITY_ERROR : sb.append( "error: " ); break; - case SEVERITY_WARNING : sb.append( "warning: " ); break; - case SEVERITY_INFO : break; - } - - if (getErrorCode() != null) - { - sb.append(getErrorCode()).append(": "); - } - - String msg = getMessage(); - - sb.append( msg == null ? "" : msg ); - - return sb.toString(); - } - - public static String severityAsString(int severity) - { - switch (severity) { - case SEVERITY_ERROR: - return ("error"); - case SEVERITY_WARNING: - return ("warning"); - case SEVERITY_INFO: - return "info"; - default: - throw new IllegalArgumentException("unknown severity"); - } - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlFactoryHook.java b/src/xmlpublic/org/apache/xmlbeans/XmlFactoryHook.java deleted file mode 100644 index 6aca07f..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlFactoryHook.java +++ /dev/null @@ -1,117 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import org.w3c.dom.Node; -import org.w3c.dom.DOMImplementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.lang.ref.SoftReference; - -import javax.xml.stream.XMLStreamReader; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLStreamException; - -/** - * A hook for the XML Bean Factory mechanism. - * Provided for advanced users who wish to provide their own - * implementation of the Factory.parse methods. This is used, for example, - * to defer reading XML streams until needed. - *

      - * To use the hook, call XmlFactoryHook.ThreadContext.setHook(), passing - * your own XmlFactoryHook implementation. Then every call to a Factory - * method will be delgated to your hook. - * - *

      - * MyHook hook = new MyHook();
      - * XmlFactoryHook.ThreadContext.setHook(hook);
      - * // this results in a call to hook.parse(...)
      - * XmlObject.Factory.parse(new File("test.xml"));
      - * 
      - * - * If the hook needs to turn around and invoke the built-in parsers, then - * it should do so by calling the appropriate method on the passed - * SchemaTypeLoader. Since SchemaTypeLoader.parse() methods delegate - * to the registered hook, a hook that wishes to actually invoke the - * default parser without having itself called back again should - * unregister itself before calling loader.parse(), and then re-register - * itself again after the call. - *
      - * void parse(SchemaTypeLoader loader, ...)
      - * {
      - *     XmlFactoryHook remember = XmlFactoryHook.ThreadContext.getHook();
      - *     XmlFactoryHook.ThreadContext.setHook(null);
      - *     loader.parse(...); // isn't hooked.
      - *     XmlFactoryHook.ThreadContext.setHook(remember);
      - * }
      - * 
      - */ -public interface XmlFactoryHook -{ - /** Hooks Factory.newInstance calls */ - public XmlObject newInstance ( SchemaTypeLoader loader, SchemaType type, XmlOptions options ); - /** Hooks Factory.parse calls */ - public XmlObject parse ( SchemaTypeLoader loader, String xmlText, SchemaType type, XmlOptions options ) throws XmlException; - /** Hooks Factory.parse calls */ - public XmlObject parse ( SchemaTypeLoader loader, InputStream jiois, SchemaType type, XmlOptions options ) throws XmlException, IOException; - /** Hooks Factory.parse calls */ - public XmlObject parse ( SchemaTypeLoader loader, XMLStreamReader xsr, SchemaType type, XmlOptions options ) throws XmlException; - /** Hooks Factory.parse calls */ - public XmlObject parse ( SchemaTypeLoader loader, Reader jior, SchemaType type, XmlOptions options ) throws XmlException, IOException; - /** Hooks Factory.parse calls */ - public XmlObject parse ( SchemaTypeLoader loader, Node node, SchemaType type, XmlOptions options ) throws XmlException; - /** Hooks Factory.parse calls - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public XmlObject parse ( SchemaTypeLoader loader, XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException; - /** Hooks Factory.newXmlSaxHandler calls */ - public XmlSaxHandler newXmlSaxHandler ( SchemaTypeLoader loader, SchemaType type, XmlOptions options ); - /** Hooks Factory.newDomImplementation calls */ - public DOMImplementation newDomImplementation ( SchemaTypeLoader loader, XmlOptions options ); - - /** - * Used to manage the XmlFactoryHook for the current thread. - */ - public final static class ThreadContext - { - private static ThreadLocal threadHook = new ThreadLocal(); - - /** - * Returns the current thread's hook, or null if none. - */ - public static XmlFactoryHook getHook() - { - SoftReference softRef = (SoftReference)threadHook.get(); - return softRef==null ? null : (XmlFactoryHook)softRef.get(); - } - - /** - * Sets the hook for the current thread. - */ - public static void setHook(XmlFactoryHook hook) - { - threadHook.set(new SoftReference(hook)); - } - - // provided to prevent unwanted construction - private ThreadContext() - { - } - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlFloat.java b/src/xmlpublic/org/apache/xmlbeans/XmlFloat.java deleted file mode 100644 index 23dd2eb..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlFloat.java +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:float type. - *

      - * Naturally, convertible to a Java float. - */ -public interface XmlFloat extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_float"); - - /** Returns this value as a float */ - float getFloatValue(); - /** Sets this value as a float */ - void setFloatValue(float v); - - /** - * Returns this value as a float - * @deprecated replaced by {@link #getFloatValue} - **/ - float floatValue(); - /** - * Sets this value as a float - * @deprecated replaced by {@link #setFloatValue} - **/ - void set(float v); - - /** - * A class with methods for creating instances - * of {@link XmlFloat}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlFloat} */ - public static XmlFloat newInstance() { - return (XmlFloat) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlFloat} */ - public static XmlFloat newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlFloat) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlFloat} value */ - public static XmlFloat newValue(Object obj) { - return (XmlFloat) type.newValue( obj ); } - - /** Parses a {@link XmlFloat} fragment from a String. For example: "<xml-fragment>12.34e+5</xml-fragment>". */ - public static XmlFloat parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlFloat} fragment from a String. For example: "<xml-fragment>12.34e+5</xml-fragment>". */ - public static XmlFloat parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlFloat} fragment from a File. */ - public static XmlFloat parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlFloat} fragment from a File. */ - public static XmlFloat parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlFloat} fragment from a URL. */ - public static XmlFloat parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlFloat} fragment from a URL. */ - public static XmlFloat parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlFloat} fragment from an InputStream. */ - public static XmlFloat parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlFloat} fragment from an InputStream. */ - public static XmlFloat parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlFloat} fragment from a Reader. */ - public static XmlFloat parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlFloat} fragment from a Reader. */ - public static XmlFloat parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlFloat} fragment from a DOM Node. */ - public static XmlFloat parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlFloat} fragment from a DOM Node. */ - public static XmlFloat parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlFloat} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlFloat parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlFloat} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlFloat parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlFloat} fragment from an XMLStreamReader. */ - public static XmlFloat parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlFloat} fragment from an XMLStreamReader. */ - public static XmlFloat parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlFloat) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlGDay.java b/src/xmlpublic/org/apache/xmlbeans/XmlGDay.java deleted file mode 100644 index 913fdd6..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlGDay.java +++ /dev/null @@ -1,184 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:gDay type. - * A gDay specifies only a day-of-month. - *

      - * Convertible to {@link Calendar}, {@link GDate}, or an int. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlGDay extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gDay"); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - /** Returns this value as an int from 1-31 */ - int getIntValue(); - /** Sets this value as an int from 1-31 */ - void setIntValue(int v); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - /** - * Returns this value as an int from 1-31 - * @deprecated replaced with {@link #getIntValue} - **/ - int intValue(); - /** - * Sets this value as an int from 1-31 - * @deprecated replaced with {@link #setIntValue} - **/ - void set(int v); - - /** - * A class with methods for creating instances - * of {@link XmlGDay}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlGDay} */ - public static XmlGDay newInstance() { - return (XmlGDay) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlGDay} */ - public static XmlGDay newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlGDay) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlGDay} value */ - public static XmlGDay newValue(Object obj) { - return (XmlGDay) type.newValue( obj ); } - - /** Parses a {@link XmlGDay} fragment from a String. For example: "<xml-fragment>---14</xml-fragment>". */ - public static XmlGDay parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlGDay} fragment from a String. For example: "<xml-fragment>---14</xml-fragment>". */ - public static XmlGDay parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlGDay} fragment from a File. */ - public static XmlGDay parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlGDay} fragment from a File. */ - public static XmlGDay parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlGDay} fragment from a URL. */ - public static XmlGDay parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlGDay} fragment from a URL. */ - public static XmlGDay parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlGDay} fragment from an InputStream. */ - public static XmlGDay parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlGDay} fragment from an InputStream. */ - public static XmlGDay parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlGDay} fragment from a Reader. */ - public static XmlGDay parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlGDay} fragment from a Reader. */ - public static XmlGDay parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlGDay} fragment from a DOM Node. */ - public static XmlGDay parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlGDay} fragment from a DOM Node. */ - public static XmlGDay parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlGDay} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGDay parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlGDay} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGDay parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlGDay} fragment from an XMLStreamReader. */ - public static XmlGDay parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlGDay} fragment from an XMLStreamReader. */ - public static XmlGDay parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlGDay) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlGMonth.java b/src/xmlpublic/org/apache/xmlbeans/XmlGMonth.java deleted file mode 100644 index f9a310e..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlGMonth.java +++ /dev/null @@ -1,184 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:gMonth type. - * A gMonth specifies only a month-of-year. - *

      - * Convertible to {@link Calendar}, {@link GDate}, or an int. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlGMonth extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gMonth"); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - /** Returns this value as an int from 1-12 */ - int getIntValue(); - /** Sets this value as an int from 1-12 */ - void setIntValue(int v); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - /** - * Returns this value as an int from 1-12 - * @deprecated replaced with {@link #getIntValue} - **/ - int intValue(); - /** - * Sets this value as an int from 1-12 - * @deprecated replaced with {@link #setIntValue} - **/ - void set(int v); - - /** - * A class with methods for creating instances - * of {@link XmlGMonth}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlGMonth} */ - public static XmlGMonth newInstance() { - return (XmlGMonth) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlGMonth} */ - public static XmlGMonth newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlGMonth) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlGMonth} value */ - public static XmlGMonth newValue(Object obj) { - return (XmlGMonth) type.newValue( obj ); } - - /** Parses a {@link XmlGMonth} fragment from a String. For example: "<xml-fragment>--06</xml-fragment>". */ - public static XmlGMonth parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from a String. For example: "<xml-fragment>--06</xml-fragment>". */ - public static XmlGMonth parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from a File. */ - public static XmlGMonth parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from a File. */ - public static XmlGMonth parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from a URL. */ - public static XmlGMonth parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from a URL. */ - public static XmlGMonth parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from an InputStream. */ - public static XmlGMonth parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from an InputStream. */ - public static XmlGMonth parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from a Reader. */ - public static XmlGMonth parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from a Reader. */ - public static XmlGMonth parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from a DOM Node. */ - public static XmlGMonth parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from a DOM Node. */ - public static XmlGMonth parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGMonth parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGMonth parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlGMonth} fragment from an XMLStreamReader. */ - public static XmlGMonth parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlGMonth} fragment from an XMLStreamReader. */ - public static XmlGMonth parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlGMonth) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlGMonthDay.java b/src/xmlpublic/org/apache/xmlbeans/XmlGMonthDay.java deleted file mode 100644 index 20c7c73..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlGMonthDay.java +++ /dev/null @@ -1,170 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:gMonthDay type. - * A gMonthDay specifies a day of a specific month without specifying the year. - *

      - * Convertible to {@link Calendar} or {@link GDate}. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlGMonthDay extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gMonthDay"); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - - /** - * A class with methods for creating instances - * of {@link XmlGMonthDay}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlGMonthDay} */ - public static XmlGMonthDay newInstance() { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlGMonthDay} */ - public static XmlGMonthDay newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlGMonthDay} value */ - public static XmlGMonthDay newValue(Object obj) { - return (XmlGMonthDay) type.newValue( obj ); } - - /** Parses a {@link XmlGMonthDay} fragment from a String. For example: "<xml-fragment>--06-14</xml-fragment>". */ - public static XmlGMonthDay parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from a String. For example: "<xml-fragment>--06-14</xml-fragment>". */ - public static XmlGMonthDay parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from a File. */ - public static XmlGMonthDay parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from a File. */ - public static XmlGMonthDay parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from a URL. */ - public static XmlGMonthDay parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from a URL. */ - public static XmlGMonthDay parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from an InputStream. */ - public static XmlGMonthDay parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from an InputStream. */ - public static XmlGMonthDay parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from a Reader. */ - public static XmlGMonthDay parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from a Reader. */ - public static XmlGMonthDay parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from a DOM Node. */ - public static XmlGMonthDay parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from a DOM Node. */ - public static XmlGMonthDay parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGMonthDay parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGMonthDay parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlGMonthDay} fragment from an XMLStreamReader. */ - public static XmlGMonthDay parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlGMonthDay} fragment from an XMLStreamReader. */ - public static XmlGMonthDay parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlGMonthDay) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlGYear.java b/src/xmlpublic/org/apache/xmlbeans/XmlGYear.java deleted file mode 100644 index 52ebb43..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlGYear.java +++ /dev/null @@ -1,184 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:gYear type. - * A gYear specifies a Gregorian year (AD). - *

      - * Convertible to {@link Calendar}, {@link GDate}, or an int. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlGYear extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gYear"); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - /** Returns this value as an int from 1-31 */ - int getIntValue(); - /** Sets this value as an int from 1-31 */ - void setIntValue(int v); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - /** - * Returns this value as an int from 1-31 - * @deprecated replaced with {@link #getIntValue} - **/ - int intValue(); - /** - * Sets this value as an int from 1-31 - * @deprecated replaced with {@link #setIntValue} - **/ - void set(int v); - - /** - * A class with methods for creating instances - * of {@link XmlGYear}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlGYear} */ - public static XmlGYear newInstance() { - return (XmlGYear) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlGYear} */ - public static XmlGYear newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlGYear) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlGYear} value */ - public static XmlGYear newValue(Object obj) { - return (XmlGYear) type.newValue( obj ); } - - /** Parses a {@link XmlGYear} fragment from a String. For example: "<xml-fragment>2003</xml-fragment>". */ - public static XmlGYear parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlGYear} fragment from a String. For example: "<xml-fragment>2003</xml-fragment>". */ - public static XmlGYear parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlGYear} fragment from a File. */ - public static XmlGYear parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlGYear} fragment from a File. */ - public static XmlGYear parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlGYear} fragment from a URL. */ - public static XmlGYear parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlGYear} fragment from a URL. */ - public static XmlGYear parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlGYear} fragment from an InputStream. */ - public static XmlGYear parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlGYear} fragment from an InputStream. */ - public static XmlGYear parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlGYear} fragment from a Reader. */ - public static XmlGYear parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlGYear} fragment from a Reader. */ - public static XmlGYear parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlGYear} fragment from a DOM Node. */ - public static XmlGYear parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlGYear} fragment from a DOM Node. */ - public static XmlGYear parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlGYear} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGYear parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlGYear} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGYear parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlGYear} fragment from an XMLStreamReader. */ - public static XmlGYear parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlGYear} fragment from an XMLStreamReader. */ - public static XmlGYear parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlGYear) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlGYearMonth.java b/src/xmlpublic/org/apache/xmlbeans/XmlGYearMonth.java deleted file mode 100644 index cb2f55c..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlGYearMonth.java +++ /dev/null @@ -1,171 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Date; -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:gYearMonth type. - * A gYearMonth specifies a month in a specific year. - *

      - * Convertible to {@link Calendar}, {@link GDate}. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlGYearMonth extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_gYearMonth"); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - - /** - * A class with methods for creating instances - * of {@link XmlGYearMonth}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlGYearMonth} */ - public static XmlGYearMonth newInstance() { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlGYearMonth} */ - public static XmlGYearMonth newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlGYearMonth} value */ - public static XmlGYearMonth newValue(Object obj) { - return (XmlGYearMonth) type.newValue( obj ); } - - /** Parses a {@link XmlGYearMonth} fragment from a String. For example: "<xml-fragment>2003-06</xml-fragment>". */ - public static XmlGYearMonth parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from a String. For example: "<xml-fragment>2003-06</xml-fragment>". */ - public static XmlGYearMonth parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from a File. */ - public static XmlGYearMonth parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from a File. */ - public static XmlGYearMonth parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from a URL. */ - public static XmlGYearMonth parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from a URL. */ - public static XmlGYearMonth parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from an InputStream. */ - public static XmlGYearMonth parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from an InputStream. */ - public static XmlGYearMonth parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from a Reader. */ - public static XmlGYearMonth parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from a Reader. */ - public static XmlGYearMonth parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from a DOM Node. */ - public static XmlGYearMonth parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from a DOM Node. */ - public static XmlGYearMonth parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGYearMonth parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlGYearMonth parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlGYearMonth} fragment from an XMLStreamReader. */ - public static XmlGYearMonth parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlGYearMonth} fragment from an XMLStreamReader. */ - public static XmlGYearMonth parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlGYearMonth) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlHexBinary.java b/src/xmlpublic/org/apache/xmlbeans/XmlHexBinary.java deleted file mode 100644 index 54fd14c..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlHexBinary.java +++ /dev/null @@ -1,152 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:hexBinary type. - *

      - * Convertible to a byte array. - */ -public interface XmlHexBinary extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_hexBinary"); - - /** - * Returns this value as a byte array. - * @deprecated replaced by {@link #getByteArrayValue} - **/ - byte[] byteArrayValue(); - - /** - * Sets this value as a byte array. - * @deprecated replaced by {@link #setByteArrayValue} - **/ - void set(byte[] ba); - - /** Returns this value as a byte array. **/ - byte[] getByteArrayValue(); - /** Sets this value as a byte array. */ - void setByteArrayValue(byte[] ba); - - - - /** - * A class with methods for creating instances - * of {@link XmlHexBinary}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlHexBinary} */ - public static XmlHexBinary newInstance() { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlHexBinary} */ - public static XmlHexBinary newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlHexBinary} value */ - public static XmlHexBinary newValue(Object obj) { - return (XmlHexBinary) type.newValue( obj ); } - - /** Parses a {@link XmlHexBinary} fragment from a String. For example: "<xml-fragment>68656c6c6f</xml-fragment>". */ - public static XmlHexBinary parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from a String. For example: "<xml-fragment>68656c6c6f</xml-fragment>". */ - public static XmlHexBinary parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from a File. */ - public static XmlHexBinary parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from a File. */ - public static XmlHexBinary parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from a URL. */ - public static XmlHexBinary parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from a URL. */ - public static XmlHexBinary parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from an InputStream. */ - public static XmlHexBinary parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from an InputStream. */ - public static XmlHexBinary parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from a Reader. */ - public static XmlHexBinary parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from a Reader. */ - public static XmlHexBinary parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from a DOM Node. */ - public static XmlHexBinary parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from a DOM Node. */ - public static XmlHexBinary parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlHexBinary parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlHexBinary parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlHexBinary} fragment from an XMLStreamReader. */ - public static XmlHexBinary parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlHexBinary} fragment from an XMLStreamReader. */ - public static XmlHexBinary parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlHexBinary) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlID.java b/src/xmlpublic/org/apache/xmlbeans/XmlID.java deleted file mode 100644 index 4493f7d..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlID.java +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:ID type. - *

      - * When validated, IDs must be unique within a document. An element - * may not have more than one attribute whose type is ID. - *

      - * Convertible to a {@link String}. - */ -public interface XmlID extends XmlNCName -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_ID"); - - /** - * A class with methods for creating instances - * of {@link XmlID}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlID} */ - public static XmlID newInstance() { - return (XmlID) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlID} */ - public static XmlID newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlID) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlID} value */ - public static XmlID newValue(Object obj) { - return (XmlID) type.newValue( obj ); } - - /** Parses a {@link XmlID} fragment from a String. For example: "<xml-fragment>n1</xml-fragment>". */ - public static XmlID parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlID} fragment from a String. For example: "<xml-fragment>n1</xml-fragment>". */ - public static XmlID parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlID} fragment from a File. */ - public static XmlID parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlID} fragment from a File. */ - public static XmlID parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlID} fragment from a URL. */ - public static XmlID parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlID} fragment from a URL. */ - public static XmlID parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlID} fragment from an InputStream. */ - public static XmlID parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlID} fragment from an InputStream. */ - public static XmlID parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlID} fragment from a Reader. */ - public static XmlID parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlID} fragment from a Reader. */ - public static XmlID parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlID} fragment from a DOM Node. */ - public static XmlID parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlID} fragment from a DOM Node. */ - public static XmlID parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlID} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlID parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlID} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlID parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlID} fragment from an XMLStreamReader. */ - public static XmlID parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlID) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlID} fragment from an XMLStreamReader. */ - public static XmlID parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlID) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlIDREF.java b/src/xmlpublic/org/apache/xmlbeans/XmlIDREF.java deleted file mode 100644 index 6f6e7ef..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlIDREF.java +++ /dev/null @@ -1,137 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:IDREF type. - *

      - * When validated, IDREF values must match an ID value that is present within - * the document. This rule is only verified when a whole document is validated - * at once. - *

      - * Convertible to a {@link String}. - */ -public interface XmlIDREF extends XmlNCName -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_IDREF"); - - /** - * A class with methods for creating instances - * of {@link XmlIDREF}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlIDREF} */ - public static XmlIDREF newInstance() { - return (XmlIDREF) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlIDREF} */ - public static XmlIDREF newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlIDREF) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlIDREF} value */ - public static XmlIDREF newValue(Object obj) { - return (XmlIDREF) type.newValue( obj ); } - - /** Parses a {@link XmlIDREF} fragment from a String. */ - public static XmlIDREF parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from a String. */ - public static XmlIDREF parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from a File. */ - public static XmlIDREF parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from a File. */ - public static XmlIDREF parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from a URL. */ - public static XmlIDREF parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from a URL. */ - public static XmlIDREF parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from an InputStream. */ - public static XmlIDREF parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from an InputStream. */ - public static XmlIDREF parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from a Reader. */ - public static XmlIDREF parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from a Reader. */ - public static XmlIDREF parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from a DOM Node. */ - public static XmlIDREF parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from a DOM Node. */ - public static XmlIDREF parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlIDREF parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlIDREF parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlIDREF} fragment from an XMLStreamReader. */ - public static XmlIDREF parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlIDREF} fragment from an XMLStreamReader. */ - public static XmlIDREF parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlIDREF) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlIDREFS.java b/src/xmlpublic/org/apache/xmlbeans/XmlIDREFS.java deleted file mode 100644 index 8674772..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlIDREFS.java +++ /dev/null @@ -1,164 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.List; - - -/** - * Corresponds to the XML Schema - * xs:IDREFS type, - * a list type. - *

      - * When validated, IDREF values must match an ID value that is present within - * the document. This rule is only verified when a whole document is validated - * at once. - *

      - * Convertible to a {@link List}. - */ -public interface XmlIDREFS extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_IDREFS"); - - /** Returns the value as a {@link List} of {@link String} values */ - List getListValue(); - /** Returns the value as a {@link List} of {@link XmlIDREF} values */ - List xgetListValue(); - /** Sets the value as a {@link List} */ - void setListValue(List l); - - /** - * Returns the value as a {@link List} of {@link String} values - * @deprecated replaced by {@link #getListValue} - **/ - List listValue(); - /** - * Returns the value as a {@link List} of {@link XmlIDREF} values - * @deprecated replaced by {@link #getListValue} - **/ - List xlistValue(); - /** - * Sets the value as a {@link List} - * @deprecated replaced by {@link #getListValue} - **/ - void set(List l); - - /** - * A class with methods for creating instances - * of {@link XmlIDREFS}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlIDREFS} */ - public static XmlIDREFS newInstance() { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlIDREFS} */ - public static XmlIDREFS newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlIDREFS} value */ - public static XmlIDREFS newValue(Object obj) { - return (XmlIDREFS) type.newValue( obj ); } - - /** Parses a {@link XmlIDREFS} fragment from a String. */ - public static XmlIDREFS parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from a String. */ - public static XmlIDREFS parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from a File. */ - public static XmlIDREFS parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from a File. */ - public static XmlIDREFS parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from a URL. */ - public static XmlIDREFS parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from a URL. */ - public static XmlIDREFS parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from an InputStream. */ - public static XmlIDREFS parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from an InputStream. */ - public static XmlIDREFS parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from a Reader. */ - public static XmlIDREFS parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from a Reader. */ - public static XmlIDREFS parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from a DOM Node. */ - public static XmlIDREFS parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from a DOM Node. */ - public static XmlIDREFS parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlIDREFS parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlIDREFS parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlIDREFS} fragment from an XMLStreamReader. */ - public static XmlIDREFS parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlIDREFS} fragment from an XMLStreamReader. */ - public static XmlIDREFS parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlIDREFS) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlInt.java b/src/xmlpublic/org/apache/xmlbeans/XmlInt.java deleted file mode 100644 index a2b3df4..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlInt.java +++ /dev/null @@ -1,150 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:int type. - * One of the derived types based on xs:decimal. - *

      - * Naturally, convertible to a Java int. - */ -public interface XmlInt extends XmlLong -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_int"); - - /** Returns this value as an int */ - int getIntValue(); - /** Sets this value as an int */ - void setIntValue(int v); - - /** - * Returns this value as an int - * @deprecated replaced with {@link #getIntValue} - **/ - int intValue(); - /** - * Sets this value as an int - * @deprecated replaced with {@link #setIntValue} - **/ - void set(int v); - - /** - * A class with methods for creating instances - * of {@link XmlInt}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlInt} */ - public static XmlInt newInstance() { - return (XmlInt) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlInt} */ - public static XmlInt newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlInt) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlInt} value */ - public static XmlInt newValue(Object obj) { - return (XmlInt) type.newValue( obj ); } - - /** Parses a {@link XmlInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". */ - public static XmlInt parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". */ - public static XmlInt parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlInt} fragment from a File. */ - public static XmlInt parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlInt} fragment from a File. */ - public static XmlInt parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlInt} fragment from a URL. */ - public static XmlInt parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlInt} fragment from a URL. */ - public static XmlInt parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlInt} fragment from an InputStream. */ - public static XmlInt parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlInt} fragment from an InputStream. */ - public static XmlInt parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlInt} fragment from a Reader. */ - public static XmlInt parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlInt} fragment from a Reader. */ - public static XmlInt parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlInt} fragment from a DOM Node. */ - public static XmlInt parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlInt} fragment from a DOM Node. */ - public static XmlInt parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlInt} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlInt parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlInt} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlInt parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlInt} fragment from an XMLStreamReader. */ - public static XmlInt parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlInt) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlInt} fragment from an XMLStreamReader. */ - public static XmlInt parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlInt) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlInteger.java b/src/xmlpublic/org/apache/xmlbeans/XmlInteger.java deleted file mode 100644 index dbb013e..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlInteger.java +++ /dev/null @@ -1,156 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.math.BigInteger; - -/** - * Corresponds to the XML Schema - * xs:integer type. - * One of the derived types based on xs:decimal. - *

      - * This type should not be confused with xs:int - * or Java {@link Integer}. This type represents an arbitrary-precision integer with - * any number of digits, while a Java int or an xs:int is a 32-bit finite-precision integer. - *

      - * Convertible to a Java {@link BigInteger}. - */ -public interface XmlInteger extends XmlDecimal -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_integer"); - - /** Returns this value as a {@link BigInteger} */ - BigInteger getBigIntegerValue(); - /** Sets this value as a {@link BigInteger} */ - void setBigIntegerValue(BigInteger bi); - - /** - * Returns this value as a {@link BigInteger} - * @deprecated replaced with {@link #getBigIntegerValue} - **/ - BigInteger bigIntegerValue(); - /** - * Sets this value as a {@link BigInteger} - * @deprecated replaced with {@link #setBigIntegerValue} - **/ - void set(BigInteger bi); - - /** - * A class with methods for creating instances - * of {@link XmlInteger}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlInteger} */ - public static XmlInteger newInstance() { - return (XmlInteger) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlInteger} */ - public static XmlInteger newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlInteger) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlInteger} value */ - public static XmlInteger newValue(Object obj) { - return (XmlInteger) type.newValue( obj ); } - - /** Parses a {@link XmlInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". */ - public static XmlInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". */ - public static XmlInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlInteger} fragment from a File. */ - public static XmlInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlInteger} fragment from a File. */ - public static XmlInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlInteger} fragment from a URL. */ - public static XmlInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlInteger} fragment from a URL. */ - public static XmlInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlInteger} fragment from an InputStream. */ - public static XmlInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlInteger} fragment from an InputStream. */ - public static XmlInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlInteger} fragment from a Reader. */ - public static XmlInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlInteger} fragment from a Reader. */ - public static XmlInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlInteger} fragment from a DOM Node. */ - public static XmlInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlInteger} fragment from a DOM Node. */ - public static XmlInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlInteger} fragment from an XMLStreamReader. */ - public static XmlInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlInteger} fragment from an XMLStreamReader. */ - public static XmlInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlLanguage.java b/src/xmlpublic/org/apache/xmlbeans/XmlLanguage.java deleted file mode 100644 index 59ccc60..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlLanguage.java +++ /dev/null @@ -1,135 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:language type. - *

      - * This type is intended to represent an standard ISO language code string. - *

      - * Convertible to a Java {@link String}. - */ -public interface XmlLanguage extends XmlToken -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_language"); - - /** - * A class with methods for creating instances - * of {@link XmlLanguage}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlLanguage} */ - public static XmlLanguage newInstance() { - return (XmlLanguage) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlLanguage} */ - public static XmlLanguage newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlLanguage) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlLanguage} value */ - public static XmlLanguage newValue(Object obj) { - return (XmlLanguage) type.newValue( obj ); } - - /** Parses a {@link XmlLanguage} fragment from a String. For example: "<xml-fragment>en-us</xml-fragment>". */ - public static XmlLanguage parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from a String. For example: "<xml-fragment>en-us</xml-fragment>". */ - public static XmlLanguage parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from a File. */ - public static XmlLanguage parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from a File. */ - public static XmlLanguage parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from a URL. */ - public static XmlLanguage parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from a URL. */ - public static XmlLanguage parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from an InputStream. */ - public static XmlLanguage parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from an InputStream. */ - public static XmlLanguage parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from a Reader. */ - public static XmlLanguage parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from a Reader. */ - public static XmlLanguage parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from a DOM Node. */ - public static XmlLanguage parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from a DOM Node. */ - public static XmlLanguage parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlLanguage parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlLanguage parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlLanguage} fragment from an XMLStreamReader. */ - public static XmlLanguage parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlLanguage} fragment from an XMLStreamReader. */ - public static XmlLanguage parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlLanguage) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlLong.java b/src/xmlpublic/org/apache/xmlbeans/XmlLong.java deleted file mode 100644 index e1f296b..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlLong.java +++ /dev/null @@ -1,150 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:long type. - * One of the derived types based on xs:decimal. - *

      - * Naturally, convertible to a Java long. - */ -public interface XmlLong extends XmlInteger -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_long"); - - /** Returns this value as a long */ - long getLongValue(); - /** Sets this value as a long */ - void setLongValue(long v); - - /** - * Returns this value as a long - * @deprecated replaced with {@link #getLongValue} - **/ - long longValue(); - /** - * Sets this value as a long - * @deprecated replaced with {@link #setLongValue} - **/ - void set(long v); - - /** - * A class with methods for creating instances - * of {@link XmlLong}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlLong} */ - public static XmlLong newInstance() { - return (XmlLong) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlLong} */ - public static XmlLong newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlLong) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlLong} value */ - public static XmlLong newValue(Object obj) { - return (XmlLong) type.newValue( obj ); } - - /** Parses a {@link XmlLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". */ - public static XmlLong parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". */ - public static XmlLong parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlLong} fragment from a File. */ - public static XmlLong parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlLong} fragment from a File. */ - public static XmlLong parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlLong} fragment from a URL. */ - public static XmlLong parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlLong} fragment from a URL. */ - public static XmlLong parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlLong} fragment from an InputStream. */ - public static XmlLong parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlLong} fragment from an InputStream. */ - public static XmlLong parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlLong} fragment from a Reader. */ - public static XmlLong parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlLong} fragment from a Reader. */ - public static XmlLong parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlLong} fragment from a DOM Node. */ - public static XmlLong parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlLong} fragment from a DOM Node. */ - public static XmlLong parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlLong} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlLong parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlLong} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlLong parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlLong} fragment from an XMLStreamReader. */ - public static XmlLong parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlLong) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlLong} fragment from an XMLStreamReader. */ - public static XmlLong parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlLong) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNCName.java b/src/xmlpublic/org/apache/xmlbeans/XmlNCName.java deleted file mode 100644 index de819dd..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNCName.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:Name type. - * One of the derived types based on xs:string. - *

      - * This kind of string is the same as the non-colonized strings that are used - * for XML localnames and prefixes, "my-href.2". It is just a physical - * string, however, and it should NOT be confused with {@link XmlQName}, - * which is a logical combination of localname and namespace URI. - *

      - * Convertible to {@link String}. - */ -public interface XmlNCName extends XmlName -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NCName"); - - /** - * A class with methods for creating instances - * of {@link XmlNCName}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNCName} */ - public static XmlNCName newInstance() { - return (XmlNCName) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNCName} */ - public static XmlNCName newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNCName) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNCName} value */ - public static XmlNCName newValue(Object obj) { - return (XmlNCName) type.newValue( obj ); } - - /** Parses a {@link XmlNCName} fragment from a String. For example: "<xml-fragment>My-Name</xml-fragment>". */ - public static XmlNCName parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNCName} fragment from a String. For example: "<xml-fragment>My-Name</xml-fragment>". */ - public static XmlNCName parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNCName} fragment from a File. */ - public static XmlNCName parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNCName} fragment from a File. */ - public static XmlNCName parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNCName} fragment from a URL. */ - public static XmlNCName parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNCName} fragment from a URL. */ - public static XmlNCName parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNCName} fragment from an InputStream. */ - public static XmlNCName parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNCName} fragment from an InputStream. */ - public static XmlNCName parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNCName} fragment from a Reader. */ - public static XmlNCName parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNCName} fragment from a Reader. */ - public static XmlNCName parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNCName} fragment from a DOM Node. */ - public static XmlNCName parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNCName} fragment from a DOM Node. */ - public static XmlNCName parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNCName} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNCName parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNCName} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNCName parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNCName} fragment from an XMLStreamReader. */ - public static XmlNCName parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNCName} fragment from an XMLStreamReader. */ - public static XmlNCName parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlNCName) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKEN.java b/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKEN.java deleted file mode 100644 index 591cc43..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKEN.java +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:NMTOKEN type. - * One of the derived types based on xs:string. - *

      - * An NMTOKEN is XML's closest concept to an "identifier"; for example, - * it does not permit spaces and only limited punctuation. So NMTOKEN is - * commonly used to describe a single token or enumerated string value. - *

      - * Convertible to {@link String}. - */ -public interface XmlNMTOKEN extends XmlToken -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NMTOKEN"); - - /** - * A class with methods for creating instances - * of {@link XmlNMTOKEN}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNMTOKEN} */ - public static XmlNMTOKEN newInstance() { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNMTOKEN} */ - public static XmlNMTOKEN newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNMTOKEN} value */ - public static XmlNMTOKEN newValue(Object obj) { - return (XmlNMTOKEN) type.newValue( obj ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a String. For example: "<xml-fragment>sample-1.2</xml-fragment>". */ - public static XmlNMTOKEN parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a String. For example: "<xml-fragment>sample-1.2</xml-fragment>". */ - public static XmlNMTOKEN parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a File. */ - public static XmlNMTOKEN parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a File. */ - public static XmlNMTOKEN parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a URL. */ - public static XmlNMTOKEN parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a URL. */ - public static XmlNMTOKEN parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from an InputStream. */ - public static XmlNMTOKEN parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from an InputStream. */ - public static XmlNMTOKEN parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a Reader. */ - public static XmlNMTOKEN parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a Reader. */ - public static XmlNMTOKEN parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a DOM Node. */ - public static XmlNMTOKEN parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from a DOM Node. */ - public static XmlNMTOKEN parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNMTOKEN parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNMTOKEN parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNMTOKEN} fragment from an XMLStreamReader. */ - public static XmlNMTOKEN parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNMTOKEN} fragment from an XMLStreamReader. */ - public static XmlNMTOKEN parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlNMTOKEN) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKENS.java b/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKENS.java deleted file mode 100644 index 53fe278..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNMTOKENS.java +++ /dev/null @@ -1,161 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.List; - - -/** - * Corresponds to the XML Schema - * xs:NMTOKENS type, - * a list type. - *

      - * Convertible to {@link List}. - */ -public interface XmlNMTOKENS extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NMTOKENS"); - - /** Returns the value as a {@link List} of {@link String} values */ - List getListValue(); - /** Returns the value as a {@link List} of {@link XmlNMTOKEN} values */ - List xgetListValue(); - /** Sets the value as a {@link List} */ - void setListValue(List l); - - /** - * Returns the value as a {@link List} of {@link String} values - * @deprecated replaced by {@link #getListValue} - **/ - List listValue(); - /** - * Returns the value as a {@link List} of {@link XmlNMTOKEN} values - * @deprecated replaced by {@link #getListValue} - **/ - List xlistValue(); - /** - * Sets the value as a {@link List} - * @deprecated replaced by {@link #getListValue} - **/ - void set(List l); - - - /** - * A class with methods for creating instances - * of {@link XmlNMTOKENS}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNMTOKENS} */ - public static XmlNMTOKENS newInstance() { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNMTOKENS} */ - public static XmlNMTOKENS newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNMTOKENS} value */ - public static XmlNMTOKENS newValue(Object obj) { - return (XmlNMTOKENS) type.newValue( obj ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a String. For example: "<xml-fragment>sample-1.1 sample-1.2 sample-1.3</xml-fragment>". */ - public static XmlNMTOKENS parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a String. For example: "<xml-fragment>sample-1.1 sample-1.2 sample-1.3</xml-fragment>". */ - public static XmlNMTOKENS parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a File. */ - public static XmlNMTOKENS parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a File. */ - public static XmlNMTOKENS parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a URL. */ - public static XmlNMTOKENS parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a URL. */ - public static XmlNMTOKENS parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from an InputStream. */ - public static XmlNMTOKENS parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from an InputStream. */ - public static XmlNMTOKENS parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a Reader. */ - public static XmlNMTOKENS parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a Reader. */ - public static XmlNMTOKENS parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a DOM Node. */ - public static XmlNMTOKENS parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from a DOM Node. */ - public static XmlNMTOKENS parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNMTOKENS parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNMTOKENS parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNMTOKENS} fragment from an XMLStreamReader. */ - public static XmlNMTOKENS parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNMTOKENS} fragment from an XMLStreamReader. */ - public static XmlNMTOKENS parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlNMTOKENS) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNOTATION.java b/src/xmlpublic/org/apache/xmlbeans/XmlNOTATION.java deleted file mode 100644 index 8729559..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNOTATION.java +++ /dev/null @@ -1,137 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:NOTATION type. - *

      - * NOTATIONs are a mechanism in XML Schema that is provided - * for partial backward compatibility with NOTATIONs in DTDs. XML Schema - * users should almost never have any reason to use this data type. - *

      - * Convertible to {@link String}. - */ -public interface XmlNOTATION extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_NOTATION"); - - /** - * A class with methods for creating instances - * of {@link XmlNOTATION}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNOTATION} */ - public static XmlNOTATION newInstance() { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNOTATION} */ - public static XmlNOTATION newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNOTATION} value */ - public static XmlNOTATION newValue(Object obj) { - return (XmlNOTATION) type.newValue( obj ); } - - /** Parses a {@link XmlNOTATION} fragment from a String. */ - public static XmlNOTATION parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from a String. */ - public static XmlNOTATION parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from a File. */ - public static XmlNOTATION parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from a File. */ - public static XmlNOTATION parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from a URL. */ - public static XmlNOTATION parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from a URL. */ - public static XmlNOTATION parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from an InputStream. */ - public static XmlNOTATION parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from an InputStream. */ - public static XmlNOTATION parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from a Reader. */ - public static XmlNOTATION parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from a Reader. */ - public static XmlNOTATION parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from a DOM Node. */ - public static XmlNOTATION parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from a DOM Node. */ - public static XmlNOTATION parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNOTATION parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNOTATION parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNOTATION} fragment from an XMLStreamReader. */ - public static XmlNOTATION parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNOTATION} fragment from an XMLStreamReader. */ - public static XmlNOTATION parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlNOTATION) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlName.java b/src/xmlpublic/org/apache/xmlbeans/XmlName.java deleted file mode 100644 index b6b51c4..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlName.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:Name type. - * One of the derived types based on xs:string. - *

      - * This kind of string is the same as the lexical representation used for XML 1.0 - * element and attribute names, e.g., "pre:a-b.cdef". It is just a physical - * string, however, and it should NOT be confused with {@link XmlQName}, - * which is a logical combination of localname and namespace URI. - *

      - * Convertible to {@link String}. - */ -public interface XmlName extends XmlToken -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_Name"); - - /** - * A class with methods for creating instances - * of {@link XmlName}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlName} */ - public static XmlName newInstance() { - return (XmlName) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlName} */ - public static XmlName newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlName) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlName} value */ - public static XmlName newValue(Object obj) { - return (XmlName) type.newValue( obj ); } - - /** Parses a {@link XmlName} fragment from a String. For example: "<xml-fragment>My:Name</xml-fragment>". */ - public static XmlName parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlName} fragment from a String. For example: "<xml-fragment>My:Name</xml-fragment>". */ - public static XmlName parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlName} fragment from a File. */ - public static XmlName parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlName} fragment from a File. */ - public static XmlName parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlName} fragment from a URL. */ - public static XmlName parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlName} fragment from a URL. */ - public static XmlName parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlName} fragment from an InputStream. */ - public static XmlName parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlName} fragment from an InputStream. */ - public static XmlName parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlName} fragment from a Reader. */ - public static XmlName parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlName} fragment from a Reader. */ - public static XmlName parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlName} fragment from a DOM Node. */ - public static XmlName parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlName} fragment from a DOM Node. */ - public static XmlName parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlName} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlName parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlName} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlName parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlName} fragment from an XMLStreamReader. */ - public static XmlName parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlName) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlName} fragment from an XMLStreamReader. */ - public static XmlName parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlName) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNegativeInteger.java b/src/xmlpublic/org/apache/xmlbeans/XmlNegativeInteger.java deleted file mode 100644 index d6ef98d..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNegativeInteger.java +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:negativeInteger type. - * One of the derived types based on xs:decimal. - *

      - * Verified to be negative when validating. - *

      - * Convertible to {@link java.math.BigInteger}. - */ -public interface XmlNegativeInteger extends XmlNonPositiveInteger -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_negativeInteger"); - - /** - * A class with methods for creating instances - * of {@link XmlNegativeInteger}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNegativeInteger} */ - public static XmlNegativeInteger newInstance() { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNegativeInteger} */ - public static XmlNegativeInteger newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNegativeInteger} value */ - public static XmlNegativeInteger newValue(Object obj) { - return (XmlNegativeInteger) type.newValue( obj ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". */ - public static XmlNegativeInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". */ - public static XmlNegativeInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a File. */ - public static XmlNegativeInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a File. */ - public static XmlNegativeInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a URL. */ - public static XmlNegativeInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a URL. */ - public static XmlNegativeInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from an InputStream. */ - public static XmlNegativeInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from an InputStream. */ - public static XmlNegativeInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a Reader. */ - public static XmlNegativeInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a Reader. */ - public static XmlNegativeInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a DOM Node. */ - public static XmlNegativeInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from a DOM Node. */ - public static XmlNegativeInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNegativeInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNegativeInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNegativeInteger} fragment from an XMLStreamReader. */ - public static XmlNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNegativeInteger} fragment from an XMLStreamReader. */ - public static XmlNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlNegativeInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNonNegativeInteger.java b/src/xmlpublic/org/apache/xmlbeans/XmlNonNegativeInteger.java deleted file mode 100644 index 5b47c07..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNonNegativeInteger.java +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:nonNegativeInteger type. - * One of the derived types based on xs:decimal. - *

      - * Verified to be zero or positive when validating. - *

      - * Convertible to {@link java.math.BigInteger}. - */ -public interface XmlNonNegativeInteger extends XmlInteger -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_nonNegativeInteger"); - - /** - * A class with methods for creating instances - * of {@link XmlNonNegativeInteger}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNonNegativeInteger} */ - public static XmlNonNegativeInteger newInstance() { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNonNegativeInteger} */ - public static XmlNonNegativeInteger newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNonNegativeInteger} value */ - public static XmlNonNegativeInteger newValue(Object obj) { - return (XmlNonNegativeInteger) type.newValue( obj ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". */ - public static XmlNonNegativeInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". */ - public static XmlNonNegativeInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a File. */ - public static XmlNonNegativeInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a File. */ - public static XmlNonNegativeInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a URL. */ - public static XmlNonNegativeInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a URL. */ - public static XmlNonNegativeInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from an InputStream. */ - public static XmlNonNegativeInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from an InputStream. */ - public static XmlNonNegativeInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a Reader. */ - public static XmlNonNegativeInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a Reader. */ - public static XmlNonNegativeInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a DOM Node. */ - public static XmlNonNegativeInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from a DOM Node. */ - public static XmlNonNegativeInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNonNegativeInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNonNegativeInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from an XMLStreamReader. */ - public static XmlNonNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNonNegativeInteger} fragment from an XMLStreamReader. */ - public static XmlNonNegativeInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNonNegativeInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNonPositiveInteger.java b/src/xmlpublic/org/apache/xmlbeans/XmlNonPositiveInteger.java deleted file mode 100644 index 3f22e4a..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNonPositiveInteger.java +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:nonPositiveInteger type. - * One of the derived types based on xs:decimal. - *

      - * Verified to be zero or negative when validating. - *

      - * Convertible to {@link java.math.BigInteger}. - */ -public interface XmlNonPositiveInteger extends XmlInteger -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_nonPositiveInteger"); - - /** - * A class with methods for creating instances - * of {@link XmlNonPositiveInteger}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNonPositiveInteger} */ - public static XmlNonPositiveInteger newInstance() { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNonPositiveInteger} */ - public static XmlNonPositiveInteger newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNonPositiveInteger} value */ - public static XmlNonPositiveInteger newValue(Object obj) { - return (XmlNonPositiveInteger) type.newValue( obj ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". */ - public static XmlNonPositiveInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a String. For example: "<xml-fragment>-1234567890</xml-fragment>". */ - public static XmlNonPositiveInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a File. */ - public static XmlNonPositiveInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a File. */ - public static XmlNonPositiveInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a URL. */ - public static XmlNonPositiveInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a URL. */ - public static XmlNonPositiveInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from an InputStream. */ - public static XmlNonPositiveInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from an InputStream. */ - public static XmlNonPositiveInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a Reader. */ - public static XmlNonPositiveInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a Reader. */ - public static XmlNonPositiveInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a DOM Node. */ - public static XmlNonPositiveInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from a DOM Node. */ - public static XmlNonPositiveInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNonPositiveInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNonPositiveInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from an XMLStreamReader. */ - public static XmlNonPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNonPositiveInteger} fragment from an XMLStreamReader. */ - public static XmlNonPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNonPositiveInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlNormalizedString.java b/src/xmlpublic/org/apache/xmlbeans/XmlNormalizedString.java deleted file mode 100644 index a0cf2d6..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlNormalizedString.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:normalizedString type. - * One of the derived types based on xs:string. - *

      - * An normalizedString simply is a string where all the carriage return, - * linefeed, and tab characters have been normalized (switched to) ordinary - * space characters. Use normalizedString for long strings to make them - * insensitive to line breaking. If you wish to often be insensitive to - * runs of whitespace (as is often the case), use - * xs:token - * (aka {@link XmlToken}) instead. - *

      - * Convertible to {@link String}. When obtaining the stringValue, the - * whitespace-normalized value is returned. - */ -public interface XmlNormalizedString extends XmlString -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_normalizedString"); - - /** - * A class with methods for creating instances - * of {@link XmlNormalizedString}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlNormalizedString} */ - public static XmlNormalizedString newInstance() { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlNormalizedString} */ - public static XmlNormalizedString newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlNormalizedString} value */ - public static XmlNormalizedString newValue(Object obj) { - return (XmlNormalizedString) type.newValue( obj ); } - - /** Parses a {@link XmlNormalizedString} fragment from a String. For example: "<xml-fragment> string to normalize </xml-fragment>". */ - public static XmlNormalizedString parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from a String. For example: "<xml-fragment> string to normalize </xml-fragment>". */ - public static XmlNormalizedString parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from a File. */ - public static XmlNormalizedString parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from a File. */ - public static XmlNormalizedString parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from a URL. */ - public static XmlNormalizedString parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from a URL. */ - public static XmlNormalizedString parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from an InputStream. */ - public static XmlNormalizedString parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from an InputStream. */ - public static XmlNormalizedString parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from a Reader. */ - public static XmlNormalizedString parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from a Reader. */ - public static XmlNormalizedString parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from a DOM Node. */ - public static XmlNormalizedString parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from a DOM Node. */ - public static XmlNormalizedString parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNormalizedString parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlNormalizedString parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlNormalizedString} fragment from an XMLStreamReader. */ - public static XmlNormalizedString parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlNormalizedString} fragment from an XMLStreamReader. */ - public static XmlNormalizedString parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlNormalizedString) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlOptionCharEscapeMap.java b/src/xmlpublic/org/apache/xmlbeans/XmlOptionCharEscapeMap.java deleted file mode 100644 index 91ffc73..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlOptionCharEscapeMap.java +++ /dev/null @@ -1,142 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.util.HashMap; - -/** - * Corresponds to the Saver and XmlOptions. - *

      - * This class is used to set up a map containing characters to be escaped. - * Characters can be escaped as hex, decimal or as a predefined entity (this - * latter option applies only to the 5 characters defined as predefined entities - * in the XML Spec). - *

      - *

        - * For example: - *
        - *      XmlOptionCharEscapeMap escapes = new XmlOptionCharEscapeMap();
        - *      escapes.addMapping('A', XmlOptionCharEscapeMap.HEXADECIMAL);
        - *      escapes.addMapping('B', XmlOptionCharEscapeMap.DECIMAL);
        - *      escapes.addMapping('>', XmlOptionCharEscapeMap.PREDEF_ENTITY);
        - *
        - *      XmlOptions opts = new XmlOptions();
        - *      opts.setSaveSubstituteCharacters(escapes);
        - *      System.out.println(myXml.xmlText(opts));
        - *
        - *      will result in:
        - *      A being printed as A
        - *      B being printed as B
        - *      > being printed as >
        - *
        - * 
        - */ -public class XmlOptionCharEscapeMap -{ - public static final int PREDEF_ENTITY = 0; - public static final int DECIMAL = 1; - public static final int HEXADECIMAL = 2; - - // map of Character to String which will represent it in the output document - private HashMap _charMap; - - // internal HashMap just for predefined entities - private static final HashMap _predefEntities = new HashMap(); - static { - _predefEntities.put(new Character('<'), "<"); - _predefEntities.put(new Character('>'), ">"); - _predefEntities.put(new Character('&'), "&"); - _predefEntities.put(new Character('\''), "'"); - _predefEntities.put(new Character('"'), """); - } - - /** - * Construct a new XmlOptionCharEncoder. - */ - public XmlOptionCharEscapeMap() - { - _charMap = new HashMap(); - } - - /** - * @return whether a character encoding exists for this character - */ - public boolean containsChar(char ch) - { - return _charMap.containsKey(new Character(ch)); - } - - /** - * set up this character to be escaped in output documents - * according to the given mode - */ - public void addMapping(char ch, int mode) throws XmlException - { - Character theChar = new Character(ch); - switch(mode) - { - case PREDEF_ENTITY: - String replString = (String)_predefEntities.get(theChar); - if ( replString == null ) - { - throw new XmlException("XmlOptionCharEscapeMap.addMapping(): " + - "the PREDEF_ENTITY mode can only be used for the following " + - "characters: <, >, &, \" and '"); - } - _charMap.put(theChar, replString); - break; - - case DECIMAL: - _charMap.put(theChar, "&#" + (int)ch + ";"); - break; - - case HEXADECIMAL: - String hexCharPoint = Integer.toHexString((int)ch); - _charMap.put(theChar, "&#x" + hexCharPoint + ";"); - break; - - default: - throw new XmlException("XmlOptionCharEscapeMap.addMapping(): " + - "mode must be PREDEF_ENTITY, DECIMAL or HEXADECIMAL"); - } - } - - /** - * set up this contiguous set of characters to be escaped in - * output documents according to the given mode - */ - public void addMappings(char ch1, char ch2, int mode) throws XmlException - { - if (ch1 > ch2) - { - throw new XmlException("XmlOptionCharEscapeMap.addMappings(): " + - "ch1 must be <= ch2"); - } - - for (char c = ch1; c <= ch2; c++) - { - addMapping(c, mode); - } - } - - /** - * returns the escaped String for the character - */ - public String getEscapedString(char ch) - { - return (String)_charMap.get(new Character(ch)); - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlOptions.java b/src/xmlpublic/org/apache/xmlbeans/XmlOptions.java deleted file mode 100644 index 7b57fc3..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlOptions.java +++ /dev/null @@ -1,1079 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import org.xml.sax.EntityResolver; -import org.xml.sax.XMLReader; - -import java.net.URI; -import java.util.HashMap; -import java.util.Map; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; -import javax.xml.namespace.QName; - -/** - * Used to supply options for loading, saving, and compiling, and validating. - *

        - * There are two styles for using XmlOptions: multiline setup, and single-line use. - * Here are two examples. First, multiline style: - *

        - * XmlOptions opts = new XmlOptions();
        - * opts.setSavePrettyPrint();
        - * opts.setSavePrettyPrintIndent(4);
        - * System.out.println(xobj.xmlText(opts));
        - * 
        - * - * The alternative is single-line usage: - *
        - * System.out.println(xobj.xmlText(
        - *     new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(4)));
        - * 
        - * - * Table showing where each option gets used. - * Note that: - *
          - *
        • options available for newInstance methods will also - * apply for parse methods
        • - *
        • options used for validate methods are also used for - * compile methods, since compilation usually implies - * validation against Schema for Schemas
        • - *
        - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
        newInstance methodsparse methodsvalidate methodscompile methodssave and xmlTextmethods
        setDocumentType
        - * setDocumentSourceName
        - * setValidateOnSet
        - * setUnsynchronized
        setLoad***
        - * setEntityResolver
        setErrorListener
        - * setValidateTreatLaxAsSkip - * setValidateStrict
        setErrorListener
        - * setCompile***
        - * setEntityResolver
        - * setBaseURI
        - * setGenerateJavaVersion
        setSave***
        - * setUseDefaultNamespace
        - * setCharacterEncoding
        - */ -public class XmlOptions implements java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private Map _map = new HashMap(); - - - /** - * Construct a new blank XmlOptions. - */ - public XmlOptions ( ) { } - - /** - * Construct a new XmlOptions, copying the options. - */ - public XmlOptions (XmlOptions other) { - if (other != null) _map.putAll(other._map); - } - - // - // Handy-dandy helper methods for setting some options - // - - /** - * This option will cause the saver to save namespace attributes first. - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveNamespacesFirst() { - return set( SAVE_NAMESPACES_FIRST ); - } - /** - * This option will cause the saver to reformat white space for easier reading. - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSavePrettyPrint() { - return set( SAVE_PRETTY_PRINT ); - } - - /** - * When used with setSavePrettyPrint this sets the indent - * amount to use. - * - * @param indent the indent amount to use - * @see #setSavePrettyPrint - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSavePrettyPrintIndent(int indent) { - return set( SAVE_PRETTY_PRINT_INDENT, indent ); - } - - /** - * When used with setSavePrettyPrint this sets the offset - * amount to use. - * - * @param offset the offset amount to use - * @see #setSavePrettyPrint - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSavePrettyPrintOffset(int offset) { - return set( SAVE_PRETTY_PRINT_OFFSET, offset ); - } - - /** - * When writing a document, this sets the character - * encoding to use. - * - * @param encoding the character encoding - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - * @see XmlTokenSource#save(java.io.File, XmlOptions) - */ - public XmlOptions setCharacterEncoding(String encoding) { - return set( CHARACTER_ENCODING, encoding ); - } - - /** - * When parsing a document, this sets the type of the root - * element. If this is set, the parser will not try to guess - * the type based on the document's QName. - * - * @param type The root element's document type. - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setDocumentType(SchemaType type) { - return set( DOCUMENT_TYPE, type ); - } - - /** - *

        Sets a collection object for collecting {@link XmlError} objects - * during parsing, validation, and compilation. When set, the collection - * will contain all the errors after the operation takes place. Notice that - * the errors will only have line numbers if the document was - * loaded with line numbers enabled.

        - * - *

        The following simple example illustrates using an error listener - * during validation.

        - * - *
        -     * // Create an XmlOptions instance and set the error listener.
        -     * XmlOptions validateOptions = new XmlOptions();
        -     * ArrayList errorList = new ArrayList();
        -     * validateOptions.setErrorListener(errorList);
        -     * 
        -     * // Validate the XML.
        -     * boolean isValid = newEmp.validate(validateOptions);
        -     * 
        -     * // If the XML isn't valid, loop through the listener's contents,
        -     * // printing contained messages.
        -     * if (!isValid)
        -     * {
        -     *      for (int i = 0; i < errorList.size(); i++)
        -     *      {
        -     *          XmlError error = (XmlError)errorList.get(i);
        -     *          
        -     *          System.out.println("\n");
        -     *          System.out.println("Message: " + error.getMessage() + "\n");
        -     *          System.out.println("Location of invalid XML: " + 
        -     *              error.getCursorLocation().xmlText() + "\n");
        -     *      }
        -     * }
        -     * 
        - * - * @param c A collection that will be filled with {@link XmlError} objects - * via {@link Collection#add} - * - * @see XmlError - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - * @see XmlObject#validate(XmlOptions) - * @see XmlBeans#compileXsd - * @see XmlOptions#setLoadLineNumbers - */ - public XmlOptions setErrorListener (Collection c) { - return set( ERROR_LISTENER, c ); - } - - /** - * Causes the saver to reduce the number of namespace prefix declarations. - * The saver will do this by passing over the document twice, first to - * collect the set of needed namespace declarations, and then second - * to actually save the document with the declarations collected - * at the root. - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveAggressiveNamespaces() { - return set( SAVE_AGGRESSIVE_NAMESPACES ); - } - - /** - * @deprecated replaced by {@link #setSaveAggressiveNamespaces} - */ - public XmlOptions setSaveAggresiveNamespaces() { - return setSaveAggressiveNamespaces(); - } - - /** - * This option causes the saver to wrap the current fragment in - * an element with the given name. - * - * @param name the name to use for the top level element - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveSyntheticDocumentElement (QName name) { - return set( SAVE_SYNTHETIC_DOCUMENT_ELEMENT, name ); - } - - /** - * If this option is set, the saver will try to use the default - * namespace for the most commonly used URI. If it is not set - * the saver will always created named prefixes. - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setUseDefaultNamespace () { - return set( SAVE_USE_DEFAULT_NAMESPACE ); - } - - /** - * If namespaces have already been declared outside the scope of the - * fragment being saved, this allows those mappings to be passed - * down to the saver, so the prefixes are not re-declared. - * - * @param implicitNamespaces a map of prefixes to uris that can be - * used by the saver without being declared - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveImplicitNamespaces (Map implicitNamespaces) { - return set( SAVE_IMPLICIT_NAMESPACES, implicitNamespaces ); - } - - /** - * A map of hints to pass to the saver for which prefixes to use - * for which namespace URI. - * - * @param suggestedPrefixes a map from URIs to prefixes - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveSuggestedPrefixes (Map suggestedPrefixes) { - return set( SAVE_SUGGESTED_PREFIXES, suggestedPrefixes ); - } - - /** - * This option causes the saver to filter a Processing Instruction - * with the given target - * - * @param filterProcinst the name of a Processing Instruction to filter - * on save - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveFilterProcinst (String filterProcinst) { - return set( SAVE_FILTER_PROCINST, filterProcinst ); - } - - /** - * This option causes the saver to replace characters with other values in - * the output stream. It is intended to be used for escaping non-standard - * characters during output. - * - * @param characterReplacementMap is an XmlOptionCharEscapeMap containing - * the characters to be escaped. - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - * @see XmlOptionCharEscapeMap - */ - public XmlOptions setSaveSubstituteCharacters ( - XmlOptionCharEscapeMap characterReplacementMap) { - return set( SAVE_SUBSTITUTE_CHARACTERS, characterReplacementMap ); - } - - /** - * When saving a fragment, this option changes the qname of the synthesized - * root element. Normally <xml-fragment> is used. - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveUseOpenFrag () { - return set( SAVE_USE_OPEN_FRAGMENT ); - } - - /** - * This option controls whether saving begins on the element or its contents - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveOuter () { - return set( SAVE_OUTER ); - } - - /** - * This option controls whether saving begins on the element or its contents - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveInner () { - return set( SAVE_INNER ); - } - - /** - * This option controls whether saving saves out the XML - * declaration ( - * - * @see XmlTokenSource#save(java.io.File, XmlOptions) - * @see XmlTokenSource#xmlText(XmlOptions) - */ - public XmlOptions setSaveNoXmlDecl () { - return set( SAVE_NO_XML_DECL ); - } - - /** - * This option controls when saving will use CDATA blocks. - * CDATA will be used if the folowing condition is true: - *
        textLength > cdataLengthThreshold && entityCount > cdataEntityCountThreshold - *
        The default value of cdataLengthThreshold is 32. - *
        - *
        Use the folowing values for these cases: - * - * - * - * - * - * - * - *
        Scenario cdataLengthThreshold cdataEntityCountThreshold
        Every text is CDATA 0 -1
        Only text that has an entity is CDATA 0 0
        Only text longer than x chars is CDATA x -1
        Only text that has y entitazable chars is CDATA 0 y
        Only text longer than x chars and has y entitazable chars is CDATA x y
        - * @see XmlOptions#setSaveCDataEntityCountThreshold(int) - */ - public XmlOptions setSaveCDataLengthThreshold (int cdataLengthThreshold) { - return set( SAVE_CDATA_LENGTH_THRESHOLD, cdataLengthThreshold ); - } - - /** - * This option controls when saving will use CDATA blocks. - * CDATA will be used if the folowing condition is true: - *
        textLength > cdataLengthThreshold && entityCount > cdataEntityCountThreshold - *
        The default value of cdataEntityCountThreshold is 5. - * - * @see XmlOptions#setSaveCDataLengthThreshold(int) - */ - public XmlOptions setSaveCDataEntityCountThreshold (int cdataEntityCountThreshold) { - return set( SAVE_CDATA_ENTITY_COUNT_THRESHOLD, cdataEntityCountThreshold ); - } - - /** - *

        Use this option when parsing and saving XML documents.

        - * - *

        For parsing this option will annotate the text fields in the store with CDataBookmark.

        - * - *

        For saving this option will save the text fields annotated with CDataBookmark as - * CDATA XML text.
        - * Note: The SaveCDataEntityCountThreshold and SaveCDataLengthThreshold options and - * their default values still apply.

        - * - *

        Note: Due to the store representation, a CDATA will not be recognized - * if it is imediately after non CDATA text and all text following it will - * be considered CDATA.
        - * Example:
        - *

        -     * <a><![CDATA[cdata text]]></a>               - is considered as: <a><![CDATA[cdata text]]></a>
        -     * <b><![CDATA[cdata text]]> regular text</b>  - is considered as: <b><![CDATA[cdata text regular text]]></b>
        -     * <c>text <![CDATA[cdata text]]></c>          - is considered as: <c>text cdata text</c>
        -     * 
        - *

        - * - *

        Sample code: - *

        -        String xmlText = "<a>\n" +
        -                "<a><![CDATA[cdata text]]></a>\n" +
        -                "<b><![CDATA[cdata text]]> regular text</b>\n" +
        -                "<c>text <![CDATA[cdata text]]></c>\n" +
        -                "</a>";
        -        System.out.println(xmlText);
        -
        -        XmlOptions opts = new XmlOptions();
        -        opts.setUseCDataBookmarks();
        -
        -        XmlObject xo = XmlObject.Factory.parse( xmlText , opts);
        -
        -        System.out.println("xo1:\n" + xo.xmlText(opts));
        -        System.out.println("\n");
        -
        -        opts.setSavePrettyPrint();
        -        System.out.println("xo2:\n" + xo.xmlText(opts));
        -     * 
        - *

        - * - * @see CDataBookmark - * @see CDataBookmark#CDATA_BOOKMARK - */ - public XmlOptions setUseCDataBookmarks() - { - return set( LOAD_SAVE_CDATA_BOOKMARKS ); - } - - /** - * This option controls whether namespace declarations are included as attributes in the - * startElement event. By default, up to and including XMLBeans 2.3.0 they were included, in - * subsequent versions, they are no longer included. - */ - public XmlOptions setSaveSaxNoNSDeclsInAttributes () { - return set( SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES ); - } - - /** - * If this option is set, the document element is replaced with the - * given QName when parsing. If null is supplied, the document element - * is removed. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadReplaceDocumentElement ( QName replacement ) { - return set( LOAD_REPLACE_DOCUMENT_ELEMENT, replacement ); - } - - /** - * If this option is set, all insignificant whitespace is stripped - * when parsing a document. Can be used to save memory on large - * documents when you know there is no mixed content. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadStripWhitespace () { - return set( LOAD_STRIP_WHITESPACE); - } - - /** - * If this option is set, all comments are stripped when parsing - * a document. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadStripComments() { - return set( LOAD_STRIP_COMMENTS ); - } - - /** - * If this option is set, all processing instructions - * are stripped when parsing a document. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadStripProcinsts () { - return set( LOAD_STRIP_PROCINSTS ); - } - - /** - * If this option is set, line number annotations are placed - * in the store when parsing a document. This is particularly - * useful when you want {@link XmlError} objects to contain - * line numbers. - *
        Note: This adds line numbers info only for start tags. - * For line number info on end tags use: - * {@link XmlOptions#setLoadLineNumbers(java.lang.String)} - *
        Example: xmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT) - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - * @see XmlError - */ - public XmlOptions setLoadLineNumbers () { - return set( LOAD_LINE_NUMBERS ); - } - - /** - * If this option is set, line number annotations are placed - * in the store when parsing a document. This is particularly - * useful when you want {@link XmlError} objects to contain - * line numbers. Use the option to load line numbers at the end of an element. - *
        Example: xmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT) - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - * @see XmlError - */ - public XmlOptions setLoadLineNumbers (String option) { - XmlOptions temp = setLoadLineNumbers(); - temp = temp.set( option ); - return temp; - } - - /** - * This option sets a map of namespace uri substitutions that happen - * when parsing a document. - *

        - * This is particularly useful if you - * have documents that use no namespace, but you wish to avoid - * the name collision problems that occur when you introduce - * schema definitions without a target namespace. - *

        - * By mapping the empty string "" (the absence of a URI) to a specific - * namespace, you can force the parser to behave as if a no-namespace - * document were actually in the specified namespace. This allows you - * to type the instance according to a schema in a nonempty namespace, - * and therefore avoid the problematic practice of using schema - * definitions without a target namespace. - * - * @param substNamespaces a map of document URIs to replacement URIs - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadSubstituteNamespaces (Map substNamespaces) { - return set( LOAD_SUBSTITUTE_NAMESPACES, substNamespaces ); - } - - /** - * If this option is set, the underlying xml text buffer is trimmed - * immediately after parsing a document resulting in a smaller memory - * footprint. Use this option if you are loading a large number - * of unchanging documents that will stay in memory for some time. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadTrimTextBuffer () { - return set( LOAD_TRIM_TEXT_BUFFER ); - } - - /** - * Set additional namespace mappings to be added when parsing - * a document. - * - * @param nses additional namespace mappings - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadAdditionalNamespaces (Map nses) { - return set( LOAD_ADDITIONAL_NAMESPACES, nses ); - } - - /** - * If this option is set when loading from an InputStream or File, then - * the loader will compute a 160-bit SHA-1 message digest of the XML - * file while loading it and make it available via - * XmlObject.documentProperties().getMessageDigest(); - *
        - * The schema compiler uses message digests to detect and eliminate - * duplicate imported xsd files. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadMessageDigest () { - return set( LOAD_MESSAGE_DIGEST ); - } - - /** - * By default, XmlBeans does not resolve entities when parsing xml - * documents (unless an explicit entity resolver is specified). - * Use this option to turn on entity resolving by default. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadUseDefaultResolver () { - return set( LOAD_USE_DEFAULT_RESOLVER ); - } - - /** - * By default, XmlBeans creates a JAXP parser, - * other parsers can be used by providing an XMLReader. - * For using the default JDK's SAX parser use: - * xmlOptions.setLoadUseXMLReader( SAXParserFactory.newInstance().newSAXParser().getXMLReader() ); - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setLoadUseXMLReader (XMLReader xmlReader) { - return set( LOAD_USE_XMLREADER, xmlReader ); - } - - /** - * Sets the name of the variable that represents - * the current node in a query expression. - * - * @param varName The new variable name to use for the query. - * - * @see XmlObject#execQuery - * @see XmlCursor#execQuery - */ - public XmlOptions setXqueryCurrentNodeVar (String varName) { - return set( XQUERY_CURRENT_NODE_VAR, varName ); - } - - /** - * Map the names and values of external variables in an xquery - * expression. The keys of the map are the variable names - * in the query without the '$' prefix. The values of the map - * are objects and can be any of the primitive wrapper classes, - * String, XmlObject, or XmlCursor. The mapping only applies to - * xquery and has no effect on xpath expressions. - * - * @param varMap a map from Strings to variable instances. - * - * @see XmlObject#execQuery - * @see XmlCursor#execQuery - */ - public XmlOptions setXqueryVariables (Map varMap) { - return set( XQUERY_VARIABLE_MAP, varMap ); - } - - /** - * This option sets the document source name into the xml store - * when parsing a document. If a document is parsed from a - * File or URI, it is automatically set to the URI of the - * source; otherwise, for example, when parsing a String, - * you can use this option to specify the source name yourself. - * - * @see XmlObject.Factory#parse(java.lang.String, XmlOptions) - */ - public XmlOptions setDocumentSourceName (String documentSourceName) { - return set( DOCUMENT_SOURCE_NAME, documentSourceName ); - } - - /** - * This option allows for QName substitution during schema compilation. - * - * @param nameMap a map from QNames to substitute QNames. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileSubstituteNames (Map nameMap) { - return set( COMPILE_SUBSTITUTE_NAMES, nameMap ); - } - - /** - * If this option is set, validation is not done on the Schema XmlBeans - * when building a SchemaTypeSystem - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileNoValidation () { - return set( COMPILE_NO_VALIDATION ); - } - - /** - * If this option is set, the unique particle attribution rule is not - * enforced when building a SchemaTypeSystem. See - * Appendix H of the XML Schema specification - * for information on the UPA rule. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileNoUpaRule () { - return set( COMPILE_NO_UPA_RULE ); - } - - /** - * If this option is set, the particle valid (restriciton) rule is not - * enforced when building a SchemaTypeSystem. See - * Section 3.9.6 of the XML Schema specification - * for information on the PVR rule. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileNoPvrRule () { - return set( COMPILE_NO_PVR_RULE ); - } - - /** - * if this option is set, the schema compiler will skip annotations when - * processing Schema components. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileNoAnnotations() { - return set( COMPILE_NO_ANNOTATIONS ); - } - - /** - * If this option is set, then the schema compiler will try to download - * schemas that appear in imports and includes from network based URLs. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileDownloadUrls () { - return set( COMPILE_DOWNLOAD_URLS); - } - - /** - * If this option is set, then the schema compiler will permit and - * ignore multiple definitions of the same component (element, attribute, - * type, etc) names in the given namespaces. If multiple definitions - * with the same name appear, the definitions that happen to be processed - * last will be ignored. - * - * @param mdefNamespaces a set of namespace URIs as Strings - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setCompileMdefNamespaces(Set mdefNamespaces) - { - return set( COMPILE_MDEF_NAMESPACES, mdefNamespaces ); - } - - /** - * If this option is set when an instance is created, then value - * facets will be checked on each call to a setter or getter - * method on instances of XmlObject within the instance document. - * If the facets are not satisfied, then an unchecked exception is - * thrown immediately. This option is useful for finding code that - * is introducing invalid values in an XML document, but it - * slows performance. - * - * @see XmlObject.Factory#parse(java.io.File, XmlOptions) - */ - public XmlOptions setValidateOnSet() { - return set( VALIDATE_ON_SET ); - } - - /** - * Instructs the validator to skip elements matching an - * particle with contentModel="lax". This is useful because, - * in certain situations, XmlBeans will find types on the - * classpath that the document author did not anticipate. - */ - public XmlOptions setValidateTreatLaxAsSkip() { - return set ( VALIDATE_TREAT_LAX_AS_SKIP ); - } - - /** - * Performs additional validation checks that are disabled by - * default for better compatibility. - */ - public XmlOptions setValidateStrict() { - return set ( VALIDATE_STRICT ); - } - - /** - * This option controls whether or not operations on XmlBeans are - * thread safe. When not on, all XmlBean operations will be syncronized. - * This provides for multiple thread the ability to access a single - * XmlBeans simultainously, but has a perf impact. If set, then - * only one thread may access an XmlBean. - */ - public XmlOptions setUnsynchronized ( ) - { - return set( UNSYNCHRONIZED ); - } - - /** - * If this option is set when compiling a schema, then the given - * EntityResolver will be consulted in order to resolve any - * URIs while downloading imported schemas. - * - * EntityResolvers are currently only used by compileXsd; they - * are not consulted by other functions, for example, parse. - * This will likely change in the future. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setEntityResolver(EntityResolver resolver) { - return set( ENTITY_RESOLVER, resolver ); - } - - /** - * If this option is set when compiling a schema, then the given - * URI will be considered as base URI when deciding the directory - * structure for saving the sources inside the generated JAR file. - * @param baseURI the URI to be considered as "base" - * @see XmlBeans#compileXsd - */ - public XmlOptions setBaseURI(URI baseURI) { - return set( BASE_URI, baseURI ); - } - - /** - * If this option is set when compiling a schema, then the given - * SchemaTypeCodePrinter.Printer will be used to generate the - * Java code. - * - * @see XmlBeans#compileXsd - */ - public XmlOptions setSchemaCodePrinter(SchemaCodePrinter printer) { - return set( SCHEMA_CODE_PRINTER, printer ); - } - - /** - * If this option is set, then the schema compiler will print java code - * that is compatible with the desired Java version. If not set, the - * current Java version is used. Currently, only "1.4" and "1.5" are - * supported. - * - * @param source A Java version number - * - * @see #GENERATE_JAVA_14 - * @see #GENERATE_JAVA_15 - * @see XmlBeans#compileXmlBeans - */ - public XmlOptions setGenerateJavaVersion (String source) { - return set( GENERATE_JAVA_VERSION, source ); - } - - /** - * If this option is set to true, the return of XmlObject.copy() method will - * return an object in it's own synchronization domain, otherwise both objects - * will share the same synchronization domain, requiring explicit synchronization - * when concurent accessing the two objects. - * - * @param useNewSyncDomain A flag representing the usage of new domain - * - * @see XmlObject#copy() - */ - public XmlOptions setCopyUseNewSynchronizationDomain (boolean useNewSyncDomain) - { - return set(COPY_USE_NEW_SYNC_DOMAIN, useNewSyncDomain); - } - - /** - * Sets the maximum number of bytes allowed when an Entity is expanded during parsing. - * The default value is 10240 bytes. - * @param entityBytesLimit - * @return - */ - public XmlOptions setLoadEntityBytesLimit (int entityBytesLimit) - { - return set(LOAD_ENTITY_BYTES_LIMIT,entityBytesLimit); - } - - /** - * Sets the maximum number of entity expansions allowed during parsing. - * The default value is 2048. - * @param entityExpansionLimit - * @return this - */ - public XmlOptions setEntityExpansionLimit (int entityExpansionLimit) - { - return set(ENTITY_EXPANSION_LIMIT, entityExpansionLimit); - } - - /** - * Controls whether DTD grammar is loaded during parsing. - * The default value is false. - * - * @param loadDTDGrammar - * @return this - */ - public XmlOptions setLoadDTDGrammar (boolean loadDTDGrammar) - { - return set(LOAD_DTD_GRAMMAR, loadDTDGrammar); - } - - /** - * Controls whether external DTDs are loaded during parsing. - * The default value is false. - * - * @param loadExternalDTD - * @return this - */ - public XmlOptions setLoadExternalDTD (boolean loadExternalDTD) - { - return set(LOAD_EXTERNAL_DTD, loadExternalDTD); - } - - public static final String GENERATE_JAVA_14 = "1.4"; - public static final String GENERATE_JAVA_15 = "1.5"; - - - // - // Complete set of XmlOption's - // - - // TODO - Add selectPath option to track the seletion (deault is to clean selections fast). - - /** @exclude */ - public static final String SAVE_NAMESPACES_FIRST = "SAVE_NAMESPACES_FIRST"; - /** @exclude */ - public static final String SAVE_SYNTHETIC_DOCUMENT_ELEMENT = "SAVE_SYNTHETIC_DOCUMENT_ELEMENT"; - /** @exclude */ - public static final String SAVE_PRETTY_PRINT = "SAVE_PRETTY_PRINT"; - /** @exclude */ - public static final String SAVE_PRETTY_PRINT_INDENT = "SAVE_PRETTY_PRINT_INDENT"; - /** @exclude */ - public static final String SAVE_PRETTY_PRINT_OFFSET = "SAVE_PRETTY_PRINT_OFFSET"; - /** @exclude */ - public static final String SAVE_AGGRESSIVE_NAMESPACES = "SAVE_AGGRESSIVE_NAMESPACES"; - /** @exclude */ - public static final String SAVE_USE_DEFAULT_NAMESPACE = "SAVE_USE_DEFAULT_NAMESPACE"; - /** @exclude */ - public static final String SAVE_IMPLICIT_NAMESPACES = "SAVE_IMPLICIT_NAMESPACES"; - /** @exclude */ - public static final String SAVE_SUGGESTED_PREFIXES = "SAVE_SUGGESTED_PREFIXES"; - /** @exclude */ - public static final String SAVE_FILTER_PROCINST = "SAVE_FILTER_PROCINST"; - /** @exclude */ - public static final String SAVE_USE_OPEN_FRAGMENT = "SAVE_USE_OPEN_FRAGMENT"; - /** @exclude */ - public static final String SAVE_OUTER = "SAVE_OUTER"; - /** @exclude */ - public static final String SAVE_INNER = "SAVE_INNER"; - /** @exclude */ - public static final String SAVE_NO_XML_DECL = "SAVE_NO_XML_DECL"; - /** @exclude */ - public static final String SAVE_SUBSTITUTE_CHARACTERS = "SAVE_SUBSTITUTE_CHARACTERS"; - /** @exclude */ - public static final String SAVE_OPTIMIZE_FOR_SPEED = "SAVE_OPTIMIZE_FOR_SPEED"; - /** @exclude */ - public static final String SAVE_CDATA_LENGTH_THRESHOLD = "SAVE_CDATA_LENGTH_THRESHOLD"; - /** @exclude */ - public static final String SAVE_CDATA_ENTITY_COUNT_THRESHOLD = "SAVE_CDATA_ENTITY_COUNT_THRESHOLD"; - /** @exclude */ - public static final String SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES = "SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES"; - /** @exclude */ - public static final String LOAD_REPLACE_DOCUMENT_ELEMENT = "LOAD_REPLACE_DOCUMENT_ELEMENT"; - /** @exclude */ - public static final String LOAD_STRIP_WHITESPACE = "LOAD_STRIP_WHITESPACE"; - /** @exclude */ - public static final String LOAD_STRIP_COMMENTS = "LOAD_STRIP_COMMENTS"; - /** @exclude */ - public static final String LOAD_STRIP_PROCINSTS = "LOAD_STRIP_PROCINSTS"; - /** @exclude */ - public static final String LOAD_LINE_NUMBERS = "LOAD_LINE_NUMBERS"; - /** @exclude */ - public static final String LOAD_LINE_NUMBERS_END_ELEMENT = "LOAD_LINE_NUMBERS_END_ELEMENT"; - /** @exclude */ - public static final String LOAD_SAVE_CDATA_BOOKMARKS = "LOAD_SAVE_CDATA_BOOKMARKS"; - /** @exclude */ - public static final String LOAD_SUBSTITUTE_NAMESPACES = "LOAD_SUBSTITUTE_NAMESPACES"; - /** @exclude */ - public static final String LOAD_TRIM_TEXT_BUFFER = "LOAD_TRIM_TEXT_BUFFER"; - /** @exclude */ - public static final String LOAD_ADDITIONAL_NAMESPACES = "LOAD_ADDITIONAL_NAMESPACES"; - /** @exclude */ - public static final String LOAD_MESSAGE_DIGEST = "LOAD_MESSAGE_DIGEST"; - /** @exclude */ - public static final String LOAD_USE_DEFAULT_RESOLVER = "LOAD_USE_DEFAULT_RESOLVER"; - /** @exclude */ - public static final String LOAD_USE_XMLREADER = "LOAD_USE_XMLREADER"; - - /** @exclude */ - public static final String XQUERY_CURRENT_NODE_VAR = "XQUERY_CURRENT_NODE_VAR"; - /** @exclude */ - public static final String XQUERY_VARIABLE_MAP = "XQUERY_VARIABLE_MAP"; - - /** @exclude */ - public static final String CHARACTER_ENCODING = "CHARACTER_ENCODING"; - /** @exclude */ - public static final String ERROR_LISTENER = "ERROR_LISTENER"; - /** @exclude */ - public static final String DOCUMENT_TYPE = "DOCUMENT_TYPE"; - /** @exclude */ - public static final String DOCUMENT_SOURCE_NAME = "DOCUMENT_SOURCE_NAME"; - /** @exclude */ - public static final String COMPILE_SUBSTITUTE_NAMES = "COMPILE_SUBSTITUTE_NAMES"; - /** @exclude */ - public static final String COMPILE_NO_VALIDATION = "COMPILE_NO_VALIDATION"; - /** @exclude */ - public static final String COMPILE_NO_UPA_RULE = "COMPILE_NO_UPA_RULE"; - /** @exclude */ - public static final String COMPILE_NO_PVR_RULE = "COMPILE_NO_PVR_RULE"; - /** @exclude */ - public static final String COMPILE_NO_ANNOTATIONS = "COMPILE_NO_ANNOTATIONS"; - /** @exclude */ - public static final String COMPILE_DOWNLOAD_URLS = "COMPILE_DOWNLOAD_URLS"; - /** @exclude */ - public static final String COMPILE_MDEF_NAMESPACES = "COMPILE_MDEF_NAMESPACES"; - /** @exclude */ - public static final String VALIDATE_ON_SET = "VALIDATE_ON_SET"; - /** @exclude */ - public static final String VALIDATE_TREAT_LAX_AS_SKIP = "VALIDATE_TREAT_LAX_AS_SKIP"; - /** @exclude */ - public static final String VALIDATE_STRICT = "VALIDATE_STRICT"; - /** @exclude */ - public static final String VALIDATE_TEXT_ONLY = "VALIDATE_TEXT_ONLY"; - /** @exclude */ - public static final String UNSYNCHRONIZED = "UNSYNCHRONIZED"; - /** @exclude */ - public static final String ENTITY_RESOLVER = "ENTITY_RESOLVER"; - /** @exclude */ - public static final String BASE_URI = "BASE_URI"; - /** @exclude */ - public static final String SCHEMA_CODE_PRINTER = "SCHEMA_CODE_PRINTER"; - /** @exclude */ - public static final String GENERATE_JAVA_VERSION = "GENERATE_JAVA_VERSION"; - /** @exclude */ - public static final String COPY_USE_NEW_SYNC_DOMAIN = "COPY_USE_NEW_LOCALE"; - /** @exclude */ - public static final String LOAD_ENTITY_BYTES_LIMIT = "LOAD_ENTITY_BYTES_LIMIT"; - /** @exclude */ - public static final String ENTITY_EXPANSION_LIMIT = "ENTITY_EXPANSION_LIMIT"; - /** @exclude */ - public static final String LOAD_DTD_GRAMMAR = "LOAD_DTD_GRAMMAR"; - /** @exclude */ - public static final String LOAD_EXTERNAL_DTD = "LOAD_EXTERNAL_DTD"; - - public static final int DEFAULT_ENTITY_EXPANSION_LIMIT = 2048; - - private static final XmlOptions EMPTY_OPTIONS; - static { - EMPTY_OPTIONS = new XmlOptions(); - EMPTY_OPTIONS._map = Collections.unmodifiableMap(EMPTY_OPTIONS._map); - } - - /** If passed null, returns an empty options object. Otherwise, returns its argument. */ - public static XmlOptions maskNull(XmlOptions o) { - return (o == null) ? EMPTY_OPTIONS : o; - } - - - /** Used to set a generic option */ - public void put ( Object option ) { put( option, null ); } - /** Used to set a generic option */ - public void put ( Object option, Object value ) { _map.put(option, value); } - /** Used to set a generic option */ - public void put ( Object option, int value ) { put( option, new Integer( value ) ); } - - private XmlOptions set(Object option) { return set(option, null); } - private XmlOptions set(Object option, Object value) { _map.put(option, value); return this;} - private XmlOptions set(Object option, int value) { return set(option, new Integer(value)); } - - /** Used to test a generic option */ - public boolean hasOption ( Object option ) { return _map.containsKey( option ); } - public static boolean hasOption ( XmlOptions options, Object option ) { return options == null ? false : options.hasOption( option ); } - - /** Used to get a generic option */ - public Object get ( Object option ) { return _map.get( option ); } - public void remove ( Object option ) { _map.remove( option ); } - - /** Used to test a generic option on an options object that may be null */ - public static Object safeGet(XmlOptions o, Object option) { - return o == null ? null : o.get(option); - } - -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlOptionsBean.java b/src/xmlpublic/org/apache/xmlbeans/XmlOptionsBean.java deleted file mode 100644 index a148758..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlOptionsBean.java +++ /dev/null @@ -1,478 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import org.xml.sax.XMLReader; -import org.xml.sax.EntityResolver; - -import javax.xml.namespace.QName; -import java.util.Map; -import java.util.Set; - -/** - * Same as {@link XmlOptions} but adhering to JavaBean conventions - */ -public class XmlOptionsBean extends XmlOptions -{ - /** - * Construct a new blank XmlOptions. - */ - public XmlOptionsBean ( ) { } - - /** - * Construct a new XmlOptions, copying the options. - * @param other the source XmlOptions object - */ - public XmlOptionsBean (XmlOptions other) { - super( other ); - } - - - public void setSaveNamespacesFirst(boolean b) - { - if (b) - super.setSaveNamespacesFirst(); - else - remove( SAVE_NAMESPACES_FIRST ); - } - - public boolean isSaveNamespacesFirst() - { - return hasOption( SAVE_NAMESPACES_FIRST ); - } - - public void setSavePrettyPrint(boolean b) - { - if (b) - super.setSavePrettyPrint(); - else - remove( SAVE_PRETTY_PRINT ); - } - - public boolean isSavePrettyPrint() - { - return hasOption( SAVE_PRETTY_PRINT ); - } - - public Integer getSavePrettyPrintIndent() - { - return (Integer) get( SAVE_PRETTY_PRINT_INDENT ); - } - - public Integer getSavePrettyPrintOffset() - { - return (Integer) get( SAVE_PRETTY_PRINT_OFFSET ); - } - - public String getCharacterEncoding() - { - return (String) get( CHARACTER_ENCODING ); - } - - public SchemaType getDocumentType() - { - return (SchemaType) get ( DOCUMENT_TYPE ); - } - - public void setSaveAggressiveNamespaces(boolean b) - { - if (b) - super.setSaveAggressiveNamespaces(); - else - remove( SAVE_AGGRESSIVE_NAMESPACES ); - } - - public boolean isSaveAggressiveNamespaces() - { - return hasOption( SAVE_AGGRESSIVE_NAMESPACES ); - } - - public QName getSaveSyntheticDocumentElement() - { - return (QName) get( SAVE_SYNTHETIC_DOCUMENT_ELEMENT ); - } - - public void setUseDefaultNamespace(boolean b) - { - if (b) - super.setUseDefaultNamespace(); - else - remove( SAVE_USE_DEFAULT_NAMESPACE ); - } - - public boolean isUseDefaultNamespace() - { - return hasOption( SAVE_USE_DEFAULT_NAMESPACE ); - } - - public Map getSaveImplicitNamespaces() - { - return (Map) get( SAVE_IMPLICIT_NAMESPACES ); - } - - public Map getSaveSuggestedPrefixes() - { - return (Map) get( SAVE_SUGGESTED_PREFIXES ); - } - - public String getSaveFilterProcinst() - { - return (String) get( SAVE_FILTER_PROCINST ); - } - - public XmlOptionCharEscapeMap getSaveSubstituteCharacters() - { - return (XmlOptionCharEscapeMap) get( SAVE_SUBSTITUTE_CHARACTERS ); - } - - public void setSaveUseOpenFrag(boolean b) - { - if (b) - super.setSaveUseOpenFrag(); - else - remove( SAVE_USE_OPEN_FRAGMENT ); - } - - public boolean isSaveUseOpenFrag() - { - return hasOption( SAVE_USE_OPEN_FRAGMENT ); - } - - public void setSaveOuter(boolean b) - { - if (b) - super.setSaveOuter(); - else - remove( SAVE_OUTER ); - } - - public boolean isSaveOuter() - { - return hasOption( SAVE_OUTER ); - } - - public void setSaveInner(boolean b) - { - if (b) - super.setSaveInner(); - else - remove( SAVE_INNER ); - } - - public boolean isSaveInner() - { - return hasOption( SAVE_INNER ); - } - - public void setSaveNoXmlDecl(boolean b) - { - if (b) - super.setSaveNoXmlDecl(); - else - remove( SAVE_NO_XML_DECL ); - } - - public boolean isSaveNoXmlDecl() - { - return hasOption( SAVE_NO_XML_DECL ); - } - - public Integer getSaveCDataLengthThreshold() - { - return (Integer) get( SAVE_CDATA_LENGTH_THRESHOLD ); - } - - public Integer getSaveCDataEntityCountThreshold() - { - return (Integer) get( SAVE_CDATA_ENTITY_COUNT_THRESHOLD ); - } - - public void setSaveSaxNoNSDeclsInAttributes(boolean b) - { - if (b) - super.setSaveSaxNoNSDeclsInAttributes(); - else - remove( SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES ); - } - - public boolean isSaveSaxNoNSDeclsInAttributes() - { - return hasOption( SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES ); - } - - public QName getLoadReplaceDocumentElement() - { - return (QName) get( LOAD_REPLACE_DOCUMENT_ELEMENT ); - } - - public void setLoadStripWhitespace(boolean b) - { - if (b) - super.setLoadStripWhitespace(); - else - remove( LOAD_STRIP_WHITESPACE ); - } - - public boolean isSetLoadStripWhitespace() - { - return hasOption( LOAD_STRIP_WHITESPACE ); - } - - public void setLoadStripComments(boolean b) - { - if (b) - super.setLoadStripComments(); - else - remove( LOAD_STRIP_COMMENTS ); - } - - public boolean isLoadStripComments() - { - return hasOption( LOAD_STRIP_COMMENTS ); - } - - public void setLoadStripProcinsts(boolean b) - { - if (b) - super.setLoadStripProcinsts(); - else - remove( LOAD_STRIP_PROCINSTS ); - } - - public boolean isLoadStripProcinsts() - { - return hasOption( LOAD_STRIP_PROCINSTS ); - } - - public void setLoadLineNumbers(boolean b) - { - if (b) - super.setLoadLineNumbers(); - else - remove( LOAD_LINE_NUMBERS ); - } - - public boolean isLoadLineNumbers() - { - return hasOption( LOAD_LINE_NUMBERS ); - } - - public Map getLoadSubstituteNamespaces() - { - return (Map) get( LOAD_SUBSTITUTE_NAMESPACES ); - } - - public void setLoadTrimTextBuffer(boolean b) - { - if (b) - super.setLoadTrimTextBuffer(); - else - remove( LOAD_TRIM_TEXT_BUFFER ); - } - - public boolean isLoadTrimTextBuffer() - { - return hasOption( LOAD_TRIM_TEXT_BUFFER ); - } - - public Map getLoadAdditionalNamespaces() - { - return (Map) get( LOAD_ADDITIONAL_NAMESPACES ); - } - - public void setLoadMessageDigest(boolean b) - { - if (b) - super.setLoadMessageDigest(); - else - remove( LOAD_MESSAGE_DIGEST ); - } - - public boolean isLoadMessageDigest() - { - return hasOption( LOAD_MESSAGE_DIGEST ); - } - - public void setLoadUseDefaultResolver(boolean b) - { - if (b) - super.setLoadUseDefaultResolver(); - else - remove( LOAD_USE_DEFAULT_RESOLVER ); - } - - public boolean isLoadUseDefaultResolver() - { - return hasOption( LOAD_USE_DEFAULT_RESOLVER ); - } - - public String getXqueryCurrentNodeVar() - { - return (String) get( XQUERY_CURRENT_NODE_VAR ); - } - - public Map getXqueryVariables() - { - return (Map) get( XQUERY_VARIABLE_MAP ); - } - - public String getDocumentSourceName() - { - return (String) get( DOCUMENT_SOURCE_NAME ); - } - - public Map getCompileSubstituteNames() - { - return (Map) get( COMPILE_SUBSTITUTE_NAMES ); - } - - public void setCompileNoUpaRule(boolean b) - { - if (b) - super.setCompileNoUpaRule(); - else - remove( COMPILE_NO_UPA_RULE ); - } - - public boolean isCompileNoUpaRule() - { - return hasOption( COMPILE_NO_UPA_RULE ); - } - - public void setCompileNoPvrRule(boolean b) - { - if (b) - super.setCompileNoPvrRule(); - else - remove( COMPILE_NO_PVR_RULE ); - } - - public boolean isCompileNoPvrRule() - { - return hasOption( COMPILE_NO_PVR_RULE ); - } - - public void setCompileNoAnnotations(boolean b) - { - if (b) - super.setCompileNoAnnotations(); - else - remove( COMPILE_NO_ANNOTATIONS ); - } - - public boolean isCompileNoAnnotations() - { - return hasOption( COMPILE_NO_ANNOTATIONS ); - } - - public void setCompileDownloadUrls(boolean b) - { - if (b) - super.setCompileDownloadUrls(); - else - remove( COMPILE_DOWNLOAD_URLS ); - } - - public boolean isCompileDownloadUrls() - { - return hasOption( COMPILE_DOWNLOAD_URLS ); - } - - public Set getCompileMdefNamespaces() - { - return (Set) get( COMPILE_MDEF_NAMESPACES ); - } - - public void setValidateOnSet(boolean b) - { - if (b) - super.setValidateOnSet(); - else - remove( VALIDATE_ON_SET ); - } - - public boolean isValidateOnSet() - { - return hasOption( VALIDATE_ON_SET ); - } - - public void setValidateTreatLaxAsSkip(boolean b) - { - if (b) - super.setValidateTreatLaxAsSkip(); - else - remove( VALIDATE_TREAT_LAX_AS_SKIP ); - } - - public boolean isValidateTreatLaxAsSkip() - { - return hasOption( VALIDATE_TREAT_LAX_AS_SKIP ); - } - - public void setValidateStrict(boolean b) - { - if (b) - super.setValidateStrict(); - else - remove( VALIDATE_STRICT ); - } - - public boolean isValidateStrict() - { - return hasOption( VALIDATE_STRICT ); - } - - public void setUnsynchronized(boolean b) - { - if (b) - super.setUnsynchronized(); - else - remove( UNSYNCHRONIZED ); - } - - public boolean isUnsynchronized() - { - return hasOption( UNSYNCHRONIZED ); - } - - public EntityResolver getEntityResolver() - { - return (EntityResolver) get( ENTITY_RESOLVER ); - } - - public String getGenerateJavaVersion() - { - return (String) get( GENERATE_JAVA_VERSION ); - } - - public int getEntityExpansionLimit() - { - Integer limit = (Integer) get( ENTITY_EXPANSION_LIMIT ); - return limit == null ? DEFAULT_ENTITY_EXPANSION_LIMIT : limit; - } - - public boolean isLoadDTDGrammar() - { - Boolean flag = (Boolean) get( LOAD_DTD_GRAMMAR ); - return flag == null ? false : flag; - } - - public boolean isLoadExternalDTD() - { - Boolean flag = (Boolean) get( LOAD_EXTERNAL_DTD ); - return flag == null ? false : flag; - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlPositiveInteger.java b/src/xmlpublic/org/apache/xmlbeans/XmlPositiveInteger.java deleted file mode 100644 index 69ef620..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlPositiveInteger.java +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:positiveInteger type. - * One of the derived types based on xs:decimal. - *

        - * Verified to be positive when validating. - *

        - * Convertible to {@link java.math.BigInteger}. - */ -public interface XmlPositiveInteger extends XmlNonNegativeInteger -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_positiveInteger"); - - /** - * A class with methods for creating instances - * of {@link XmlPositiveInteger}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlPositiveInteger} */ - public static XmlPositiveInteger newInstance() { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlPositiveInteger} */ - public static XmlPositiveInteger newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlPositiveInteger} value */ - public static XmlPositiveInteger newValue(Object obj) { - return (XmlPositiveInteger) type.newValue( obj ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". */ - public static XmlPositiveInteger parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a String. For example: "<xml-fragment>1234567890</xml-fragment>". */ - public static XmlPositiveInteger parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a File. */ - public static XmlPositiveInteger parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a File. */ - public static XmlPositiveInteger parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a URL. */ - public static XmlPositiveInteger parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a URL. */ - public static XmlPositiveInteger parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from an InputStream. */ - public static XmlPositiveInteger parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from an InputStream. */ - public static XmlPositiveInteger parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a Reader. */ - public static XmlPositiveInteger parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a Reader. */ - public static XmlPositiveInteger parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a DOM Node. */ - public static XmlPositiveInteger parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from a DOM Node. */ - public static XmlPositiveInteger parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlPositiveInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlPositiveInteger parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlPositiveInteger} fragment from an XMLStreamReader. */ - public static XmlPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlPositiveInteger} fragment from an XMLStreamReader. */ - public static XmlPositiveInteger parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlPositiveInteger) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlQName.java b/src/xmlpublic/org/apache/xmlbeans/XmlQName.java deleted file mode 100644 index 69993be..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlQName.java +++ /dev/null @@ -1,159 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import javax.xml.namespace.QName; - - -/** - * Corresponds to the XML Schema - * xs:QName type. - *

        - * A QName is the logical combination of an XML namespace URI and a localName. - * Although in an XML instance document, a QName appears as "prefix:localName", - * the logical value of a QName does NOT contain any information about the - * prefix, only the namespace URI to which the prefix maps. For example, - * two QNames "a:hello" and "b:hello" are perfectly equivalent if "a:" in - * the first instance maps to the same URI as "b:" in the second instance. - *

        - * Convertible to {@link javax.xml.namespace.QName}. - */ -public interface XmlQName extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_QName"); - - /** Returns this value as a {@link QName} */ - QName getQNameValue(); - /** Sets this value as a {@link QName} */ - void setQNameValue(QName name); - - /** - * Returns this value as a {@link QName} - * @deprecated replaced with {@link #getQNameValue} - **/ - QName qNameValue(); - /** - * Sets this value as a {@link QName} - * @deprecated replaced with {@link #setQNameValue} - **/ - void set(QName name); - - /** - * A class with methods for creating instances - * of {@link XmlQName}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlQName} */ - public static XmlQName newInstance() { - return (XmlQName) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlQName} */ - public static XmlQName newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlQName) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlQName} value */ - public static XmlQName newValue(Object obj) { - return (XmlQName) type.newValue( obj ); } - - /** Parses a {@link XmlQName} fragment from a String. For example: "<xml-fragment xmlns:x="http://openuri.org/">x:sample</xml-fragment>". */ - public static XmlQName parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlQName} fragment from a String. For example: "<xml-fragment xmlns:x="http://openuri.org/">x:sample</xml-fragment>". */ - public static XmlQName parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlQName} fragment from a File. */ - public static XmlQName parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlQName} fragment from a File. */ - public static XmlQName parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlQName} fragment from a URL. */ - public static XmlQName parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlQName} fragment from a URL. */ - public static XmlQName parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlQName} fragment from an InputStream. */ - public static XmlQName parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlQName} fragment from an InputStream. */ - public static XmlQName parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlQName} fragment from a Reader. */ - public static XmlQName parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlQName} fragment from a Reader. */ - public static XmlQName parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlQName} fragment from a DOM Node. */ - public static XmlQName parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlQName} fragment from a DOM Node. */ - public static XmlQName parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlQName} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlQName parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlQName} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlQName parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlQName} fragment from an XMLStreamReader. */ - public static XmlQName parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlQName) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlQName} fragment from an XMLStreamReader. */ - public static XmlQName parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlQName) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlShort.java b/src/xmlpublic/org/apache/xmlbeans/XmlShort.java deleted file mode 100644 index db5a62a..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlShort.java +++ /dev/null @@ -1,150 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:short type. - * One of the derived types based on xs:decimal. - *

        - * Naturally, convertible to a Java short. - */ -public interface XmlShort extends XmlInt -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_short"); - - /** Returns this value as a short */ - public short getShortValue(); - /** Sets this value as a short */ - public void setShortValue(short s); - - /** - * Returns this value as a short - * @deprecated replaced with {@link #getShortValue} - **/ - public short shortValue(); - /** - * Sets this value as a short - * @deprecated replaced with {@link #setShortValue} - **/ - public void set(short s); - - /** - * A class with methods for creating instances - * of {@link XmlShort}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlShort} */ - public static XmlShort newInstance() { - return (XmlShort) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlShort} */ - public static XmlShort newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlShort) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlShort} value */ - public static XmlShort newValue(Object obj) { - return (XmlShort) type.newValue( obj ); } - - /** Parses a {@link XmlShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". */ - public static XmlShort parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". */ - public static XmlShort parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlShort} fragment from a File. */ - public static XmlShort parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlShort} fragment from a File. */ - public static XmlShort parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlShort} fragment from a URL. */ - public static XmlShort parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlShort} fragment from a URL. */ - public static XmlShort parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlShort} fragment from an InputStream. */ - public static XmlShort parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlShort} fragment from an InputStream. */ - public static XmlShort parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlShort} fragment from a Reader. */ - public static XmlShort parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlShort} fragment from a Reader. */ - public static XmlShort parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlShort} fragment from a DOM Node. */ - public static XmlShort parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlShort} fragment from a DOM Node. */ - public static XmlShort parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlShort} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlShort parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlShort} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlShort parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlShort} fragment from an XMLStreamReader. */ - public static XmlShort parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlShort) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlShort} fragment from an XMLStreamReader. */ - public static XmlShort parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlShort) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlSimpleList.java b/src/xmlpublic/org/apache/xmlbeans/XmlSimpleList.java deleted file mode 100644 index cde96f8..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlSimpleList.java +++ /dev/null @@ -1,188 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import java.util.Iterator; -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -/** - * The immutable {@link List} returned for XML simple list values. - * - * XmlSimpleList implements an equals() and hashCode() that compare list - * contents, so two XmlSimpleLists are the same if they have the same - * values in the same order. - */ -public class XmlSimpleList implements List, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private List underlying; - - /** - * Constructs an immutable XmlSimpleList that wraps (does not copy) - * the given {@link List}. All non-mutating methods delegate to - * the underlying List instance. - */ - public XmlSimpleList(List list) { this.underlying = list; } - - /** Returns the number of elements in this list. */ - public int size() { return underlying.size(); } - /** True if the list is empty. */ - public boolean isEmpty() { return underlying.isEmpty(); } - /** True if the list is contains an object equal to o. */ - public boolean contains(Object o) { return underlying.contains(o); } - /** True if the list is contains all the objects in the given collection. */ - public boolean containsAll(Collection coll) { return underlying.containsAll(coll); } - /** Copies the collection to an array. */ - public Object[] toArray() { return underlying.toArray(); } - /** Copies the collection to an array of a specified type. */ - public Object[] toArray(Object[] a) { return underlying.toArray(a); } - - /** Unsupported because this list is immutable. */ - public boolean add(Object o) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public boolean addAll(Collection coll) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public boolean remove(Object o) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public boolean removeAll(Collection coll) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public boolean retainAll(Collection coll) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public void clear() { throw new UnsupportedOperationException(); } - - /** Returns the object at the specified position in this list. */ - public Object get(int index) { return underlying.get(index); } - /** Unsupported because this list is immutable. */ - public Object set(int index, Object element) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public void add(int index, Object element) { throw new UnsupportedOperationException(); } - /** Unsupported because this list is immutable. */ - public Object remove(int index) { throw new UnsupportedOperationException(); } - /** Returns index of the first occurance of an object equal to o. */ - public int indexOf(Object o) { return underlying.indexOf(o); } - /** Returns index of the last occurance of an object equal to o. */ - public int lastIndexOf(Object o) { return underlying.lastIndexOf(o); } - /** Unsupported because this list is immutable. */ - public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } - /** Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. */ - public List subList(int from, int to) { return new XmlSimpleList(underlying.subList(from, to)); } - - /** Returns an iterator over the elements in this list in proper sequence. */ - public Iterator iterator() - { - return new Iterator() - { - Iterator i = underlying.iterator(); - public boolean hasNext() { return i.hasNext(); } - public Object next() { return i.next(); } - public void remove() { throw new UnsupportedOperationException(); } - }; - } - - /** Returns a list iterator of the elements in this list in proper sequence. */ - public ListIterator listIterator() { return listIterator(0); } - /** Returns a list iterator of the elements in this list in proper sequence, starting at the specified position in this list. */ - public ListIterator listIterator(final int index) - { - return new ListIterator() - { - ListIterator i = underlying.listIterator(index); - - public boolean hasNext() { return i.hasNext(); } - public Object next() { return i.next(); } - public boolean hasPrevious(){ return i.hasPrevious(); } - public Object previous() { return i.previous(); } - public int nextIndex() { return i.nextIndex(); } - public int previousIndex() { return i.previousIndex(); } - - public void remove() { throw new UnsupportedOperationException(); } - public void set(Object o) { throw new UnsupportedOperationException(); } - public void add(Object o) { throw new UnsupportedOperationException(); } - }; - } - - private String stringValue(Object o) - { - if (o instanceof SimpleValue) - return ((SimpleValue)o).stringValue(); - return o.toString(); - } - - /** - * Returns a space-separated list of the string representations of all - * the items in the list. For most lists, this is a valid xml lexical - * value for the list. (The notable exception is a list of QNames.) - */ - public String toString() - { - int size = underlying.size(); - if (size == 0) - return ""; - String first = stringValue(underlying.get(0)); - if (size == 1) - return first; - StringBuffer result = new StringBuffer(first); - for (int i = 1; i < size; i++) - { - result.append(' '); - result.append(stringValue(underlying.get(i))); - } - return result.toString(); - } - - /** - * Two XmlSimpleLists are equal if all their items are equal. - * (They must have the same number of items, and the items must be in - * the same order.) - */ - public boolean equals(Object o) - { - if (this == o) return true; - if (!(o instanceof XmlSimpleList)) return false; - final XmlSimpleList xmlSimpleList = (XmlSimpleList)o; - List underlying2 = xmlSimpleList.underlying; - int size = underlying.size(); - if (size != underlying2.size()) - return false; - for (int i = 0; i < size; i++) - { - Object item = underlying.get(i); - Object item2 = underlying2.get(i); - if (item == null ? item2 != null : !item.equals(item2)) - return false; - } - return true; - } - - /** - * Combines the hash codes of all the list items. - */ - public int hashCode() - { - int size = underlying.size(); - int hash = 0; - for (int i = 0; i < size; i++) - { - Object item = underlying.get(i); - hash *= 19; - hash += item.hashCode(); - } - return hash; - } -} diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlString.java b/src/xmlpublic/org/apache/xmlbeans/XmlString.java deleted file mode 100644 index e0bfd15..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlString.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:string type. - *

        - * A basic string in XML schema is not whitespace normalized. If you - * want your string type to be insensitive to variations in runs of - * whitespace, consider using - * xs:token - * (aka {@link XmlToken}) instead. - * To forbid whitespace and permit just alphanumeric and other - * common identifier characters consider - * xs:NMTOKEN - * (aka {@link XmlNMTOKEN}) instead. - *

        - * Convertible to {@link String}. - */ -public interface XmlString extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_string"); - - /** - * A class with methods for creating instances - * of {@link XmlString}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlString} */ - public static XmlString newInstance() { - return (XmlString) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlString} */ - public static XmlString newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlString) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlString} value */ - public static XmlString newValue(Object obj) { - return (XmlString) type.newValue( obj ); } - - /** Parses a {@link XmlString} fragment from a String. For example: "<xml-fragment> arbitrary string </xml-fragment>". */ - public static XmlString parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlString} fragment from a String. For example: "<xml-fragment> arbitrary string </xml-fragment>". */ - public static XmlString parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlString} fragment from a File. */ - public static XmlString parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlString} fragment from a File. */ - public static XmlString parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlString} fragment from a URL. */ - public static XmlString parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlString} fragment from a URL. */ - public static XmlString parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlString} fragment from an InputStream. */ - public static XmlString parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlString} fragment from an InputStream. */ - public static XmlString parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlString} fragment from a Reader. */ - public static XmlString parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlString} fragment from a Reader. */ - public static XmlString parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlString} fragment from a DOM Node. */ - public static XmlString parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlString} fragment from a DOM Node. */ - public static XmlString parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlString} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlString parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlString} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlString parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlString} fragment from an XMLStreamReader. */ - public static XmlString parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlString) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlString} fragment from an XMLStreamReader. */ - public static XmlString parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlString) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlTime.java b/src/xmlpublic/org/apache/xmlbeans/XmlTime.java deleted file mode 100644 index d0c6267..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlTime.java +++ /dev/null @@ -1,171 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.util.Calendar; - - -/** - * Corresponds to the XML Schema - * xs:time type. - * A gDay specifies only a day-of-month. - *

        - * Convertible to {@link Calendar} or {@link GDate}. - * - * @see XmlCalendar - * @see GDate - */ -public interface XmlTime extends XmlAnySimpleType -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_time"); - - /** Returns this value as a {@link Calendar} */ - Calendar getCalendarValue(); - /** Sets this value as a {@link Calendar} */ - void setCalendarValue(Calendar c); - /** Returns this value as a {@link GDate} */ - GDate getGDateValue(); - /** Sets this value as a {@link GDateSpecification} */ - void setGDateValue(GDate gd); - - /** - * Returns this value as a {@link Calendar} - * @deprecated replaced with {@link #getCalendarValue} - **/ - Calendar calendarValue(); - /** - * Sets this value as a {@link Calendar} - * @deprecated replaced with {@link #setCalendarValue} - **/ - void set(Calendar c); - /** - * Returns this value as a {@link GDate} - * @deprecated replaced with {@link #getGDateValue} - **/ - GDate gDateValue(); - /** - * Sets this value as a {@link GDateSpecification} - * @deprecated replaced with {@link #setGDateValue} - **/ - void set(GDateSpecification gd); - - - /** - * A class with methods for creating instances - * of {@link XmlTime}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlTime} */ - public static XmlTime newInstance() { - return (XmlTime) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlTime} */ - public static XmlTime newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlTime) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlTime} value */ - public static XmlTime newValue(Object obj) { - return (XmlTime) type.newValue( obj ); } - - /** Parses a {@link XmlTime} fragment from a String. For example: "<xml-fragment>12:00:00</xml-fragment>". */ - public static XmlTime parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlTime} fragment from a String. For example: "<xml-fragment>12:00:00</xml-fragment>". */ - public static XmlTime parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlTime} fragment from a File. */ - public static XmlTime parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlTime} fragment from a File. */ - public static XmlTime parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlTime} fragment from a URL. */ - public static XmlTime parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlTime} fragment from a URL. */ - public static XmlTime parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlTime} fragment from an InputStream. */ - public static XmlTime parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlTime} fragment from an InputStream. */ - public static XmlTime parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlTime} fragment from a Reader. */ - public static XmlTime parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlTime} fragment from a Reader. */ - public static XmlTime parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlTime} fragment from a DOM Node. */ - public static XmlTime parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlTime} fragment from a DOM Node. */ - public static XmlTime parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlTime} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlTime parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlTime} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlTime parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlTime} fragment from an XMLStreamReader. */ - public static XmlTime parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlTime) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlTime} fragment from an XMLStreamReader. */ - public static XmlTime parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlTime) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlToken.java b/src/xmlpublic/org/apache/xmlbeans/XmlToken.java deleted file mode 100644 index 8d820a8..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlToken.java +++ /dev/null @@ -1,147 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:token type. - * One of the derived types based on xs:string. - *

        - * A token is XML's best representation for a "whitespace insensitive string." - * All carriage returns, linefeeds, and tabs are converted to ordinary space - * characters (as with xs:normalizedString), - * and furthermore, all contiguous runs of space are collapsed to single spaces, - * and leading and trailing spaces are trimmed. - *

        - * If you want "  high  priority  " - * to be equivalent to "high priority", you should consider - * using xs:token or a subtype of xs:token. - *

        - * When the {@link #stringValue} is obtained from an XmlToken, the normalized, - * trimmed, whitespace collapsed value is returned. - *

        - * Convertible to {@link String}. - */ -public interface XmlToken extends XmlNormalizedString -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_token"); - - /** - * A class with methods for creating instances - * of {@link XmlToken}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlToken} */ - public static XmlToken newInstance() { - return (XmlToken) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlToken} */ - public static XmlToken newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlToken) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlToken} value */ - public static XmlToken newValue(Object obj) { - return (XmlToken) type.newValue( obj ); } - - /** Parses a {@link XmlToken} fragment from a String. For example: "<xml-fragment>string to collapse</xml-fragment>". */ - public static XmlToken parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlToken} fragment from a String. For example: "<xml-fragment>string to collapse</xml-fragment>". */ - public static XmlToken parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlToken} fragment from a File. */ - public static XmlToken parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlToken} fragment from a File. */ - public static XmlToken parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlToken} fragment from a URL. */ - public static XmlToken parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlToken} fragment from a URL. */ - public static XmlToken parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlToken} fragment from an InputStream. */ - public static XmlToken parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlToken} fragment from an InputStream. */ - public static XmlToken parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlToken} fragment from a Reader. */ - public static XmlToken parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlToken} fragment from a Reader. */ - public static XmlToken parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlToken} fragment from a DOM Node. */ - public static XmlToken parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlToken} fragment from a DOM Node. */ - public static XmlToken parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlToken} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlToken parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlToken} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlToken parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlToken} fragment from an XMLStreamReader. */ - public static XmlToken parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlToken) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlToken} fragment from an XMLStreamReader. */ - public static XmlToken parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlToken) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedByte.java b/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedByte.java deleted file mode 100644 index 49b889f..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedByte.java +++ /dev/null @@ -1,152 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:unsignedByte type. - * One of the derived types based on xs:decimal. - *

        - * Verified to be in the range 0..255 when validating. - *

        - * As suggested by JAXB, convertible to Java short. - */ -public interface XmlUnsignedByte extends XmlUnsignedShort -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedByte"); - - /** Returns this value as a short */ - public short getShortValue(); - /** Sets this value as a short */ - public void setShortValue(short s); - - /** - * Returns this value as a short - * @deprecated replaced with {@link #getShortValue} - **/ - public short shortValue(); - /** - * Sets this value as a short - * @deprecated replaced with {@link #setShortValue} - **/ - public void set(short s); - - /** - * A class with methods for creating instances - * of {@link XmlUnsignedByte}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlUnsignedByte} */ - public static XmlUnsignedByte newInstance() { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlUnsignedByte} */ - public static XmlUnsignedByte newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlUnsignedByte} value */ - public static XmlUnsignedByte newValue(Object obj) { - return (XmlUnsignedByte) type.newValue( obj ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". */ - public static XmlUnsignedByte parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a String. For example: "<xml-fragment>123</xml-fragment>". */ - public static XmlUnsignedByte parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a File. */ - public static XmlUnsignedByte parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a File. */ - public static XmlUnsignedByte parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a URL. */ - public static XmlUnsignedByte parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a URL. */ - public static XmlUnsignedByte parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from an InputStream. */ - public static XmlUnsignedByte parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from an InputStream. */ - public static XmlUnsignedByte parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a Reader. */ - public static XmlUnsignedByte parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a Reader. */ - public static XmlUnsignedByte parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a DOM Node. */ - public static XmlUnsignedByte parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from a DOM Node. */ - public static XmlUnsignedByte parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedByte parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedByte parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlUnsignedByte} fragment from an XMLStreamReader. */ - public static XmlUnsignedByte parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlUnsignedByte} fragment from an XMLStreamReader. */ - public static XmlUnsignedByte parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlUnsignedByte) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedInt.java b/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedInt.java deleted file mode 100644 index f124221..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedInt.java +++ /dev/null @@ -1,152 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:unsignedInt type. - * One of the derived types based on xs:decimal. - *

        - * Verified to be in the range 0..4294967295 when validating. - *

        - * Convertible to Java long. - */ -public interface XmlUnsignedInt extends XmlUnsignedLong -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedInt"); - - /** Returns this value as a long */ - long getLongValue(); - /** Sets this value as a long */ - void setLongValue(long v); - - /** - * Returns this value as a long - * @deprecated replaced with {@link #getLongValue} - **/ - long longValue(); - /** - * Sets this value as a long - * @deprecated replaced with {@link #setLongValue} - **/ - void set(long v); - - /** - * A class with methods for creating instances - * of {@link XmlUnsignedInt}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlUnsignedInt} */ - public static XmlUnsignedInt newInstance() { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlUnsignedInt} */ - public static XmlUnsignedInt newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlUnsignedInt} value */ - public static XmlUnsignedInt newValue(Object obj) { - return (XmlUnsignedInt) type.newValue( obj ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". */ - public static XmlUnsignedInt parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a String. For example: "<xml-fragment>1234567</xml-fragment>". */ - public static XmlUnsignedInt parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a File. */ - public static XmlUnsignedInt parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a File. */ - public static XmlUnsignedInt parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a URL. */ - public static XmlUnsignedInt parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a URL. */ - public static XmlUnsignedInt parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from an InputStream. */ - public static XmlUnsignedInt parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from an InputStream. */ - public static XmlUnsignedInt parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a Reader. */ - public static XmlUnsignedInt parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a Reader. */ - public static XmlUnsignedInt parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a DOM Node. */ - public static XmlUnsignedInt parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from a DOM Node. */ - public static XmlUnsignedInt parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedInt parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedInt parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlUnsignedInt} fragment from an XMLStreamReader. */ - public static XmlUnsignedInt parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlUnsignedInt} fragment from an XMLStreamReader. */ - public static XmlUnsignedInt parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlUnsignedInt) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedLong.java b/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedLong.java deleted file mode 100644 index a507ce7..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedLong.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -import java.math.BigInteger; - - -/** - * Corresponds to the XML Schema - * xs:unsignedLong type. - * One of the derived types based on xs:decimal. - *

        - * Verified to be in the range 0..264-1 when validating. - *

        - * Convertible to {@link BigInteger}. - */ -public interface XmlUnsignedLong extends XmlNonNegativeInteger -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedLong"); - - /** - * A class with methods for creating instances - * of {@link XmlUnsignedLong}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlUnsignedLong} */ - public static XmlUnsignedLong newInstance() { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlUnsignedLong} */ - public static XmlUnsignedLong newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlUnsignedLong} value */ - public static XmlUnsignedLong newValue(Object obj) { - return (XmlUnsignedLong) type.newValue( obj ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". */ - public static XmlUnsignedLong parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a String. For example: "<xml-fragment>123456789</xml-fragment>". */ - public static XmlUnsignedLong parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a File. */ - public static XmlUnsignedLong parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a File. */ - public static XmlUnsignedLong parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a URL. */ - public static XmlUnsignedLong parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a URL. */ - public static XmlUnsignedLong parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from an InputStream. */ - public static XmlUnsignedLong parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from an InputStream. */ - public static XmlUnsignedLong parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a Reader. */ - public static XmlUnsignedLong parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a Reader. */ - public static XmlUnsignedLong parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a DOM Node. */ - public static XmlUnsignedLong parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from a DOM Node. */ - public static XmlUnsignedLong parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedLong parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedLong parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlUnsignedLong} fragment from an XMLStreamReader. */ - public static XmlUnsignedLong parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlUnsignedLong} fragment from an XMLStreamReader. */ - public static XmlUnsignedLong parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlUnsignedLong) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedShort.java b/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedShort.java deleted file mode 100644 index 9a6af78..0000000 --- a/src/xmlpublic/org/apache/xmlbeans/XmlUnsignedShort.java +++ /dev/null @@ -1,152 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans; - -import javax.xml.stream.XMLStreamReader; - - -/** - * Corresponds to the XML Schema - * xs:unsignedShort type. - * One of the derived types based on xs:decimal. - *

        - * Verified to be in the range 0..65535 when validating. - *

        - * Convertible to a Java int. - */ -public interface XmlUnsignedShort extends XmlUnsignedInt -{ - /** The constant {@link SchemaType} object representing this schema type. */ - public static final SchemaType type = XmlBeans.getBuiltinTypeSystem().typeForHandle("_BI_unsignedShort"); - - /** Returns this value as an int */ - int getIntValue(); - /** Sets this value as an int */ - void setIntValue(int v); - - /** - * Returns this value as an int - * @deprecated replaced with {@link #getIntValue} - **/ - int intValue(); - /** - * Sets this value as an int - * @deprecated replaced with {@link #setIntValue} - **/ - void set(int v); - - /** - * A class with methods for creating instances - * of {@link XmlUnsignedShort}. - */ - public static final class Factory - { - /** Creates an empty instance of {@link XmlUnsignedShort} */ - public static XmlUnsignedShort newInstance() { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().newInstance( type, null ); } - - /** Creates an empty instance of {@link XmlUnsignedShort} */ - public static XmlUnsignedShort newInstance(org.apache.xmlbeans.XmlOptions options) { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().newInstance( type, options ); } - - /** Creates an immutable {@link XmlUnsignedShort} value */ - public static XmlUnsignedShort newValue(Object obj) { - return (XmlUnsignedShort) type.newValue( obj ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". */ - public static XmlUnsignedShort parse(java.lang.String s) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( s, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a String. For example: "<xml-fragment>12345</xml-fragment>". */ - public static XmlUnsignedShort parse(java.lang.String s, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( s, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a File. */ - public static XmlUnsignedShort parse(java.io.File f) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( f, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a File. */ - public static XmlUnsignedShort parse(java.io.File f, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( f, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a URL. */ - public static XmlUnsignedShort parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( u, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a URL. */ - public static XmlUnsignedShort parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( u, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from an InputStream. */ - public static XmlUnsignedShort parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( is, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from an InputStream. */ - public static XmlUnsignedShort parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( is, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a Reader. */ - public static XmlUnsignedShort parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( r, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a Reader. */ - public static XmlUnsignedShort parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( r, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a DOM Node. */ - public static XmlUnsignedShort parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( node, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from a DOM Node. */ - public static XmlUnsignedShort parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( node, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedShort parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( xis, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from an XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static XmlUnsignedShort parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( xis, type, options ); } - - /** Parses a {@link XmlUnsignedShort} fragment from an XMLStreamReader. */ - public static XmlUnsignedShort parse(javax.xml.stream.XMLStreamReader xsr) throws org.apache.xmlbeans.XmlException { - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( xsr, type, null ); } - - /** Parses a {@link XmlUnsignedShort} fragment from an XMLStreamReader. */ - public static XmlUnsignedShort parse(javax.xml.stream.XMLStreamReader xsr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException{ - return (XmlUnsignedShort) XmlBeans.getContextTypeLoader().parse( xsr, type, options ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } - - /** Returns a validating XMLInputStream. - * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API. - */ - public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { - return XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } - - private Factory() { } // No instance of this class allowed - } -} - diff --git a/src/xpath_xquery/QueryInterface.g b/src/xpath_xquery/QueryInterface.g deleted file mode 100644 index ba74206..0000000 --- a/src/xpath_xquery/QueryInterface.g +++ /dev/null @@ -1 +0,0 @@ -org.apache.xmlbeans.impl.xquery.saxon.XBeansXQuery diff --git a/src/xpath_xquery/SelectPathInterface.g b/src/xpath_xquery/SelectPathInterface.g deleted file mode 100644 index b26a145..0000000 --- a/src/xpath_xquery/SelectPathInterface.g +++ /dev/null @@ -1 +0,0 @@ -org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath diff --git a/src/xpath_xquery/org/apache/xmlbeans/impl/xpath/saxon/XBeansXPath.java b/src/xpath_xquery/org/apache/xmlbeans/impl/xpath/saxon/XBeansXPath.java deleted file mode 100644 index f210e95..0000000 --- a/src/xpath_xquery/org/apache/xmlbeans/impl/xpath/saxon/XBeansXPath.java +++ /dev/null @@ -1,173 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.xpath.saxon; - -import java.util.List; -import java.util.Map; -import java.util.ListIterator; - -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.TransformerException; - -import org.w3c.dom.Node; - -import net.sf.saxon.Configuration; -import net.sf.saxon.dom.NodeWrapper; -import net.sf.saxon.om.NodeInfo; -import net.sf.saxon.om.VirtualNode; -import net.sf.saxon.om.Item; -import net.sf.saxon.value.Value; -import net.sf.saxon.sxpath.XPathEvaluator; -import net.sf.saxon.sxpath.XPathExpression; -import net.sf.saxon.sxpath.IndependentContext; -import net.sf.saxon.sxpath.XPathDynamicContext; -import net.sf.saxon.sxpath.XPathVariable; - -import org.apache.xmlbeans.impl.store.PathDelegate; - -public class XBeansXPath - implements PathDelegate.SelectPathInterface -{ - private Object[] namespaceMap; - private String path; - private String contextVar; - private String defaultNS; - - /** - * Construct given an XPath expression string. - * @param path The XPath expression - * @param contextVar The name of the context variable - * @param namespaceMap a map of prefix/uri bindings for NS support - * @param defaultNS the uri for the default element NS, if any - */ - public XBeansXPath(String path, String contextVar, - Map namespaceMap, String defaultNS) - { - this.path = path; - this.contextVar = contextVar; - this.defaultNS = defaultNS; - this.namespaceMap = namespaceMap.entrySet().toArray(); - } - - /** - * Select all nodes that are selectable by this XPath - * expression. If multiple nodes match, multiple nodes - * will be returned. - *

        - *

        - * NOTE: In most cases, nodes will be returned - * in document-order, as defined by the XML Canonicalization - * specification. The exception occurs when using XPath - * expressions involving the union operator - * (denoted with the pipe '|' character). - *

        - *

        - *

        - * NOTE: Param node must be a DOM node which will be used - * during the xpath execution and iteration through the results. - * A call of node.dispose() must be done after reading all results. - *

        - * - * @param node The node, nodeset or Context object for evaluation. - * This value can be null. - * @return The List of all items selected - * by this XPath expression. - */ - public List selectNodes(Object node) - { - try - { - Node contextNode = (Node)node; - XPathEvaluator xpe = new XPathEvaluator(); - Configuration config = new Configuration(); - config.setDOMLevel(2); - config.setTreeModel(net.sf.saxon.event.Builder.STANDARD_TREE); - IndependentContext sc = new IndependentContext(config); - // Declare ns bindings - if (defaultNS != null) - sc.setDefaultElementNamespace(defaultNS); - - for (int i = 0; i < namespaceMap.length; i++) - { - Map.Entry entry = (Map.Entry) namespaceMap[i]; - sc.declareNamespace((String) entry.getKey(), - (String) entry.getValue()); - } - xpe.setStaticContext(sc); - XPathVariable thisVar = xpe.declareVariable("", contextVar); - XPathExpression xpath = xpe.createExpression(path); - NodeInfo contextItem = - //config.buildDocument(new DOMSource(contextNode)); - config.unravel(new DOMSource(contextNode)); - XPathDynamicContext dc = xpath.createDynamicContext(null); - dc.setContextItem(contextItem); - dc.setVariable(thisVar, contextItem); - - List saxonNodes = xpath.evaluate(dc); - for (ListIterator it = saxonNodes.listIterator(); it.hasNext(); ) - { - Object o = it.next(); - if (o instanceof NodeInfo) - { - if (o instanceof NodeWrapper) - { - Node n = getUnderlyingNode((NodeWrapper)o); - it.set(n); - } - else - { - it.set(((NodeInfo)o).getStringValue()); - } - } - else if (o instanceof Item) - it.set(Value.convertToJava((Item)o)); - } - return saxonNodes; - } - catch (TransformerException e) - { - throw new RuntimeException(e); - } - } - - public List selectPath(Object node) - { - return selectNodes(node); - } - - /** - * According to the Saxon javadoc: - * getUnderlyingNode in NodeWrapper implements - * the method specified in the interface VirtualNode, and - * the specification of the latter says that it may return another - * VirtualNode, and you may have to drill down through - * several layers of wrapping. - * To be safe, this method is provided to drill down through multiple - * layers of wrapping. - * @param v The VirtualNode - * @return The underlying node - */ - private static Node getUnderlyingNode(VirtualNode v) - { - Object o = v; - while (o instanceof VirtualNode) - { - o = ((VirtualNode)o).getUnderlyingNode(); - } - return (Node)o; - } - -} diff --git a/src/xpath_xquery/org/apache/xmlbeans/impl/xquery/saxon/XBeansXQuery.java b/src/xpath_xquery/org/apache/xmlbeans/impl/xquery/saxon/XBeansXQuery.java deleted file mode 100644 index de93503..0000000 --- a/src/xpath_xquery/org/apache/xmlbeans/impl/xquery/saxon/XBeansXQuery.java +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.xmlbeans.impl.xquery.saxon; - -import java.util.List; -import java.util.Map; -import java.util.Iterator; -import java.util.ListIterator; - -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.TransformerException; - -import org.w3c.dom.Node; - -import net.sf.saxon.Configuration; -import net.sf.saxon.dom.NodeOverNodeInfo; -import net.sf.saxon.om.NodeInfo; -import net.sf.saxon.query.DynamicQueryContext; -import net.sf.saxon.query.StaticQueryContext; -import net.sf.saxon.query.XQueryExpression; - -import org.apache.xmlbeans.XmlRuntimeException; -import org.apache.xmlbeans.XmlTokenSource; -import org.apache.xmlbeans.impl.store.QueryDelegate; - -public class XBeansXQuery - implements QueryDelegate.QueryInterface -{ - private XQueryExpression xquery; - private String contextVar; - private Configuration config; - - /** - * Construct given an XQuery expression string. - * @param query The XQuery expression - * @param contextVar The name of the context variable - * @param boundary The offset of the end of the prolog - */ - public XBeansXQuery(String query, String contextVar, Integer boundary) - { - config = new Configuration(); - config.setDOMLevel(2); - config.setTreeModel(net.sf.saxon.event.Builder.STANDARD_TREE); - StaticQueryContext sc = new StaticQueryContext(config); - this.contextVar = contextVar; - int bdry = boundary.intValue(); - //Saxon requires external variables at the end of the prolog... - query = (bdry == 0) ? - "declare variable $" + - contextVar + " external;" + query : - query.substring(0, bdry) + - "declare variable $" + - contextVar + " external;" + - query.substring(bdry); - try - { - xquery = sc.compileQuery(query); - } - catch (TransformerException e) - { - throw new XmlRuntimeException(e); - } - } - - public List execQuery(Object node, Map variableBindings) - { - try - { - Node contextNode = (Node)node; - NodeInfo contextItem = - config.buildDocument(new DOMSource(contextNode)); - //config.unravel(new DOMSource(contextNode)); - DynamicQueryContext dc = new DynamicQueryContext(config); - dc.setContextItem(contextItem); - dc.setParameter(contextVar, contextItem); - // Set the other variables - if (variableBindings != null) - { - for (Iterator it = variableBindings.entrySet().iterator(); - it.hasNext(); ) - { - Map.Entry entry = (Map.Entry)it.next(); - String key = (String)entry.getKey(); - Object value = entry.getValue(); - if (value instanceof XmlTokenSource) - { - Node paramObject = ((XmlTokenSource)value).getDomNode(); - dc.setParameter(key, paramObject); - } - else if (value instanceof String) - dc.setParameter(key, value); - } - } - - List saxonNodes = xquery.evaluate(dc); - for (ListIterator it = saxonNodes.listIterator(); it.hasNext(); ) - { - Object o = it.next(); - if(o instanceof NodeInfo) - { - Node n = NodeOverNodeInfo.wrap((NodeInfo)o); - it.set(n); - } - } - return saxonNodes; - } - catch (TransformerException e) - { - throw new RuntimeException("Error binding " + contextVar, e); - } - } -} diff --git a/src/zipcompare/zipcompare/ZipCompare.java b/src/zipcompare/zipcompare/ZipCompare.java deleted file mode 100644 index 27f902b..0000000 --- a/src/zipcompare/zipcompare/ZipCompare.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package zipcompare; - -import java.util.zip.ZipFile; -import java.util.zip.ZipEntry; -import java.util.*; -import java.io.IOException; -import java.io.InputStream; - -public class ZipCompare -{ - public static void main(String[] args) - { - if (args.length != 2) - { - System.out.println("Usage: zipcompare [file1] [file2]"); - System.exit(1); - } - - ZipFile file1; - try { file1 = new ZipFile(args[0]); } - catch (IOException e) { System.out.println("Could not open zip file " + args[0] + ": " + e); System.exit(1); return; } - - ZipFile file2; - try { file2 = new ZipFile(args[1]); } - catch (IOException e) { System.out.println("Could not open zip file " + args[0] + ": " + e); System.exit(1); return; } - - System.out.println("Comparing " + args[0] + " with " + args[1] + ":"); - - Set set1 = new LinkedHashSet(); - for (Enumeration e = file1.entries(); e.hasMoreElements(); ) - set1.add(((ZipEntry)e.nextElement()).getName()); - - Set set2 = new LinkedHashSet(); - for (Enumeration e = file2.entries(); e.hasMoreElements(); ) - set2.add(((ZipEntry)e.nextElement()).getName()); - - int errcount = 0; - int filecount = 0; - for (Iterator i = set1.iterator(); i.hasNext(); ) - { - String name = (String)i.next(); - if (!set2.contains(name)) - { - System.out.println(name + " not found in " + args[1]); - errcount += 1; - continue; - } - try - { - set2.remove(name); - if (!streamsEqual(file1.getInputStream(file1.getEntry(name)), file2.getInputStream(file2.getEntry(name)))) - { - System.out.println(name + " does not match"); - errcount += 1; - continue; - } - } - catch (Exception e) - { - System.out.println(name + ": IO Error " + e); - e.printStackTrace(); - errcount += 1; - continue; - } - filecount += 1; - } - for (Iterator i = set2.iterator(); i.hasNext(); ) - { - String name = (String)i.next(); - System.out.println(name + " not found in " + args[0]); - errcount += 1; - } - System.out.println(filecount + " entries matched"); - if (errcount > 0) - { - System.out.println(errcount + " entries did not match"); - System.exit(1); - } - System.exit(0); - } - - static boolean streamsEqual(InputStream stream1, InputStream stream2) throws IOException - { - byte[] buf1 = new byte[4096]; - byte[] buf2 = new byte[4096]; - boolean done1 = false; - boolean done2 = false; - - try - { - while (!done1) - { - int off1 = 0; - int off2 = 0; - - while (off1 < buf1.length) - { - int count = stream1.read(buf1, off1, buf1.length - off1); - if (count < 0) - { - done1 = true; - break; - } - off1 += count; - } - while (off2 < buf2.length) - { - int count = stream2.read(buf2, off2, buf2.length - off2); - if (count < 0) - { - done2 = true; - break; - } - off2 += count; - } - if (off1 != off2 || done1 != done2) - return false; - for (int i = 0; i < off1; i++) - { - if (buf1[i] != buf2[i]) - return false; - } - } - return true; - } - finally { stream1.close(); stream2.close(); } - } -} diff --git a/test/cases/schema/appview/Add_AcctSiebel7.xml b/test/cases/schema/appview/Add_AcctSiebel7.xml deleted file mode 100644 index 869a2d2..0000000 --- a/test/cases/schema/appview/Add_AcctSiebel7.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - USD - - - - - - - Bea Demo - - Commercial - - - - Default Organization - - - - - - NY - NY - USA - 9876543211 - - 1234567890 - 07301 - - NY - 2 Madision Square - - - - - - diff --git a/test/cases/xbean/ValidatingStream/CarLocationMessage-inv.xml b/test/cases/xbean/ValidatingStream/CarLocationMessage-inv.xml deleted file mode 100755 index bc751d9..0000000 --- a/test/cases/xbean/ValidatingStream/CarLocationMessage-inv.xml +++ /dev/null @@ -1,38 +0,0 @@ - - FLEETNAME - CSXT - - - GATX - 123456 - L - - 2001-03-23 - - - P - - Q12345 - - DALLAS - TX - - CSXT - - - DALLAS - TX - - - - - DALLAS - TX - - 2001-03-23 - - P - - Y - - diff --git a/test/cases/xbean/ValidatingStream/CarLocationMessage.xml b/test/cases/xbean/ValidatingStream/CarLocationMessage.xml deleted file mode 100755 index bc751d9..0000000 --- a/test/cases/xbean/ValidatingStream/CarLocationMessage.xml +++ /dev/null @@ -1,38 +0,0 @@ - - FLEETNAME - CSXT - - - GATX - 123456 - L - - 2001-03-23 - - - P - - Q12345 - - DALLAS - TX - - CSXT - - - DALLAS - TX - - - - - DALLAS - TX - - 2001-03-23 - - P - - Y - - diff --git a/test/cases/xbean/ValidatingStream/Employees.xml b/test/cases/xbean/ValidatingStream/Employees.xml deleted file mode 100755 index 4575895..0000000 --- a/test/cases/xbean/ValidatingStream/Employees.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - Fred Jones - - 900 Aurora Ave. - Seattle - WA - 98115 - - - 2011 152nd Avenue NE - Redmond - WA - 98052 - - (425)555-5665 - (206)555-5555 - (206)555-4321 - - - Sally Smith - - 1430 Oak Place - Salem - OR - 97125 - - - 765 Main St. - Kaiser - OR - 97103 - - (503)555-3856 - (503)555-6951 - (503)555-5152 - - - Gladys Kravitz - - 1313 Mockingbird Lane - Seattle - WA - 98115 - - - 2011 152nd Avenue NE - Redmond - WA - 98052 - - (425)555-6897 - (206)555-6594 - (206)555-7894 - - diff --git a/test/cases/xbean/ValidatingStream/foo-inv.xml b/test/cases/xbean/ValidatingStream/foo-inv.xml deleted file mode 100644 index d4ccf72..0000000 --- a/test/cases/xbean/ValidatingStream/foo-inv.xml +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/foo.xsd b/test/cases/xbean/ValidatingStream/foo.xsd deleted file mode 100644 index 0f449c8..0000000 --- a/test/cases/xbean/ValidatingStream/foo.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - diff --git a/test/cases/xbean/ValidatingStream/global-attr.xml b/test/cases/xbean/ValidatingStream/global-attr.xml deleted file mode 100755 index 403af38..0000000 --- a/test/cases/xbean/ValidatingStream/global-attr.xml +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/location-inv.xml b/test/cases/xbean/ValidatingStream/location-inv.xml deleted file mode 100755 index 5c04fca..0000000 --- a/test/cases/xbean/ValidatingStream/location-inv.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - Bellevue - WA - 98033 - USA - NA - 1234 - - diff --git a/test/cases/xbean/ValidatingStream/location.xml b/test/cases/xbean/ValidatingStream/location.xml deleted file mode 100755 index b2a74bc..0000000 --- a/test/cases/xbean/ValidatingStream/location.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - Bellevue - WA - 98033 - USA - NA - 1234 - diff --git a/test/cases/xbean/ValidatingStream/location.xsd b/test/cases/xbean/ValidatingStream/location.xsd deleted file mode 100755 index cca1eea..0000000 --- a/test/cases/xbean/ValidatingStream/location.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/ValidatingStream/mixed-content-inv.xml b/test/cases/xbean/ValidatingStream/mixed-content-inv.xml deleted file mode 100755 index 2d0d277..0000000 --- a/test/cases/xbean/ValidatingStream/mixed-content-inv.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - Your Order is being Shipped. - John Doe - 1000 - Your expected Ship-date is: 2004-12-12 - Thank you for your order - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/mixed-content.xml b/test/cases/xbean/ValidatingStream/mixed-content.xml deleted file mode 100755 index 2d0d277..0000000 --- a/test/cases/xbean/ValidatingStream/mixed-content.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - Your Order is being Shipped. - John Doe - 1000 - Your expected Ship-date is: 2004-12-12 - Thank you for your order - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/mixed-content.xsd b/test/cases/xbean/ValidatingStream/mixed-content.xsd deleted file mode 100755 index 3ddf085..0000000 --- a/test/cases/xbean/ValidatingStream/mixed-content.xsd +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/nomixed-content-inv.xml b/test/cases/xbean/ValidatingStream/nomixed-content-inv.xml deleted file mode 100755 index 53be907..0000000 --- a/test/cases/xbean/ValidatingStream/nomixed-content-inv.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - Your Order is being Shipped. - John Doe - 1000 - Your expected Ship-date is: 2004-12-12 - Thank you for your order - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/numerals.xsd b/test/cases/xbean/ValidatingStream/numerals.xsd deleted file mode 100755 index 2168a18..0000000 --- a/test/cases/xbean/ValidatingStream/numerals.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person-frag.xml b/test/cases/xbean/ValidatingStream/person-frag.xml deleted file mode 100755 index bced09f..0000000 --- a/test/cases/xbean/ValidatingStream/person-frag.xml +++ /dev/null @@ -1,6 +0,0 @@ - - Person - Two - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person-frag2.xml b/test/cases/xbean/ValidatingStream/person-frag2.xml deleted file mode 100755 index c6252b0..0000000 --- a/test/cases/xbean/ValidatingStream/person-frag2.xml +++ /dev/null @@ -1,5 +0,0 @@ -Person - Two - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person-inv.xml b/test/cases/xbean/ValidatingStream/person-inv.xml deleted file mode 100755 index c1dde0a..0000000 --- a/test/cases/xbean/ValidatingStream/person-inv.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - Person - One - - - - Person - Two - - - - Person - Three - - - - diff --git a/test/cases/xbean/ValidatingStream/person-justname-inv.xml b/test/cases/xbean/ValidatingStream/person-justname-inv.xml deleted file mode 100755 index ed188e3..0000000 --- a/test/cases/xbean/ValidatingStream/person-justname-inv.xml +++ /dev/null @@ -1,6 +0,0 @@ - - Person - Two - M - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person-justname.xml b/test/cases/xbean/ValidatingStream/person-justname.xml deleted file mode 100755 index 48bd167..0000000 --- a/test/cases/xbean/ValidatingStream/person-justname.xml +++ /dev/null @@ -1,7 +0,0 @@ - - Person - Two - M - diff --git a/test/cases/xbean/ValidatingStream/person-sibling-inv.xml b/test/cases/xbean/ValidatingStream/person-sibling-inv.xml deleted file mode 100755 index f8f1a72..0000000 --- a/test/cases/xbean/ValidatingStream/person-sibling-inv.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - Person - Two - - - - Person - Three - - - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person-sibling.xml b/test/cases/xbean/ValidatingStream/person-sibling.xml deleted file mode 100755 index b3653f1..0000000 --- a/test/cases/xbean/ValidatingStream/person-sibling.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - Person - Two - - - - Person - Three - - - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person-xsi-inv.xml b/test/cases/xbean/ValidatingStream/person-xsi-inv.xml deleted file mode 100755 index f833a81..0000000 --- a/test/cases/xbean/ValidatingStream/person-xsi-inv.xml +++ /dev/null @@ -1,7 +0,0 @@ - - Person - Two - M - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/person.xml b/test/cases/xbean/ValidatingStream/person.xml deleted file mode 100755 index af0f25c..0000000 --- a/test/cases/xbean/ValidatingStream/person.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - Person - One - - - - Person - Two - - - - Person - Three - - - - diff --git a/test/cases/xbean/ValidatingStream/person.xsd b/test/cases/xbean/ValidatingStream/person.xsd deleted file mode 100755 index a5b5024..0000000 --- a/test/cases/xbean/ValidatingStream/person.xsd +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/ValidatingStream/po.xml b/test/cases/xbean/ValidatingStream/po.xml deleted file mode 100755 index b9d8cb8..0000000 --- a/test/cases/xbean/ValidatingStream/po.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - Alice Smith - 123 Maple Street - Mill Valley - CA - 90952 - - - Robert Smith - 8 Oak Avenue - Old Town - PA - 95819 - - Hurry, my lawn is going wild! - - - Lawnmower - 1 - 148.95 - Confirm this is electric - - - Baby Monitor - 1 - 39.98 - 1999-05-21 - - - \ No newline at end of file diff --git a/test/cases/xbean/ValidatingStream/simpleTypes.xsd b/test/cases/xbean/ValidatingStream/simpleTypes.xsd deleted file mode 100755 index 9d9d822..0000000 --- a/test/cases/xbean/ValidatingStream/simpleTypes.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/compile/scomp/detailed/laxDoc.xsd b/test/cases/xbean/compile/scomp/detailed/laxDoc.xsd deleted file mode 100644 index 2631fd3..0000000 --- a/test/cases/xbean/compile/scomp/detailed/laxDoc.xsd +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - Ensure that XML content is allowed and not validated when the novdoc option is set - provided content is XHTML compliant and no elements use the schema namespaces - - - foobaz - - - - - - - provided content is XHTML compliant and no elements use the schema namespaces - - - - - - - Ensure that XML content is allowed and not validated when the novdoc option is set - provided content is XHTML compliant and no elements use the schema namespaces - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/incr/incr1.xsd b/test/cases/xbean/compile/scomp/incr/incr1.xsd deleted file mode 100644 index 17d2111..0000000 --- a/test/cases/xbean/compile/scomp/incr/incr1.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/incr/incr2-1.xsd b/test/cases/xbean/compile/scomp/incr/incr2-1.xsd deleted file mode 100644 index ba12f4b..0000000 --- a/test/cases/xbean/compile/scomp/incr/incr2-1.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/incr/incr2.xsd b/test/cases/xbean/compile/scomp/incr/incr2.xsd deleted file mode 100644 index 7691f66..0000000 --- a/test/cases/xbean/compile/scomp/incr/incr2.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/incr/incr3.xsd b/test/cases/xbean/compile/scomp/incr/incr3.xsd deleted file mode 100644 index e2b4b56..0000000 --- a/test/cases/xbean/compile/scomp/incr/incr3.xsd +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/test/cases/xbean/compile/scomp/incr/incr4.xsd b/test/cases/xbean/compile/scomp/incr/incr4.xsd deleted file mode 100644 index c48cf66..0000000 --- a/test/cases/xbean/compile/scomp/incr/incr4.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/pricequote/PriceQuote.xsd b/test/cases/xbean/compile/scomp/pricequote/PriceQuote.xsd deleted file mode 100755 index 6672fbd..0000000 --- a/test/cases/xbean/compile/scomp/pricequote/PriceQuote.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/enum1.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/enum1.xsd_ deleted file mode 100644 index 03e3d24..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/enum1.xsd_ +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/enum1_redefine.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/enum1_redefine.xsd_ deleted file mode 100644 index e3e150c..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/enum1_redefine.xsd_ +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/enum2.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/enum2.xsd_ deleted file mode 100644 index 7000f19..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/enum2.xsd_ +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/enum2_redefine.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/enum2_redefine.xsd_ deleted file mode 100644 index 8b00600..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/enum2_redefine.xsd_ +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/enum3.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/enum3.xsd_ deleted file mode 100644 index fbecefd..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/enum3.xsd_ +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/enum3_redefine.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/enum3_redefine.xsd_ deleted file mode 100644 index 16c7979..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/enum3_redefine.xsd_ +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/ext/H1.java b/test/cases/xbean/compile/scomp/schemacompiler/ext/H1.java deleted file mode 100644 index 3e0c18f..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/ext/H1.java +++ /dev/null @@ -1,8 +0,0 @@ -package ext; - -public class H1 -{ - public static void get(org.apache.xmlbeans.XmlObject xo) - { - } -} \ No newline at end of file diff --git a/test/cases/xbean/compile/scomp/schemacompiler/ext/H2.java b/test/cases/xbean/compile/scomp/schemacompiler/ext/H2.java deleted file mode 100644 index 9c35315..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/ext/H2.java +++ /dev/null @@ -1,9 +0,0 @@ -package ext; - -public class H2 -{ - public static String get(org.apache.xmlbeans.XmlObject xo) - { - return null; - } -} \ No newline at end of file diff --git a/test/cases/xbean/compile/scomp/schemacompiler/ext/I1.java b/test/cases/xbean/compile/scomp/schemacompiler/ext/I1.java deleted file mode 100644 index a2aef85..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/ext/I1.java +++ /dev/null @@ -1,6 +0,0 @@ -package ext; - -public interface I1 -{ - public void get(); -} \ No newline at end of file diff --git a/test/cases/xbean/compile/scomp/schemacompiler/ext/I2.java b/test/cases/xbean/compile/scomp/schemacompiler/ext/I2.java deleted file mode 100644 index c103866..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/ext/I2.java +++ /dev/null @@ -1,6 +0,0 @@ -package ext; - -public interface I2 -{ - public String get(); -} \ No newline at end of file diff --git a/test/cases/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsd_ b/test/cases/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsd_ deleted file mode 100644 index 87307b1..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsd_ +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsdconfig_ b/test/cases/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsdconfig_ deleted file mode 100644 index 0ab5bb5..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/methodsColide_jira205_278.xsdconfig_ +++ /dev/null @@ -1,17 +0,0 @@ - - - - - ext.H1 - - - - - - - ext.H2 - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/union_initial.xsd b/test/cases/xbean/compile/scomp/schemacompiler/union_initial.xsd deleted file mode 100644 index 7e821ce..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/union_initial.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/schemacompiler/union_redefine.xsd b/test/cases/xbean/compile/scomp/schemacompiler/union_redefine.xsd deleted file mode 100644 index bfca936..0000000 --- a/test/cases/xbean/compile/scomp/schemacompiler/union_redefine.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/simple/javasrc/SimplePersonTest.java b/test/cases/xbean/compile/scomp/simple/javasrc/SimplePersonTest.java deleted file mode 100755 index fc36ee0..0000000 --- a/test/cases/xbean/compile/scomp/simple/javasrc/SimplePersonTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.openuri.mytest.Person; -import org.openuri.mytest.CustomerDocument; - -import java.util.Date; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor; -import drtcases.TestEnv; -import junit.framework.Assert; - -public class SimplePersonTest -{ - public static void main(String args[]) throws Exception - { - test(); - } - - public static void test() throws Exception - { - CustomerDocument doc = - CustomerDocument.Factory.parse( - TestEnv.xbeanCase("schema/simple/person.xml"), null); - - // Move from the root to the root customer element - Person person = doc.getCustomer(); - Assert.assertEquals("Howdy", person.getFirstname()); - Assert.assertEquals(4, person.sizeOfNumberArray()); - Assert.assertEquals(436, person.getNumberArray(0)); - Assert.assertEquals(123, person.getNumberArray(1)); - Assert.assertEquals(44, person.getNumberArray(2)); - Assert.assertEquals(933, person.getNumberArray(3)); - Assert.assertEquals(2, person.sizeOfBirthdayArray()); - Assert.assertEquals(new Date("Tue Aug 25 17:00:00 PDT 1998"), person.getBirthdayArray(0)); - - Person.Gender.Enum g = person.getGender(); - Assert.assertEquals(Person.Gender.MALE, g); - - Assert.assertEquals("EGIQTWYZJ", new String(person.getHex())); - Assert.assertEquals("This string is base64Binary encoded!", - new String(person.getBase64())); - - Assert.assertEquals("GGIQTWYGG", new String(person.getHexAtt())); - Assert.assertEquals("This string is base64Binary encoded!", - new String(person.getBase64Att())); - - person.setFirstname("George"); - Assert.assertEquals("George", person.getFirstname()); - - person.setHex("hex encoding".getBytes()); - Assert.assertEquals("hex encoding", new String(person.getHex())); - - person.setBase64("base64 encoded".getBytes()); - Assert.assertEquals("base64 encoded", - new String(person.getBase64())); - - //person.setHexAtt("hex encoding in attributes".getBytes()); - //Assert.assertEquals("hex encoding in attributes", - // new String(person.getHexAtt())); - - //person.setBase64Att("base64 encoded in attributes".getBytes()); - //Assert.assertEquals("base64 encoded in attributes", - // new String(person.getBase64Att())); -// -// XmlCursor cp = person.newXmlCursor(); -// Root.dump( cp ); - -// XmlCursor c = person.xgetBirthdayArray(0).newXmlCursor(); - -// Root.dump( c ); - -// person.setBirthday(0,new Date("Tue Aug 25 16:00:00 PDT 2001")); - -// Root.dump( c ); - -// c.toNextToken(); - -// System.out.println( "---" + c.getText() + "---" ); - -// Root.dump( c ); - -// Assert.assertEquals(person.getBirthdayArray(0), new Date("Tue Aug 25 16:00:00 PDT 2002")); -// -// person.setFirstname("George"); -// Assert.assertEquals(person.getFirstname(), "George"); -// -// person.addNumber( (short) 69 ); -// Assert.assertEquals(person.countNumber(), 5); -// Assert.assertEquals(person.getNumberArray(4), 69); -// -// -// while ( c.hasNextToken() ) -// c.toNextToken(); - } -} diff --git a/test/cases/xbean/compile/scomp/simple/person.xml b/test/cases/xbean/compile/scomp/simple/person.xml deleted file mode 100755 index 6baf35a..0000000 --- a/test/cases/xbean/compile/scomp/simple/person.xml +++ /dev/null @@ -1,16 +0,0 @@ - - Howdy - 436 - 123 - 1998-08-26Z - 44 - 933 - 2000-08-06-08:00 - 454749515457595A4A - VGhpcyBzdHJpbmcgaXMgYmFzZTY0QmluYXJ5IGVuY29kZWQh - diff --git a/test/cases/xbean/compile/scomp/simple/person.xsd b/test/cases/xbean/compile/scomp/simple/person.xsd deleted file mode 100755 index c986ecb..0000000 --- a/test/cases/xbean/compile/scomp/simple/person.xsd +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/compile/scomp/simple/simplec.xsd b/test/cases/xbean/compile/scomp/simple/simplec.xsd deleted file mode 100755 index f7076a9..0000000 --- a/test/cases/xbean/compile/scomp/simple/simplec.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/extensions/interfaceFeature/averageCase/po.xsd b/test/cases/xbean/extensions/interfaceFeature/averageCase/po.xsd deleted file mode 100755 index 896cdb9..0000000 --- a/test/cases/xbean/extensions/interfaceFeature/averageCase/po.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - Purchase order schema for Example.com. - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/extensions/interfaceFeature/methodNameCollision/company.xsd b/test/cases/xbean/extensions/interfaceFeature/methodNameCollision/company.xsd deleted file mode 100755 index 678f25c..0000000 --- a/test/cases/xbean/extensions/interfaceFeature/methodNameCollision/company.xsd +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/extensions/interfaceFeature/multInterfaces/po.xsd b/test/cases/xbean/extensions/interfaceFeature/multInterfaces/po.xsd deleted file mode 100755 index 681218b..0000000 --- a/test/cases/xbean/extensions/interfaceFeature/multInterfaces/po.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - Purchase order schema for Example.com. - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/extensions/interfaceFeature/readOnlyBean/po.xsd b/test/cases/xbean/extensions/interfaceFeature/readOnlyBean/po.xsd deleted file mode 100755 index 0705182..0000000 --- a/test/cases/xbean/extensions/interfaceFeature/readOnlyBean/po.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - Purchase order schema for Example.com. - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/extensions/prePostFeature/ValueRestriction/company.xsd b/test/cases/xbean/extensions/prePostFeature/ValueRestriction/company.xsd deleted file mode 100755 index 8ba0f22..0000000 --- a/test/cases/xbean/extensions/prePostFeature/ValueRestriction/company.xsd +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/extensions/prePostFeature/readOnlyBean/po.xsd b/test/cases/xbean/extensions/prePostFeature/readOnlyBean/po.xsd deleted file mode 100755 index 4fd9bd9..0000000 --- a/test/cases/xbean/extensions/prePostFeature/readOnlyBean/po.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - Purchase order schema for Example.com. - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/dyntest.xml b/test/cases/xbean/misc/dyntest.xml deleted file mode 100755 index 4cf1433..0000000 --- a/test/cases/xbean/misc/dyntest.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - 42 - - \ No newline at end of file diff --git a/test/cases/xbean/misc/dyntest.xsd b/test/cases/xbean/misc/dyntest.xsd deleted file mode 100755 index f3a3007..0000000 --- a/test/cases/xbean/misc/dyntest.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/dyntest2.xml b/test/cases/xbean/misc/dyntest2.xml deleted file mode 100755 index e662e4d..0000000 --- a/test/cases/xbean/misc/dyntest2.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/dyntest2.xsd b/test/cases/xbean/misc/dyntest2.xsd deleted file mode 100755 index 6dc4e37..0000000 --- a/test/cases/xbean/misc/dyntest2.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/easypo.xml b/test/cases/xbean/misc/jira/easypo.xml deleted file mode 100644 index 510821e..0000000 --- a/test/cases/xbean/misc/jira/easypo.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - Gladys Kravitz -
        Anytown, PA
        -
        - 2003-01-07T14:16:00-05:00 - - Burnham's Celestial Handbook, Vol 1 - 5 - 21.79 - 2 - - - Burnham's Celestial Handbook, Vol 2 - 5 - 19.89 - 2 - - - ZipShip - 0.74 - -
        \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_04.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_04.xsd_ deleted file mode 100644 index 942f5d6..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_04.xsd_ +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_08.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_08.xsd_ deleted file mode 100644 index 2ad4352..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_08.xsd_ +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_08a.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_08a.xsd_ deleted file mode 100644 index 6d94638..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_08a.xsd_ +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_09.xml b/test/cases/xbean/misc/jira/xmlbeans_09.xml deleted file mode 100644 index 50b5ad4..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_09.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - enum1 - - - one - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_09.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_09.xsd_ deleted file mode 100644 index 47e5375..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_09.xsd_ +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_105.xml b/test/cases/xbean/misc/jira/xmlbeans_105.xml deleted file mode 100644 index 6adce4b..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_105.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - 2004-05-14T10:21:18.6939682+08:00 - diff --git a/test/cases/xbean/misc/jira/xmlbeans_105.xsd b/test/cases/xbean/misc/jira/xmlbeans_105.xsd deleted file mode 100644 index 715b866..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_105.xsd +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_105a.xsd b/test/cases/xbean/misc/jira/xmlbeans_105a.xsd deleted file mode 100644 index 9daa771..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_105a.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_175.xsd b/test/cases/xbean/misc/jira/xmlbeans_175.xsd deleted file mode 100644 index dea6374..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_175.xsd +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_177.xml b/test/cases/xbean/misc/jira/xmlbeans_177.xml deleted file mode 100644 index 32663d0..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_177.xml +++ /dev/null @@ -1,9 +0,0 @@ - - This is a greater than sign: > - This is a less than sign: < - This is a single quote: ' - This is a double quote: " - W.L.Gore & Associates - Character data may not contain the three-character sequence ]]> with the > unescaped. - In particular, with the > unescaped. - diff --git a/test/cases/xbean/misc/jira/xmlbeans_177.xsd b/test/cases/xbean/misc/jira/xmlbeans_177.xsd deleted file mode 100644 index 7fc82ff..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_177.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_177a.xml b/test/cases/xbean/misc/jira/xmlbeans_177a.xml deleted file mode 100644 index e074a03..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_177a.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_177a.xsd b/test/cases/xbean/misc/jira/xmlbeans_177a.xsd deleted file mode 100644 index 5ace134..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_177a.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_ehd_header_V1.30.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_184_ehd_header_V1.30.xsd_ deleted file mode 100644 index 2596f14..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_184_ehd_header_V1.30.xsd_ +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - ehd-header - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_ehd_root_V1.30.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_184_ehd_root_V1.30.xsd_ deleted file mode 100644 index 36d37bd..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_184_ehd_root_V1.30.xsd_ +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - alle Metainformationen zu den Daten - - - - - die eigentlichen Daten - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_184_keytabs_V1.30.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_184_keytabs_V1.30.xsd_ deleted file mode 100644 index 1cb23f2..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_184_keytabs_V1.30.xsd_ +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - Schl�sseltabellen zu den Daten - - - - - - - - - - - - - - - - Scl�sseltabelle mit S=OID, SN=Name der Schl�sseltabelle, SV=Version - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Schl�ssel mit V=Wert, DN=WertBezeichnung, S=OID zur welchen Scl�sseltabelle der Wert geh�rt, SV=Version der Schl�sseltabelle - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_208.xsd b/test/cases/xbean/misc/jira/xmlbeans_208.xsd deleted file mode 100644 index e8bea6f..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_208.xsd +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_228.xsd b/test/cases/xbean/misc/jira/xmlbeans_228.xsd deleted file mode 100644 index d29f0b4..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_228.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - Wrong element order after substitution. - 14.11.05 11:11 - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_236.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_236.xsd_ deleted file mode 100644 index d926d36..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_236.xsd_ +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_239a.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_239a.xsd_ deleted file mode 100644 index b890b8e..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_239a.xsd_ +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_239b.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_239b.xsd_ deleted file mode 100644 index 820e3cb..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_239b.xsd_ +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_239c.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_239c.xsd_ deleted file mode 100644 index c2dd5bb..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_239c.xsd_ +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_251.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_251.xsd_ deleted file mode 100644 index e2aa9be..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_251.xsd_ +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_33a.xsd b/test/cases/xbean/misc/jira/xmlbeans_33a.xsd deleted file mode 100644 index 090ca22..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_33a.xsd +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_33b.xsd b/test/cases/xbean/misc/jira/xmlbeans_33b.xsd deleted file mode 100644 index 5126be7..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_33b.xsd +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_34a.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_34a.xsd_ deleted file mode 100644 index dd5d6f9..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_34a.xsd_ +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_34b.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_34b.xsd_ deleted file mode 100644 index 7a9e930..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_34b.xsd_ +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_45a.xsd b/test/cases/xbean/misc/jira/xmlbeans_45a.xsd deleted file mode 100644 index 1770359..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_45a.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_45b.xsd b/test/cases/xbean/misc/jira/xmlbeans_45b.xsd deleted file mode 100644 index 6770320..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_45b.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_46.xsd b/test/cases/xbean/misc/jira/xmlbeans_46.xsd deleted file mode 100644 index 6e6da4f..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_46.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_48.xsd b/test/cases/xbean/misc/jira/xmlbeans_48.xsd deleted file mode 100644 index 2f697d1..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_48.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_54.xsd_ b/test/cases/xbean/misc/jira/xmlbeans_54.xsd_ deleted file mode 100644 index 70b0856..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_54.xsd_ +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_57.xml b/test/cases/xbean/misc/jira/xmlbeans_57.xml deleted file mode 100644 index 740c529..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_57.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_62.xml b/test/cases/xbean/misc/jira/xmlbeans_62.xml deleted file mode 100644 index 110e670..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_62.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_68.xsd b/test/cases/xbean/misc/jira/xmlbeans_68.xsd deleted file mode 100644 index 4220313..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_68.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_71.xml b/test/cases/xbean/misc/jira/xmlbeans_71.xml deleted file mode 100644 index df2bb68..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_71.xml +++ /dev/null @@ -1,7 +0,0 @@ - - -SUCCESS - -0 -0 - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_71.xsd b/test/cases/xbean/misc/jira/xmlbeans_71.xsd deleted file mode 100644 index 127891c..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_71.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_78.xml b/test/cases/xbean/misc/jira/xmlbeans_78.xml deleted file mode 100644 index 7f1a284..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_78.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - -
        - - 123456 - - - - 1234 - - - - True - - xyz - 123 - - - - 123 - http://xmlbeans.apache.org - - Apache - xmlbeans - Book - XmlBeans Apache Org - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_97.xsd b/test/cases/xbean/misc/jira/xmlbeans_97.xsd deleted file mode 100644 index 8c668b3..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_97.xsd +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_97.xsdconfig b/test/cases/xbean/misc/jira/xmlbeans_97.xsdconfig deleted file mode 100644 index f45b5fa..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_97.xsdconfig +++ /dev/null @@ -1,21 +0,0 @@ - - - - org.apache.jira.xmlbeans98 - - - - - - Xml - Bean - - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_98.xml b/test/cases/xbean/misc/jira/xmlbeans_98.xml deleted file mode 100644 index 89a8e79..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_98.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/misc/jira/xmlbeans_98.xsd b/test/cases/xbean/misc/jira/xmlbeans_98.xsd deleted file mode 100644 index 799f09f..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_98.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - Comment describing your root element - - - - - - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_98_exp.xml b/test/cases/xbean/misc/jira/xmlbeans_98_exp.xml deleted file mode 100644 index e69de29..0000000 diff --git a/test/cases/xbean/misc/jira/xmlbeans_99.xml b/test/cases/xbean/misc/jira/xmlbeans_99.xml deleted file mode 100644 index 2543b9d..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_99.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - toto - - - diff --git a/test/cases/xbean/misc/jira/xmlbeans_99.xsd b/test/cases/xbean/misc/jira/xmlbeans_99.xsd deleted file mode 100644 index c4da02f..0000000 --- a/test/cases/xbean/misc/jira/xmlbeans_99.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/misc/signature-example.xml b/test/cases/xbean/misc/signature-example.xml deleted file mode 100755 index 99a6994..0000000 --- a/test/cases/xbean/misc/signature-example.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - -]> - - - - - - - - - - - - - - j6lwx3rvEPO0vKtMup4NbeVu8nk= - - - - - - - - UrXLDLBIta6skoV5/A8Q38GEw44= - - - MC0CFFrVLtRlkMc3Daon4BqqnkhCOlEaAhUAk8pH1iRNK+q1I+sisDTz2TFEALE= - - - -

        ...

        ......... -
        -
        -
        - - - - - this is a test of the mixed content model - - - -
        diff --git a/test/cases/xbean/misc/syscachetest.xsd b/test/cases/xbean/misc/syscachetest.xsd deleted file mode 100644 index 675ebd3..0000000 --- a/test/cases/xbean/misc/syscachetest.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/schema/typesonly/typesonly.xsd b/test/cases/xbean/schema/typesonly/typesonly.xsd deleted file mode 100755 index c409608..0000000 --- a/test/cases/xbean/schema/typesonly/typesonly.xsd +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/attribute/AttributeGroup.xsd b/test/cases/xbean/scomp/attribute/AttributeGroup.xsd deleted file mode 100644 index 33a85c4..0000000 --- a/test/cases/xbean/scomp/attribute/AttributeGroup.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/attribute/GlobalAttrDefault.xsd b/test/cases/xbean/scomp/attribute/GlobalAttrDefault.xsd deleted file mode 100644 index ef23f93..0000000 --- a/test/cases/xbean/scomp/attribute/GlobalAttrDefault.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/attribute/GlobalAttrFixed.xsd b/test/cases/xbean/scomp/attribute/GlobalAttrFixed.xsd deleted file mode 100644 index 96aec86..0000000 --- a/test/cases/xbean/scomp/attribute/GlobalAttrFixed.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/attribute/GlobalAttrId.xsd b/test/cases/xbean/scomp/attribute/GlobalAttrId.xsd deleted file mode 100644 index e63c9ab..0000000 --- a/test/cases/xbean/scomp/attribute/GlobalAttrId.xsd +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/attribute/GlobalAttrType.xsd b/test/cases/xbean/scomp/attribute/GlobalAttrType.xsd deleted file mode 100644 index 7a835fa..0000000 --- a/test/cases/xbean/scomp/attribute/GlobalAttrType.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/attribute/LocalAttrFixedDefault.xsd b/test/cases/xbean/scomp/attribute/LocalAttrFixedDefault.xsd deleted file mode 100644 index 5cda4dc..0000000 --- a/test/cases/xbean/scomp/attribute/LocalAttrFixedDefault.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/attribute/LocalAttrUse.xsd b/test/cases/xbean/scomp/attribute/LocalAttrUse.xsd deleted file mode 100644 index c0ec98e..0000000 --- a/test/cases/xbean/scomp/attribute/LocalAttrUse.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/contentType/Anonymous.xsd b/test/cases/xbean/scomp/contentType/Anonymous.xsd deleted file mode 100644 index b5bfe3a..0000000 --- a/test/cases/xbean/scomp/contentType/Anonymous.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/ComplexTypeTest.xsd b/test/cases/xbean/scomp/contentType/ComplexTypeTest.xsd deleted file mode 100644 index b6bb0c1..0000000 --- a/test/cases/xbean/scomp/contentType/ComplexTypeTest.xsd +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/ListType.xsd b/test/cases/xbean/scomp/contentType/ListType.xsd deleted file mode 100644 index f176ed9..0000000 --- a/test/cases/xbean/scomp/contentType/ListType.xsd +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/Named.xsd b/test/cases/xbean/scomp/contentType/Named.xsd deleted file mode 100644 index ed9a48b..0000000 --- a/test/cases/xbean/scomp/contentType/Named.xsd +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/SimpleType.xsd b/test/cases/xbean/scomp/contentType/SimpleType.xsd deleted file mode 100644 index 521016c..0000000 --- a/test/cases/xbean/scomp/contentType/SimpleType.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/builtInTypes/DateTime.xsd b/test/cases/xbean/scomp/contentType/builtInTypes/DateTime.xsd deleted file mode 100644 index 24ff80d..0000000 --- a/test/cases/xbean/scomp/contentType/builtInTypes/DateTime.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/contentType/builtInTypes/NumberBased.xsd b/test/cases/xbean/scomp/contentType/builtInTypes/NumberBased.xsd deleted file mode 100644 index f6c2cad..0000000 --- a/test/cases/xbean/scomp/contentType/builtInTypes/NumberBased.xsd +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/contentType/builtInTypes/StringBased.xsd b/test/cases/xbean/scomp/contentType/builtInTypes/StringBased.xsd deleted file mode 100644 index 439acb1..0000000 --- a/test/cases/xbean/scomp/contentType/builtInTypes/StringBased.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/derivation/Abstract.xsd b/test/cases/xbean/scomp/derivation/Abstract.xsd deleted file mode 100644 index abeae16..0000000 --- a/test/cases/xbean/scomp/derivation/Abstract.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/AttributeExtension.xsd b/test/cases/xbean/scomp/derivation/AttributeExtension.xsd deleted file mode 100644 index c1ca389..0000000 --- a/test/cases/xbean/scomp/derivation/AttributeExtension.xsd +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/AttributeRestriction.xsd b/test/cases/xbean/scomp/derivation/AttributeRestriction.xsd deleted file mode 100644 index 685251a..0000000 --- a/test/cases/xbean/scomp/derivation/AttributeRestriction.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/AttributeUseProhibited.xsd b/test/cases/xbean/scomp/derivation/AttributeUseProhibited.xsd deleted file mode 100644 index dd074a1..0000000 --- a/test/cases/xbean/scomp/derivation/AttributeUseProhibited.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/Block.xsd b/test/cases/xbean/scomp/derivation/Block.xsd deleted file mode 100644 index 87bbdb7..0000000 --- a/test/cases/xbean/scomp/derivation/Block.xsd +++ /dev/null @@ -1,177 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/ComplexContentExtension.xsd b/test/cases/xbean/scomp/derivation/ComplexContentExtension.xsd deleted file mode 100644 index 8e65de4..0000000 --- a/test/cases/xbean/scomp/derivation/ComplexContentExtension.xsd +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/ElementRestriction.xsd b/test/cases/xbean/scomp/derivation/ElementRestriction.xsd deleted file mode 100644 index fa15155..0000000 --- a/test/cases/xbean/scomp/derivation/ElementRestriction.xsd +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/derivation/ElementWCRestriction.xsd b/test/cases/xbean/scomp/derivation/ElementWCRestriction.xsd deleted file mode 100644 index c443acf..0000000 --- a/test/cases/xbean/scomp/derivation/ElementWCRestriction.xsd +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/EmptyContent.xsd b/test/cases/xbean/scomp/derivation/EmptyContent.xsd deleted file mode 100644 index a5fa532..0000000 --- a/test/cases/xbean/scomp/derivation/EmptyContent.xsd +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/MixedContentExtension.xsd b/test/cases/xbean/scomp/derivation/MixedContentExtension.xsd deleted file mode 100644 index 870872a..0000000 --- a/test/cases/xbean/scomp/derivation/MixedContentExtension.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/SimpleContentExtension.xsd b/test/cases/xbean/scomp/derivation/SimpleContentExtension.xsd deleted file mode 100644 index 7594091..0000000 --- a/test/cases/xbean/scomp/derivation/SimpleContentExtension.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/SimpleTypeRestriction.xsd b/test/cases/xbean/scomp/derivation/SimpleTypeRestriction.xsd deleted file mode 100644 index 00b95c2..0000000 --- a/test/cases/xbean/scomp/derivation/SimpleTypeRestriction.xsd +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/derivation/facets/DateTimePattern.xsd b/test/cases/xbean/scomp/derivation/facets/DateTimePattern.xsd deleted file mode 100644 index 27ff8cf..0000000 --- a/test/cases/xbean/scomp/derivation/facets/DateTimePattern.xsd +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/derivation/facets/UnionRestriction.xsd b/test/cases/xbean/scomp/derivation/facets/UnionRestriction.xsd deleted file mode 100644 index e865c67..0000000 --- a/test/cases/xbean/scomp/derivation/facets/UnionRestriction.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/element/Any.xsd b/test/cases/xbean/scomp/element/Any.xsd deleted file mode 100644 index ddc9399..0000000 --- a/test/cases/xbean/scomp/element/Any.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/element/GlobalEltDefault.xsd b/test/cases/xbean/scomp/element/GlobalEltDefault.xsd deleted file mode 100644 index 8af2e42..0000000 --- a/test/cases/xbean/scomp/element/GlobalEltDefault.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/element/GlobalEltFixed.xsd b/test/cases/xbean/scomp/element/GlobalEltFixed.xsd deleted file mode 100644 index f353656..0000000 --- a/test/cases/xbean/scomp/element/GlobalEltFixed.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/test/cases/xbean/scomp/element/GlobalEltNillable.xsd b/test/cases/xbean/scomp/element/GlobalEltNillable.xsd deleted file mode 100644 index 52ac3fa..0000000 --- a/test/cases/xbean/scomp/element/GlobalEltNillable.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/element/LocalEltMinMaxOccurs.xsd b/test/cases/xbean/scomp/element/LocalEltMinMaxOccurs.xsd deleted file mode 100644 index 2359c78..0000000 --- a/test/cases/xbean/scomp/element/LocalEltMinMaxOccurs.xsd +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/element/NamedModelGroup.xsd b/test/cases/xbean/scomp/element/NamedModelGroup.xsd deleted file mode 100644 index c129c4f..0000000 --- a/test/cases/xbean/scomp/element/NamedModelGroup.xsd +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/element/NillTest.xsd b/test/cases/xbean/scomp/element/NillTest.xsd deleted file mode 100644 index b24c632..0000000 --- a/test/cases/xbean/scomp/element/NillTest.xsd +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/namespace/AttributeFormDefault.xsd b/test/cases/xbean/scomp/namespace/AttributeFormDefault.xsd deleted file mode 100644 index d0d3115..0000000 --- a/test/cases/xbean/scomp/namespace/AttributeFormDefault.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/namespace/ElementFormDefault.xsd b/test/cases/xbean/scomp/namespace/ElementFormDefault.xsd deleted file mode 100644 index 6617d0a..0000000 --- a/test/cases/xbean/scomp/namespace/ElementFormDefault.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/namespace/NoNamespace.xsd b/test/cases/xbean/scomp/namespace/NoNamespace.xsd deleted file mode 100644 index 92d3537..0000000 --- a/test/cases/xbean/scomp/namespace/NoNamespace.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/AttrRedefineSub.xs b/test/cases/xbean/scomp/redefine/AttrRedefineSub.xs deleted file mode 100644 index 46ea759..0000000 --- a/test/cases/xbean/scomp/redefine/AttrRedefineSub.xs +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/AttrRedefineSuper.xsd b/test/cases/xbean/scomp/redefine/AttrRedefineSuper.xsd deleted file mode 100644 index e0d57b4..0000000 --- a/test/cases/xbean/scomp/redefine/AttrRedefineSuper.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/BaseAttrGroup.xs b/test/cases/xbean/scomp/redefine/BaseAttrGroup.xs deleted file mode 100644 index 6894f3d..0000000 --- a/test/cases/xbean/scomp/redefine/BaseAttrGroup.xs +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/BaseModelGroup.xs b/test/cases/xbean/scomp/redefine/BaseModelGroup.xs deleted file mode 100644 index 11e0edb..0000000 --- a/test/cases/xbean/scomp/redefine/BaseModelGroup.xs +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/redefine/BaseSimple.xs b/test/cases/xbean/scomp/redefine/BaseSimple.xs deleted file mode 100644 index fe7c629..0000000 --- a/test/cases/xbean/scomp/redefine/BaseSimple.xs +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/scomp/redefine/ModelGroupSub.xs b/test/cases/xbean/scomp/redefine/ModelGroupSub.xs deleted file mode 100644 index 25acfc5..0000000 --- a/test/cases/xbean/scomp/redefine/ModelGroupSub.xs +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/ModelGroupSuper.xsd b/test/cases/xbean/scomp/redefine/ModelGroupSuper.xsd deleted file mode 100644 index de5d20f..0000000 --- a/test/cases/xbean/scomp/redefine/ModelGroupSuper.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/SimpleRedefined.xsd b/test/cases/xbean/scomp/redefine/SimpleRedefined.xsd deleted file mode 100644 index 4229386..0000000 --- a/test/cases/xbean/scomp/redefine/SimpleRedefined.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/TypeBase.xs b/test/cases/xbean/scomp/redefine/TypeBase.xs deleted file mode 100644 index fac9781..0000000 --- a/test/cases/xbean/scomp/redefine/TypeBase.xs +++ /dev/null @@ -1,5 +0,0 @@ - \ No newline at end of file diff --git a/test/cases/xbean/scomp/redefine/TypeRedefine.xsd b/test/cases/xbean/scomp/redefine/TypeRedefine.xsd deleted file mode 100644 index a1c8876..0000000 --- a/test/cases/xbean/scomp/redefine/TypeRedefine.xsd +++ /dev/null @@ -1,5 +0,0 @@ - \ No newline at end of file diff --git a/test/cases/xbean/scomp/substGroup/Abstract.xsd b/test/cases/xbean/scomp/substGroup/Abstract.xsd deleted file mode 100644 index 687d6b7..0000000 --- a/test/cases/xbean/scomp/substGroup/Abstract.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/substGroup/Block.xsd b/test/cases/xbean/scomp/substGroup/Block.xsd deleted file mode 100644 index e23acfa..0000000 --- a/test/cases/xbean/scomp/substGroup/Block.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/substGroup/OneLevel.xsd b/test/cases/xbean/scomp/substGroup/OneLevel.xsd deleted file mode 100644 index 4673f3d..0000000 --- a/test/cases/xbean/scomp/substGroup/OneLevel.xsd +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/substGroup/UserAbstract.xsd b/test/cases/xbean/scomp/substGroup/UserAbstract.xsd deleted file mode 100644 index 6abb042..0000000 --- a/test/cases/xbean/scomp/substGroup/UserAbstract.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/scomp/substGroup/UserReported.xsd b/test/cases/xbean/scomp/substGroup/UserReported.xsd deleted file mode 100644 index 757dcfd..0000000 --- a/test/cases/xbean/scomp/substGroup/UserReported.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/simple/dumb/dumb.xml b/test/cases/xbean/simple/dumb/dumb.xml deleted file mode 100755 index 12afee0..0000000 --- a/test/cases/xbean/simple/dumb/dumb.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/test/cases/xbean/simple/dumb/dumb.xsd b/test/cases/xbean/simple/dumb/dumb.xsd deleted file mode 100755 index 872f828..0000000 --- a/test/cases/xbean/simple/dumb/dumb.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/simple/dumb/sub/bar.xsd b/test/cases/xbean/simple/dumb/sub/bar.xsd deleted file mode 100755 index 55db24b..0000000 --- a/test/cases/xbean/simple/dumb/sub/bar.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - diff --git a/test/cases/xbean/simple/dupSchemaElements/DupElementsInSameSchema.xsd b/test/cases/xbean/simple/dupSchemaElements/DupElementsInSameSchema.xsd deleted file mode 100755 index aed76f7..0000000 --- a/test/cases/xbean/simple/dupSchemaElements/DupElementsInSameSchema.xsd +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/simple/dupSchemaElements/custOrdUdf.xsd b/test/cases/xbean/simple/dupSchemaElements/custOrdUdf.xsd deleted file mode 100755 index ba868e1..0000000 --- a/test/cases/xbean/simple/dupSchemaElements/custOrdUdf.xsd +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/simple/dupSchemaElements/viewtarget.xsd b/test/cases/xbean/simple/dupSchemaElements/viewtarget.xsd deleted file mode 100755 index 79e8970..0000000 --- a/test/cases/xbean/simple/dupSchemaElements/viewtarget.xsd +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base.xml b/test/cases/xbean/tools/inst2xsd/options/base.xml deleted file mode 100644 index b6aafea..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base.xml +++ /dev/null @@ -1,5 +0,0 @@ - - abc - 123 - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base0.xsd b/test/cases/xbean/tools/inst2xsd/options/base0.xsd deleted file mode 100644 index e0b84dd..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_rd0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_rd0.xsd deleted file mode 100644 index 6612fc9..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_rd0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_rd_eN0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_rd_eN0.xsd deleted file mode 100644 index 6612fc9..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_rd_eN0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_rd_scs0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_rd_scs0.xsd deleted file mode 100644 index 3911f9f..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_rd_scs0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_rd_scs_eN0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_rd_scs_eN0.xsd deleted file mode 100644 index 3911f9f..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_rd_scs_eN0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_ss0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_ss0.xsd deleted file mode 100644 index a56cc10..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_ss0.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_ss_eN0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_ss_eN0.xsd deleted file mode 100644 index a56cc10..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_ss_eN0.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_ss_scs0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_ss_scs0.xsd deleted file mode 100644 index 75ba3e1..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_ss_scs0.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_ss_scs_eN0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_ss_scs_eN0.xsd deleted file mode 100644 index 75ba3e1..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_ss_scs_eN0.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_vb0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_vb0.xsd deleted file mode 100644 index d6558be..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_vb0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_vb_eN0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_vb_eN0.xsd deleted file mode 100644 index d6558be..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_vb_eN0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_vb_scs0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_vb_scs0.xsd deleted file mode 100644 index 7f7554d..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_vb_scs0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/options/base_vb_scs_eN0.xsd b/test/cases/xbean/tools/inst2xsd/options/base_vb_scs_eN0.xsd deleted file mode 100644 index 7f7554d..0000000 --- a/test/cases/xbean/tools/inst2xsd/options/base_vb_scs_eN0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/choice.xml b/test/cases/xbean/tools/inst2xsd/schema/choice.xml deleted file mode 100644 index e30dab0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/choice.xml +++ /dev/null @@ -1,6 +0,0 @@ - - 123 - abc123 - abc123abc - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/choice_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/choice_ss0.xsd deleted file mode 100644 index d5538aa..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/choice_ss0.xsd +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice.xml deleted file mode 100644 index 7df2be7..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss0.xsd deleted file mode 100644 index d01586a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss0.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss1.xsd deleted file mode 100644 index 16bf145..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/attrchoice_ss1.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice.xml deleted file mode 100644 index ffe65ee..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss0.xsd deleted file mode 100644 index 5ee1714..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss1.xsd deleted file mode 100644 index fa05252..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss1.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss2.xsd deleted file mode 100644 index b57a0f1..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss2.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss3.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss3.xsd deleted file mode 100644 index 2fd69bf..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/nschoice_ss3.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/schema0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/schema0.xsd deleted file mode 100644 index 822f14c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/schema0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/schema1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/schema1.xsd deleted file mode 100644 index 2c4e9db..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/schema1.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice.xml deleted file mode 100644 index 36b65f2..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_rd0.xsd deleted file mode 100644 index f53c3f2..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_rd0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_ss0.xsd deleted file mode 100644 index b2419e0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_ss0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_vb0.xsd deleted file mode 100644 index 7e81c96..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/choice/simplechoice_vb0.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum.xml deleted file mode 100644 index ab95f31..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - baz:foo - - - foo:baz - - - foo:bar - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd0.xsd deleted file mode 100644 index 2f70838..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd1.xsd deleted file mode 100644 index 04d98ce..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd2.xsd deleted file mode 100644 index c13044b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd2.xsd +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum0.xsd deleted file mode 100644 index 2f70838..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum1.xsd deleted file mode 100644 index 04d98ce..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum2.xsd deleted file mode 100644 index c13044b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_rd_enum2.xsd +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss0.xsd deleted file mode 100644 index 2f70838..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss1.xsd deleted file mode 100644 index 04d98ce..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss2.xsd deleted file mode 100644 index 1d07917..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss2.xsd +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum0.xsd deleted file mode 100644 index 2f70838..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum1.xsd deleted file mode 100644 index e9f1eb7..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum1.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum2.xsd deleted file mode 100644 index a4a6a08..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_ss_enum2.xsd +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb0.xsd deleted file mode 100644 index 2f70838..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb1.xsd deleted file mode 100644 index 04d98ce..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb2.xsd deleted file mode 100644 index e376502..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb2.xsd +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum0.xsd deleted file mode 100644 index 2f70838..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum1.xsd deleted file mode 100644 index 04d98ce..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum2.xsd deleted file mode 100644 index e376502..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/attr/attrenum_vb_enum2.xsd +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum.xml deleted file mode 100644 index 6f23dc0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - foo:baz - - - baz:foo - - - baz:foo - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_rd0.xsd deleted file mode 100644 index c67c08b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_rd0.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_ss0.xsd deleted file mode 100644 index b8191c1..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_ss0.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_vb0.xsd deleted file mode 100644 index f851aec..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum2_vb0.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName.xml deleted file mode 100644 index c42bf06..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - foo:baz - - - baz:foo - - - baz:foo this should not be a qName - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_eN0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_eN0.xsd deleted file mode 100644 index 8c6f32e..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_eN0.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_enum0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_enum0.xsd deleted file mode 100644 index a1d6b11..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enumQName_vb_enum0.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_eN0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_eN0.xsd deleted file mode 100644 index f851aec..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_eN0.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_scs_enum0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_scs_enum0.xsd deleted file mode 100644 index 0743d2a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/enum/enum_vb_scs_enum0.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd0.xsd deleted file mode 100644 index 822f14c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd1.xsd deleted file mode 100644 index 2c4e9db..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_rd1.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss0.xsd deleted file mode 100644 index 822f14c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss1.xsd deleted file mode 100644 index 1418069..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_ss1.xsd +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb0.xsd deleted file mode 100644 index 822f14c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb1.xsd deleted file mode 100644 index f1c716b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattr_vb1.xsd +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattribute.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattribute.xml deleted file mode 100644 index b329afe..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/global/globalattribute.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd0.xsd deleted file mode 100644 index 890a6e9..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd1.xsd deleted file mode 100644 index 92ff709..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd1.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd2.xsd deleted file mode 100644 index d8a108f..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd2.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd3.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd3.xsd deleted file mode 100644 index 83d6bfe..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_rd3.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss0.xsd deleted file mode 100644 index 890a6e9..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss1.xsd deleted file mode 100644 index 92ff709..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss1.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss2.xsd deleted file mode 100644 index c83b704..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss2.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss3.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss3.xsd deleted file mode 100644 index 83d6bfe..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_ss3.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb0.xsd deleted file mode 100644 index 7129b0e..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb0.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb1.xsd deleted file mode 100644 index 2b93d3b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb1.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb2.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb2.xsd deleted file mode 100644 index 28638ed..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb2.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb3.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb3.xsd deleted file mode 100644 index a6889b0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedArray_vb3.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedNSArray.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedNSArray.xml deleted file mode 100644 index 7623a44..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/nestedNSArray/nestedNSArray.xml +++ /dev/null @@ -1,12 +0,0 @@ - - a - b - c - - b - c - - notB - notC - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice.xml b/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice.xml deleted file mode 100644 index bc3608b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice.xml +++ /dev/null @@ -1,7 +0,0 @@ - - 123 - abc123 - abc123abc - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd0.xsd deleted file mode 100644 index c3b2376..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN0.xsd deleted file mode 100644 index c3b2376..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_eN0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN0.xsd deleted file mode 100644 index c3b2376..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/choice_rd_scs_eN0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/oops0.xsd b/test/cases/xbean/tools/inst2xsd/schema/complex/sample/oops0.xsd deleted file mode 100644 index c3b2376..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/complex/sample/oops0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_rd0.xsd deleted file mode 100644 index bcaade9..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_rd0.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - Edited with XML Spy v4.2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_ss0.xsd deleted file mode 100644 index d805c8e..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_ss0.xsd +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Edited with XML Spy v4.2 - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_vb0.xsd deleted file mode 100644 index ddeb7c0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cd_catalog_vb0.xsd +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Edited with XML Spy v4.2 - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog.xml deleted file mode 100644 index 0751349..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - Empire Burlesque - Bob Dylan - USA - Columbia - 10.90 - 1985 - - - Empire Burlesque - Bob Dylan - USA - Columbia - 10.90 - 1985 - - - Empire Burlesque - Bob Dylan - USA - Columbia - 10.90 - 1985 - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_rd0.xsd deleted file mode 100644 index 2a86673..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_rd0.xsd +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_ss0.xsd deleted file mode 100644 index 4fe9794..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_ss0.xsd +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_vb0.xsd deleted file mode 100644 index b610f13..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/cdcatalog_vb0.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/component.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/component.xml deleted file mode 100644 index 153f8d3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/component.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/component_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/component_rd0.xsd deleted file mode 100644 index 978b74c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/component_rd0.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/component_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/component_ss0.xsd deleted file mode 100644 index 66b38a8..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/component_ss0.xsd +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/component_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/component_vb0.xsd deleted file mode 100644 index a9595c0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/component_vb0.xsd +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/html_example.xml deleted file mode 100644 index 8f0501a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - -
        - - - -
        - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_rd0.xsd deleted file mode 100644 index 42ee7c7..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_rd0.xsd +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_ss0.xsd deleted file mode 100644 index ffa96d5..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_ss0.xsd +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_vb0.xsd deleted file mode 100644 index 03574b5..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/html_example_vb0.xsd +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/po/po.xml deleted file mode 100644 index e659207..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - Alice Smith - 123 Maple Street - Mill Valley - CA - 90952 - - - Robert Smith - 8 Oak Avenue - Old Town - PA - 95819 - - Hurry, my lawn is going wild! - - - Lawnmower - 1 - 148.95 - Confirm this is electric - - - Baby Monitor - 1 - 39.98 - 1999-05-21 - - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb0.xsd deleted file mode 100644 index a018226..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/po/po_vb0.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_neverenum_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_neverenum_vb0.xsd deleted file mode 100644 index 8480bf6..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentsmart_neverenum_vb0.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_neverenum_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_neverenum_vb0.xsd deleted file mode 100644 index 473c834..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_contentstring_neverenum_vb0.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_neverenum_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_neverenum_vb0.xsd deleted file mode 100644 index 8480bf6..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/rss2sample_neverenum_vb0.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091.xml deleted file mode 100644 index 65788c3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss091.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - WriteTheWeb - http://writetheweb.com - News for web users that write back - en-us - Copyright 2000, WriteTheWeb team. - editor@writetheweb.com - webmaster@writetheweb.com - - WriteTheWeb - http://writetheweb.com/images/mynetscape88.gif - http://writetheweb.com - 88 - 31 - News for web users that write back - - - Giving the world a pluggable Gnutella - http://writetheweb.com/read.php?item=24 - WorldOS is a framework on which to build programs that work like Freenet or Gnutella -allowing distributed applications using peer-to-peer routing. - - - Syndication discussions hot up - http://writetheweb.com/read.php?item=23 - After a period of dormancy, the Syndication mailing list has become active again, with contributions from leaders in traditional media and Web syndication. - - - Personal web server integrates file sharing and messaging - http://writetheweb.com/read.php?item=22 - The Magi Project is an innovative project to create a combined personal web server and messaging system that enables the sharing and synchronization of information across desktop, laptop and palmtop devices. - - - Syndication and Metadata - http://writetheweb.com/read.php?item=21 - RSS is probably the best known metadata format around. RDF is probably one of the least understood. In this essay, published on my O'Reilly Network weblog, I argue that the next generation of RSS should be based on RDF. - - - UK bloggers get organised - http://writetheweb.com/read.php?item=20 - Looks like the weblogs scene is gathering pace beyond the shores of the US. There's now a UK-specific page on weblogs.com, and a mailing list at egroups. - - - Yournamehere.com more important than anything - http://writetheweb.com/read.php?item=19 - Whatever you're publishing on the web, your site name is the most valuable asset you have, according to Carl Steadman. - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_rd0.xsd deleted file mode 100644 index b904504..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_rd0.xsd +++ /dev/null @@ -1,66 +0,0 @@ - - - - - RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_ss0.xsd deleted file mode 100644 index f12f1a9..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_ss0.xsd +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_vb0.xsd deleted file mode 100644 index eda783f..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/sampleRss092_vb0.xsd +++ /dev/null @@ -1,61 +0,0 @@ - - - - - RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/schema0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/schema0.xsd deleted file mode 100644 index 6b3d8af..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/schema0.xsd +++ /dev/null @@ -1,61 +0,0 @@ - - - - - RSS generation done by 'Radio UserLand' on Fri, 13 Apr 2001 19:23:02 GMT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdot.rdf.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/slashdot.rdf.xml deleted file mode 100644 index 9506e03..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdot.rdf.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - -Slashdot: -http://slashdot.org/ -News for nerds, stuff that matters - - - -Slashdot: -http://images.slashdot.org/topics/topicslashdot.gif -http://slashdot.org/ - - - -Gene Doping: Genetically Engineered Athletes -http://slashdot.org/article.pl?sid=04/08/13/1819223 - - - -Microsoft Windows: A Lower Total Cost of 0wnership -http://slashdot.org/article.pl?sid=04/08/13/1621253 - - - -Speculation About An Apple Tablet -http://slashdot.org/article.pl?sid=04/08/13/1614232 - - - -Student Killed Driving Solar Car -http://slashdot.org/article.pl?sid=04/08/13/1416254 - - - -Digital Radio With Removable Flash Storage -http://slashdot.org/article.pl?sid=04/08/13/1353247 - - - -Nvidia 6600 Series Examined -http://slashdot.org/article.pl?sid=04/08/13/1341237 - - - -Open Source in California Government -http://slashdot.org/article.pl?sid=04/08/13/1317236 - - - -Spam's U.S. Roots -http://slashdot.org/article.pl?sid=04/08/13/132224 - - - -Human-powered Helicopter Fails to Lift Off -http://slashdot.org/article.pl?sid=04/08/13/1225238 - - - -BBC Begins Open-Source Streaming Challenge -http://slashdot.org/article.pl?sid=04/08/13/128249 - - - -Search Slashdot -Search Slashdot stories -query -http://slashdot.org/search.pl - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd0.xsd deleted file mode 100644 index 0223879..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_rd0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss0.xsd deleted file mode 100644 index 0223879..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_ss0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb0.xsd deleted file mode 100644 index 83e0509..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotrdf_vb0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_neverenum_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_neverenum_ss0.xsd deleted file mode 100644 index 8ed03b4..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/slashdotxml_neverenum_ss0.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews.xml deleted file mode 100644 index c45dda3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - Colombia Earthquake - - - - - - - 143 Dead in Colombia Earthquake - - - By Jared Kotler, Associated Press Writer - - - Bogota, Colombia - Monday January 25 1999 7:28 ET - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_rd0.xsd deleted file mode 100644 index cc30867..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_rd0.xsd +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_ss0.xsd deleted file mode 100644 index 4379902..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_ss0.xsd +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_vb0.xsd deleted file mode 100644 index 6190d6e..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xmlnews_vb0.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_example.xml b/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_example.xml deleted file mode 100644 index b9448be..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_example.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - -
        TitleArtist
        - - - -
        - - -
        -
        \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_rd0.xsd deleted file mode 100644 index 09670a0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_rd0.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_ss0.xsd deleted file mode 100644 index 5830e73..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_ss0.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_ss1.xsd deleted file mode 100644 index 93d60df..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_ss1.xsd +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_vb0.xsd deleted file mode 100644 index 9566f5d..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_vb0.xsd +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_vb1.xsd deleted file mode 100644 index 1ca4ff1..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/examples/xsl_vb1.xsd +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS.xml b/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS.xml deleted file mode 100644 index 0c4a23f..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS.xml +++ /dev/null @@ -1,17 +0,0 @@ - - abc - 123 - - abc - 123 - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_rd0.xsd deleted file mode 100644 index 1950c15..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_rd0.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_ss0.xsd deleted file mode 100644 index 0d6b937..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_ss0.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_vb0.xsd deleted file mode 100644 index 451e680..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/duplicatedNS_vb0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS.xml b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS.xml deleted file mode 100644 index a5a0c85..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS.xml +++ /dev/null @@ -1,10 +0,0 @@ - - abc - 123 - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd0.xsd deleted file mode 100644 index c256714..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd1.xsd deleted file mode 100644 index 745d73c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd1.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd2.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd2.xsd deleted file mode 100644 index 36c21f3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd2.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd3.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd3.xsd deleted file mode 100644 index 9cdfd90..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_rd3.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss0.xsd deleted file mode 100644 index c256714..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss1.xsd deleted file mode 100644 index 745d73c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss1.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss2.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss2.xsd deleted file mode 100644 index 36c21f3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss2.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss3.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss3.xsd deleted file mode 100644 index 17dc87b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_ss3.xsd +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb0.xsd deleted file mode 100644 index c256714..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb1.xsd deleted file mode 100644 index 745d73c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb1.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb2.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb2.xsd deleted file mode 100644 index 36c21f3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb2.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb3.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb3.xsd deleted file mode 100644 index 81f0fbe..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNS_vb3.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS.xml b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS.xml deleted file mode 100644 index 90101b3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS.xml +++ /dev/null @@ -1,12 +0,0 @@ - - abc - 123 - - bcd - 123 - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd0.xsd deleted file mode 100644 index 9fff009..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd1.xsd deleted file mode 100644 index e3ce003..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd2.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd2.xsd deleted file mode 100644 index 36c21f3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd2.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd3.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd3.xsd deleted file mode 100644 index 0906c65..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_rd3.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss0.xsd deleted file mode 100644 index 9fff009..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss1.xsd deleted file mode 100644 index e3ce003..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss2.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss2.xsd deleted file mode 100644 index d7eb664..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss2.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss3.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss3.xsd deleted file mode 100644 index 36c21f3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_ss3.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb0.xsd deleted file mode 100644 index 9fff009..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb0.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb1.xsd deleted file mode 100644 index e3ce003..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb2.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb2.xsd deleted file mode 100644 index 36c21f3..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb2.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb3.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb3.xsd deleted file mode 100644 index ba9a46b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/multipleNestedNS_vb3.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must.xml b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must.xml deleted file mode 100644 index 857e401..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_rd0.xsd deleted file mode 100644 index 1227f0a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_rd0.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_rd1.xsd deleted file mode 100644 index 2875a9b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_rd1.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_ss0.xsd deleted file mode 100644 index 1227f0a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_ss0.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_ss1.xsd deleted file mode 100644 index 2875a9b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_ss1.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_vb0.xsd deleted file mode 100644 index 02f60e2..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_vb0.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_vb1.xsd deleted file mode 100644 index 7026c33..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/must_vb1.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple.xml b/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple.xml deleted file mode 100644 index b22750b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple.xml +++ /dev/null @@ -1,6 +0,0 @@ - - abc - 123 - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_rd0.xsd deleted file mode 100644 index 878f603..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_rd0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_ss0.xsd deleted file mode 100644 index d19ecea..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_ss0.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_vb0.xsd deleted file mode 100644 index 8a9063a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/namespaces/simple_vb0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/simpleName.xml b/test/cases/xbean/tools/inst2xsd/schema/simpleName.xml deleted file mode 100644 index 6eec001..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/simpleName.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Bill - Gates - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/simpleName_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/simpleName_rd0.xsd deleted file mode 100644 index 1013acd..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/simpleName_rd0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/simpleName_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/simpleName_ss0.xsd deleted file mode 100644 index 98069bd..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/simpleName_ss0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/simpleName_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/simpleName_vb0.xsd deleted file mode 100644 index e1d3d87..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/simpleName_vb0.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/CData.xml b/test/cases/xbean/tools/inst2xsd/schema/types/CData.xml deleted file mode 100644 index 7de8370..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/CData.xml +++ /dev/null @@ -1,15 +0,0 @@ - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/cdata_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/cdata_rd0.xsd deleted file mode 100644 index 3aaab03..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/cdata_rd0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/cdata_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/cdata_ss0.xsd deleted file mode 100644 index 3aaab03..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/cdata_ss0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/cdata_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/cdata_vb0.xsd deleted file mode 100644 index 3aaab03..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/cdata_vb0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/comments.xml b/test/cases/xbean/tools/inst2xsd/schema/types/comments.xml deleted file mode 100644 index 2fa143a..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/comments.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 123456 - - asdsa - 12323 - - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/comments_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/comments_rd0.xsd deleted file mode 100644 index 56e751b..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/comments_rd0.xsd +++ /dev/null @@ -1,37 +0,0 @@ - - - - - final comment - - - - - - this is a comment 1 - - - - - this is a comment 2 - - - - - this is a comment 4 this is a comment 5 - - - - - this is a comment 6 - - - - - this is a comment 7 this is a comment 8 - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/comments_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/comments_ss0.xsd deleted file mode 100644 index 0bc8aab..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/comments_ss0.xsd +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - final comment - - - - - - this is a comment 1 - - - - - this is a comment 2 - - - - - this is a comment 4 this is a comment 5 - - - - - this is a comment 6 - - - - - this is a comment 7 this is a comment 8 - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/comments_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/comments_vb0.xsd deleted file mode 100644 index 7fc36b8..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/comments_vb0.xsd +++ /dev/null @@ -1,37 +0,0 @@ - - - - - final comment - - - - - - - this is a comment 1 - - - - - this is a comment 2 - - - - - this is a comment 4 this is a comment 5 - - - - - this is a comment 6 - - - - - this is a comment 7 this is a comment 8 - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice.xml b/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice.xml deleted file mode 100644 index a55fcfb..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 123456 - - asdsa - 12323 - - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNrd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNrd0.xsd deleted file mode 100644 index f1673a0..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNrd0.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - final comment - - - - - - this is a comment 1 - - - - - this is a comment 4 this is a comment 5 - - - - - this is a comment 7 this is a comment 8 - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNss0.xsd deleted file mode 100644 index ad92de9..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNss0.xsd +++ /dev/null @@ -1,30 +0,0 @@ - - - - - final comment - - - - - - this is a comment 1 - - - - - this is a comment 4 this is a comment 5 - - - - - this is a comment 7 this is a comment 8 - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNvb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNvb0.xsd deleted file mode 100644 index bdcc34f..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_eNvb0.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - final comment - - - - - - - this is a comment 1 - - - - - this is a comment 4 this is a comment 5 - - - - - this is a comment 7 this is a comment 8 - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_vb0.xsd deleted file mode 100644 index 4f7bd68..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/commentschoice_vb0.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - final comment - - - - - - - this is a comment 1 - - - - - this is a comment 4 this is a comment 5 - - - - - - - - - - - this is a comment 7 this is a comment 8 - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/innercomment.xml b/test/cases/xbean/tools/inst2xsd/schema/types/innercomment.xml deleted file mode 100644 index 05d038c..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/innercomment.xml +++ /dev/null @@ -1,4 +0,0 @@ - - 1232323 - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/innercomment_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/innercomment_vb0.xsd deleted file mode 100644 index e1390dd..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/innercomment_vb0.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - this is a comment 6 - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/person.xml b/test/cases/xbean/tools/inst2xsd/schema/types/person.xml deleted file mode 100644 index 44f9ef9..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/person.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/po.xml b/test/cases/xbean/tools/inst2xsd/schema/types/po.xml deleted file mode 100644 index 48567f5..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/po.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - John Smith - - Ola Nordmann -
        Langgt 23
        - 4000 Stavanger - Norway -
        - - Empire Burlesque - Special Edition - 1 - 10.90 - - - Hide your heart - 1 - 9.90 - -
        \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/po_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/po_vb0.xsd deleted file mode 100644 index 11b675d..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/po_vb0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation.xml b/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation.xml deleted file mode 100644 index b593c91..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation.xml +++ /dev/null @@ -1,21 +0,0 @@ - - John - 28 - 59 - - Red - 4 - 2 - - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb0.xsd deleted file mode 100644 index fc70eac..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb0.xsd +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb1.xsd deleted file mode 100644 index b0d1024..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb1.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb2.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb2.xsd deleted file mode 100644 index 5b528fe..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb2.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb3.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb3.xsd deleted file mode 100644 index 04c1f51..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/schemaLocation_vb3.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/unicode.xml b/test/cases/xbean/tools/inst2xsd/schema/types/unicode.xml deleted file mode 100644 index b153ab7..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/unicode.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - Jani - Tove - Norwegian: ���. French: ��� - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/unicode_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/unicode_rd0.xsd deleted file mode 100644 index 2532193..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/unicode_rd0.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/unicode_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/unicode_ss0.xsd deleted file mode 100644 index 417b6a2..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/unicode_ss0.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/unicode_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/unicode_vb0.xsd deleted file mode 100644 index 21235f8..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/unicode_vb0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil.xml b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil.xml deleted file mode 100644 index 73d3376..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil.xml +++ /dev/null @@ -1,5 +0,0 @@ - - John - - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_rd0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_rd0.xsd deleted file mode 100644 index 753e5cd..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_rd0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_rd1.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_rd1.xsd deleted file mode 100644 index c1c91fa..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_rd1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_ss0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_ss0.xsd deleted file mode 100644 index 753e5cd..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_ss0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_ss1.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_ss1.xsd deleted file mode 100644 index c1c91fa..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_ss1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_vb0.xsd deleted file mode 100644 index 7638ea6..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_vb0.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_vb1.xsd deleted file mode 100644 index c1c91fa..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsinil_vb1.xsd +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsitype.xml b/test/cases/xbean/tools/inst2xsd/schema/types/xsitype.xml deleted file mode 100644 index 43ad7da..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsitype.xml +++ /dev/null @@ -1,8 +0,0 @@ - - John - 59 - manager - diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsitype_vb0.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsitype_vb0.xsd deleted file mode 100644 index 802c799..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsitype_vb0.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/tools/inst2xsd/schema/types/xsitype_vb1.xsd b/test/cases/xbean/tools/inst2xsd/schema/types/xsitype_vb1.xsd deleted file mode 100644 index e254b4d..0000000 --- a/test/cases/xbean/tools/inst2xsd/schema/types/xsitype_vb1.xsd +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/usertype/averageCase/po.xsd b/test/cases/xbean/usertype/averageCase/po.xsd deleted file mode 100644 index 5779045..0000000 --- a/test/cases/xbean/usertype/averageCase/po.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - Purchase order schema for Example.com. - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/usertype/multipleItems/company.xsd b/test/cases/xbean/usertype/multipleItems/company.xsd deleted file mode 100644 index 0bd26cc..0000000 --- a/test/cases/xbean/usertype/multipleItems/company.xsd +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/CR196679.xsd b/test/cases/xbean/xmlcursor/CR196679.xsd deleted file mode 100644 index 4a971b8..0000000 --- a/test/cases/xbean/xmlcursor/CR196679.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/CarLocationMessage.xml b/test/cases/xbean/xmlcursor/CarLocationMessage.xml deleted file mode 100755 index bc751d9..0000000 --- a/test/cases/xbean/xmlcursor/CarLocationMessage.xml +++ /dev/null @@ -1,38 +0,0 @@ - - FLEETNAME - CSXT - - - GATX - 123456 - L - - 2001-03-23 - - - P - - Q12345 - - DALLAS - TX - - CSXT - - - DALLAS - TX - - - - - DALLAS - TX - - 2001-03-23 - - P - - Y - - diff --git a/test/cases/xbean/xmlcursor/Employees.xml b/test/cases/xbean/xmlcursor/Employees.xml deleted file mode 100755 index 4575895..0000000 --- a/test/cases/xbean/xmlcursor/Employees.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - Fred Jones - - 900 Aurora Ave. - Seattle - WA - 98115 - - - 2011 152nd Avenue NE - Redmond - WA - 98052 - - (425)555-5665 - (206)555-5555 - (206)555-4321 - - - Sally Smith - - 1430 Oak Place - Salem - OR - 97125 - - - 765 Main St. - Kaiser - OR - 97103 - - (503)555-3856 - (503)555-6951 - (503)555-5152 - - - Gladys Kravitz - - 1313 Mockingbird Lane - Seattle - WA - 98115 - - - 2011 152nd Avenue NE - Redmond - WA - 98052 - - (425)555-6897 - (206)555-6594 - (206)555-7894 - - diff --git a/test/cases/xbean/xmlcursor/XQueryInput.xml b/test/cases/xbean/xmlcursor/XQueryInput.xml deleted file mode 100644 index 7ea5193..0000000 --- a/test/cases/xbean/xmlcursor/XQueryInput.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - Bob - 1000 - - - Beth - 1001 - - - NotBob - 1000 - - - diff --git a/test/cases/xbean/xmlcursor/XQueryInput.xsd b/test/cases/xbean/xmlcursor/XQueryInput.xsd deleted file mode 100644 index d40d80b..0000000 --- a/test/cases/xbean/xmlcursor/XQueryInput.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/doc.xml b/test/cases/xbean/xmlcursor/doc.xml deleted file mode 100755 index 6f92a76..0000000 --- a/test/cases/xbean/xmlcursor/doc.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/location.xsd b/test/cases/xbean/xmlcursor/location.xsd deleted file mode 100755 index fd80031..0000000 --- a/test/cases/xbean/xmlcursor/location.xsd +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/person.xsd b/test/cases/xbean/xmlcursor/person.xsd deleted file mode 100755 index 2067850..0000000 --- a/test/cases/xbean/xmlcursor/person.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/po.xml b/test/cases/xbean/xmlcursor/po.xml deleted file mode 100755 index b3b702a..0000000 --- a/test/cases/xbean/xmlcursor/po.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - Alice Smith - 123 Maple Street - Mill Valley - CA - 90952 - - - Robert Smith - 8 Oak Avenue - Old Town - PA - 95819 - - Hurry, my lawn is going wild! - - - Lawnmower - 1 - 148.95 - Confirm this is electric - - - Baby Monitor - 1 - 39.98 - 1999-05-21 - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/po.xsd b/test/cases/xbean/xmlcursor/po.xsd deleted file mode 100755 index afdca90..0000000 --- a/test/cases/xbean/xmlcursor/po.xsd +++ /dev/null @@ -1,62 +0,0 @@ - - - - - Purchase order schema for Example.com. - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xpath/cdcatalog.xml b/test/cases/xbean/xmlcursor/xpath/cdcatalog.xml deleted file mode 100755 index 4fcbac9..0000000 --- a/test/cases/xbean/xmlcursor/xpath/cdcatalog.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - - Empire Burlesque - Bob Dylan - USA - Columbia - 10.90 - 1985 - - - Hide your heart - Bonnie Tyler - UK - CBS Records - 9.90 - 1988 - - - Greatest Hits - Dolly Parton - USA - RCA - 9.90 - 1982 - - - Still got the blues - Gary Moore - UK - Virgin records - 10.20 - 1990 - - - Eros - Eros Ramazzotti - EU - BMG - 9.90 - 1997 - - - One night only - Bee Gees - UK - Polydor - 10.90 - 1998 - - - Sylvias Mother - Dr.Hook - UK - CBS - 8.10 - 1973 - - - Maggie May - Rod Stewart - UK - Pickwick - 8.50 - 1990 - - - Romanza - Andrea Bocelli - EU - Polydor - 10.80 - 1996 - - - When a man loves a woman - Percy Sledge - USA - Atlantic - 8.70 - 1987 - - - Black angel - Savage Rose - EU - Mega - 10.90 - 1995 - - - 1999 Grammy Nominees - Many - USA - Grammy - 10.20 - 1999 - - - For the good times - Kenny Rogers - UK - Mucik Master - 8.70 - 1995 - - - Big Willie style - Will Smith - USA - Columbia - 9.90 - 1997 - - - Tupelo Honey - Van Morrison - UK - Polydor - 8.20 - 1971 - - - Soulsville - Jorn Hoel - Norway - WEA - 7.90 - 1996 - - - The very best of - Cat Stevens - UK - Island - 8.90 - 1990 - - - Stop - Sam Brown - UK - A and M - 8.90 - 1988 - - - Bridge of Spies - T`Pau - UK - Siren - 7.90 - 1987 - - - Private Dancer - Tina Turner - UK - Capitol - 8.90 - 1983 - - - Midt om natten - Kim Larsen - EU - Medley - 7.80 - 1983 - - - Pavarotti Gala Concert - Luciano Pavarotti - UK - DECCA - 9.90 - 1991 - - - The dock of the bay - Otis Redding - USA - Atlantic - 7.90 - 1987 - - - Picture book - Simply Red - EU - Elektra - 7.20 - 1985 - - - Red - The Communards - UK - London - 7.80 - 1987 - - - Unchain my heart - Joe Cocker - USA - EMI - 8.20 - 1987 - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/axis.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/axis.xml deleted file mode 100755 index bc996c5..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/axis.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/basic.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/basic.xml deleted file mode 100755 index 88385fb..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/basic.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/basicupdate.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/basicupdate.xml deleted file mode 100755 index 57d458c..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/basicupdate.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - Goudse kaas - Rond - - - - - - - More cheese! - - - - - Even more cheese! - - - - - No sausages today - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/defaultNamespace.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/defaultNamespace.xml deleted file mode 100755 index 1e32981..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/defaultNamespace.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - Hello - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/evaluate.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/evaluate.xml deleted file mode 100755 index 90d06bd..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/evaluate.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - brown - - - moderate - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/fibo.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/fibo.xml deleted file mode 100755 index 9b5d0ec..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/fibo.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 0 - 1 - 1 - 2 - 3 - 5 - 8 - 13 - 21 - 34 - 55 - 89 - 144 - 233 - 377 - 610 - 987 - 1597 - 2584 - 4181 - 6765 - 10946 - 17711 - 28657 - 46368 - 75025 - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/id.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/id.xml deleted file mode 100755 index 749ab20..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/id.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - -]> - - - - baz - gouda - baz - cheddar - baz - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/lang.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/lang.xml deleted file mode 100755 index 49b45db..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/lang.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/message.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/message.xml deleted file mode 100755 index 3b81df2..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/message.xml +++ /dev/null @@ -1,27 +0,0 @@ - - -
        - lookupformservice - 9 - stammdaten - new -
        - - - - - iteminfo - ELE - - - parentinfo - Pruefgebiete - - - id - 1 - - - - -
        diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/namespaces.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/namespaces.xml deleted file mode 100755 index e8e4df8..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/namespaces.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - Hello - - - - Hey - - - - Hey2 - - - - Hey3 - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/numbers.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/numbers.xml deleted file mode 100755 index a1791cd..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/numbers.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - 3 - 24 - 55 - 11 - 2 - -3 - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/pi.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/pi.xml deleted file mode 100755 index 980bbf9..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/pi.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/pi2.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/pi2.xml deleted file mode 100755 index 46bce45..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/pi2.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - foo - - bar - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/simple.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/simple.xml deleted file mode 100755 index 126ea0c..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/simple.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - a - b - - d - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/testNamespaces.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/testNamespaces.xml deleted file mode 100755 index cdc99f1..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/testNamespaces.xml +++ /dev/null @@ -1,21 +0,0 @@ - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/text.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/text.xml deleted file mode 100755 index e1865c7..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/text.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - baz - - baz - - baz - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/underscore.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/underscore.xml deleted file mode 100755 index 111446f..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/underscore.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - 1 - <_b>2 - - diff --git a/test/cases/xbean/xmlcursor/xpath/jaxen/web.xml b/test/cases/xbean/xmlcursor/xpath/jaxen/web.xml deleted file mode 100755 index 972cf5d..0000000 --- a/test/cases/xbean/xmlcursor/xpath/jaxen/web.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - snoop - SnoopServlet - - - file - ViewFile - - initial - - 1000 - - - The initial value for the counter - - - - - - mv - - - *.wm - - - - - - - - manager - - - director - - - president - - - diff --git a/test/cases/xbean/xmlcursor/xquery/2DocJoin.xq b/test/cases/xbean/xmlcursor/xquery/2DocJoin.xq deleted file mode 100644 index e69de29..0000000 diff --git a/test/cases/xbean/xmlcursor/xquery/Constructor.xq b/test/cases/xbean/xmlcursor/xquery/Constructor.xq deleted file mode 100644 index 811cc4e..0000000 --- a/test/cases/xbean/xmlcursor/xquery/Constructor.xq +++ /dev/null @@ -1,6 +0,0 @@ -for $e in .//employee -return - - { $e/name } - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/xquery/Join.xq b/test/cases/xbean/xmlcursor/xquery/Join.xq deleted file mode 100644 index a2a10f1..0000000 --- a/test/cases/xbean/xmlcursor/xquery/Join.xq +++ /dev/null @@ -1,10 +0,0 @@ -for $a in .//employee -return - { $a/ssn }, - { $a/name }, - { - for $b in .//employee - where $b/ssn=$a/ssn and $a/name !=$b/name - return $b/name - } - diff --git a/test/cases/xbean/xmlcursor/xquery/bookstore.xml b/test/cases/xbean/xmlcursor/xquery/bookstore.xml deleted file mode 100644 index 45423fc..0000000 --- a/test/cases/xbean/xmlcursor/xquery/bookstore.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - Everyday Italian - Giada De Laurentiis - 2005 - 30.00 - - - - Harry Potter - J K. Rowling - 2005 - 29.99 - - - - XQuery Kick Start - James McGovern - Per Bothner - Kurt Cagle - James Linn - Vaidyanathan Nagarajan - 2003 - 49.99 - - - - Learning XML - Erik T. Ray - 2003 - 39.95 - - - diff --git a/test/cases/xbean/xmlcursor/xquery/employees.xml b/test/cases/xbean/xmlcursor/xquery/employees.xml deleted file mode 100644 index fcadbc5..0000000 --- a/test/cases/xbean/xmlcursor/xquery/employees.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - Fred Jones -
        - 900 Aurora Ave. - Seattle - WA - 98115 -
        -
        - 2011 152nd Avenue NE - Redmond - WA - 98052 -
        - (425)555-5665 - (206)555-5555 - (206)555-4321 -
        - - Sally Smith -
        - 1430 Oak Place - Salem - OR - 97125 -
        -
        - 765 Main St. - Keizer - OR - 97303 -
        - (503)555-3856 - (503)555-6951 - (503)555-5152 -
        - - Gladys Kravitz -
        - 1313 Mockingbird Lane - Seattle - WA - 98115 -
        -
        - 2011 152nd Avenue NE - Redmond - WA - 98052 -
        - (425)555-6897 - (206)555-6594 - (206)555-7894 -
        -
        diff --git a/test/cases/xbean/xmlcursor/xquery/xmlUseCases/catalog.xml b/test/cases/xbean/xmlcursor/xquery/xmlUseCases/catalog.xml deleted file mode 100644 index 3de5563..0000000 --- a/test/cases/xbean/xmlcursor/xquery/xmlUseCases/catalog.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/xquery/xmlUseCases/catalog.xsd b/test/cases/xbean/xmlcursor/xquery/xmlUseCases/catalog.xsd deleted file mode 100644 index d8cd0ed..0000000 --- a/test/cases/xbean/xmlcursor/xquery/xmlUseCases/catalog.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlcursor/xstypes/default.xsd b/test/cases/xbean/xmlcursor/xstypes/default.xsd deleted file mode 100755 index f4e8ae5..0000000 --- a/test/cases/xbean/xmlcursor/xstypes/default.xsd +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xstypes/person.xsd b/test/cases/xbean/xmlcursor/xstypes/person.xsd deleted file mode 100755 index a99c632..0000000 --- a/test/cases/xbean/xmlcursor/xstypes/person.xsd +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xstypes/setters.xsd b/test/cases/xbean/xmlcursor/xstypes/setters.xsd deleted file mode 100755 index 5155cd7..0000000 --- a/test/cases/xbean/xmlcursor/xstypes/setters.xsd +++ /dev/null @@ -1,6 +0,0 @@ - - - diff --git a/test/cases/xbean/xmlcursor/xstypes/simplec.xsd b/test/cases/xbean/xmlcursor/xstypes/simplec.xsd deleted file mode 100755 index f7076a9..0000000 --- a/test/cases/xbean/xmlcursor/xstypes/simplec.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlcursor/xstypes/xstypes.xml b/test/cases/xbean/xmlcursor/xstypes/xstypes.xml deleted file mode 100755 index 8d30b88..0000000 --- a/test/cases/xbean/xmlcursor/xstypes/xstypes.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - Howdy - 436 - 123 - 1998-08-26Z - 44 - 933 - 2000-08-06-08:00 - 454749515457595A4A - VGhpcyBzdHJpbmcgaXMgYmFzZTY0QmluYXJ5IGVuY29kZWQh - http://3space.org/space%20space/ - openuri_org_localname - GIF - diff --git a/test/cases/xbean/xmlobject/CR192525.xsd b/test/cases/xbean/xmlobject/CR192525.xsd deleted file mode 100644 index 9f30a37..0000000 --- a/test/cases/xbean/xmlobject/CR192525.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/SelectAttribute-Doc.xml b/test/cases/xbean/xmlobject/SelectAttribute-Doc.xml deleted file mode 100755 index 1733453..0000000 --- a/test/cases/xbean/xmlobject/SelectAttribute-Doc.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/SelectAttribute.xsd b/test/cases/xbean/xmlobject/SelectAttribute.xsd deleted file mode 100755 index 9f2f993..0000000 --- a/test/cases/xbean/xmlobject/SelectAttribute.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/SelectChildren-AnyTypeDoc.xml b/test/cases/xbean/xmlobject/SelectChildren-AnyTypeDoc.xml deleted file mode 100755 index 35519de..0000000 --- a/test/cases/xbean/xmlobject/SelectChildren-AnyTypeDoc.xml +++ /dev/null @@ -1,14 +0,0 @@ - - Simple String - - ABC Namespace - DEF Namespace - XYX Namespace - - ABC-SameElem - DEF-SameElem - XYZ-SameElem - diff --git a/test/cases/xbean/xmlobject/SelectChildren-NormalDoc.xml b/test/cases/xbean/xmlobject/SelectChildren-NormalDoc.xml deleted file mode 100755 index ea1ca16..0000000 --- a/test/cases/xbean/xmlobject/SelectChildren-NormalDoc.xml +++ /dev/null @@ -1,7 +0,0 @@ - - first element - second element - 10 - 11 - 12 - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/SelectChildren.xsd b/test/cases/xbean/xmlobject/SelectChildren.xsd deleted file mode 100755 index 8329b28..0000000 --- a/test/cases/xbean/xmlobject/SelectChildren.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/SimpleXmlObject.java.txt b/test/cases/xbean/xmlobject/SimpleXmlObject.java.txt deleted file mode 100755 index 8a27c3d..0000000 --- a/test/cases/xbean/xmlobject/SimpleXmlObject.java.txt +++ /dev/null @@ -1,68 +0,0 @@ - -import javax.xml.namespace.QName; -import org.apache.xmlbeans.*; - -import dumbNS.RootDocument; - - -/** - * Test Class that extends the abstract base class FilterXmlObject - * The only method that needs to be implemented is underlyingXmlObject(); - * - * @author: Raju Subramanian. - */ - -public class SimpleXmlObject - extends FilterXmlObject -{ - - /** - * The underlying XmlObject to which all calls will be delegated - */ - private transient XmlObject _under; - - /** - * Default constructor that creates a XmlObject from the instance - * xbean/simple/dumb/dumb.xml - */ - public SimpleXmlObject() - throws Exception - { - try { - String xml = ""+ - ""; - RootDocument rootDoc = (RootDocument)XmlObject.Factory.parse(xml); - // Set the underlying XmlObject - _under = (XmlObject) rootDoc; - - } catch (Exception e) - { - throw new Exception("Error creating XmlObject: " + e); - } - } - - /** - * The underlyingXmlObject() implementation - */ - public XmlObject underlyingXmlObject() - { - return _under; - } - - public XmlObject substitute(javax.xml.namespace.QName qName,org.apache.xmlbeans.SchemaType schemaType){ - return underlyingXmlObject().substitute(qName, schemaType); - } - - public void dump(){ - System.out.println( _under.xmlText()); - } - - /** - * - */ - public static void main (String args[]) throws Exception - { - SimpleXmlObject test = new SimpleXmlObject(); - System.out.println(test.xmlText()); - } -} \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/Test.xsd b/test/cases/xbean/xmlobject/Test.xsd deleted file mode 100755 index f5b686e..0000000 --- a/test/cases/xbean/xmlobject/Test.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/Test36510.xsd b/test/cases/xbean/xmlobject/Test36510.xsd deleted file mode 100755 index f90eca5..0000000 --- a/test/cases/xbean/xmlobject/Test36510.xsd +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/Test40907.xsd b/test/cases/xbean/xmlobject/Test40907.xsd deleted file mode 100755 index 54263f8..0000000 --- a/test/cases/xbean/xmlobject/Test40907.xsd +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/defaults.xsd b/test/cases/xbean/xmlobject/defaults.xsd deleted file mode 100755 index f9a2116..0000000 --- a/test/cases/xbean/xmlobject/defaults.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/easypo.xsd b/test/cases/xbean/xmlobject/easypo.xsd deleted file mode 100755 index 769c68c..0000000 --- a/test/cases/xbean/xmlobject/easypo.xsd +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/easypo1.xml b/test/cases/xbean/xmlobject/easypo1.xml deleted file mode 100755 index f8d877e..0000000 --- a/test/cases/xbean/xmlobject/easypo1.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - David Bau - Gladwyne, PA - - 2002-09-30T14:16:00-05:00 - - Burnham's Celestial Handbook, Vol 1 - 5 - 21.79 - 2 - - - Burnham's Celestial Handbook, Vol 2 - 5 - 19.89 - 2 - - - Burnham's Celestial Handbook, Vol 3 - 5 - 19.89 - 1 - - - UPS - 0.74 - - diff --git a/test/cases/xbean/xmlobject/enumtest.xml b/test/cases/xbean/xmlobject/enumtest.xml deleted file mode 100755 index b5268cb..0000000 --- a/test/cases/xbean/xmlobject/enumtest.xml +++ /dev/null @@ -1,6 +0,0 @@ - - all - few - most - none - diff --git a/test/cases/xbean/xmlobject/enumtest.xsdconfig b/test/cases/xbean/xmlobject/enumtest.xsdconfig deleted file mode 100755 index 60de8cb..0000000 --- a/test/cases/xbean/xmlobject/enumtest.xsdconfig +++ /dev/null @@ -1,7 +0,0 @@ - - - - com.enumtest - - - diff --git a/test/cases/xbean/xmlobject/inttest.xsd b/test/cases/xbean/xmlobject/inttest.xsd deleted file mode 100755 index c1721de..0000000 --- a/test/cases/xbean/xmlobject/inttest.xsd +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - Degrees of Latitude - See USMTF field latitude.degrees.17.1 - TBD - - - - - - - - - - - - - Degrees of Longitude - See USMTF field longitude.degrees.18.1 - TBD - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/listandunion.xsd b/test/cases/xbean/xmlobject/listandunion.xsd deleted file mode 100755 index 87deaa8..0000000 --- a/test/cases/xbean/xmlobject/listandunion.xsd +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/nameworld.xml b/test/cases/xbean/xmlobject/nameworld.xml deleted file mode 100755 index 652561f..0000000 --- a/test/cases/xbean/xmlobject/nameworld.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/nameworld.xsd b/test/cases/xbean/xmlobject/nameworld.xsd deleted file mode 100755 index 8cd0ae8..0000000 --- a/test/cases/xbean/xmlobject/nameworld.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/numerals.xsd b/test/cases/xbean/xmlobject/numerals.xsd deleted file mode 100755 index 612c18d..0000000 --- a/test/cases/xbean/xmlobject/numerals.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/person.xml b/test/cases/xbean/xmlobject/person.xml deleted file mode 100755 index 8d30b88..0000000 --- a/test/cases/xbean/xmlobject/person.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - Howdy - 436 - 123 - 1998-08-26Z - 44 - 933 - 2000-08-06-08:00 - 454749515457595A4A - VGhpcyBzdHJpbmcgaXMgYmFzZTY0QmluYXJ5IGVuY29kZWQh - http://3space.org/space%20space/ - openuri_org_localname - GIF - diff --git a/test/cases/xbean/xmlobject/person.xsd b/test/cases/xbean/xmlobject/person.xsd deleted file mode 100755 index a99c632..0000000 --- a/test/cases/xbean/xmlobject/person.xsd +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/redefine1.xsd b/test/cases/xbean/xmlobject/redefine1.xsd deleted file mode 100755 index 9a6c300..0000000 --- a/test/cases/xbean/xmlobject/redefine1.xsd +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/redefine2.xsd b/test/cases/xbean/xmlobject/redefine2.xsd deleted file mode 100755 index 8e2dc81..0000000 --- a/test/cases/xbean/xmlobject/redefine2.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/soapfaults.xsd b/test/cases/xbean/xmlobject/soapfaults.xsd deleted file mode 100755 index 47e7453..0000000 --- a/test/cases/xbean/xmlobject/soapfaults.xsd +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Comment describing your root element - - - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/store/ConsolidateTest.xml b/test/cases/xbean/xmlobject/store/ConsolidateTest.xml deleted file mode 100755 index 821086a..0000000 --- a/test/cases/xbean/xmlobject/store/ConsolidateTest.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - Fred Jones -
        - 900 Aurora Ave. - Seattle - WA - 98109 -
        -
        - 2011 152nd Avenue NE - Redmond - WA - 98052 -
        - (425)641-9385 - (206)441-1695 - (206)714-2515 -
        - - Sally Smith -
        - 1430 Oak Place - Salem - OR - 97125 -
        -
        - 765 Main St. - Kaiser - OR - 97103 -
        - (503)264-3856 - (503)416-6951 - (503)214-5152 -
        -
        diff --git a/test/cases/xbean/xmlobject/store/easypo1.xml b/test/cases/xbean/xmlobject/store/easypo1.xml deleted file mode 100755 index f8d877e..0000000 --- a/test/cases/xbean/xmlobject/store/easypo1.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - David Bau - Gladwyne, PA - - 2002-09-30T14:16:00-05:00 - - Burnham's Celestial Handbook, Vol 1 - 5 - 21.79 - 2 - - - Burnham's Celestial Handbook, Vol 2 - 5 - 19.89 - 2 - - - Burnham's Celestial Handbook, Vol 3 - 5 - 19.89 - 1 - - - UPS - 0.74 - - diff --git a/test/cases/xbean/xmlobject/store/erictest.xml b/test/cases/xbean/xmlobject/store/erictest.xml deleted file mode 100755 index 3b993bd..0000000 --- a/test/cases/xbean/xmlobject/store/erictest.xml +++ /dev/null @@ -1 +0,0 @@ -12 \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/store/small.xml b/test/cases/xbean/xmlobject/store/small.xml deleted file mode 100755 index cde6453..0000000 --- a/test/cases/xbean/xmlobject/store/small.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - diff --git a/test/cases/xbean/xmlobject/store/test.xml b/test/cases/xbean/xmlobject/store/test.xml deleted file mode 100755 index 75d928a..0000000 --- a/test/cases/xbean/xmlobject/store/test.xml +++ /dev/null @@ -1 +0,0 @@ -ab \ No newline at end of file diff --git a/test/cases/xbean/xmlobject/version1.xsddonotcompile b/test/cases/xbean/xmlobject/version1.xsddonotcompile deleted file mode 100644 index ad0b8af..0000000 --- a/test/cases/xbean/xmlobject/version1.xsddonotcompile +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/version2.xsddonotcompile b/test/cases/xbean/xmlobject/version2.xsddonotcompile deleted file mode 100644 index c41d212..0000000 --- a/test/cases/xbean/xmlobject/version2.xsddonotcompile +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmlobject/version3.xsd b/test/cases/xbean/xmlobject/version3.xsd deleted file mode 100644 index ec2a357..0000000 --- a/test/cases/xbean/xmlobject/version3.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/test/cases/xbean/xmltokensource/PrettyPrintNamespaceTest.xsd b/test/cases/xbean/xmltokensource/PrettyPrintNamespaceTest.xsd deleted file mode 100755 index 99adf3c..0000000 --- a/test/cases/xbean/xmltokensource/PrettyPrintNamespaceTest.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/test/perf/build.xml b/test/perf/build.xml index 738548a..ccf97e8 100644 --- a/test/perf/build.xml +++ b/test/perf/build.xml @@ -348,7 +348,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="tools.classpath" includes="org/apache/xmlbeans/test/tools/**" - source="1.6"> + source="1.8"> @@ -363,7 +363,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="svn.classpath" includes="org/apache/xmlbeans/test/performance/svn/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> @@ -378,7 +378,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="v1.classpath" includes="org/apache/xmlbeans/test/performance/v1/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> @@ -393,7 +393,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="v2.classpath" includes="org/apache/xmlbeans/test/performance/v2/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> @@ -408,7 +408,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="castor.classpath" includes="org/apache/xmlbeans/test/performance/castor/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> @@ -424,7 +424,7 @@ classpathref="jibx.classpath" includes="org/apache/xmlbeans/test/performance/jibx/**,org/apache/xmlbeans/test/performance/utils/**" excludes="org/apache/xmlbeans/test/performance/jibx/binding/**" - source="1.6"> + source="1.8"> @@ -439,7 +439,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="jaxb.classpath" includes="org/apache/xmlbeans/test/performance/jaxb/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> @@ -470,7 +470,7 @@ executable="${env.JAVA_HOME}/bin/javac" classpathref="xerces.classpath" includes="org/apache/xmlbeans/test/performance/xerces/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> @@ -667,7 +667,7 @@ memoryMaximumSize="1000M" compiler="modern" executable="${env.JAVA_HOME}/bin/javac" - source="1.6" + source="1.8" classpathref="castor.classpath"/> @@ -689,7 +689,7 @@ classpathref="jibx.binding.classpath" includes="org/apache/xmlbeans/test/performance/jibx/binding/**" excludes="org/apache/xmlbeans/test/performance/castor/**,org/apache/xmlbeans/test/performance/svn/**,org/apache/xmlbeans/test/performance/utils/**" - source="1.6"> + source="1.8"> + source="1.8"> diff --git a/test/perf/src/org/apache/xmlbeans/test/performance/utils/PerfUtil.java b/test/perf/src/org/apache/xmlbeans/test/performance/utils/PerfUtil.java index d77d0b3..bf27e71 100644 --- a/test/perf/src/org/apache/xmlbeans/test/performance/utils/PerfUtil.java +++ b/test/perf/src/org/apache/xmlbeans/test/performance/utils/PerfUtil.java @@ -18,15 +18,13 @@ import java.io.BufferedInputStream; import java.io.IOException; import java.io.FileNotFoundException; -import java.lang.StringBuffer; -import java.lang.Math; public class PerfUtil { // TODO: add more flavors public char[] createXmlData(String flavor, int size){ - StringBuffer buff = new StringBuffer(size); + StringBuilder buff = new StringBuilder(size); final String rootStart = ""; final String rootEnd = ""; final String childStart = ""; @@ -91,7 +89,7 @@ public byte[] createXmlDataBytes(String flavor, int size) { char[] chars = createXmlData(flavor,size); System.gc(); - StringBuffer buff = new StringBuffer(chars.length); + StringBuilder buff = new StringBuilder(chars.length); buff.append(chars); chars = null; System.gc(); @@ -115,7 +113,7 @@ public char[] fileToChars(String filename) throws IOException,FileNotFoundExcept { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename)); - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); int c; while( (c=bis.read()) != -1){ buff.append((char)c); @@ -128,7 +126,7 @@ public byte[] fileToBytes(String filename) throws IOException,FileNotFoundExcept { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename)); - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); int c; while( (c=bis.read()) != -1){ buff.append((char)c); @@ -139,7 +137,7 @@ public byte[] fileToBytes(String filename) throws IOException,FileNotFoundExcept public String createString(int size) { - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); for(int i=0; i 0) - { - // The first element has attributes.. this is part of - // the content. So the first event should XMLEvent.ATTRIBUTE - _next = XMLEvent.ATTRIBUTE; - } - else - { - // return super.next(); - /* - If content is then we will have returned - END_ELEMENT above, without ever generating a START_ELEMENT - In this case probably we should detect this and return a - END_DOCUMENT - */ - _next = super.next(); - if (_next == XMLEvent.END_ELEMENT) - { - _next = XMLEvent.END_DOCUMENT; - state = ENDCONTENT; - } - } - return _next; - } - - _next = super.next(); - switch (_next) - { - case XMLEvent.START_ELEMENT: - state = TAGOPEN; - depth++; - break; - - case XMLEvent.END_ELEMENT: - --depth; - if (depth < 0 && state == TAGOPEN) - { - throw new XMLStreamException( - "Illegal XML Stream state"); - } - else if (depth == 0 && state == TAGOPEN) - { - state = ENDCONTENT; - // at this point we will return ENDDOCUMENT - _next = XMLEvent.END_DOCUMENT; - } - break; - } - - return _next; - } - - } - - -} diff --git a/test/src/common/Common.java b/test/src/common/Common.java deleted file mode 100644 index e355a8e..0000000 --- a/test/src/common/Common.java +++ /dev/null @@ -1,336 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package common; - -import org.apache.xmlbeans.*; - -import java.io.File; -import java.io.IOException; -import java.util.*; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import javax.xml.namespace.QName; - -/** - * - */ -public class Common extends TestCase -{ - public static final String NEWLINE = System.getProperty("line.separator"); - public static final String P = File.separator; - - public static String FWROOT = getRootFile(); - public static String CASEROOT = getCaseLocation(); - public static String XBEAN_CASE_ROOT = getCaseLocation() + P + "xbean"; - - //location of files under "cases folder" - public static String OUTPUTROOT = FWROOT+P+"build" + P + "test" + P + "output"; - - - public LinkedList errorList; - public XmlOptions xmOpts; - - public Common(String name) - { - super(name); - errorList = new LinkedList(); - xmOpts = new XmlOptions(); - xmOpts.setErrorListener(errorList); - } - - /** - * If System.property for 'xbean.rootdir' == null - * use '.' as basePath - * '.' should be where the build.xml file lives - * - * @return - * @throws IllegalStateException - */ - public static String getRootFile() throws IllegalStateException - { - String baseDir = System.getProperty("xbean.rootdir"); - if (baseDir == null) - return new File(".").getAbsolutePath(); - else - return new File(baseDir).getAbsolutePath(); - } - - /** - * If System.property for 'cases.location' == null - * use '.' as basePath and add test/cases/xbea'.' - * should be where the build.xml file lives - * - * @return - * @throws IllegalStateException - */ - public static String getCaseLocation() throws IllegalStateException - { - String baseDir = System.getProperty("cases.location"); - if (baseDir == null) { - return new File("." + P + "test" + P + "cases").getAbsolutePath(); - } else { - return new File(baseDir).getAbsolutePath(); - } - } - - /** - * Gets a case file from under CASEROOT with location passed in as strPath - * - * @param strPath - * @return file Object for references location - */ - public static File xbeanCase(String strPath) - { - return (new File(CASEROOT, strPath)); - } - - /** - * Creates directory under output directory as noted by strPath - * - * @param strPath - * @return File Object specified by strPath - */ - public static File xbeanOutput(String strPath) - { - File result = (new File(OUTPUTROOT, strPath)); - File parentdir = result.getParentFile(); - parentdir.mkdirs(); - return result; - } - - /** - * Recursively deletes files under specified directory - * - * @param dir - */ - public static void deltree(File dir) - { - if (dir.exists()) { - if (dir.isDirectory()) { - String[] list = dir.list(); - for (int i = 0; i < list.length; i++) - deltree(new File(dir, list[i])); - } - if (!dir.delete()) - System.out.println("Could not delete " + dir); - //throw new IllegalStateException("Could not delete " + dir); - } - } - - /** - * Convenience method for displaying errorListener contents after validation - * - * @param errors - */ - public static void listErrors(List errors) - { - for (int i = 0; i < errors.size(); i++) { - XmlError error = (XmlError) errors.get(i); - if (error.getSeverity() == XmlError.SEVERITY_ERROR) - System.out.println(error.toString()); - } - } - - /** - * check list of errors/warnings/msgs and print them. Return true if errors found - * @param errors - * @return - */ - public static boolean printOptionErrMsgs(Collection errors) - { - boolean errFound = false; - if (!errors.isEmpty()) { - for (Iterator i = errors.iterator(); i.hasNext();) { - XmlError eacherr = (XmlError) i.next(); - int errSeverity = eacherr.getSeverity(); - if (errSeverity == XmlError.SEVERITY_ERROR) { - System.out.println("Err Msg (s) at line #" + eacherr.getLine() + ": " + eacherr.getMessage()); - errFound = true; - } else if (errSeverity == XmlError.SEVERITY_WARNING) { - System.out.println("Warning Msg (s) at line #" + eacherr.getLine() + ": " + eacherr.getMessage()); - } else if (errSeverity == XmlError.SEVERITY_INFO) { - System.out.println("Info Msg (s) at line #" + eacherr.getLine() + ": " + eacherr.getMessage()); - } - } - errors.clear(); - } - return errFound; - } - - /** - * Validate schemas to instance based on the docType - * @param schemas - * @param instances - * @param docType - * @throws Exception - */ - public static void validateInstance(String[] schemas, String[] instances, QName docType) throws Exception - { - SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); - XmlOptions options = new XmlOptions(); - - if (docType != null) { - SchemaType docSchema = stl.findDocumentType(docType); - Assert.assertTrue(docSchema != null); - options.put(XmlOptions.DOCUMENT_TYPE, docSchema); - } - - for (int i = 0; i < instances.length; i++) { - XmlObject x = - stl.parse((String) instances[i], null, options); - - //if (!startOnDocument) { - // XmlCursor c = x.newCursor(); - // c.toFirstChild(); - // x = c.getObject(); - // c.dispose(); - //} - - List xel = new ArrayList(); - - options.put(XmlOptions.ERROR_LISTENER, xel); - - boolean isValid = x.validate(options); - - if (!isValid) { - StringBuffer errorTxt = new StringBuffer("Invalid doc, expected a valid doc: "); - errorTxt.append("Instance(" + i + "): "); - errorTxt.append(x.xmlText()); - errorTxt.append("Errors: "); - for (int j = 0; j < xel.size(); j++) - errorTxt.append(xel.get(j) + "\n"); - System.err.println(errorTxt.toString()); - throw new Exception("Instance not valid\n" + errorTxt.toString()); - } - } - } - - - /** - * Convenience method for creating an XmlObject from a String - * - * @param XsdAsString - * @return - */ - public static XmlObject compileXsdString(String XsdAsString) - { - XmlObject xobj = null; - try { - xobj = XmlObject.Factory.parse(XsdAsString); - } catch (XmlException xme) { - if (!xme.getErrors().isEmpty()) { - for (Iterator itr = xme.getErrors().iterator(); itr.hasNext();) { - System.out.println("Parse Errors :" + itr.next()); - } - } - } finally { - Assert.assertNotNull(xobj); - return xobj; - } - } - - - /** - * Convenience method for creating an XmlObject from a File referenced as a String of the path to the file - * - * @param XsdFilePath - * @return - */ - public static XmlObject compileXsdFile(String XsdFilePath) - { - XmlObject xobj = null; - try { - xobj = XmlObject.Factory.parse(new File(XsdFilePath)); - } catch (XmlException xme) { - if (!xme.getErrors().isEmpty()) { - for (Iterator itr = xme.getErrors().iterator(); itr.hasNext();) { - System.out.println("Parse Errors :" + itr.next()); - } - } - } catch (IOException ioe) { - ioe.printStackTrace(); - ioe.getMessage(); - } finally { - Assert.assertNotNull(xobj); - return xobj; - } - } - - /** - * Convenience method to create a SchemaTypeLoader from a set of xsds - * - * @param schemas - * @return - * @throws Exception - */ - public static SchemaTypeLoader makeSchemaTypeLoader(String[] schemas) - throws Exception - { - XmlObject[] schemaDocs = new XmlObject[schemas.length]; - - for (int i = 0; i < schemas.length; i++) { - schemaDocs[i] = - XmlObject.Factory.parse(schemas[i]); - } - - return XmlBeans.loadXsd(schemaDocs); - } - - /** - * Is the JVM being used a 1.4 version? - * Used for tests involving the javasource=1.5 compilation setting - * - * @return true if java.version starts with 1.4 - */ - public static boolean isJDK14() - { - return System.getProperty("java.version").startsWith("1.4"); - } - - /** - * Convenience class for creating tests in a multithreaded env - */ - public static abstract class TestThread extends Thread - { - protected Throwable _throwable; - protected boolean _result; - protected XmlOptions xm; - protected ArrayList errors; - - public TestThread() - { - xm = new XmlOptions(); - ArrayList errors = new ArrayList(); - xm.setErrorListener(errors); - xm.setValidateOnSet(); - } - - public Throwable getException() - { - return _throwable; - } - - public boolean getResult() - { - return _result; - } - - - } - - -} diff --git a/test/src/compile/scomp/common/mockobj/TestBindingConfig.java b/test/src/compile/scomp/common/mockobj/TestBindingConfig.java deleted file mode 100644 index 59267ec..0000000 --- a/test/src/compile/scomp/common/mockobj/TestBindingConfig.java +++ /dev/null @@ -1,165 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package compile.scomp.common.mockobj; - -import org.apache.xmlbeans.BindingConfig; -import org.apache.xmlbeans.InterfaceExtension; -import org.apache.xmlbeans.PrePostExtension; -import org.apache.xmlbeans.impl.config.BindingConfigImpl; - -import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument.Config; -import org.apache.xmlbeans.impl.xb.xmlconfig.Extensionconfig; -import org.apache.xmlbeans.impl.xb.xmlconfig.Nsconfig; -import org.apache.xmlbeans.impl.xb.xmlconfig.Qnameconfig; -import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument; -import org.apache.xmlbeans.BindingConfig; - -import javax.xml.namespace.QName; -import java.io.File; - -/** - * - * - */ -public class TestBindingConfig extends BindingConfig -{ - BindingConfig bindingConfig; - private boolean islookupPackageForNamespace; - private boolean islookupPrefixForNamespace; - private boolean islookupSuffixForNamespace; - private boolean islookupJavanameForQName; - private boolean isgetInterfaceExtensions; - private boolean isgetInterfaceExtensionsString; - private boolean isgetPrePostExtensions; - private boolean isgetPrePostExtensionsString; - - public TestBindingConfig(ConfigDocument.Config[] configs, File[] javaFiles, File[] classpath) - { - - bindingConfig = BindingConfigImpl.forConfigDocuments(configs, javaFiles, classpath); - islookupPackageForNamespace = false; - islookupPrefixForNamespace = false; - islookupSuffixForNamespace = false; - islookupJavanameForQName = false; - isgetInterfaceExtensions = false; - isgetInterfaceExtensionsString = false; - isgetPrePostExtensions = false; - isgetPrePostExtensionsString = false; - } - - public boolean isIslookupPackageForNamespace() - { - return islookupPackageForNamespace; - } - - public boolean isIslookupPrefixForNamespace() - { - return islookupPrefixForNamespace; - } - - public boolean isIslookupSuffixForNamespace() - { - return islookupSuffixForNamespace; - } - - public boolean isIslookupJavanameForQName() - { - return islookupJavanameForQName; - } - - public boolean isIsgetInterfaceExtensions() - { - return isgetInterfaceExtensions; - } - - public boolean isIsgetInterfaceExtensionsString() - { - return isgetInterfaceExtensionsString; - } - - public boolean isIsgetPrePostExtensions() - { - return isgetPrePostExtensions; - } - - public boolean isIsgetPrePostExtensionsString() - { - return isgetPrePostExtensionsString; - } - - public String lookupPackageForNamespace(String s) - { - System.out.println("lookupPackageForNamespace: "+s); - islookupPackageForNamespace = true; - return bindingConfig.lookupPackageForNamespace(s); - } - - public String lookupPrefixForNamespace(String s) - { - System.out.println("lookupPrefixForNamespace: "+s); - islookupPrefixForNamespace = true; - return bindingConfig.lookupPrefixForNamespace(s); - } - - public String lookupSuffixForNamespace(String s) - { - System.out.println("lookupSuffixForNamespace: "+s); - islookupSuffixForNamespace = true; - return bindingConfig.lookupSuffixForNamespace(s); - } - - /** @deprecated */ - public String lookupJavanameForQName(QName qName) - { - System.out.println("lookupJavanameForQName: "+qName); - islookupJavanameForQName = true; - return bindingConfig.lookupJavanameForQName(qName); - } - - public String lookupJavanameForQName(QName qName, int kind) - { - System.out.println("lookupJavanameForQName: "+qName); - islookupJavanameForQName = true; - return bindingConfig.lookupJavanameForQName(qName, kind); - } - - public InterfaceExtension[] getInterfaceExtensions() - { - System.out.println("getInterfaceExtensions "); - isgetInterfaceExtensions = true; - return bindingConfig.getInterfaceExtensions(); - } - - public InterfaceExtension[] getInterfaceExtensions(String s) - { - System.out.println("getInterfaceExtensions: "+s); - isgetInterfaceExtensionsString = true; - return bindingConfig.getInterfaceExtensions(s); - } - - public PrePostExtension[] getPrePostExtensions() - { - System.out.println("getPrePostExtensions"); - isgetPrePostExtensions = true; - return bindingConfig.getPrePostExtensions(); - } - - public PrePostExtension getPrePostExtension(String s) - { - System.out.println("getPrePostExtension: "+s); - isgetPrePostExtensionsString = true; - return bindingConfig.getPrePostExtension(s); - } -} diff --git a/test/src/compile/scomp/detailed/XmlBeanCompilationTests.java b/test/src/compile/scomp/detailed/XmlBeanCompilationTests.java deleted file mode 100644 index 89d5681..0000000 --- a/test/src/compile/scomp/detailed/XmlBeanCompilationTests.java +++ /dev/null @@ -1,327 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package compile.scomp.detailed; - -import junit.framework.Assert; -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.xb.xmlconfig.ConfigDocument; - -import java.io.*; -import java.util.*; - -import compile.scomp.common.CompileCommon; -import compile.scomp.common.CompileTestBase; -import compile.scomp.common.mockobj.TestFiler; -import compile.scomp.common.mockobj.TestBindingConfig; - -import javax.xml.namespace.QName; - - - -/** - * Ensure that several compilation mechanisms all generate - * the same schematypesystem - * - */ -public class XmlBeanCompilationTests extends CompileTestBase -{ - public List xm_errors; - public XmlOptions xm_opts; - Vector expBinType; - Vector expSrcType; - - public XmlBeanCompilationTests(String name) - { - super(name); - expBinType = new Vector(); - expBinType.add("schema/system/apiCompile/atypedb57type.xsb"); - expBinType.add("schema/system/apiCompile/elname429edoctype.xsb"); - expBinType.add("schema/system/apiCompile/elnameelement.xsb"); - expBinType.add("schema/system/apiCompile/index.xsb"); - expBinType.add("schema/element/http_3A_2F_2Fbaz/elName.xsb"); - expBinType.add("schema/type/http_3A_2F_2Fbaz/aType.xsb"); - expBinType.add("schema/namespace/http_3A_2F_2Fbaz/xmlns.xsb"); - expBinType.add("schema/javaname/baz/ElNameDocument.xsb"); - expBinType.add("schema/javaname/baz/AType.xsb"); - expBinType.add("schema/system/apiCompile/TypeSystemHolder.class"); - - expSrcType = new Vector(); - expSrcType.add("baz.AType"); - expSrcType.add("baz.impl.ATypeImpl"); - expSrcType.add("baz.ElNameDocument"); - expSrcType.add("baz.impl.ElNameDocumentImpl"); - - xm_errors = new ArrayList(); - xm_opts = new XmlOptions(); - xm_opts.setErrorListener(xm_errors); - xm_opts.setSavePrettyPrint(); - - } - - - public void tearDown() throws Exception - { - super.tearDown(); - if (xm_errors.size() > 0) - xm_errors.clear(); - } - - /** - * Filer != null for BindingConfig to be used - * - * @throws Exception - */ - public void test_bindingconfig_extension_compilation() throws Exception - { - TestFiler f = new TestFiler(); - //initialize all of the values - String extCaseDir = XBEAN_CASE_ROOT + P + "extensions" + P; - String extSrcDir = CASEROOT + P + - ".." + P + "src" + P + "xmlobject" + P + "extensions" + P; - File[] cPath = CompileTestBase.getClassPath(); - String dir = extCaseDir + P + "interfaceFeature" + P + "averageCase"; - String dir2 = extCaseDir + P + "prePostFeature" + P + - "ValueRestriction"; - - ConfigDocument.Config bConf = ConfigDocument.Factory.parse( - new File(dir + P + "po.xsdconfig")) - .getConfig(); - ConfigDocument.Config cConf = ConfigDocument.Factory.parse( - new File(dir2 + P + "company.xsdconfig")) - .getConfig(); - - String simpleConfig = "\n" + - "\n" + - "com.easypo\n" + - ""; - ConfigDocument.Config confDoc = ConfigDocument.Factory.parse(simpleConfig).getConfig(); - ConfigDocument.Config[] confs = new ConfigDocument.Config[]{bConf, confDoc, cConf}; - - String fooHandlerPath = extSrcDir + P + "interfaceFeature" + P + - "averageCase" + P + "existing" + P + "FooHandler.java"; - String iFooPath = extSrcDir + P + "interfaceFeature" + P + - "averageCase" + P + "existing" + P + "IFoo.java"; - String iSetterPath = extSrcDir + P + "prePostFeature" + P + - "ValueRestriction" + P + "existing" + P + "ISetter.java"; - String setterHandlerPath = extSrcDir + P + "prePostFeature" + P + - "ValueRestriction" + P + "existing" + P + "SetterHandler.java"; - - - File[] fList = new File[]{new File(fooHandlerPath), new File(iFooPath), - new File(iSetterPath), - new File(setterHandlerPath)}; - - //use created BindingConfig - TestBindingConfig bind = new TestBindingConfig(confs, fList, cPath); - - //set XSDs - XmlObject obj1 = XmlObject.Factory.parse(new File(dir + P + "po.xsd")); - XmlObject obj2 = XmlObject.Factory.parse( - new File(dir2 + P + "company.xsd")); - XmlObject[] schemas = new XmlObject[]{obj1, obj2}; - - //filer must be present on this method - SchemaTypeSystem apiSts = XmlBeans.compileXmlBeans("apiCompile", null, - schemas, bind, XmlBeans.getBuiltinTypeSystem(), f, xm_opts); - - if (!bind.isIslookupPrefixForNamespace()) - throw new Exception("isIslookupPrefixForNamespace not invoked"); - if (!bind.isIslookupPackageForNamespace()) - throw new Exception("isIslookupPackageForNamespace not invoked"); - if (!bind.isIslookupSuffixForNamespace()) - throw new Exception("isIslookupSuffixForNamespace not invoked"); - if (!bind.isIslookupJavanameForQName()) - throw new Exception("isIslookupJavanameForQName not invoked"); - if (!bind.isIsgetInterfaceExtensionsString()) - throw new Exception("isIsgetInterfaceExtensionsString not invoked"); - if (!bind.isIsgetInterfaceExtensions()) - throw new Exception("isIsgetInterfaceExtensions not invoked"); - if (!bind.isIsgetPrePostExtensions()) - throw new Exception("isIsgetPrePostExtensions not invoked"); - if (!bind.isIsgetInterfaceExtensions()) - throw new Exception("isIsgetInterfaceExtensions not invoked"); - if (!bind.isIsgetPrePostExtensionsString()) - throw new Exception("isIsgetPrePostExtensionsString not invoked"); - } - - /** - * Verify basic incremental compilation - * and compilation with partial SOM usages - */ - public void test_incrCompile() throws Exception - { - XmlObject obj1 = XmlObject.Factory.parse(forXsd); - obj1.documentProperties().setSourceName("OBJ1"); - XmlObject[] schemas = new XmlObject[]{obj1}; - QName sts1 = new QName("http://baz", "elName"); - - XmlObject obj2 = XmlObject.Factory.parse(incrXsd); - obj2.documentProperties().setSourceName("OBJ2"); - XmlObject[] schemas2 = new XmlObject[]{obj2}; - QName sts2 = new QName("http://bar", "elName"); - - XmlObject obj3 = XmlObject.Factory.parse(errXsd); - obj3.documentProperties().setSourceName("OBJ3"); - XmlObject[] schemas3 = new XmlObject[]{obj3}; - QName sts3 = new QName("http://bar", "elErrName"); - - SchemaTypeSystem sts; - ArrayList err = new ArrayList(); - XmlOptions opt = new XmlOptions().setErrorListener(err); - opt.put("COMPILE_PARTIAL_TYPESYSTEM"); - - //BASIC COMPILATION - sts = XmlBeans.compileXmlBeans(null, - null, schemas, null, - XmlBeans.getBuiltinTypeSystem(), null, opt); - - Assert.assertTrue("Errors should have been empty", err.isEmpty()); - // find element in the type System - if (!findGlobalElement(sts.globalElements(), sts1)) - throw new Exception( - "Could Not find Type from first Type System: " + sts1); - - //SIMPLE INCR COMPILATION - sts = XmlBeans.compileXmlBeans(null, - sts, schemas2, null, - XmlBeans.getBuiltinTypeSystem(), null, opt); - Assert.assertTrue("Errors should have been empty", err.isEmpty()); - // find element in the type System - - if (!findGlobalElement(sts.globalElements(), sts1)) - throw new Exception("Could Not find Type from first Type System: " + - sts1); - - if (!findGlobalElement(sts.globalElements(), sts2)) - throw new Exception("Could Not find Type from 2nd Type System: " + - sts2); - - System.out.println("Building over Existing"); - //BUILDING OFF BASE SIMPLE INCR COMPILATION - sts = XmlBeans.compileXmlBeans(null, - sts, schemas2, null, - sts, null, opt); - Assert.assertTrue("Errors should have been empty", err.isEmpty()); - // find element in the type System - - if (!findGlobalElement(sts.globalElements(), sts1)) - throw new Exception("Could Not find Type from first Type System: " + - sts1); - - if (!findGlobalElement(sts.globalElements(), sts2)) - throw new Exception("Could Not find Type from 2nd Type System: " + - sts2); - - //INCR COMPILATION WITH RECOVERABLE ERROR - err.clear(); - SchemaTypeSystem b = XmlBeans.compileXmlBeans(null, - sts, schemas3, null, - XmlBeans.getBuiltinTypeSystem(), null, opt); - // find element in the type System - if (!findGlobalElement(b.globalElements(), sts1)) - throw new Exception("Could Not find Type from first Type System: " + - sts1); - - if (!findGlobalElement(b.globalElements(), sts2)) - throw new Exception("Could Not find Type from 2nd Type System: " + - sts2); - - if (!findGlobalElement(b.globalElements(), sts3)) - throw new Exception("Could Not find Type from 3rd Type System: " + - sts3); - - printSTS(b); - - //INSPECT ERRORS - boolean psom_expError = false; - // print out the recovered xm_errors - if (!err.isEmpty()) { - System.out.println( - "Schema invalid: partial schema type system recovered"); - for (Iterator i = err.iterator(); i.hasNext();) { - XmlError xErr = (XmlError) i.next(); - System.out.println(xErr); - //compare to the expected xm_errors - if ((xErr.getErrorCode().compareTo("src-resolve") == 0) && - (xErr.getMessage().compareTo( - "type 'bType@http://baz' not found.") == - 0)) - psom_expError = true; - } - } - if (!psom_expError) - throw new Exception("Error Code was not as Expected"); - - - } - - - - - - - /*public void test_diff_compilationMethods() throws IOException, - XmlException, Exception - { - - - //initialize the schema compiler - SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setXsdFiles(new File[]{scompFile}); - params.setSrcDir(scompDirFile); - params.setClassesDir(scompDirFile); - - //save out schema for use in scomp later - XmlObject obj1 = XmlObject.Factory.parse(forXsd); - obj1.save(scompFile); - - //scomp saved out schema - SchemaCompiler.compile(params); - - //use new api to get typesystem - XmlObject[] schemas = new XmlObject[]{obj1}; - SchemaTypeSystem apiSts = XmlBeans.compileXmlBeans("apiCompile", null, - schemas, null, XmlBeans.getBuiltinTypeSystem(), null, xm_opts); - - //use alternative api to get typesystem - SchemaTypeSystem altSts = XmlBeans.compileXsd(schemas, - XmlBeans.getBuiltinTypeSystem(), null); - - //save out sts for diff later - SchemaCodeGenerator.saveTypeSystem(apiSts, apiDirFile, null, null, - null); - SchemaCodeGenerator.saveTypeSystem(altSts, baseDirFile, null, null, - null); - - //diff new api to old api - xm_errors = null; - xm_errors = new ArrayList(); - Diff.dirsAsTypeSystems(apiDirFile, baseDirFile, xm_errors); - if (xm_errors.size() >= 1) - throw new Exception("API STS ERRORS: " + xm_errors.toString()); - - //diff scomp sts to new api - xm_errors = null; - xm_errors = new ArrayList(); - Diff.dirsAsTypeSystems(apiDirFile, scompDirFile, xm_errors); - if (xm_errors.size() >= 1) - throw new Exception("API SCOMP ERRORS: " + xm_errors.toString()); - } */ - - -} diff --git a/test/src/compile/scomp/incr/schemaCompile/detailed/ModelGroupTests.java b/test/src/compile/scomp/incr/schemaCompile/detailed/ModelGroupTests.java deleted file mode 100644 index 1385093..0000000 --- a/test/src/compile/scomp/incr/schemaCompile/detailed/ModelGroupTests.java +++ /dev/null @@ -1,355 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package compile.scomp.incr.schemaCompile.detailed; - -import junit.framework.TestCase; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.impl.common.QNameHelper; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; -import org.apache.xmlbeans.impl.tool.CodeGenUtil; -import org.apache.xmlbeans.impl.tool.SchemaCodeGenerator; -import org.apache.xmlbeans.impl.tool.Diff; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType; -import org.apache.xmlbeans.*; - -import java.io.File; -import java.io.StringWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Arrays; -import java.util.Collections; - -import tools.util.TestRunUtil; -import compile.scomp.common.CompileCommon; -import compile.scomp.common.CompileTestBase; - -import javax.xml.namespace.QName; - - -/** - * - * - */ -public class ModelGroupTests extends CompileTestBase { - - - public ModelGroupTests(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(ModelGroupTests.class); - } - - public void setUp() throws IOException { - CompileCommon.deltree(CompileCommon.xbeanOutput(outputDir)); - out = CompileCommon.xbeanOutput(outPath); - sanity = CompileCommon.xbeanOutput(sanityPath); - outincr = CompileCommon.xbeanOutput(incrPath); - - errors = new ArrayList(); - xm = new XmlOptions(); - xm.setErrorListener(errors); - xm.setSavePrettyPrint(); - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (errors.size() > 0) - errors.clear(); - } - - public void test_model_diffns_choice2seqchange() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject obj2 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - public void test_model_seq2choicechange() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject obj2 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - public void test_model_seq2choicechange_diffns() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getBaseSchema("bar", "elName", "string", "attrName", "string")); - XmlObject obj2 = XmlObject.Factory.parse( - getSchemaTop("baz")+ - "" + - "" + - "" + - "" + - "" + - "" + - ""+getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://bar", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - public void test_model_seq2allchange() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject obj2 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - public void test_model_all2seqchange() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject obj2 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - public void test_model_all2choicechange() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject obj2 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - public void test_model_choice2choicechange() throws Exception { - //XmlObject.Factory.parse(getBaseSchema("baz","elName", "elType", "attrName","attrType")); - XmlObject obj1 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject obj2 = XmlObject.Factory.parse(getSchemaTop("baz") + - "" + - "" + - "" + - "" + - "" + - "" + - "" + getSchemaBottom()); - XmlObject[] schemas = new XmlObject[]{obj1}; - XmlObject[] schemas2 = new XmlObject[]{obj2}; - schemas[0].documentProperties().setSourceName("obj1"); - schemas2[0].documentProperties().setSourceName("obj2"); - - SchemaTypeSystem base = compileSchemas(schemas, builtin, xm); - SchemaTypeSystem incr = incrCompileXsd(base, schemas2, builtin, xm); - - echoSts(base, incr); - QName[] baseTypes = new QName[]{new QName("http://baz", "elName")}; - QName[] incrTypes = new QName[]{new QName("http://baz", "elName")}; - - findElementbyQName(base, baseTypes); - findElementbyQName(incr, incrTypes); - - // if (incr.findElement(incrTypes[0]).getType().g - Assert.assertNotSame(base, incr); - - compareandPopErrors(out, outincr, errors); - handleErrors(errors); - } - - - -} diff --git a/test/src/compile/scomp/som/checkin/PartialSOMCheckinTest.java b/test/src/compile/scomp/som/checkin/PartialSOMCheckinTest.java deleted file mode 100644 index 7804878..0000000 --- a/test/src/compile/scomp/som/checkin/PartialSOMCheckinTest.java +++ /dev/null @@ -1,1424 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package compile.scomp.som.checkin; - -import compile.scomp.som.common.SomTestBase; -import junit.framework.Assert; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.impl.tool.Diff; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; - -/** - * - * - */ - -public class PartialSOMCheckinTest extends SomTestBase -{ - - public PartialSOMCheckinTest(String name) - { - super(name); - } - - - public void setUp() - { - // initialize the built in schema type - builtin = XmlBeans.getBuiltinTypeSystem(); - - // populate the XmlOptions - if (errors == null) - { - errors = new ArrayList(); - } - if (options == null) - { - options = (new XmlOptions()).setErrorListener(errors); - options.setCompileDownloadUrls(); - options.put("COMPILE_PARTIAL_TYPESYSTEM"); - options.setLoadLineNumbers(); - } - - // initialize the runid to be used for generating output files for the PSOM walk thro's - runid = new Date().getTime(); - - // clean the output from the previous run - // delete directories created by checkPSOMSave() and output text file created by inspectPSOM() - deleteDirRecursive(new File(somOutputRootDir)); - - } - - public void tearDown() - { - errors.clear(); - } - - - public void testAddAttributeAndElements() throws Exception - { - System.out.println("Inside test case testAddAttributeAndElements()"); - - // Step 1 : create a Schema Type System with the base 'bad' xsd and create the Schema Type System (STS) for it - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("elemattr.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", - baseSTS); - - // the tests - Walk thro the SOM, save, validate against an xml instance - inspectSOM(baseSTS, 1, 1, 1, 0); - - // test for recoverable errors - Assert.assertTrue("No Recovered Errors for Invalid Schema", - printRecoveredErrors()); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should fail!", - checkPSOMSave(baseSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance Success - should fail ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), baseSTS)); - - // additional validation - Assert.assertFalse("Attribute found but not expected - 'testAttributeComplex'", - lookForAttributeInSTS(baseSTS, - "testAttributeComplex")); - Assert.assertFalse("Element found but not expected 'ComplexTypeElem'", - lookForElemInSTS(baseSTS, - "ComplexTypeElem")); - Assert.assertFalse("Element found but not expected 'SimpleTypeElem'", - lookForElemInSTS(baseSTS, "SimpleTypeElem")); - - - // Step 2: create a Schema Type System with the new xsd file that has additions to this schema - SchemaTypeSystem modifiedSTS = createNewSTS("elemattr_added.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", - modifiedSTS); - - // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups - inspectSOM(modifiedSTS, 3, 2, 1, 0); - - // Test for successful saving of the PSOM - Assert.assertTrue("Valid Partial SOM " + modifiedSTS.getName() + "Save failed", - checkPSOMSave(modifiedSTS)); - - // Look for added attribute(s)/Element(s) by name in the STS - Assert.assertTrue("Attribute expected, not found 'testAttributeComplex'", - lookForAttributeInSTS(modifiedSTS, - "testAttributeComplex")); - Assert.assertTrue("Element expected, not found 'ComplexTypeElem'", - lookForElemInSTS(modifiedSTS, - "ComplexTypeElem")); - Assert.assertTrue("Element expected, not found 'SimpleTypeElem'", - lookForElemInSTS(modifiedSTS, - "SimpleTypeElem")); - - // validate against an xml instance - Assert.assertTrue("Validation against instance failed ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), modifiedSTS)); - - // Step 3: now creat the Schema Type System with the original XSD again - SchemaTypeSystem finalSTS = createNewSTS("elemattr.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - //walk the SOM - inspectSOM(finalSTS, 1, 1, 1, 0); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("Partial SOM " + finalSTS.getName() + "Save successful - should fail!", - checkPSOMSave(finalSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance Success - should fail ", - validateInstance(getTestCaseFile("instance_elemattr.xml"), finalSTS)); - - } - - public void testModifyAttributeAndElements() throws Exception - { - System.out.println("Inside test case testModifyAttributeAndElements()"); - - // Step 1 : create a Schema Type System with the base 'good' xsd and create the Schema Type System (STS) for it - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("elemattr_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // the tests - Walk thro the SOM, save, validate against an xml instance - inspectSOM(baseSTS, 3, 2, 1, 0); - - // validate successful save - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed ", - checkPSOMSave(baseSTS)); - - // validate against instance successfully - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), baseSTS)); - - // Step 2: create a Schema Type System with the new xsd file with modifications to existing schema - SchemaTypeSystem modifiedSTS = createNewSTS("elemattr_modified.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // test for recoverable errors - Assert.assertTrue("No Recovered Errors for Invalid Schema", - printRecoveredErrors()); - - // test the PSOM created - inspectSOM(modifiedSTS, 2, 2, 1, 0); // walk thro the PSOM, look for # of elements,attributes,types & attribute groups - - // Look for a modified attribute(s)/elements by name in the STS - Assert.assertTrue("Attribute expected, not found 'testAttributeComplex'", - lookForAttributeInSTS(modifiedSTS, "testAttributeComplex")); - Assert.assertTrue("Element expected, not found 'ComplexTypeElem'", - lookForElemInSTS(modifiedSTS, "ComplexTypeElem")); - Assert.assertFalse("Element expected, not found 'SimpleTypeElem'", - lookForElemInSTS(modifiedSTS, "SimpleTypeElem")); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("Partial SOM " + modifiedSTS.getName() + " Save successful- should fail", - checkPSOMSave(modifiedSTS)); - - // validate against an xml instance - should fail - Assert.assertFalse("Validation against instance Success - should Fail", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), modifiedSTS)); - - // Step 3: now creat the Schema Type System with the original XSD again - SchemaTypeSystem finalSTS = createNewSTS("elemattr_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // walk the PSOM - inspectSOM(finalSTS, 3, 2, 1, 0); - - // should be able to save as its a valid SOM - Assert.assertTrue("Partial SOM " + finalSTS.getName() + "Save failed for complete SOM", - checkPSOMSave(finalSTS)); - - // validate against instance successfully - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), finalSTS)); - - // compare this to the original schema here - the root dir names used to save the PSOMs are the same as the STS names - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testDeleteAttributeAndElements() throws Exception - { - System.out.println("Inside test case testDeleteAttributeAndElements()"); - - // Step 1 : create a Schema Type System with the base 'good' xsd and create the Schema Type System (STS) for it - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("elemattr_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // the tests - Walk thro the SOM, save, validate against an xml instance - inspectSOM(baseSTS, 3, 2, 1, 0); - - // validate successful save - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed ", - checkPSOMSave(baseSTS)); - - // validate against instance successfully - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), baseSTS)); - - // Step 2: create a Schema Type System with the new xsd file that has deletions - SchemaTypeSystem modifiedSTS = createNewSTS("elemattr.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // test for recoverable errors - Assert.assertTrue("No Recovered Errors for Invalid Schema", - printRecoveredErrors()); - - // test the PSOM created - inspectSOM(modifiedSTS, 1, 1, 1, 0); // walk thro the PSOM, look for # of elements,attributes,types & attribute groups - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("Invalid PSOM " + modifiedSTS.getName() + " Save successful - Should fail", - checkPSOMSave(modifiedSTS)); - - // verify types - Assert.assertFalse("Attribute found but not expected - 'testAttributeComplex'", - lookForAttributeInSTS(modifiedSTS, "testAttributeComplex")); - Assert.assertFalse("Element found but not expected 'ComplexTypeElem'", - lookForElemInSTS(modifiedSTS, "ComplexTypeElem")); - Assert.assertFalse("Element found but not expected 'SimpleTypeElem'", - lookForElemInSTS(modifiedSTS, "SimpleTypeElem")); - - // validate against an xml instance - should fail - Assert.assertFalse("Validation against success - should Fail ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), modifiedSTS)); - - // Step 3: now creat the Schema Type System with the original XSD again - SchemaTypeSystem finalSTS = createNewSTS("elemattr_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // walk the SOM - inspectSOM(finalSTS, 3, 2, 1, 0); - - // should be able to save as its a valid SOM - Assert.assertTrue("Partial SOM " + finalSTS.getName() + "Save failed for complete SOM", - checkPSOMSave(finalSTS)); - - // validate against instance - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_elemattr_valid.xml"), finalSTS)); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - - } - - public void testAddDataTypes() throws Exception - { - System.out.println("Inside test case testAddDataTypes()"); - // Step 1 : create a PSOM from an incomplete/invalid xsd (datatypes.xsd) with unresolved references to various types - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("datatypes.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // recovearble errors should exist - Assert.assertTrue("No Recovered Errors for Invalid Schema", - printRecoveredErrors()); - - // Walk thro the SOM (pass #Elems, #Attr, #Types, #AttrGroups) - inspectSOM(baseSTS, 12, 1, 4, 1); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should fail!", - checkPSOMSave(baseSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance Success - should fail ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); - - // additional validation - check to see if the unresolved references to types are 'anyType' - // validate unresolved types - Assert.assertEquals("Unresolved Simple Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testUnionTypeElem")); - - // moved to detailed PSOMDetailedTest class - //Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", anySimpleType, getElementType(baseSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testComplexTypeSimpleContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testComplexTypeElementOnlyContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testComplexTypeMixedElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testComplexTypeEmptyElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testChoiceGroupElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(baseSTS, "testAllGroupElem")); - - // Step 2 : create an incremental PSOM that is valid by loading datatypes_added.xsd - SchemaTypeSystem modifiedSTS = createNewSTS("datatypes_added.xsd_", baseSTS, "ModifiedSchemaTS", sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // no errors expected to be recovered - should be a valid SOM - Assert.assertFalse("Valid Schema Type System, Errors recovered", - printRecoveredErrors()); - - // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups - inspectSOM(modifiedSTS, 13, 1, 15, 1); - - // test successful save - Assert.assertTrue("Valid SOM " + modifiedSTS.getName() + " Save failed", - checkPSOMSave(modifiedSTS)); - - // validate against an xml valid instance - should succeed - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), modifiedSTS)); - - // validate against an xml invalid instance - should fail - Assert.assertFalse("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_simple_types_invalid.xml"), modifiedSTS)); - - // additional validation - check to see if all types are resolved to their respective types - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(modifiedSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType'", - "union.attachmentUnionType", - getElementType(modifiedSTS, "testUnionTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(modifiedSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Complex Type should be 'headerType'", - "headerType", - getElementType(modifiedSTS, "testComplexTypeSimpleContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'mailsType'", - "mailsType", - getElementType(modifiedSTS, "testComplexTypeElementOnlyContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'mixedContentType'", - "mixedContentType", - getElementType(modifiedSTS, "testComplexTypeMixedElem")); - Assert.assertEquals("Unresolved Complex Type should be 'emptyContentType'", - "emptyContentType", - getElementType(modifiedSTS, "testComplexTypeEmptyElem")); - Assert.assertEquals("Unresolved Complex Type should be 'choiceGroupType'", - "choiceGroupType", - getElementType(modifiedSTS, "testChoiceGroupElem")); - Assert.assertEquals("Unresolved Complex Type should be 'allGroupType'", - "allGroupType", - getElementType(modifiedSTS, "testAllGroupElem")); - - - // Step 3 : create an incremental STS with the file in step 1 - SchemaTypeSystem finalSTS = createNewSTS("datatypes.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups - inspectSOM(finalSTS, 12, 1, 4, 1); - - // test save failure - Assert.assertFalse("Partial SOM " + finalSTS.getName() + "Save Success ", - checkPSOMSave(finalSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance Success - should fail ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), finalSTS)); - - } - - public void testDeleteDataTypes() throws Exception - { - System.out.println("Inside test case testDeleteDataTypes()"); - - // Step 1: read a clean XSD file to get a valid SOM - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("datatypes_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertEquals("Recovered Errors for Valid Schema", false, printRecoveredErrors()); - - // the tests - Walk thro the SOM, save, validate against an xml instance - inspectSOM(baseSTS, 13, 1, 15, 1); - - // Recovered Errors, Test for saving of the PSOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); - - // additional validation - check to see if all types are resolved to their respective types - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(baseSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType'", - "union.attachmentUnionType", - getElementType(baseSTS, "testUnionTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(baseSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Complex Type should be 'headerType'", - "headerType", - getElementType(baseSTS, "testComplexTypeSimpleContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'mailsType'", - "mailsType", - getElementType(baseSTS, "testComplexTypeElementOnlyContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'mixedContentType'", - "mixedContentType", - getElementType(baseSTS, "testComplexTypeMixedElem")); - Assert.assertEquals("Unresolved Complex Type should be 'emptyContentType'", - "emptyContentType", - getElementType(baseSTS, "testComplexTypeEmptyElem")); - Assert.assertEquals("Unresolved Complex Type should be 'choiceGroupType'", - "choiceGroupType", - getElementType(baseSTS, "testChoiceGroupElem")); - Assert.assertEquals("Unresolved Complex Type should be 'allGroupType'", - "allGroupType", - getElementType(baseSTS, "testAllGroupElem")); - - - //Step 2 : delete/remove types from the schema - should result in STS with unresolved refs - SchemaTypeSystem modifiedSTS = createNewSTS("datatypes.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // PSOM - recovered errors are expected - Assert.assertEquals("Valid Schema Type System, Errors recovered", true, printRecoveredErrors()); - - // test the PSOM created : walk thro the PSOM, look for # of elements,attributes,types & attribute groups - inspectSOM(modifiedSTS, 12, 1, 4, 1); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("PSOM " + modifiedSTS.getName() + " Save should fail", - checkPSOMSave(modifiedSTS)); - - // validate unresolved types - Assert.assertEquals("Unresolved Simple Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testUnionTypeElem")); - // moved to detailed PSOMDetailedTest class - // Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", anySimpleType, getElementType(modifiedSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testComplexTypeSimpleContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testComplexTypeElementOnlyContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testComplexTypeMixedElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testComplexTypeEmptyElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testChoiceGroupElem")); - Assert.assertEquals("Unresolved Complex Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testAllGroupElem")); - - // validate against an xml valid instance - should fail - Assert.assertEquals("Validation against instance should Failed ", false, validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), modifiedSTS)); - - // Step 3 : reaload the xsd in Step 1 - SchemaTypeSystem finalSTS = createNewSTS("datatypes_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - - // should be able to save as its a valid SOM - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // walk the PSOM - inspectSOM(finalSTS, 13, 1, 15, 1); - - // should be able to save as its a valid SOM - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed", - checkPSOMSave(finalSTS)); - - // instance validation - should be fine - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), finalSTS)); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - - // additional validation - check to see if all types are resolved to their respective types - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(baseSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType'", - "union.attachmentUnionType", - getElementType(baseSTS, "testUnionTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(baseSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Complex Type should be 'headerType'", - "headerType", - getElementType(baseSTS, "testComplexTypeSimpleContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'mailsType'", - "mailsType", - getElementType(baseSTS, "testComplexTypeElementOnlyContentElem")); - Assert.assertEquals("Unresolved Complex Type should be 'mixedContentType'", - "mixedContentType", - getElementType(baseSTS, "testComplexTypeMixedElem")); - Assert.assertEquals("Unresolved Complex Type should be 'emptyContentType'", - "emptyContentType", - getElementType(baseSTS, "testComplexTypeEmptyElem")); - Assert.assertEquals("Unresolved Complex Type should be 'choiceGroupType'", - "choiceGroupType", - getElementType(baseSTS, "testChoiceGroupElem")); - Assert.assertEquals("Unresolved Complex Type should be 'allGroupType'", - "allGroupType", - getElementType(baseSTS, "testAllGroupElem")); - - } - - public void testModifyDataTypes() throws Exception - { - System.out.println("Inside test case testModifyDataTypes()"); - - // Step 1: read in a clean XSD datatypes_added.xsd, to create a base schema with no unresolved components - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("datatypes_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 13, 1, 15, 1); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); - - // check types before modify - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(baseSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(baseSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", - "union.attachmentUnionType", - getElementType(baseSTS, "testUnionTypeElem")); - - - //Step 2 : modify types from the schema - should result in STS with unresolved refs - //remove one of the constituent types for the union and test to see if union is anySimpleType - SchemaTypeSystem modifiedSTS = createNewSTS("datatypes_modified.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // test the PSOM created :walk thro the PSOM, look for # of elements,attributes,types & attribute groups - inspectSOM(modifiedSTS, 13, 1, 13, 1); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("PSOM " + modifiedSTS.getName() + " Save should fail", - checkPSOMSave(modifiedSTS)); - - // validate unresolved types - Assert.assertEquals("Unresolved Simple Type - Atomic should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testAtomicTypeElem")); - - // moved to detailed PSOMDetailedTest class - //Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", anySimpleType, getElementType(modifiedSTS, "testListTypeElem")); - //Assert.assertEquals("Unresolved Simple Type - Union should be 'anySimpleType'", anySimpleType, getElementType(modifiedSTS, "testUnionTypeElem")); - - // validate against an xml valid instance - should fail - Assert.assertFalse("Validation against instance should Failed ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), modifiedSTS)); - - // step 3: reload the original STS - SchemaTypeSystem finalSTS = createNewSTS("datatypes_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // walk the SOM - inspectSOM(finalSTS, 13, 1, 15, 1); - - // validate successful save - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed", - checkPSOMSave(finalSTS)); // should be able to save as its a valid SOM - - // validate instance - should validate - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), finalSTS)); - - // check types after modify - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(finalSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(finalSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", - "union.attachmentUnionType", - getElementType(finalSTS, "testUnionTypeElem")); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testDeleteDerivedTypes() throws Exception - { - System.out.println("Inside test case testDeleteDerivedTypes()"); - - // Step 1: read in a clean XSD derived_types_added.xsd with base and derived types to create a base schema with no unresolved components - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("derived_types_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 13, 0, 14, 0); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); - - // check types before deletion of base types - Assert.assertEquals("Elem Type should be 'ExtensionBaseType' (base)", - "ExtensionBaseType", - getElementType(baseSTS, "ExtensionBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedComplexContentType", - getElementType(baseSTS, "ExtensionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'ExtensionBaseMixedContentType' (base)", - "ExtensionBaseMixedContentType", - getElementType(baseSTS, "ExtensionBaseMixedContentTypElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedMixedContentType' (derived)", - "ExtensionDerivedMixedContentType", - getElementType(baseSTS, "ExtensionDerivedMixedContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionSimpleContentBaseType'", - "RestrictionSimpleContentBaseType", getElementType(baseSTS, "RestrictionSimpleContentBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionSimpleContentDerivedType'", - "RestrictionSimpleContentDerivedType", getElementType(baseSTS, "RestrictionSimpleContentDerivedTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionBaseComplexContentType'", - "RestrictionBaseComplexContentType", - getElementType(baseSTS, "RestrictionBaseComplexContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedComplexContentType'", - "RestrictionDerivedComplexContentType", - getElementType(baseSTS, "RestrictionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionBaseMixedContentType'", - "RestrictionBaseMixedContentType", getElementType(baseSTS, "RestrictionBaseMixedContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedMixedContentType'", - "RestrictionDerivedMixedContentType", getElementType(baseSTS, "RestrictionDerivedMixedContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionBaseEmptyContentType'", - "RestrictionBaseEmptyContentType", getElementType(baseSTS, "RestrictionBaseEmptyContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedEmptyContentType'", - "RestrictionDerivedEmptyContentType", getElementType(baseSTS, "RestrictionDerivedEmptyContentTypeElem")); - - // Step 2: create invalid PSOM with base type removed - SchemaTypeSystem modifiedSTS = createNewSTS("derived_types.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // recovearble errors - Assert.assertTrue("No Recovered Errors for Invalid PSOM", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 13, 0, 9, 0); - - // Recovered Errors, Test for saving of the SOM - Assert.assertEquals("SOM " + modifiedSTS.getName() + "Save Success - should fail!", - false, checkPSOMSave(modifiedSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); - - // check types - base should be 'anyType' - Assert.assertEquals("Elem Type should be 'anyType' (base)", - anyType, - getElementType(modifiedSTS, "ExtensionBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedComplexContentType", - getElementType(modifiedSTS, "ExtensionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'anyType' (base)", - anyType, - getElementType(modifiedSTS, "ExtensionBaseMixedContentTypElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedMixedContentType", - getElementType(modifiedSTS, "ExtensionDerivedMixedContentTypeElem")); - - // Restriction Simple Content Base type commented does not result in recoverable SOM - // moved to Detailed Test - //Assert.assertEquals("Elem Type should be 'anyType'", - // anyType, - // getElementType(modifiedSTS, "RestrictionSimpleContentBaseTypeElem")); - // - - Assert.assertEquals("Elem Type should be 'RestrictionSimpleContentDerivedType'", - "RestrictionSimpleContentDerivedType", - getElementType(modifiedSTS, "RestrictionSimpleContentDerivedTypeElem")); - - Assert.assertEquals("Elem Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "RestrictionBaseComplexContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedComplexContentType'", - "RestrictionDerivedComplexContentType", - getElementType(modifiedSTS, "RestrictionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "RestrictionBaseMixedContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedMixedContentType'", - "RestrictionDerivedMixedContentType", - getElementType(modifiedSTS, "RestrictionDerivedMixedContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'anyType'", anyType, - getElementType(modifiedSTS, "RestrictionBaseEmptyContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedEmptyContentType'", - "RestrictionDerivedEmptyContentType", getElementType(modifiedSTS, "RestrictionDerivedEmptyContentTypeElem")); - - - // step 3: reload the original STS - SchemaTypeSystem finalSTS = createNewSTS("derived_types_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(finalSTS, 13, 0, 14, 0); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed!", - checkPSOMSave(finalSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), finalSTS)); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - - public void testAddDerivedTypes() throws Exception - { - System.out.println("Inside test case testAddDerivedTypes()"); - - // Step 1: start with invalid SOM - one that has derived types but the base types are not defined - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("derived_types.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - Assert.assertTrue("No Recovered Errors for Invalid PSOM", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 13, 0, 9, 0); - - // Recovered Errors, Test for saving of the SOM - Assert.assertFalse("SOM " + baseSTS.getName() + "Save Success - should fail!", - checkPSOMSave(baseSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); - - // check types - base should be 'anyType' - Assert.assertEquals("Elem Type should be 'anyType' (base)", - anyType, - getElementType(baseSTS, "ExtensionBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedComplexContentType", - getElementType(baseSTS, "ExtensionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'anyType' (base)", - anyType, - getElementType(baseSTS, "ExtensionBaseMixedContentTypElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedMixedContentType", - getElementType(baseSTS, "ExtensionDerivedMixedContentTypeElem")); - - // Step 2: create valid PSOM now from xsd with base types defined - SchemaTypeSystem modifiedSTS = createNewSTS("derived_types_added.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 13, 0, 14, 0); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + modifiedSTS.getName() + "Save failed!", - checkPSOMSave(modifiedSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); - - // check types before deletion of base types - Assert.assertEquals("Elem Type should be 'ExtensionBaseType' (base)", - "ExtensionBaseType", - getElementType(modifiedSTS, "ExtensionBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedComplexContentType", - getElementType(modifiedSTS, "ExtensionDerivedComplexContentTypeElem")); - Assert.assertEquals("Elem Type should be 'ExtensionBaseMixedContentType' (base)", - "ExtensionBaseMixedContentType", - getElementType(modifiedSTS, "ExtensionBaseMixedContentTypElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedMixedContentType' (derived)", - "ExtensionDerivedMixedContentType", - getElementType(modifiedSTS, "ExtensionDerivedMixedContentTypeElem")); - - } - - // moved to PSOMDetaiedTest - //public void testDeleteReusableGroups() throws Exception - //{} - //public void testModifyReusableGroups() throws Exception - - public void testAddReusableGroups() throws Exception - { - System.out.println("Inside test case testAddReusableGroups()"); - - // Step 1: read in invalid XSD groups.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("groups.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // recovearble errors - Assert.assertTrue("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 7, 0, 4, 1); - - // Recovered Errors, Test for saving of the SOM - should fail - Assert.assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); - - // verify types - // named model groups - Assert.assertEquals("Elem Type should be 'ModelGrpType'", - "ModelGrpType", - getElementType(baseSTS, "ModelGrpTypeElem")); - Assert.assertTrue("Elem Type should be 'AttributeGroup'", - getAttributeGroup(baseSTS, "AttributeGroup")); - - // Step 2: create a SOM with valid xsd - SchemaTypeSystem modifiedSTS = createNewSTS("groups_added.xsd_", - baseSTS, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 7, 0, 5, 2); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + modifiedSTS.getName() + "Save failed!", - checkPSOMSave(modifiedSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); - - // verify named model groups - Assert.assertEquals("Elem Type should be 'ModelGrpType'", - "ModelGrpType", - getElementType(modifiedSTS, "ModelGrpTypeElem")); - Assert.assertTrue("Elem Type should be 'AttributeGroup'", - getAttributeGroup(modifiedSTS, "AttributeGroup")); - - - } - - - public void testAddSubstitutionGroups() throws Exception - { - System.out.println("Inside test case testAddSubstitutionGroups()"); - - // step1: load an invalid PSOM by with incomplete/missing Subst Grp head elem definition - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("groups.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // errors recovered - Assert.assertTrue("No Recovered Errors for recovered PSOM", - printRecoveredErrors()); - - // Recovered Errors, Test for saving of the SOM - Assert.assertFalse("SOM " + baseSTS.getName() + "Save Success - should fail!", - checkPSOMSave(baseSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 7, 0, 4, 1); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); - - // verify types - Assert.assertEquals("Elem Type should be 'anyType'", - anyType, - getElementType(baseSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'anyType' (Member of Sub. Group)", - anyType, - getElementType(baseSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(baseSTS, "SubGrpMemberElem2")); - - // named model groups - Assert.assertEquals("Elem Type should be 'ModelGrpType'", - "ModelGrpType", - getElementType(baseSTS, "ModelGrpTypeElem")); - Assert.assertTrue("Elem Type should be 'AttributeGroup'", - getAttributeGroup(baseSTS, "AttributeGroup")); - - // Step 2: create a valid SOM and add to these - SchemaTypeSystem modifiedSTS = createNewSTS("groups_added.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 7, 0, 5, 2); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + modifiedSTS.getName() + "Save failed!", - checkPSOMSave(modifiedSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); - - // verify types - substitution groups - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", - "SubGrpHeadElemType", - getElementType(modifiedSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", - "SubGrpHeadElemType", - getElementType(modifiedSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(modifiedSTS, "SubGrpMemberElem2")); - - // named model groups - moved to check in test - //Assert.assertEquals("Elem Type should be 'ModelGrpType'", "ModelGrpType", getElementType(baseSTS, "ModelGrpTypeElem")); - //Assert.assertEquals("Elem Type should be 'AttributeGroup'", "AttributeGroup", getAttributeGroup(baseSTS,"AttributeGroup")); - } - - - - public void testDeleteSubstitutionGroups() throws Exception - { - System.out.println("Inside test case testDeleteSubstitutionGroups()"); - - // Step 1: read in a clean XSD groups_added.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("groups_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 7, 0, 5, 2); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); - - // verify types - substitution groups - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", - "SubGrpHeadElemType", - getElementType(baseSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", - "SubGrpHeadElemType", - getElementType(baseSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(baseSTS, "SubGrpMemberElem2")); - - // named model groups - //Assert.assertEquals("Elem Type should be 'ModelGrpType'", "ModelGrpType", getElementType(baseSTS, "ModelGrpTypeElem")); - //Assert.assertEquals("Elem Type should be 'AttributeGroup'", "AttributeGroup", getAttributeGroup(baseSTS,"AttributeGroup")); - - // step2: load an invalid PSOM by deleting the Subst Grp head elem definition - SchemaTypeSystem modifiedSTS = createNewSTS("groups.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - Assert.assertTrue("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // Recovered Errors, Test for saving of the SOM - Assert.assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", - checkPSOMSave(modifiedSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 7, 0, 4, 1); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); - - // verify types - Assert.assertEquals("Elem Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'anyType' (Member of Sub. Group)", - anyType, - getElementType(modifiedSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(modifiedSTS, "SubGrpMemberElem2")); - - // named model groups - Assert.assertEquals("Elem Type should be 'ModelGrpType'", - "ModelGrpType", - getElementType(modifiedSTS, "ModelGrpTypeElem")); - Assert.assertTrue("Elem Type should be 'AttributeGroup'", - getAttributeGroup(modifiedSTS, "AttributeGroup")); - - // step 3: create a PSOM with the original xsd - SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // Test for saving of the SOM - should go thro - Assert.assertEquals("SOM " + finalSTS.getName() + "Save failed!", - true, - checkPSOMSave(finalSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); - - // verify types - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", - "SubGrpHeadElemType", - getElementType(finalSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", - "SubGrpHeadElemType", - getElementType(finalSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(finalSTS, "SubGrpMemberElem2")); - - // named model groups - //Assert.assertEquals("Elem Type should be 'ModelGrpType'", "ModelGrpType", getElementType(baseSTS, "ModelGrpTypeElem")); - //Assert.assertEquals("Elem Type should be 'AttributeGroup'", "AttributeGroup", getAttributeGroup(baseSTS,"AttributeGroup")); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testModifySubstitutionGroups() throws Exception - { - System.out.println("Inside test case testModifySubstitutionGroups()"); - - // Step 1: read in a clean XSD groups_added.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("groups_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 7, 0, 5, 2); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); - - // verify types - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", - "SubGrpHeadElemType", - getElementType(baseSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", - "SubGrpHeadElemType", - getElementType(baseSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(baseSTS, "SubGrpMemberElem2")); - - // step2: load a modified xsd with type of head elem in subs grp changed - SchemaTypeSystem modifiedSTS = createNewSTS("groups_modified.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // Recovered Errors, Test for saving of the SOM - still a valid PSOM - Assert.assertTrue("SOM " + modifiedSTS.getName() + "Save Success - should fail!", - checkPSOMSave(modifiedSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 5, 0, 3, 0); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); - - // verify types - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType2'", - "SubGrpHeadElemType2", - getElementType(modifiedSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType2' (derived)", - "SubGrpHeadElemType2", - getElementType(modifiedSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", - getElementType(modifiedSTS, "SubGrpMemberElem2")); - - // step3 : reload the original xsd - SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed!", - checkPSOMSave(finalSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(finalSTS, 7, 0, 5, 2); - - // verify types - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (base)", - "SubGrpHeadElemType", - getElementType(finalSTS, "SubGrpHeadElem")); - Assert.assertEquals("Elem Type should be 'SubGrpHeadElemType' (derived)", - "SubGrpHeadElemType", - getElementType(finalSTS, "SubGrpMemberElem1")); - Assert.assertEquals("Elem Type should be 'ExtensionSubGrpHeadElemType' (base)", - "ExtensionSubGrpHeadElemType", getElementType(finalSTS, "SubGrpMemberElem2")); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testModifyIdConstraints() throws Exception - { - System.out.println("Inside test case testModifyIdConstraints()"); - - // Step 1: read in a clean XSD groups_added.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("constraints_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 5, 0, 2, 0); - - Assert.assertTrue("Constraint 'uniqueConstraint' should be found",lookForIdentityConstraint(baseSTS,"uniqueConstraint")); - Assert.assertTrue("Constraint 'keyConstraint' should be found",lookForIdentityConstraint(baseSTS,"keyConstraint")); - Assert.assertTrue("Constraint 'KeyRefConstraint' should be found",lookForIdentityConstraint(baseSTS,"KeyRefConstraint")); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation against valid instance- should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_constraints_valid.xml"), baseSTS)); - - // validation against instance which violates the Constraints - should fail - Assert.assertFalse("Validation against invalid should fail", - validateInstance(getTestCaseFile("instance_constraints_invalid.xml"), baseSTS)); - - // Step 2: create an incremental PSOM with the constraint commented out - // Note: Partial SOMs cannot be created for Unique/Key constraints. They generate valid complete SOMs. - // The xsd includes these but the invalid SOM in this case is from a keyref definition referring to a - // non existant key - - SchemaTypeSystem modifiedSTS = createNewSTS("constraints.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // recovearble errors - Assert.assertTrue("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // Recovered Errors, Test for saving of the SOM - Assert.assertFalse("valid PSOM " + modifiedSTS.getName() + "Save failed !", - checkPSOMSave(modifiedSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 5, 0, 2, 0); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_constraints_valid.xml"), modifiedSTS)); - - // Invalid instance validation - should fail bcos of Unique constraint definition missing - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_constraints_invalid.xml"), modifiedSTS)); - - Assert.assertFalse("KeyRef 'KeyRefConstraint' should not be resolved", - lookForIdentityConstraint(modifiedSTS, "KeyConstraint")); - - // Step 3 : recreate SOM in first step and compare it - SchemaTypeSystem finalSTS = createNewSTS("constraints_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(finalSTS, 5, 0, 2, 0); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed!", - checkPSOMSave(finalSTS)); - - // instance validation against valid instance- should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_constraints_valid.xml"), finalSTS)); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - -} - - - - diff --git a/test/src/compile/scomp/som/detailed/PartialSOMDetailedTest.java b/test/src/compile/scomp/som/detailed/PartialSOMDetailedTest.java deleted file mode 100644 index 4168d2a..0000000 --- a/test/src/compile/scomp/som/detailed/PartialSOMDetailedTest.java +++ /dev/null @@ -1,632 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package compile.scomp.som.detailed; - -import compile.scomp.som.common.SomTestBase; -import junit.framework.Assert; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; - - -/** - * - * - */ -public class PartialSOMDetailedTest extends SomTestBase -{ - - public PartialSOMDetailedTest(String name) - { - super(name); - } - - // inherited methods - public void setUp() throws Exception - { - super.setUp(); - // initialize the built in schema type - builtin = XmlBeans.getBuiltinTypeSystem(); - - // populate the XmlOptions - if (errors== null) { - errors = new ArrayList(); - } - if (options == null) { - options = (new XmlOptions()).setErrorListener(errors); - options.setCompileDownloadUrls(); - options.put("COMPILE_PARTIAL_TYPESYSTEM"); - options.setLoadLineNumbers(); - } - - // initialize the runid to be used for generating output files for the PSOM walk thro's - runid = new Date().getTime(); - - // clean the output from the previous run - // delete directories created by checkPSOMSave() and output text file created by inspectPSOM() - deleteDirRecursive(new File(somOutputRootDir)); - } - - public void tearDown() throws Exception - { - errors.clear(); - super.tearDown(); - } - - public void testAddDataTypesList() throws Exception - { - System.out.println("Inside test case testAddDataTypesList()"); - - // Step 1 : create a PSOM from an incomplete/invalid xsd (datatypes.xsd) with unresolved references to various types - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("datatypes.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // recovearble errors should exist - Assert.assertTrue("No Recovered Errors for Invalid Schema", - printRecoveredErrors()); - - // Walk thro the SOM (pass #Elems, #Attr, #Types, #AttrGroups) - inspectSOM(baseSTS, 12, 1, 4, 1); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("Partial SOM " + baseSTS.getName() + "Save successful - should fail!", - checkPSOMSave(baseSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance Success - should fail ", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); - - // validate unresolved types - the ListType should resolve to 'anySimpleType' - Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", - anySimpleType, - getElementType(baseSTS, "testListTypeElem")); - } - - public void testDeleteReusableGroups() throws Exception - { - System.out.println("Inside test case testDeleteSubstitutionGroups()"); - - // Step 1: read in a clean XSD groups_added.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("reusable_grps_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 7, 0, 5, 1); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); - - // verify named model groups - Assert.assertTrue("Attribute Group 'AttributeGroup' should exist", - getAttributeGroup(baseSTS, "AttributeGroup")); - Assert.assertTrue("Model Group 'NamedModelGroup' should exist", - getModelGroup(baseSTS, "NamedModelGroup")); - - // step2: load an invalid PSOM by deleting the ModelGroup and AttributeGroup definitions commented - SchemaTypeSystem modifiedSTS = createNewSTS("reusable_grps.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // Recovered Errors, Test for saving of the SOM - printRecoveredErrors(); - Assert.assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", - checkPSOMSave(modifiedSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 7, 0, 5, 0); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); - - // named model groups - Assert.assertFalse("Attribute Group 'AttributeGroup' should not exist", - getAttributeGroup(modifiedSTS, "AttributeGroup")); - Assert.assertFalse("Model Group 'NamedModelGroup' should not exist", - getModelGroup(modifiedSTS, "NamedModelGroup")); - - // step 3: create a PSOM with the original xsd - SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", - modifiedSTS, - "FinalSchemaTS", sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed!", - checkPSOMSave(finalSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); - - // verify named model groups types - Assert.assertTrue("Attribute Group 'AttributeGroup' should exist", - getAttributeGroup(baseSTS, "AttributeGroup")); - Assert.assertTrue("Model Group 'NamedModelGroup' should exist", - getModelGroup(baseSTS, "NamedModelGroup")); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testModifyDataTypesList() throws Exception - { - System.out.println("Inside test case testModifyDataTypes()"); - - // 1. remove one of the constituent types for the union and test to see if union is anySimpleType - - // Step 1: read in a clean XSD datatypes_added.xsd, to create a base schema with no unresolved components - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("datatypes_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 13, 1, 15, 1); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_datatypes_valid.xml"), baseSTS)); - - // check types before modify - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(baseSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(baseSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", - "union.attachmentUnionType", - getElementType(baseSTS, "testUnionTypeElem")); - - - //Step 2 : modify types from the schema - should result in STS with unresolved refs - SchemaTypeSystem modifiedSTS = createNewSTS("datatypes_modified.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // test the PSOM created :walk thro the PSOM, look for # of elements,attributes,types & attribute groups - inspectSOM(modifiedSTS, 13, 1, 13, 1); - - // Test for saving of the PSOM - should not be able to save - Assert.assertFalse("PSOM " + modifiedSTS.getName() + " Save should fail", - checkPSOMSave(modifiedSTS)); - - // validate unresolved types - Assert.assertEquals("Unresolved Simple Type - Atomic should be 'anyType'", - anyType, - getElementType(modifiedSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'anySimpleType'", - anySimpleType, - getElementType(modifiedSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Simple Type - Union should be 'anySimpleType'", - anySimpleType, - getElementType(modifiedSTS, "testUnionTypeElem")); - - // validate against an xml valid instance - should fail - Assert.assertFalse("Validation against instance should Failed ", - validateInstance(getTestCaseFile("instance_simple_types_valid.xml"), modifiedSTS)); - - // step 3: reload the original STS - SchemaTypeSystem finalSTS = createNewSTS("datatypes_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // walk the SOM - inspectSOM(finalSTS, 13, 1, 15, 1); - - // validate successful save - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed", - checkPSOMSave(finalSTS)); // should be able to save as its a valid SOM - - // validate instance - should validate - Assert.assertTrue("Validation against instance Failed ", - validateInstance(getTestCaseFile("instance_simple_types_valid.xml"), finalSTS)); - - // check types after modify - Assert.assertEquals("Unresolved Simple Type should be 'attachmentTypes'", - "attachmentTypes", - getElementType(finalSTS, "testAtomicTypeElem")); - Assert.assertEquals("Unresolved List Type should be 'attchmentExtensionListTypes'", - "attchmentExtensionListTypes", - getElementType(finalSTS, "testListTypeElem")); - Assert.assertEquals("Unresolved Simple Type should be 'union.attachmentUnionType", - "union.attachmentUnionType", - getElementType(finalSTS, "testUnionTypeElem")); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testDeleteDerivedTypes() throws Exception - { - System.out.println("Inside test case testDeleteDerivedTypes()"); - - // Step 1: read in a clean XSD derived_types_added.xsd with base and derived types to create a base schema with no unresolved components - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("derived_types_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 13, 0, 14, 0); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); - - // check types before deletion of base types - Assert.assertEquals("Elem Type should be 'RestrictionSimpleContentBaseType'", - "RestrictionSimpleContentBaseType", getElementType(baseSTS, "RestrictionSimpleContentBaseTypeElem")); - - // Step 2: create invalid PSOM with base type removed - SchemaTypeSystem modifiedSTS = createNewSTS("derived_types.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // recovearble errors - Assert.assertTrue("No Recovered Errors for Invalid PSOM", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 13, 0, 9, 0); - - // Recovered Errors, Test for saving of the SOM - Assert.assertEquals("SOM " + modifiedSTS.getName() + "Save Success - should fail!", - false, checkPSOMSave(modifiedSTS)); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); - - // check types - base should be 'anyType' - // Restriction Complex Content Base type commented - Assert.assertEquals("Elem Type should be 'anyType'", - anyType, - getElementType(modifiedSTS, "RestrictionBaseComplexContentTypeElem")); - - - } - - public void testModifyReusableGroups() throws Exception - { - System.out.println("Inside test case testModifyReusableGroups()"); - - // Step 1: read in a clean XSD groups_added.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("groups_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 7, 0, 5, 2); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), baseSTS)); - - // verify named model groups - Assert.assertTrue("Model Group 'NamedModelGroup' should exist ", - getModelGroup(baseSTS, "NamedModelGroup")); - Assert.assertTrue("Attribute Group 'AttributeGroup' should exist", - getAttributeGroup(baseSTS, "AttributeGroup")); - - // step2: load a modified xsd with type of head elem in subs grp changed - SchemaTypeSystem modifiedSTS = createNewSTS("reusable_grps_modified.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // Recovered Errors, Test for saving of the SOM , invalid since grp definitions are commented out - printRecoveredErrors(); - Assert.assertFalse("SOM " + modifiedSTS.getName() + "Save Success - should fail!", - checkPSOMSave(modifiedSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 7, 0, 5, 1); - - // instance validation - should fail - Assert.assertFalse("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), modifiedSTS)); - - // verify named model groups - Assert.assertEquals("Elem Type should be 'ModelGrpType'", - "ModelGrpType", - getElementType(modifiedSTS, "ModelGrpTypeElem")); - Assert.assertTrue("Elem Type should be 'AttributeGroup'", - getAttributeGroup(modifiedSTS, "AttributeGroup")); - - // step3 : reload the original xsd - SchemaTypeSystem finalSTS = createNewSTS("groups_added.xsd_", - modifiedSTS, - "FinalSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", finalSTS); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("SOM " + finalSTS.getName() + "Save failed!", - checkPSOMSave(finalSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_subst_grps_valid.xml"), finalSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(finalSTS, 7, 0, 5, 2); - - // verify named model groups - Assert.assertEquals("Elem Type should be 'ModelGrpType'", - "ModelGrpType", - getElementType(finalSTS, "ModelGrpTypeElem")); - Assert.assertTrue("Elem Type should be 'AttributeGroup'", - getAttributeGroup(finalSTS, "AttributeGroup")); - - // compare this to the original schema here - Assert.assertTrue(compareSavedSOMs("BaseSchemaTS","FinalSchemaTS")); - } - - public void testModifyDerivedTypes() throws Exception - { - System.out.println("Inside test case testModifyDerivedTypes()"); - - // Step 1: read in a clean XSD derived_types_added.xsd - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("derived_types_added.xsd_", - null, - "BaseSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 13, 0, 14, 0); - - // Recovered Errors, Test for saving of the SOM - should go thro - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // instance validation - should be ok - Assert.assertTrue("Validation against instance failed", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), baseSTS)); - - // check types before deletion of base types - Assert.assertEquals("Elem Type should be 'ExtensionBaseType' (base)", - "ExtensionBaseType", - getElementType(baseSTS, "ExtensionBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedComplexContentType' (derived)", - "ExtensionDerivedComplexContentType", - getElementType(baseSTS, "ExtensionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'ExtensionBaseMixedContentType' (base)", - "ExtensionBaseMixedContentType", - getElementType(baseSTS, "ExtensionBaseMixedContentTypElem")); - Assert.assertEquals("Elem Type should be 'ExtensionDerivedMixedContentType' (derived)", - "ExtensionDerivedMixedContentType", - getElementType(baseSTS, "ExtensionDerivedMixedContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionSimpleContentBaseType'", - "RestrictionSimpleContentBaseType", - getElementType(baseSTS, "RestrictionSimpleContentBaseTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionSimpleContentDerivedType'", - "RestrictionSimpleContentDerivedType", - getElementType(baseSTS, "RestrictionSimpleContentDerivedTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionBaseComplexContentType'", - "RestrictionBaseComplexContentType", - getElementType(baseSTS, "RestrictionBaseComplexContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedComplexContentType'", - "RestrictionDerivedComplexContentType", - getElementType(baseSTS, "RestrictionDerivedComplexContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionBaseMixedContentType'", - "RestrictionBaseMixedContentType", - getElementType(baseSTS, "RestrictionBaseMixedContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedMixedContentType'", - "RestrictionDerivedMixedContentType", - getElementType(baseSTS, "RestrictionDerivedMixedContentTypeElem")); - - Assert.assertEquals("Elem Type should be 'RestrictionBaseEmptyContentType'", - "RestrictionBaseEmptyContentType", - getElementType(baseSTS, "RestrictionBaseEmptyContentTypeElem")); - Assert.assertEquals("Elem Type should be 'RestrictionDerivedEmptyContentType'", - "RestrictionDerivedEmptyContentType", - getElementType(baseSTS, "RestrictionDerivedEmptyContentTypeElem")); - - - // step 2 : change the base types now : derived_types_modified.xsd - SchemaTypeSystem modifiedSTS = createNewSTS("derived_types_modifed.xsd_", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // no recovearble errors just added another type - Assert.assertFalse("valid PSOM", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - //inspectSOM(modifiedSTS, 13, 0, 14, 0); - inspectSOM(modifiedSTS, 13, 0, 17, 0); - - // instance validation - should fail - Assert.assertFalse("Validation against instance success - should fail", - validateInstance(getTestCaseFile("instance_derived_types_valid.xml"), modifiedSTS)); - - // now validate instance with new base type - this should go thro - // TODO resolve this validation - //Assert.assertTrue("Validation against instance failed", - // validateInstance(getTestCaseFile("instance_derived_types_modify.xml"), modifiedSTS)); - - } - - public void testNameSpacesImportFile() throws Exception - { - System.out.println("Inside test case testNameSpacesImportFile()"); - - // Step 1: read in an xsd that imports from another xsd file providing file name only - // The source name is not specified as this confuses the dereferecing of the location for the schemaLocation Attribute - // The absolute rul specified in tbe basename (if specified) would also work. - - //String sBaseSourceName = "file:/D:/SVNNEW/xmlbeans/trunk/test/cases/xbean/compile/som/"; - SchemaTypeSystem baseSTS = createNewSTS("namespaces_import_fileonly.xsd_", - null, - "BaseSchemaTS", - null); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors this should not be a partial Schema - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - } - - public void testNameSpacesWithInclude() throws Exception - { - System.out.println("Inside test case testNameSpacesWithInclude()"); - - // Step 1: read in an xsd that includes another namespace in xsd file namespaces2.xsd - //String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("namespaces_include.xsd_", - null, - "BaseSchemaTS", - null); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - this should not be a partial Schema - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 2, 0, 1, 0); - - - } - - /* - public void testNameSpacesImportFileWithPath() throws Exception - { - System.out.println("Inside test case testNameSpacesImportFileWithPath()"); - - //Step 1: read in an xsd that does not have any imports - String sBaseSourceName = "testsourcename"; - SchemaTypeSystem baseSTS = createNewSTS("namespaces_noimports.xsd", - null, - "BaseSchemaTS", - sBaseSourceName); - - Assert.assertNotNull("Schema Type System created is Null.", baseSTS); - - // there should be NO recovearble errors - this should not be a partial Schema - Assert.assertFalse("Recovered Errors for Valid Schema", - printRecoveredErrors()); - - // Test for saving of the SOM - should go thro - Assert.assertTrue("Valid SOM " + baseSTS.getName() + "Save failed!", - checkPSOMSave(baseSTS)); - - // the tests - Walk thro the valid SOM - inspectSOM(baseSTS, 1, 0, 0, 0); - - // step 2 : read in an xsd that imports a namespace from another xsd file providing the complete file path for the imported xsd - SchemaTypeSystem modifiedSTS = createNewSTS("namespaces_import_filepath.xsd", - baseSTS, - "ModifiedSchemaTS", - sBaseSourceName); - Assert.assertNotNull("Schema Type System created is Null.", modifiedSTS); - - // no recovearble errors just added another type - Assert.assertFalse("valid PSOM", - printRecoveredErrors()); - - // the tests - Walk thro the valid SOM - inspectSOM(modifiedSTS, 2, 0, 1, 0); - - } - */ - - -} - - - - diff --git a/test/src/dom/checkin/AttributeTest.java b/test/src/dom/checkin/AttributeTest.java deleted file mode 100755 index 2f4b775..0000000 --- a/test/src/dom/checkin/AttributeTest.java +++ /dev/null @@ -1,417 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package dom.checkin; - - -import dom.common.DomUtils; -import dom.common.NodeWithChildrenTest; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.w3c.dom.*; - - -/** - * - * - */ - -public class AttributeTest extends NodeWithChildrenTest { - - public AttributeTest(String s) { - super(s); - String sDTD = "" + - "" + - "" + - "]>"; - - sXml = - "some text"; - if (bDTD) - sXml = sDTD + sXml; - sXmlNS = - ""; - } - - public static Test suite() { - return new TestSuite(AttributeTest.class); - } - - - public void testNodeName() { - - String sExpected = "myns:at0"; - assertEquals(sExpected, m_node.getNodeName()); - } - - public void testGetName() { - - String sExpected = "myns:at0"; - assertEquals(sExpected, ((Attr) m_node).getName()); - } - - public void testNodeType() { - assertEquals(Node.ATTRIBUTE_NODE, m_node.getNodeType()); - } - - - public void testNodeValue() { - assertEquals("val01", m_node.getNodeValue()); - } - - - //following are null here - - public void testNextSibling() { - assertEquals(null, m_node.getNextSibling()); - } - - public void testPreviousSibling() { - assertEquals(null, m_node.getPreviousSibling()); - } - - public void testParent() { - assertEquals(null, m_node.getParentNode()); - } - - - public void testPrefix() { - assertEquals("myns", m_node.getPrefix()); - } - - public void testNamespaceUri() { - assertEquals("uri:foo", m_node.getNamespaceURI()); - } - - public void testLocalName() { - assertEquals("at0", m_node.getLocalName()); - } - - - public void testAppendChild() { - //elt - Node newChild = m_doc.createElement("foo"); - try { - m_node.appendChild(newChild); - fail( - "Cannot append an element children to attributes " + - m_node.getChildNodes().getLength()); - } - catch (DOMException de) { - assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); - } - - newChild = m_doc.createTextNode("foobar"); - m_node.appendChild(newChild); - assertEquals(2, m_node.getChildNodes().getLength()); - -//TODO - m_node.normalize(); - assertEquals(1, m_node.getChildNodes().getLength()); - assertEquals("val01foobar", ((Text) m_node.getFirstChild()).getData()); - - } - - public void testCloneNode() { - Attr cloned, - cloned1; - cloned = (Attr) m_node.cloneNode(true); - - - assertEquals(true, DomUtils.compareNodesDeep(m_node, cloned)); - assertEquals(false, m_node == cloned); - - -//TODO - cloned1 = (Attr) m_node.cloneNode(false); - // assertEquals(m_node.getChildNodes(), ); - assertEquals(true, DomUtils.compareNodesShallow(m_node, cloned)); - - if (bDTD) { - assertEquals(false, cloned.getSpecified()); - assertEquals(false, ((Attr) m_node).getSpecified()); - m_node = m_doc.getAttributes().getNamedItem("at_spec"); - cloned = (Attr) m_node.cloneNode(true); - cloned1 = (Attr) m_node.cloneNode(false); - assertEquals(cloned, cloned1); - assertEquals(true, m_node.equals(cloned)); - assertEquals(false, m_node == cloned); - assertEquals(true, cloned.getSpecified()); - assertEquals(false, ((Attr) m_node).getSpecified()); - } - } - - /** - * public void testXercesClone()throws Exception{ - * org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); - * parser.parse(new InputSource(new StringReader(sXml))); - * Document xercesDocument = parser.getDocument(); - * assertFalse (xercesDocument==null); - *

        - * Node test = m_doc.getFirstChild(); - * assertTrue(test.hasChildNodes()); - * test = ((Element) test).getAttributeNodeNS("uri:foo", "at0"); - * Node clone=test.cloneNode(false); - * assertTrue(clone.hasChildNodes()); - *

        - * } - */ - - public void testGetChildNodes() { - assertEquals(1, m_node.getChildNodes().getLength()); - } - - public void testFirstChild() { - assertEquals("val01", ((Text) m_node.getFirstChild()).getData()); - } - - public void testLastChild() { - assertEquals("val01", ((Text) m_node.getLastChild()).getData()); - } - - public void testInsertBefore() { - Node newChild = m_doc.createElement("foo"); - assertEquals(1, m_node.getChildNodes().getLength()); - - Node textNode = m_node.getFirstChild(); - - try { - m_node.insertBefore(newChild, textNode); - } - catch (DOMException de) { - assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); - } - - newChild = m_doc.createTextNode("foo"); - m_node.insertBefore(newChild, textNode); - assertEquals("foo", m_node.getFirstChild().getNodeValue()); - assertEquals("val01", m_node.getLastChild().getNodeValue()); - } - - - public void testRemoveChild() { - //attr w/o a value - Element owner = (Element) ((Attr) m_node).getOwnerElement(); - m_node.removeChild(m_node.getFirstChild()); - assertEquals("", ((Attr) m_node).getValue()); - // assertEquals(false,owner.hasAttributeNS("uri:foo","at0")); - } - - public void testReplaceChild() { - - //assertFalse(m_node.hasChildNodes()); - Node newChild = m_doc.createElement("foo"); - assertEquals(1, m_node.getChildNodes().getLength()); - try { - m_node.replaceChild(newChild, m_node.getFirstChild()); - fail("can not put an element under an attr"); - } - catch (DOMException de) { - assertEquals(DOMException.HIERARCHY_REQUEST_ERR, de.code); - } - newChild = m_doc.createTextNode("realnewval"); - assertEquals(1, m_node.getChildNodes().getLength()); - m_node.replaceChild(newChild, m_node.getFirstChild()); - if (!"realnewval".equals(((Attr) m_node).getValue())) - fail(" Expected realnewval but got " + ((Attr) m_node).getValue()); - - } - - - public void testGetOwnerElement() { - assertEquals("foo", ((Attr) m_node).getOwnerElement().getLocalName()); - Node newNode = m_doc.createAttributeNS("foo1:org", "name"); - assertEquals(null, ((Attr) newNode).getOwnerElement()); - newNode = m_doc.createAttribute("name"); - assertEquals(null, ((Attr) newNode).getOwnerElement()); - } - - /*Not implem - //TODO - public void testGetSpecified(){ - if (bDTD){ - Attr at_true=(Attr)m_doc.getAttributes().getNamedItem("at_spec"); - assertEquals(false,at_true.getSpecified()); - } - assertEquals(true,((Attr)m_node).getSpecified()); - } - */ - public void testSetValue() { - String newVal = "new" + - "" + - "" + - "" + - "]>"; - sXmlNS = "" + - "" + - "txt0nestedfoo" + - "" + - "nstext" + - ""; - if (bDTD) - sXmlNS = sDTD + sXmlNS; - sXml = Common.XML_FOO_BAR_NESTED_SIBLINGS; - } - - public static Test suite() { - return new TestSuite(ElementTest.class); - } - - - public void testNodeName() { - assertEquals("zed", m_node.getNodeName()); - } - - public void testNodeType() { - assertEquals(Node.ELEMENT_NODE, m_node.getNodeType()); - } - - - public void testNodeValue() { - assertEquals(null, m_node.getNodeValue()); - } - - - public void testNextSibling() { - assertEquals(null, m_node.getNextSibling()); - } - - public void testPreviousSibling() { - Node prSib = m_node.getPreviousSibling(); - assertEquals("text0", prSib.getNodeValue()); - } - - public void testParent() { - Node parent = m_node.getParentNode(); - assertEquals("bar", parent.getLocalName()); - assertEquals(m_doc.getFirstChild().getFirstChild(), parent); - } - - public void testPrefix() { - assertEquals("", m_node.getPrefix()); - - m_node = m_docNS.getDocumentElement().getChildNodes().item(1); - assertEquals("myns:foo", m_node.getNodeName()); - assertEquals("myns", m_node.getPrefix()); - } - - public void testNamespaceUri() { - assertEquals("",m_node.getNamespaceURI()); - } - - public void testCloneNode() { - super.testCloneNode(); - } - - /** - * Clone node with atts - */ - public void testCloneNodeAttrs() { - Node toClone = m_docNS.getFirstChild(); //the foo elt - /* Node clone1=toClone.cloneNode(false); - - NamedNodeMap attrSet1=toClone.getAttributes(); - assertEquals(true,DomUtils.compareNamedNodeMaps(attrSet1,clone1.getAttributes())); - */ - Node clone2 = toClone.cloneNode(true); - } - - public void testHasAttributes() { - super.testHasAttributes(); - m_node = m_doc.getFirstChild(); - assertEquals(true, ((Element) m_node).hasAttributes()); - } - - public void testGetAttribute() { - m_node = m_docNS.getFirstChild(); - if (bDTD) - assertEquals("0", ((Element) m_node).getAttribute("at_spec")); - assertEquals("val2", - ((Element) m_node.getFirstChild()).getAttribute("at2")); - } - - public void testGetAttributeDNE() { - m_node = m_docNS.getFirstChild(); - assertEquals("", ((Element) m_node).getAttribute("at3")); - assertEquals("", ((Element) m_node).getAttribute("foobar")); - String sNull = null; - assertEquals("", ((Element) m_node).getAttribute(sNull)); - } - - public void testGetAttributeNode() { - m_node = m_docNS.getFirstChild(); - assertEquals("bar", ((Element) m_node).getTagName()); - //assertEquals("uri:foo",((Attr)((Element)m_node).getAttributeNodeNS("xmlns","myns")).getNodeValue()); - m_node = m_node.getFirstChild(); - assertEquals("val2", - ((Attr) ((Element) m_node).getAttributeNode("at2")).getNodeValue()); - if (bDTD) - assertEquals("0", - ((Attr) ((Element) m_node).getAttributeNode("at_spec")).getNodeValue()); - } - - public void testGetAttributeNodeDNE() { - m_node = m_docNS.getFirstChild(); - assertEquals(null, ((Element) m_node).getAttributeNode("at3")); - assertEquals(null, ((Element) m_node).getAttributeNode("foobar")); - String sNull = null; - assertEquals("", ((Element) m_node).getAttribute(sNull)); - } - - public void getAttributeNodeNS() { - m_node = m_docNS.getFirstChild(); - assertEquals("0", - ((Attr) ((Element) m_node).getAttributeNodeNS("", "at_spec")).getNodeValue()); - assertEquals("val01", - ((Attr) ((Element) m_node).getAttributeNodeNS("uri:foo", "at0")).getNodeValue()); - assertEquals("val0", - ((Attr) ((Element) m_node).getAttributeNodeNS(null, "at0")).getNodeValue()); - assertEquals("val3", - ((Attr) ((Element) m_node).getAttributeNodeNS("uri:foo", "at3")).getNodeValue()); - } - - public void testGetAttributeNodeNS_DNE() { - m_node = m_docNS.getFirstChild(); - assertEquals(null, ((Element) m_node).getAttributeNodeNS("", "at3")); - assertEquals(null, - ((Element) m_node).getAttributeNodeNS("uri:foo", "at1")); - String sNull = null; - assertEquals(null, - ((Element) m_node).getAttributeNodeNS("uri:foo", sNull)); - } - - public void testGetAttributeNS() { - m_node = m_docNS.getFirstChild().getFirstChild(); - if (bDTD) - assertEquals("0", - ((Element) m_node).getAttributeNS(null, "at_spec")); - assertEquals("val01", - ((Element) m_node).getAttributeNS("uri:foo", "at0")); - assertEquals("val2", ((Element) m_node).getAttributeNS("", "at2")); - } - - public void testGetAttributeNS_DNE() { - m_node = m_docNS.getFirstChild(); - assertEquals("", ((Element) m_node).getAttributeNS("", "at3")); - assertEquals("", ((Element) m_node).getAttributeNS("uri:foo", "at1")); - String sNull = null; - assertEquals("", ((Element) m_node).getAttributeNS("uri:foo", sNull)); - } - - public void testGetElementsByTagName() { - //move node @ foo - m_node = m_node.getParentNode().getParentNode(); - NodeList result = ((Element) m_node).getElementsByTagName("*"); - int nEltCount = 5;//num elts in the XML - assertEquals(nEltCount - 1, result.getLength()); - - result = ((Element) m_node).getElementsByTagName("zed"); - assertEquals(2, result.getLength()); - assertEquals("nested0", result.item(0).getFirstChild().getNodeValue()); - assertEquals("nested1", result.item(1).getFirstChild().getNodeValue()); - } - - public void testGetElementsByTagNameDNE() { - NodeList result = ((Element) m_node.getParentNode()).getElementsByTagName( - "foobar"); - assertEquals(0, result.getLength()); - } - - //elts need to come out in preorder order - public void testGetElementsByTagNamePreorder() { - m_node = m_docNS.getFirstChild(); - NodeList result = ((Element) m_node).getElementsByTagName("foo"); - assertEquals(2, result.getLength()); - assertEquals("txt0", result.item(0).getFirstChild().getNodeValue()); - assertEquals("nestedfoo", - result.item(1).getFirstChild().getNodeValue()); - } - - public void testGetElementsByTagNameDescendant() { - m_node = m_docNS.getFirstChild().getFirstChild(); - NodeList result = ((Element) m_node).getElementsByTagName("foo");//self should not be selected - assertEquals(1, result.getLength()); - assertEquals("nestedfoo", - result.item(0).getFirstChild().getNodeValue()); - } - - - public void testGetElementsByTagNameNS() { - m_node = m_docNS.getFirstChild(); - NodeList result = ((Element) m_node).getElementsByTagNameNS("*", "*"); - int nEltCount = 6; - assertEquals(nEltCount - 1, result.getLength()); - - result = ((Element) m_node).getElementsByTagNameNS("*", "foo"); - nEltCount = 3; - assertEquals(nEltCount, result.getLength()); - assertEquals("txt0", result.item(0).getFirstChild().getNodeValue()); - assertEquals("nestedfoo", - result.item(1).getFirstChild().getNodeValue()); - assertEquals("nstext", result.item(2).getFirstChild().getNodeValue()); - - - result = ((Element) m_node).getElementsByTagNameNS("uri:foo", "foo"); - assertEquals(1, result.getLength()); - assertEquals("nstext", result.item(0).getFirstChild().getNodeValue()); - - result = ((Element) m_node).getElementsByTagNameNS(null, "foo"); - assertEquals("txt0", result.item(0).getFirstChild().getNodeValue()); - assertEquals("nestedfoo", - result.item(1).getFirstChild().getNodeValue()); - NodeList result1 = ((Element) m_node).getElementsByTagNameNS("", "foo"); - assertEquals(true, compareNodeList(result, result1)); - - - result = ((Element) m_node).getElementsByTagNameNS(null, "*"); - assertEquals(3, result.getLength()); - assertEquals("ZeD", ((Element) result.item(2)).getTagName()); - } - - public void testGetElementsByTagNameNS_DNE() { - m_node = m_docNS.getFirstChild(); - NodeList result = ((Element) m_node).getElementsByTagNameNS("uri:foo", - "zed"); - assertEquals(0, result.getLength()); - - result = - ((Element) m_node).getElementsByTagNameNS("foo:uri_DNE", "foo"); - assertEquals(0, result.getLength()); - - } - - public void testGetTagName() { - m_node = - m_docNS.getFirstChild().getChildNodes().item(1).getChildNodes() - .item(1); - assertEquals("ZeD", ((Element) m_node).getTagName()); - - } - - - public void testHasAttribute() { - m_node = m_docNS.getFirstChild(); - if (bDTD) - assertEquals(true, ((Element) m_node).hasAttribute("at_spec")); - - m_node = m_docNS.getFirstChild(); - assertEquals(false, ((Element) m_node).hasAttribute("at3")); - assertEquals(false, ((Element) m_node).hasAttribute("at0")); - } - - public void testHasAttributeNS() { - m_node = m_docNS.getFirstChild(); - if (bDTD) - assertEquals(true, - ((Element) m_node).hasAttributeNS(null, "at_spec")); - - m_node = m_node.getFirstChild(); - assertEquals(true, ((Element) m_node).hasAttributeNS("uri:foo", "at3")); - assertEquals(false, - ((Element) m_node).hasAttributeNS("uri:foo:org", "at0")); - assertEquals(false, ((Element) m_node).hasAttributeNS("uri:foo", null)); - } - - public void testRemoveAttribute() { - m_node = m_docNS.getFirstChild(); - //remove default - if (bDTD) { - - ((Element) m_node).removeAttribute("at_spec"); - assertEquals(1, m_node.getAttributes().getLength()); - } - - m_node = m_node.getFirstChild(); - assertEquals("foo", m_node.getNodeName()); - assertEquals(5, m_node.getAttributes().getLength()); - ((Element) m_node).removeAttribute("at2"); - assertEquals(4, m_node.getAttributes().getLength()); - - //DNE - ((Element) m_node).removeAttribute("at3"); - assertEquals(4, m_node.getAttributes().getLength()); - - } - - public void testRemoveAttributeNode() { - Node removed; - //remove default - m_node = m_docNS.getFirstChild(); - if (bDTD) { - ((Element) m_node).removeAttributeNode( - ((Element) m_node).getAttributeNode("at_spec")); - assertEquals(1, m_node.getAttributes().getLength()); - } - m_node = m_node.getFirstChild(); - assertEquals("foo", m_node.getNodeName()); - assertEquals(5, m_node.getAttributes().getLength()); - Attr remove = ((Element) m_node).getAttributeNode("at2"); - removed = ((Element) m_node).removeAttributeNode(remove); - assertFalse(removed == null); - assertEquals(4, m_node.getAttributes().getLength()); - assertEquals(removed, remove); - } - - public void testRemoveAttributeNode_DNE() { - //DNE - Node removed; - Attr remove = ((Element) m_node).getAttributeNode("at3"); - try { - removed = ((Element) m_node).removeAttributeNode(remove); - fail("removing Non existing attr"); - } - catch (DOMException de) { - assertEquals(DOMException.NOT_FOUND_ERR, de.code); - } - - remove = null; - try { - removed = ((Element) m_node).removeAttributeNode(remove); - fail("removing Non existing attr"); - } - catch (DOMException de) { - assertEquals(DOMException.NOT_FOUND_ERR, de.code); - } - - //differentParent - remove = m_doc.getDocumentElement().getAttributeNode("attr0"); - try { - removed = ((Element) m_node).removeAttributeNode(remove); - fail("removing Non existing attr"); - } - catch (DOMException de) { - assertEquals(DOMException.NOT_FOUND_ERR, de.code); - } - } - - public void testRemoveAttributeNS() { - //remove default - m_node = m_docNS.getFirstChild(); - if (bDTD) { - ((Element) m_node).removeAttributeNS(null, "at_spec"); - assertEquals(1, m_node.getAttributes().getLength()); - } - m_node = ((Element) m_node).getFirstChild(); - ((Element) m_node).removeAttributeNS("uri:foo", "at0"); - assertEquals(4, m_node.getAttributes().getLength()); - - //DNE - ((Element) m_node).removeAttributeNS(null, "at3"); - assertEquals(4, m_node.getAttributes().getLength()); - - ((Element) m_node).removeAttributeNS("uri:foo", null); - assertEquals(4, m_node.getAttributes().getLength()); - } - - - public void testSetAttribute() { - m_node = m_doc.getDocumentElement(); - - try { - ((Element) m_node).setAttribute("invalid<", "0"); - fail("Invalid attr name"); - } - catch (DOMException de) { - assertEquals(DOMException.INVALID_CHARACTER_ERR, de.code); - } - - ((Element) m_node).setAttribute("attr0", "newval"); - assertEquals("newval", ((Element) m_node).getAttribute("attr0")); - - - ((Element) m_node).setAttribute("attr1", "newval"); - assertEquals("newval", ((Element) m_node).getAttribute("attr1")); - assertEquals(2, m_node.getAttributes().getLength()); - } - - public void testSetAttributeNode() { - Attr result; - Attr newAttr = m_doc.createAttribute("attr0"); - Attr oldAttr = ((Element) m_node).getAttributeNode("attr0"); - newAttr.setValue("newval"); - result = ((Element) m_node).setAttributeNode(newAttr); - assertEquals(oldAttr, result); - assertEquals("newval", - ((Element) m_node).getAttributeNode("attr0").getNodeValue()); - - //insert self - try { - Attr at0 = ((Element) m_node).getAttributeNode("attr0"); - String v1 = at0.getNodeValue(); - ((Element) m_node).setAttributeNode(at0); - assertEquals(v1, ((Element) m_node).getAttribute("attr0")); - } - catch (DOMException de) { - assertEquals(de.code, DOMException.INUSE_ATTRIBUTE_ERR); - } - - //insert new - newAttr = m_doc.createAttribute("attr1"); - newAttr.setValue("newval"); - result = ((Element) m_node).setAttributeNode(newAttr); - assertEquals(null, result); - assertEquals("newval", - ((Element) m_node).getAttributeNode("attr1").getNodeValue()); - assertEquals(2, m_node.getAttributes().getLength()); - } - - public void testSetAttributeNodeDiffDoc() { - Attr result; - Attr newAttr = m_docNS.createAttribute("attr0"); - try { - result = ((Element) m_node).setAttributeNode(newAttr); - fail("Attr Node diff doc in use"); - } - catch (DOMException de) { - assertEquals(DOMException.WRONG_DOCUMENT_ERR, de.code); - } - } - - public void testSetAttributeNodeInUse() { - //insert new - m_node = m_node.getParentNode().getParentNode(); - Attr newAttr = ((Element) m_node).getAttributeNode("attr0"); - m_node = m_node.getFirstChild(); - try { - ((Element) m_node).setAttributeNode(newAttr); - fail("Attr Node in use"); - } - catch (DOMException de) { - assertEquals(DOMException.INUSE_ATTRIBUTE_ERR, de.code); - } - } - - public void testSetAttributeNodeNS() { - m_node = m_docNS.getFirstChild().getFirstChild(); - Attr result; - Attr newAttr = m_docNS.createAttributeNS("uri:foo", "at0"); - Attr oldAttr = ((Element) m_node).getAttributeNodeNS("uri:foo", "at0"); - assertFalse(oldAttr == null); - newAttr.setValue("newval"); - result = ((Element) m_node).setAttributeNodeNS(newAttr); - assertEquals(oldAttr, result); - Attr insertedAtt = ((Element) m_node).getAttributeNodeNS("uri:foo", - "at0"); - assertFalse(insertedAtt == null); - assertEquals("newval", insertedAtt.getNodeValue()); - - //insert new - int nAttrCnt = m_node.getAttributes().getLength(); - newAttr = m_docNS.createAttributeNS("uri:foo", "attr1"); - newAttr.setValue("newval"); - result = ((Element) m_node).setAttributeNode(newAttr); - assertEquals(null, result); - assertEquals("newval", - ((Element) m_node).getAttributeNS("uri:foo", "attr1")); - assertEquals(nAttrCnt + 1, m_node.getAttributes().getLength()); - - //insert new - newAttr = m_docNS.createAttributeNS("uri:foo:org", "attr1"); - newAttr.setValue("newURIval"); - result = ((Element) m_node).setAttributeNodeNS(newAttr); - - assertEquals(null, result); - assertEquals("newURIval", - ((Element) m_node).getAttributeNS("uri:foo:org", "attr1")); - assertEquals(nAttrCnt + 2, m_node.getAttributes().getLength()); - - } - - public void testSetAttributeNS() { - m_node = m_docNS.getFirstChild().getFirstChild(); - //overwrite - ((Element) m_node).setAttributeNS("uri:foo", "at0", "newval"); - assertEquals("newval", - ((Element) m_node).getAttributeNS("uri:foo", "at0")); - - - ((Element) m_node).setAttributeNS("uri:foo:org", "attr1", "newval"); - assertEquals("newval", - ((Element) m_node).getAttributeNS("uri:foo:org", "attr1")); - assertEquals(6, m_node.getAttributes().getLength()); - - } - - public void testSetAttributeNSBadNS() { - //qualifiedName is malformed - try { - ((Element) m_node).setAttributeNS("foo:org", "invalid<", "0"); - fail("Invalid attr name"); - } - catch (DOMException de) { - assertEquals(DOMException.INVALID_CHARACTER_ERR, de.code); - } - - //the qualifiedName has a prefix and the namespaceURI is null - try { - String sNull = null; - ((Element) m_node).setAttributeNS(sNull, "myfoo:at", "0"); - fail("Invalid attr name"); - } - catch (DOMException de) { - assertEquals(DOMException.NAMESPACE_ERR, de.code); - } - } - - public void testSetAttributeNSBadNS_xmlns() { - //the qualifiedName, or its prefix, is "xmlns" and the namespaceURI is different from " http://www.w3.org/2000/xmlns/". - try { - ((Element) m_node).setAttributeNS("foo:org:uri", "xmlns", "0"); - fail("Invalid attr name"); - } - catch (DOMException de) { - assertEquals(DOMException.NAMESPACE_ERR, de.code); - } - - try { - ((Element) m_node).setAttributeNS("foo:org:uri", "xmlns:foo", "0"); - fail("Invalid attr name"); - } - catch (DOMException de) { - assertEquals(DOMException.NAMESPACE_ERR, de.code); - } - } - - public void testSetAttributeNSBadNS_xml() { - //if the qualifiedName has a prefix that is "xml" - // and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace" - try { - ((Element) m_node).setAttributeNS("foo:org:uri", "xml:foo", "0"); - fail("Invalid attr name"); - } - catch (DOMException de) { - assertEquals(DOMException.NAMESPACE_ERR, de.code); - } - } - - public void testGetChildNodes() { - m_node = m_node.getParentNode(); - assertEquals(2, m_node.getChildNodes().getLength()); - } - - public void testFirstChild() { - assertEquals("nested0", m_node.getFirstChild().getNodeValue()); - } - - public void testLastChild() { - assertEquals("nested0", m_node.getLastChild().getNodeValue()); - } - - //code coverage: need a node with penultimate elt and last text - public void testLastChildMixedContent() { - Node prevSibling = m_doc.createElement("penultimateNode"); - m_node.insertBefore(prevSibling, m_node.getFirstChild()); - assertEquals("nested0", m_node.getLastChild().getNodeValue()); - } - - - public void testGetAttributes() { - assertEquals(0, m_node.getAttributes().getLength()); - } - - public void testLocalName() { - assertEquals("zed", m_node.getLocalName()); - } - - public void testSetPrefix() { - //set a null prefix - m_node = - m_docNS.getFirstChild().getFirstChild().getChildNodes().item(2);// - assertFalse(m_node == null); - m_node.setPrefix(null); - assertEquals("", m_node.getPrefix()); - - m_node.setPrefix("other"); - - assertEquals("other:yana", m_node.getNodeName()); - assertEquals("other:yana", ((Element) m_node).getTagName()); - // assertEquals("uri:other",m_node.getNamespaceURI());--this is the URI @ creation--never changes - assertEquals(1, - ((Element) m_docNS.getDocumentElement()).getElementsByTagName( - "other:yana") - .getLength()); - - - } - - public void testNormalizeNode() throws Exception { - m_node = m_node.getParentNode(); - m_node.replaceChild(m_doc.createTextNode("txt1"), - m_node.getLastChild()); - assertEquals(2, m_node.getChildNodes().getLength()); - - m_node.normalize(); - assertEquals(1, m_node.getChildNodes().getLength()); - - - } - - public void testNormalizeNodeNoChildren() throws Exception { - m_node = m_doc.createElement("foobar"); - assertEquals(0, m_node.getChildNodes().getLength()); - m_node.normalize(); - assertEquals(0, m_node.getChildNodes().getLength()); - } - - public void testNormalizeNodeOneChild() throws Exception { - m_node = m_doc.createElement("foobar"); - m_node.appendChild(m_doc.createElement("foobar")); - assertEquals(1, m_node.getChildNodes().getLength()); - m_node.normalize(); - assertEquals(1, m_node.getChildNodes().getLength()); - } - - public void testAppendChildExisting() { - m_node = m_docNS.getFirstChild().getLastChild(); - Node child = m_docNS.getFirstChild().getFirstChild(); - super.testAppendChildExisting(child); - } - - public void testInsertExisitingNode() { - m_node = m_docNS.getFirstChild().getLastChild(); - Node child = m_docNS.getFirstChild().getFirstChild(); - super.testAppendChildExisting(child); - - } - - - public void testDomLevel1() { - Element elt = m_doc.createElement("foobar"); - assertNull("L1 prefix null", elt.getPrefix()); - assertNull("L1 LocalName null", elt.getLocalName()); - assertNull("L1 Uri null", elt.getNamespaceURI()); - try - { - elt.setPrefix("foo"); - fail("L1 prefix null"); - } - catch (DOMException de) - { - assertEquals(DOMException.NAMESPACE_ERR, de.code); - } - } - - public void moveToNode() { - m_node = m_doc.getFirstChild().getFirstChild().getChildNodes().item(1);//zed node; - assertFalse(m_node == null); - } - - public void setUp() throws Exception { - super.setUp(); - moveToNode(); - } - - -} diff --git a/test/src/dom/checkin/PITest.java b/test/src/dom/checkin/PITest.java deleted file mode 100755 index 8bcc32c..0000000 --- a/test/src/dom/checkin/PITest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package dom.checkin; - -import dom.common.NodeTest; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.w3c.dom.DOMException; -import org.w3c.dom.Node; -import org.w3c.dom.ProcessingInstruction; - - -/** - * - * - */ - -public class PITest extends NodeTest { - - public PITest(String s) { - super(s); - sXml = - "text"; - //inspired by Common.XML_FOO_PROCINST; - } - - public static Test suite() { - return new TestSuite(PITest.class); - } - - - public void testNodeName() { - assertEquals("xml-stylesheet", m_node.getNodeName()); - } - - public void testLocalName() { - assertEquals("xml-stylesheet", m_node.getNodeName()); - } - - public void testNodeType() { - assertEquals(Node.PROCESSING_INSTRUCTION_NODE, m_node.getNodeType()); - } - - - public void testNodeValue() { - assertEquals( - "type=\"text/xsl\" xmlns=\"http://openuri.org/shipping/\"", - m_node.getNodeValue()); - } - - - public void testNextSibling() { - Node nxtSibling = m_node.getNextSibling(); - assertEquals("foo", nxtSibling.getNodeName()); - - } - - public void testSetNodeValue() { - String sNewVal = "type=\"text/xsl\" xmlns=\"http://xbean.foo.org\""; - m_node.setNodeValue(sNewVal); - assertEquals(sNewVal, m_node.getNodeValue()); - - } - - - - public void testNormalize() { - //TODO - } - - public void testReplaceChild() { - } - - public void testRemoveChild() { - } - - public void testAppendChild() { - } - - public void testInsertBefore() { - } - - public void testPreviousSibling() { - Node prSibling = m_node.getPreviousSibling(); - assertEquals(null, prSibling); - } - - public void testParent() { - Node parent = m_node.getParentNode(); - assertEquals(m_doc.getFirstChild(), parent); - assertEquals("bar", parent.getLocalName()); - } - - public void testGetData() { - assertEquals( - "type=\"text/xsl\" xmlns=\"http://openuri.org/shipping/\"", - ((ProcessingInstruction) m_node).getData()); - } - - public void testGetTarget() { - assertEquals("xml-stylesheet", - ((ProcessingInstruction) m_node).getTarget()); - - - } - - public void testSetData(String data) { - - ((ProcessingInstruction) m_node).setData( - "\"type=\\\"text/xsl\\\" xmlns=\\\"http://newURI.org/shipping/\\\"\""); - assertEquals("type=\"text/xsl\" xmlns=\"http://newURI.org/shipping/\"", - ((ProcessingInstruction) m_node).getData()); - } - - public void moveToNode() { - m_node = m_doc.getDocumentElement().getFirstChild();//pi - assertFalse(m_node == null); - - } - - //TODO: Test PI with funky but legal chatacters in the name, eg. : - public void testPiTargetChars() { - ProcessingInstruction node = m_doc.createProcessingInstruction( - "foo:123-_", "some body"); - m_node.getParentNode().appendChild(node); - m_node = m_node.getParentNode().getLastChild(); - assertEquals("foo:123-_", ((ProcessingInstruction) m_node).getTarget()); - } - - //TODO: Test Illegal PI Targets: xml target, starting with a digit - public void testPiTargetIllegalChars() { - ProcessingInstruction node; - try { - node = - m_doc.createProcessingInstruction("7foo:?123-&", - "some body"); - fail("Can't start w/ a digit"); - } - catch (DOMException e) { - assertEquals(DOMException.INVALID_CHARACTER_ERR, e.code); - } - - try { - node = m_doc.createProcessingInstruction("xml", "foo"); - fail("Can't be xml"); - } - catch (DOMException e) { - assertEquals(DOMException.INVALID_CHARACTER_ERR, e.code); - } - } - - public void setUp() throws Exception { - super.setUp(); - moveToNode(); - } -} diff --git a/test/src/dom/checkin/TextTest.java b/test/src/dom/checkin/TextTest.java deleted file mode 100755 index b48781c..0000000 --- a/test/src/dom/checkin/TextTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package dom.checkin; - - -import dom.common.CharacterDataTest; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.w3c.dom.DOMException; -import org.w3c.dom.Node; -import org.w3c.dom.Text; -import xmlcursor.common.Common; - - -/** - * - * - */ - -public class TextTest extends CharacterDataTest { - - public TextTest(String s) { - super(s); - sXml = Common.XML_FOO_BAR_TEXT_EXT; - } - - public static Test suite() { - return new TestSuite(TextTest.class); - } - - - public void testNodeName() { - assertEquals("#text", m_node.getNodeName()); - } - - public void testNodeType() { - assertEquals(Node.TEXT_NODE, m_node.getNodeType()); - } - - - public void testNodeValue() { - assertEquals("extended", m_node.getNodeValue()); - } - - - public void testNextSibling() { - Node nxtSibling = m_node.getNextSibling(); - assertEquals(null, nxtSibling); - } - - public void testPreviousSibling() { - Node prSibling = m_node.getPreviousSibling(); - assertEquals("bar", prSibling.getLocalName()); - assertEquals("text", ((Text) prSibling.getFirstChild()).getData()); - } - - public void testParent() { - Node parent = m_node.getParentNode(); - assertEquals(m_doc.getFirstChild(), parent); - assertEquals("foo", parent.getLocalName()); - } - - - public void testSplitTextNegative() { - try { - ((Text) m_node).splitText(-1); - fail("Deleting OOB chars"); - } - catch (DOMException de) { - assertEquals(de.code, DOMException.INDEX_SIZE_ERR); - } - } - - public void testSplitTextLarge() { - try { - ((Text) m_node).splitText(((Text) m_node).getLength() + 1); - fail("Deleting OOB chars"); - } - catch (DOMException de) { - assertEquals(de.code, DOMException.INDEX_SIZE_ERR); - } - } - - public void testSplitText() { - Node parent = m_node.getParentNode(); - int nChildCount = parent.getChildNodes().getLength(); - ((Text) m_node).splitText(2); - assertEquals(nChildCount + 1, parent.getChildNodes().getLength()); - } - - public void testSplitTextBorder() { - Node parent = m_node.getParentNode(); - int nChildCount = parent.getChildNodes().getLength(); - ((Text) m_node).splitText(((Text) m_node).getLength()); - assertEquals(nChildCount + 1, parent.getChildNodes().getLength()); - ((Text) m_node).splitText(0); - assertEquals(nChildCount + 2, parent.getChildNodes().getLength()); - } - - //code coverage case; not sure why it's important - public void testSplitTextNoParent() { - m_node = m_doc.createTextNode("foobar"); - ((Text) m_node).splitText(3); - assertEquals("foo", m_node.getNodeValue()); - } - - public void testSetNodeValue() { - m_node.setNodeValue("new text value"); - assertEquals("new text value", m_node.getNodeValue()); - } - - public void moveToNode() { - m_node = m_doc.getFirstChild().getChildNodes().item(1);//"extended" - } - - public void setUp() throws Exception { - super.setUp(); - moveToNode(); - } - - public void testDelete()throws Exception{ - org.apache.xmlbeans.XmlObject o= org.apache.xmlbeans.XmlObject.Factory.parse(""); - Node d = o.newDomNode(); - assertEquals("foo",d.getFirstChild().getLocalName()); - } -} diff --git a/test/src/dom/common/NodeTest.java b/test/src/dom/common/NodeTest.java deleted file mode 100755 index aa01c54..0000000 --- a/test/src/dom/common/NodeTest.java +++ /dev/null @@ -1,406 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package dom.common; - -import junit.framework.TestCase; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -import java.io.StringReader; - - -public abstract class NodeTest extends TestCase implements - TestSetup { - protected Node m_node; - - protected Document m_doc; - protected String sXml; - - protected Document m_docNS; - protected String sXmlNS; - //attributes - - public NodeTest(String s) { - super(s); - } - - public final void testInherited() { - }; - public abstract void testNodeName(); - - public abstract void testNodeType(); - - public abstract void testNodeValue(); - - public abstract void testParent(); - - public abstract void testPreviousSibling(); - - public abstract void testNextSibling(); - - public void testOwnerDocument() { - assertEquals(m_doc, m_node.getOwnerDocument()); - } - - public void testPrefix() { - assertFalse(m_node == null); - assertEquals(null,m_node.getPrefix()); - // assertEquals("", m_node.getPrefix()); - } - - public void testNamespaceUri() { - assertFalse(m_node == null); - assertEquals(null,m_node.getNamespaceURI()); - //assertEquals("", m_node.getNamespaceURI()); - } - - public void testLocalName() { - assertFalse(m_node == null); - assertEquals(null,m_node.getLocalName()); - // assertEquals("", m_node.getLocalName()); - } - - //0 length list as of API - public void testGetChildNodes() { - assertEquals(0, m_node.getChildNodes().getLength()); - } - - public void testFirstChild() { - assertEquals(null, m_node.getFirstChild()); - } - - public void testLastChild() { - assertEquals(null, m_node.getLastChild()); - } - - public abstract void testAppendChild(); - - /** - * pathologic cases: newChild is m_node or an ancestor - * newChild is from a different document - * newChild is not allowed at this pos - */ - public void testAppendChild(Node newChild) { - Node inserted = m_node.appendChild(newChild); - if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) - assertEquals(true, compareNodeListPrefix(newChild.getChildNodes(), m_node.getChildNodes())); - else - assertEquals(inserted, m_node.getLastChild()); - if (isInTree(m_node, newChild)) //new child is in the tree - //$NOTE: assert the child is removed first - ; - } - - /** - * $NOTE: - * override for Element; - * override for Attribute - * $TODO: ER results in a mutable copy - */ - public void testCloneNode() { - - Node m_clone; - /**not implemented : Eric */ - m_clone=m_node.cloneNode(false); - assertEquals(true, DomUtils.compareNodesShallow(m_node, m_clone)); -// assertEquals(true, DomUtils.compareNodeTreePtr(m_clone.getChildNodes(),m_node.getChildNodes())); //ptr eq for ch. - assertEquals(false,m_clone==m_node); - - - m_clone = m_node.cloneNode(true); - assertEquals(true, DomUtils.compareNodesDeep(m_node, m_clone)); //deep clone: should do for whole tree, not just ch. - assertEquals(false, m_clone == m_node); - - assertEquals(null, m_clone.getParentNode()); - } - - public abstract void testInsertBefore(); - - - - public void testInsertBefore(Node newChild, Node refChild) { - - int newChPos = getChildPos(m_node, newChild); - int pos = getChildPos(m_node, refChild); - Node prevParent = null; - if (newChPos > -1) - prevParent = newChild.getParentNode(); - NodeList childNodes = m_node.getChildNodes(); - int nOrigChildNum = childNodes.getLength(); //get it now, List is live - - - if (newChild == null) { - try { - m_node.insertBefore(newChild, refChild); - fail("Inserting null"); - } catch (IllegalArgumentException e) { - return; - } - } - Node inserted = m_node.insertBefore(newChild, refChild); - - - if (refChild == null) - assertEquals(inserted, m_node.getLastChild()); - else if (pos == -1)//would have thrown exc - fail("Inserting after fake child"); - else if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) - assertEquals(true, compareNodeListPrefix(newChild.getChildNodes(), m_node.getChildNodes())); - else if (newChPos != -1) //new child is in the tree - //assert the child is removed first - assertEquals(false, inserted.getParentNode().equals(prevParent)); - else { - assertEquals(newChild, childNodes.item(pos)); - assertEquals(nOrigChildNum + 1, m_node.getChildNodes().getLength()); - } - - } - - /** - * $NOTE: override for element - */ - public void testGetAttributes() { - assertEquals(null, m_node.getAttributes()); - } - - - public void testHasChildNodes() { - int i = m_node.getChildNodes().getLength(); - if (i > 0) - assertEquals(true, m_node.hasChildNodes()); - else - assertEquals(false, m_node.hasChildNodes()); - } - - - //Override for Element - public void testHasAttributes() { - assertEquals(false, m_node.hasAttributes()); - } - - - public void testIsSupported() { - String[] features=new String[]{ - "Core","XML","Events","MutationEvents","Range","Traversal","HTML","Views","StyleSheets","CSS","CSS2","UIEvents","HTMLEvents" - }; - boolean bResult=true; - for (int i=0;i1) bResult=false; - System.out.println("============== "+features[i]+" ============="+bResult); - assertEquals(bResult,m_node.isSupported(features[i],"2.0")); - } - - } - - public void testNormalize() { - fail("Test Not implemented"); - } - - - /** - * pathological cases: - * node is read-only - * node is not a child of this node - */ - public abstract void testRemoveChild(); - - public void testRemoveChild(Node removed) { - int pos = getChildPos(m_node, removed); - int len = m_node.getChildNodes().getLength(); - if (removed == null) - try { - m_node.removeChild(removed); - fail("Should not be Removing non-existing node"); - } catch (DOMException de) { - assertEquals(DOMException.NOT_FOUND_ERR, de.code); - } - else if (pos == -1) - try { - m_node.removeChild(removed); - fail("Removing non-existing node"); - } catch (DOMException de) { - throw de; - } - else { - m_node.removeChild(removed); - assertEquals(len - 1, m_node.getChildNodes().getLength()); - } - - } - - - public abstract void testReplaceChild(); - - /** - * pathological cases: - * node is DocFrag - * node is already in tree - */ - public void testReplaceChild(Node newChild, Node oldChild) { - int pos = getChildPos(m_node, oldChild); - boolean existing = isInTree(m_doc.getDocumentElement(), newChild); //new Child has a parent - - int len = m_node.getChildNodes().getLength(); - - - if (newChild == null) { - try { - m_node.replaceChild(newChild, oldChild); - fail("Inserting null"); - } catch (IllegalArgumentException e) { - } - } else if (pos == -1) { - try { - m_node.replaceChild(newChild, oldChild); - fail("Replacing non-existing node"); - } catch (DOMException de) { - if (DOMException.NOT_FOUND_ERR != de.code) - throw de; - } - } else if (existing) { - Node oldParent = newChild.getParentNode(); - NodeList old = m_node.getChildNodes(); - assertEquals(oldChild, m_node.replaceChild(newChild, oldChild)); - assertFalse(newChild.getParentNode().equals(oldParent)); - } else if (newChild == null) { //is this equivalent to deletion? - m_node.replaceChild(newChild, oldChild); - assertEquals(len - 1, m_node.getChildNodes().getLength()); - } else if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) { - int new_len = newChild.getChildNodes().getLength(); - assertEquals(oldChild, m_node.replaceChild(newChild, oldChild)); - assertEquals(new_len + len - 1, m_node.getChildNodes().getLength());//new+old-one replaced - } else - m_node.replaceChild(newChild, oldChild); - - - } - - public abstract void testSetNodeValue(); - - //$NOTE:override for element and attribute - public void testSetPrefix() - { - //any prefix here is invalid - String val = null; - val = "blah"; //Eric's default - try - { - m_node.setPrefix(val); - fail(" set prefix only works for at/elt"); - } - catch (DOMException de) - { - assertEquals(DOMException.NAMESPACE_ERR, de.code); - } - } - - public static int getChildPos(Node node, Node child) { - if (child == null) return -1; - NodeList ch = node.getChildNodes(); - for (int i = 0; i < ch.getLength(); i++) - if (ch.item(i) == child) - return i; - return -1; - } - - public static boolean isInTree(Node root, Node find) { - if (find == null) return false; - if (root == null) return false; - if (root == find) return true; - NodeList ch = root.getChildNodes(); - boolean temp_res = false; - for (int i = 0; i < ch.getLength(); i++) - temp_res = temp_res || isInTree(ch.item(i), find); - return temp_res; - } - - public static boolean compareNodeList(NodeList l1, NodeList l2) { - if (l1.getLength() != l2.getLength()) return false; - for (int i = 0; i < l1.getLength(); i++) - if (l1.item(i) != l2.item(i)) //pointer eq - return false; - return true; - } - - //l1 is a prefix of l2 - public static boolean compareNodeListPrefix(NodeList l1, NodeList l2) { - if (l1.getLength() > l2.getLength()) return false; - for (int i = 0; i < l1.getLength(); i++) - if (l1.item(i) != l2.item(i)) //pointer eq - return false; - return true; - } - - public void loadSync() throws Exception { - _loader = Loader.getLoader(); - - if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); - m_doc = (org.w3c.dom.Document) _loader.loadSync(sXml); - if (sXmlNS != null && sXmlNS.length() > 0) - m_docNS = (org.w3c.dom.Document) _loader.loadSync(sXmlNS); - - } - - - public static Node getApacheNode(String sXml,boolean namespace,char type) - throws Exception{ - org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); - parser.parse(new InputSource(new StringReader(sXml))); - Document doc = parser.getDocument(); - - String name="apache_node"; - String nsname="pre:apache_node"; - String uri="uri:apache:test"; - - switch(type){ - case 'A': - if (namespace) - return doc.createAttributeNS(uri,nsname); - else - return doc.createAttribute(name); - case 'E': - if (namespace) - return doc.createElementNS(uri,nsname); - else return doc.createElement(name); - default: return doc.createTextNode(name); - - } - - } - - - public abstract void moveToNode(); - - //exposing a node for other tests...saver in particular - public Node getNode(){ - return m_node; - } - public void setUp() throws Exception { - //m_doc=(org.w3c.dom.Document)org.apache.xmlbeans.XmlObject.Factory.parse(xml).newDomNode(); - _loader = Loader.getLoader(); - - if (sXml == null && sXmlNS == null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); - m_doc = (org.w3c.dom.Document) _loader.load(sXml); - if (sXmlNS != null && sXmlNS.length() > 0) - m_docNS = (org.w3c.dom.Document) _loader.load(sXmlNS); - } - - private Loader _loader; -} - diff --git a/test/src/dom/detailed/IDTest.java b/test/src/dom/detailed/IDTest.java deleted file mode 100644 index bb2c092..0000000 --- a/test/src/dom/detailed/IDTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package dom.detailed; - -import junit.framework.TestCase; -import org.apache.xmlbeans.*; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import tools.util.JarUtil; -import xbean.dom.id.FooDocument; - -import java.io.File; -import java.io.IOException; -import java.io.FileOutputStream; -import java.io.OutputStreamWriter; -import java.util.*; - -import common.Common; - -public class IDTest extends TestCase -{ - String P = File.separator; - - // Test the getElementById() DOM API with DTDs , run with jvm arg -Dcases.location - public void testGetElemById() throws Exception - { - Document doc; - Element element; - String tagname; - XmlOptions xmlOptions = new XmlOptions(); - xmlOptions.setLoadUseDefaultResolver(); - XmlObject o = XmlObject.Factory.parse(new File(Common.CASEROOT + P + "xbean" + P + "dom" + P + "id.xml")); - doc = (Document) o.getDomNode(); - element = doc.getElementById("CANADA"); - assertNotNull(element); - - tagname = element.getTagName(); - assertEquals("throw_Equals", "emp:address", tagname); - assertNull(doc.getDoctype()); - } - - // test getElementById() with schema containing DTD with ID definition for untyped XmlObject - public void testIDSchema() throws Exception - { - XmlObject o = XmlObject.Factory.parse("\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "]>" + - ""); - Document n = (Document) o.getDomNode(); - Element elem = n.getElementById("25"); - assertNotNull(elem); - System.out.println("Elem: " + elem.getNodeName()); - - Element elemInvalid = n.getElementById("100"); - assertNull(elemInvalid); - } - - // typed XmlObject - public void testSchemaWithDTD() throws Exception - { - XmlOptions opt = new XmlOptions(); - List err = new ArrayList(); - opt.setErrorListener(err); - - String instance = "" + - " " + - ""; - try - { - FooDocument fooDoc = FooDocument.Factory.parse(instance, opt); - - Document d = (Document)fooDoc.getDomNode(); - Element elem = d.getElementById("25"); - assertNotNull(elem); - - Element elemInvalid = d.getElementById("100"); - assertNull(elemInvalid); - } - catch (XmlException xme) - { - Collection xmlerrs = xme.getErrors(); - for (Iterator iterator1 = xmlerrs.iterator(); iterator1.hasNext();) { - XmlError xerr = (XmlError) iterator1.next(); - System.out.println("Exception:" + xerr.getMessage()); - } - throw (new XmlException(new Throwable("XmlException occured"))); - } - - // parse errors - for (Iterator iterator = err.iterator(); iterator.hasNext();) { - System.out.println("Err:" + iterator.next()); - } - } - -} diff --git a/test/src/dom/detailed/ImportUnsupportedNodesTest.java b/test/src/dom/detailed/ImportUnsupportedNodesTest.java deleted file mode 100755 index f597ce6..0000000 --- a/test/src/dom/detailed/ImportUnsupportedNodesTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package dom.detailed; - -import dom.common.Loader; -import junit.framework.TestCase; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; - -import java.io.StringReader; - - -/** - * - * - * - */ -public class ImportUnsupportedNodesTest extends TestCase{ - String sXml=""; - // String sXmlNS=""; - Document m_doc; - Node m_node; - String sER="] >" - +"&ORG;"; - - public ImportUnsupportedNodesTest(String name){ - super(name); - } - - public void testImportEnitityNode()throws Exception{ - org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); - parser.parse(new InputSource(new StringReader(sER))); - Document xercesDocument = parser.getDocument(); - assertFalse (xercesDocument==null); - Node toImport=xercesDocument.getDoctype().getEntities().item(0); - assertEquals(Node.ENTITY_NODE,toImport.getNodeType()); - Node importedNode ; - //try{ - importedNode=m_doc.importNode(toImport, true); - m_node.insertBefore(importedNode,m_node.getFirstChild()); - - assertEquals(importedNode,m_node.getFirstChild()); - assertEquals(Node.ENTITY_NODE,m_node.getFirstChild().getNodeType()); - - } - - public void testImportERNode()throws Exception{ - org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); - parser.parse(new InputSource(new StringReader(sER))); - Document xercesDocument = parser.getDocument(); - assertFalse (xercesDocument==null); - Node toImport=xercesDocument.getDocumentElement().getFirstChild(); - - assertEquals(Node.ENTITY_REFERENCE_NODE,toImport.getNodeType()); - Node importedNode=m_doc.importNode(toImport, true); - m_node.insertBefore(importedNode,m_node.getFirstChild()); - - assertEquals(importedNode,m_node.getFirstChild()); - assertEquals(Node.ENTITY_REFERENCE_NODE,m_node.getFirstChild().getNodeType()); - } - - /** - * DOCUMENT_TYPE_NODE - * cannot be imported. - */ - - public void testImportDocType() throws Exception{ - org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); - parser.parse(new InputSource(new StringReader(sER))); - Document xercesDocument = parser.getDocument(); - assertFalse (xercesDocument==null); - Node toImport=xercesDocument.getDoctype(); - - try{ - Node importedNode=m_doc.importNode(toImport, true); - fail("can't import DocType Node"); - }catch (DOMException e){ - - } - try{ - Node importedNode=m_doc.importNode(toImport, false); - fail("can't import DocType Node"); - }catch (DOMException e){ - - } - } - - public void testImportCDATAType() throws Exception{ - org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); - parser.parse(new InputSource(new StringReader(sER))); - Document xercesDocument = parser.getDocument(); - assertFalse (xercesDocument==null); - Node toImport= xercesDocument.createCDATASection("My < CData"); - xercesDocument.getDocumentElement().appendChild(toImport); - - assertEquals(Node.CDATA_SECTION_NODE,toImport.getNodeType()); - Node importedNode=m_doc.importNode(toImport, true); - m_node.insertBefore(importedNode,m_node.getFirstChild()); - - assertEquals(importedNode,m_node.getFirstChild()); - assertEquals(Node.CDATA_SECTION_NODE,m_node.getFirstChild().getNodeType()); - - - assertEquals(Node.CDATA_SECTION_NODE,toImport.getNodeType()); - importedNode=m_doc.importNode(toImport, false); - m_node.replaceChild(importedNode,m_node.getFirstChild()); - - assertEquals(importedNode,m_node.getFirstChild()); - assertEquals(Node.CDATA_SECTION_NODE,m_node.getFirstChild().getNodeType()); - } - - - //TODO: see if code coverage can help id gaps here... - public void setUp() throws Exception{ - - Loader _loader=Loader.getLoader(); - if (sXml==null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); - m_doc=(org.w3c.dom.Document)_loader.load(sXml); - - m_node=m_doc.getFirstChild(); - } - -} - diff --git a/test/src/dom/detailed/InsertDeleteNodesTest.java b/test/src/dom/detailed/InsertDeleteNodesTest.java deleted file mode 100755 index 0bc117f..0000000 --- a/test/src/dom/detailed/InsertDeleteNodesTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package dom.detailed; - -import dom.common.Loader; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.w3c.dom.*; - - -/** - * Insertion and deletion of nodes, normalization of text children - * - * - * - */ - -public class InsertDeleteNodesTest extends TestCase{ - String sXml=""; - String sXmlNS=""; - Document m_doc, - m_docNS; - Node m_node; - - - - - public InsertDeleteNodesTest(String name){ - super(name); - } - public static Test suite() { - return new TestSuite(InsertDeleteNodesTest.class); - } - - public void testInsertNodes(){ - //insert one of each type of node: - Text txt0=m_doc.createTextNode("foo"); - Text txt1=m_doc.createTextNode(" "); - Text txt2=m_doc.createTextNode("bar"); - Element elt1=m_doc.createElement("elt1"); - - Attr attr0=m_doc.createAttributeNS("xmlns","attr0"); - - Comment comment=m_doc.createComment("A comment"); - DocumentFragment doc_frag=m_doc.createDocumentFragment(); - //Document new_doc: what to do with this... - //CDATASection cdata=m_doc.createCDATASection("");--Not impl - //ProcessingInstruction pi=m_doc.createProcessingInstruction("xml","version 1.0"); --Not impl - // DocumentType--TODO - //Entity - //EntityReference - //Notation - - Text nested_txt=m_doc.createTextNode("foo"); - - - //m_doc.appendChild(m_doc.createElement("root")); - - m_doc.getDocumentElement().appendChild(txt2); - m_doc.getDocumentElement().insertBefore(elt1,txt2); - m_doc.getDocumentElement().insertBefore(txt1,elt1); - m_doc.getDocumentElement().insertBefore(txt0,txt1); - - //insert level 1 - System.out.println("=======Basic inserts passed ==================="); - int nAttrs=20; - for (int i=0;i0) - m_docNS=(org.w3c.dom.Document)loader.load(sXmlNS); - m_doc=m_doc.getImplementation().createDocument(null,"root",null); - m_node=m_doc.getFirstChild(); - } - -} diff --git a/test/src/dom/detailed/MoveImportNodeTest.java b/test/src/dom/detailed/MoveImportNodeTest.java deleted file mode 100755 index 84f374c..0000000 --- a/test/src/dom/detailed/MoveImportNodeTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package dom.detailed; - -import dom.common.Loader; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; - -import java.io.StringReader; - - -/** - * - * - * - */ -public class MoveImportNodeTest extends TestCase{ - String sXmlNS=""; - - String sXml=""; - Document m_doc, - m_docNS; - Node m_node; - - - - public MoveImportNodeTest(String name){ - super(name); - } - - //insert a node from a ns into a non-ns: node will move "as is" - //even though ns is not in scope as DOM does no prefix resolution - public void testMoveNodeNStoNoNS(){ - Node toMove=m_docNS.getFirstChild().getFirstChild().getFirstChild(); //bar - assertEquals("myns:bar",toMove.getNodeName()); - Element newParent=(Element)m_docNS.getFirstChild(); - assertEquals("foo",newParent.getNodeName()); - newParent.insertBefore(toMove,newParent.getFirstChild()); - - assertEquals(2,newParent.getChildNodes().getLength()); - assertEquals(toMove,newParent.getElementsByTagNameNS("http://foo.org","bar").item(0)); - assertEquals(newParent.getElementsByTagName("bar").item(0), - newParent.getElementsByTagNameNS(null,"bar").item(0)); - - } - - //move node to a different namespace - //namespace of node should be unchanged -- DOM does not care - public void testMoveDiffNS(){ - Node toMove=m_docNS.getFirstChild().getFirstChild().getFirstChild(); //bar - Element newParent=(Element)m_docNS.getFirstChild(); - newParent.insertBefore(toMove,newParent.getFirstChild()); - newParent.getFirstChild().setPrefix("other"); - assertEquals(2,newParent.getChildNodes().getLength()); - assertEquals(0,(newParent).getElementsByTagNameNS(null,"bar").getLength()); - assertEquals(true,(toMove==newParent.getElementsByTagNameNS("http://foo.org","bar").item(0))); - } - - - //import to a doc where the given ns DNE - public void testMoveDiffDoc(){ - Node toMove=m_docNS.getFirstChild().getFirstChild().getFirstChild(); //bar - try{ - m_node.insertBefore(toMove,m_node.getFirstChild()); - fail(" Cannot move nodes across docs"); - }catch(DOMException de){ - assertEquals(DOMException.WRONG_DOCUMENT_ERR,de.code); - } - - } - - public void testMoveDiffImplementations() throws Exception{ - org.apache.xerces.parsers.DOMParser parser = - new org.apache.xerces.parsers.DOMParser(); - - - parser.parse(new InputSource(new StringReader(sXmlNS))); - - Document xercesDocument = parser.getDocument(); - assertFalse (xercesDocument==null); - Node toMove=xercesDocument.getFirstChild().getFirstChild().getFirstChild(); //bar - System.out.println("=======Source Impl "+xercesDocument.getImplementation()); - System.out.println("=======Dest Impl "+m_doc.getImplementation()); - - try{ - m_node.insertBefore(toMove,m_node.getFirstChild()); - fail(" Cannot move nodes across implementations"); - }catch(DOMException de){ - assertEquals(DOMException.WRONG_DOCUMENT_ERR,de.code); - } - - Node imported=m_doc.importNode(toMove,true);//deep would be the same here - m_node.appendChild(imported); - - assertEquals(2,m_node.getChildNodes().getLength()); - //node should be imported w/ prefix and all - assertEquals(imported,((Element)m_node).getElementsByTagNameNS("http://foo.org","bar").item(0)); - // assertEquals(((Element)m_node).getElementsByTagName("bar").item(1),imported); - assertEquals(((Element)m_node).getElementsByTagName("bar").item(0),((Element)m_node).getElementsByTagNameNS(null,"bar").item(0)); - } - - - // public void - public void testImportSameDoc(){ - //inspired by nist documentimportnode10? - - Node toImport=m_doc.createElement("foobar"); - toImport=m_doc.importNode(toImport,true); - - toImport=m_doc.createDocumentFragment(); - toImport.appendChild(m_doc.getDocumentElement().getFirstChild()); - - m_doc.importNode(toImport,true); - } - - public static Test suite() { - return new TestSuite(MoveImportNodeTest.class); - } - - public void setUp() throws Exception{ - - Loader loader=Loader.getLoader(); - if (sXml==null && sXmlNS==null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); - m_doc=(org.w3c.dom.Document)loader.load(sXml); - if(sXmlNS!=null && sXmlNS.length()>0) - m_docNS=(org.w3c.dom.Document)loader.load(sXmlNS); - - m_node=m_doc.getFirstChild(); - } -} diff --git a/test/src/dom/detailed/TextTest.java b/test/src/dom/detailed/TextTest.java deleted file mode 100755 index 003ea5d..0000000 --- a/test/src/dom/detailed/TextTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package dom.detailed; - -import dom.common.Loader; -import junit.framework.TestCase; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - - -/** - * - * - * - */ -public class TextTest extends TestCase{ - String sXml=""; - String sXmlNS="footext"; - Document m_doc, - m_docNS; - Node m_node; - - public TextTest(String name){ - super(name); - } - - - //insert a node from a ns into a non-ns - public void testMoveNodeNStoNoNS(){ - - - - } - - public void testTextToAttrValue(){ - m_node=m_docNS.getFirstChild().getFirstChild().getFirstChild();//footext - Attr attrib=(Attr)m_docNS.getFirstChild().getFirstChild().getAttributes().getNamedItem("xmlns:myns"); - assertEquals("http://foo.org",attrib.getNodeValue()); - //attrib.replaceChild(m_node,attrib.getFirstChild()); - attrib.setValue(m_node.getNodeValue()); - assertEquals("footext",attrib.getNodeValue()); - //assertFalse(m_docNS.getFirstChild().getFirstChild().hasChildNodes()); - } - - - - public void setUp() throws Exception{ - - Loader loader=Loader.getLoader(); - if (sXml==null && sXmlNS==null) throw new IllegalArgumentException("Test bug : Initialize xml strings"); - m_doc=(org.w3c.dom.Document)loader.load(sXml); - if(sXmlNS!=null && sXmlNS.length()>0) - m_docNS=(org.w3c.dom.Document)loader.load(sXmlNS); - - m_node=m_doc.getFirstChild(); - } - } diff --git a/test/src/dom/detailed/w3c/alltests.java b/test/src/dom/detailed/w3c/alltests.java deleted file mode 100755 index 49e5865..0000000 --- a/test/src/dom/detailed/w3c/alltests.java +++ /dev/null @@ -1,339 +0,0 @@ - -/* -This Java source file was generated by test-to-java.xsl -and is a derived work from the source document. -The source document contained the following notice: - - -Copyright (c) 2001-2003 World Wide Web Consortium, -(Massachusetts Institute of Technology, Institut National de -Recherche en Informatique et en Automatique, Keio University). All -Rights Reserved. This program is distributed under the W3C's Software -Intellectual Property License. This program is distributed in the -hope that it will be useful, but WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. -See W3C License http://www.w3.org/Consortium/Legal/ for more details. - -*/ - -//package org.w3c.domts.level2.core; -package dom.detailed.w3c; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.w3c.domts.level2.core.*; - - - /** - * Test suite - * @author W3C DOM Test Working Group - **/ - public class alltests extends TestCase{ - - public static Test suite() { - TestSuite sink= new TestSuite(); - // sink.addTestSuite(attrgetownerelement01.class); - sink.addTestSuite(attrgetownerelement02.class); - sink.addTestSuite(attrgetownerelement03.class); - // sink.addTestSuite(attrgetownerelement04.class); - sink.addTestSuite(attrgetownerelement05.class); - sink.addTestSuite(createAttributeNS01.class); - sink.addTestSuite(createAttributeNS02.class); - sink.addTestSuite(createAttributeNS03.class); - sink.addTestSuite(createAttributeNS04.class); - sink.addTestSuite(createAttributeNS05.class); - sink.addTestSuite(createDocument01.class); - sink.addTestSuite(createDocument02.class); - // sink.addTestSuite(createDocument03.class); - // sink.addTestSuite(createDocument04.class); - sink.addTestSuite(createDocument05.class); - sink.addTestSuite(createDocument06.class); - sink.addTestSuite(createDocument07.class); - // sink.addTestSuite(createDocumentType01.class); - // sink.addTestSuite(createDocumentType02.class); - // sink.addTestSuite(createDocumentType03.class); - sink.addTestSuite(createElementNS01.class); - sink.addTestSuite(createElementNS02.class); - sink.addTestSuite(createElementNS03.class); - sink.addTestSuite(createElementNS04.class); - sink.addTestSuite(createElementNS05.class); - sink.addTestSuite(documentcreateattributeNS01.class); - sink.addTestSuite(documentcreateattributeNS02.class); - sink.addTestSuite(documentcreateattributeNS03.class); - sink.addTestSuite(documentcreateattributeNS04.class); - sink.addTestSuite(documentcreateattributeNS05.class); - sink.addTestSuite(documentcreateattributeNS06.class); - sink.addTestSuite(documentcreateattributeNS07.class); - sink.addTestSuite(documentcreateelementNS01.class); - sink.addTestSuite(documentcreateelementNS02.class); - sink.addTestSuite(documentcreateelementNS05.class); - sink.addTestSuite(documentcreateelementNS06.class); - // sink.addTestSuite(documentgetelementbyid01.class); - sink.addTestSuite(documentgetelementsbytagnameNS01.class); - sink.addTestSuite(documentgetelementsbytagnameNS02.class); - sink.addTestSuite(documentgetelementsbytagnameNS03.class); - sink.addTestSuite(documentgetelementsbytagnameNS04.class); - sink.addTestSuite(documentgetelementsbytagnameNS05.class); - sink.addTestSuite(documentimportnode01.class); - // sink.addTestSuite(documentimportnode02.class); - // sink.addTestSuite(documentimportnode03.class); - // sink.addTestSuite(documentimportnode04.class); - sink.addTestSuite(documentimportnode05.class); - sink.addTestSuite(documentimportnode06.class); - // sink.addTestSuite(documentimportnode07.class); - // sink.addTestSuite(documentimportnode08.class); - sink.addTestSuite(documentimportnode09.class); - sink.addTestSuite(documentimportnode10.class); - sink.addTestSuite(documentimportnode11.class); - sink.addTestSuite(documentimportnode12.class); - sink.addTestSuite(documentimportnode13.class); - sink.addTestSuite(documentimportnode14.class); - sink.addTestSuite(documentimportnode15.class); - sink.addTestSuite(documentimportnode17.class); - sink.addTestSuite(documentimportnode18.class); - // sink.addTestSuite(documentimportnode19.class); - // sink.addTestSuite(documentimportnode20.class); - // sink.addTestSuite(documentimportnode21.class); - // sink.addTestSuite(documentimportnode22.class); - // sink.addTestSuite(documenttypeinternalSubset01.class); - // sink.addTestSuite(documenttypepublicid01.class); - // sink.addTestSuite(documenttypesystemid01.class); - sink.addTestSuite(domimplementationcreatedocument03.class); - sink.addTestSuite(domimplementationcreatedocument04.class); - sink.addTestSuite(domimplementationcreatedocument05.class); - sink.addTestSuite(domimplementationcreatedocument07.class); - // sink.addTestSuite(domimplementationcreatedocumenttype01.class); - // sink.addTestSuite(domimplementationcreatedocumenttype02.class); - // sink.addTestSuite(domimplementationcreatedocumenttype04.class); - // sink.addTestSuite(domimplementationfeaturecore.class); - // sink.addTestSuite(domimplementationfeaturexmlversion2.class); - // sink.addTestSuite(domimplementationhasfeature01.class); - // sink.addTestSuite(domimplementationhasfeature02.class); - sink.addTestSuite(elementgetattributenodens01.class); - sink.addTestSuite(elementgetattributenodens02.class); - // sink.addTestSuite(elementgetattributenodens03.class); - // sink.addTestSuite(elementgetattributens02.class); - sink.addTestSuite(elementgetelementsbytagnamens02.class); - sink.addTestSuite(elementgetelementsbytagnamens04.class); - sink.addTestSuite(elementgetelementsbytagnamens05.class); - sink.addTestSuite(elementhasattribute01.class); - // sink.addTestSuite(elementhasattribute02.class); - sink.addTestSuite(elementhasattribute03.class); - sink.addTestSuite(elementhasattribute04.class); - sink.addTestSuite(elementhasattributens01.class); - sink.addTestSuite(elementhasattributens02.class); - sink.addTestSuite(elementhasattributens03.class); - sink.addTestSuite(elementremoveattributens01.class); - sink.addTestSuite(elementsetattributenodens01.class); - sink.addTestSuite(elementsetattributenodens02.class); - sink.addTestSuite(elementsetattributenodens03.class); - sink.addTestSuite(elementsetattributenodens04.class); - sink.addTestSuite(elementsetattributenodens05.class); - // sink.addTestSuite(elementsetattributenodens06.class); - sink.addTestSuite(elementsetattributens01.class); - sink.addTestSuite(elementsetattributens02.class); - sink.addTestSuite(elementsetattributens03.class); - sink.addTestSuite(elementsetattributens04.class); - sink.addTestSuite(elementsetattributens05.class); - sink.addTestSuite(elementsetattributens08.class); - sink.addTestSuite(elementsetattributensurinull.class); - // sink.addTestSuite(getAttributeNS01.class); - sink.addTestSuite(getAttributeNS02.class); - sink.addTestSuite(getAttributeNS03.class); - sink.addTestSuite(getAttributeNS04.class); - sink.addTestSuite(getAttributeNS05.class); - sink.addTestSuite(getAttributeNodeNS01.class); - sink.addTestSuite(getAttributeNodeNS02.class); - // sink.addTestSuite(getElementById01.class); - // sink.addTestSuite(getElementById02.class); - // sink.addTestSuite(getElementsByTagNameNS01.class); - sink.addTestSuite(getElementsByTagNameNS02.class); - sink.addTestSuite(getElementsByTagNameNS03.class); - sink.addTestSuite(getElementsByTagNameNS04.class); - sink.addTestSuite(getElementsByTagNameNS05.class); - sink.addTestSuite(getElementsByTagNameNS06.class); - sink.addTestSuite(getElementsByTagNameNS07.class); - sink.addTestSuite(getElementsByTagNameNS08.class); - sink.addTestSuite(getElementsByTagNameNS09.class); - sink.addTestSuite(getElementsByTagNameNS10.class); - sink.addTestSuite(getElementsByTagNameNS11.class); - sink.addTestSuite(getElementsByTagNameNS12.class); - sink.addTestSuite(getElementsByTagNameNS13.class); - sink.addTestSuite(getElementsByTagNameNS14.class); - sink.addTestSuite(getNamedItemNS01.class); - sink.addTestSuite(getNamedItemNS02.class); - // sink.addTestSuite(getNamedItemNS03.class); - // sink.addTestSuite(getNamedItemNS04.class); - sink.addTestSuite(hasAttribute01.class); - sink.addTestSuite(hasAttribute02.class); - sink.addTestSuite(hasAttribute03.class); - sink.addTestSuite(hasAttribute04.class); - sink.addTestSuite(hasAttributeNS01.class); - sink.addTestSuite(hasAttributeNS02.class); - sink.addTestSuite(hasAttributeNS03.class); - // sink.addTestSuite(hasAttributeNS04.class); - sink.addTestSuite(hasAttributeNS05.class); - sink.addTestSuite(hasAttributes01.class); - sink.addTestSuite(hasAttributes02.class); - sink.addTestSuite(hc_attrcreatedocumentfragment.class); - sink.addTestSuite(hc_attrname.class); - sink.addTestSuite(hc_documentcreateattribute.class); - sink.addTestSuite(hc_elementgetattributenode.class); - // sink.addTestSuite(hc_entitiesremovenameditemns1.class); - // sink.addTestSuite(hc_entitiessetnameditemns1.class); - sink.addTestSuite(hc_namednodemapgetnameditem.class); - sink.addTestSuite(hc_nodedocumentfragmentnormalize1.class); - sink.addTestSuite(hc_nodedocumentfragmentnormalize2.class); - // sink.addTestSuite(hc_notationsremovenameditemns1.class); - // sink.addTestSuite(hc_notationssetnameditemns1.class); - // sink.addTestSuite(ibmtests.class); - // sink.addTestSuite(importNode01.class); - // sink.addTestSuite(importNode02.class); - sink.addTestSuite(importNode03.class); - sink.addTestSuite(importNode04.class); - // sink.addTestSuite(importNode05.class); - // sink.addTestSuite(importNode06.class); - sink.addTestSuite(importNode07.class); - sink.addTestSuite(importNode08.class); - // sink.addTestSuite(importNode09.class); - // sink.addTestSuite(importNode10.class); - // sink.addTestSuite(importNode11.class); - // sink.addTestSuite(importNode12.class); - // sink.addTestSuite(importNode13.class); - sink.addTestSuite(importNode14.class); - sink.addTestSuite(importNode15.class); - // sink.addTestSuite(importNode16.class); - sink.addTestSuite(importNode17.class); - // sink.addTestSuite(internalSubset01.class); - sink.addTestSuite(isSupported01.class); - sink.addTestSuite(isSupported02.class); - sink.addTestSuite(isSupported04.class); - sink.addTestSuite(isSupported05.class); - sink.addTestSuite(isSupported06.class); - sink.addTestSuite(isSupported07.class); - sink.addTestSuite(isSupported09.class); - sink.addTestSuite(isSupported10.class); - sink.addTestSuite(isSupported11.class); - sink.addTestSuite(isSupported12.class); - sink.addTestSuite(isSupported13.class); - sink.addTestSuite(isSupported14.class); - sink.addTestSuite(localName01.class); - sink.addTestSuite(localName02.class); - sink.addTestSuite(localName03.class); - sink.addTestSuite(localName04.class); - // sink.addTestSuite(namednodemapgetnameditemns01.class); - sink.addTestSuite(namednodemapgetnameditemns02.class); - sink.addTestSuite(namednodemapgetnameditemns03.class); - sink.addTestSuite(namednodemapgetnameditemns04.class); - sink.addTestSuite(namednodemapgetnameditemns05.class); - sink.addTestSuite(namednodemapgetnameditemns06.class); - sink.addTestSuite(namednodemapremovenameditemns01.class); - //default Attr - // sink.addTestSuite(namednodemapremovenameditemns02.class); - // ER - // sink.addTestSuite(namednodemapremovenameditemns03.class); - sink.addTestSuite(namednodemapremovenameditemns04.class); - // sink.addTestSuite(namednodemapremovenameditemns05.class); - sink.addTestSuite(namednodemapremovenameditemns06.class); - sink.addTestSuite(namednodemapremovenameditemns07.class); - sink.addTestSuite(namednodemapremovenameditemns08.class); - sink.addTestSuite(namednodemapremovenameditemns09.class); - sink.addTestSuite(namednodemapsetnameditemns01.class); - sink.addTestSuite(namednodemapsetnameditemns02.class); - sink.addTestSuite(namednodemapsetnameditemns03.class); - sink.addTestSuite(namednodemapsetnameditemns04.class); - // sink.addTestSuite(namednodemapsetnameditemns05.class); - sink.addTestSuite(namednodemapsetnameditemns06.class); - sink.addTestSuite(namednodemapsetnameditemns07.class); - sink.addTestSuite(namednodemapsetnameditemns08.class); - // sink.addTestSuite(namednodemapsetnameditemns09.class); - // sink.addTestSuite(namednodemapsetnameditemns10.class); - // sink.addTestSuite(namednodemapsetnameditemns11.class); - sink.addTestSuite(namespaceURI01.class); - sink.addTestSuite(namespaceURI02.class); - sink.addTestSuite(namespaceURI03.class); - sink.addTestSuite(namespaceURI04.class); - sink.addTestSuite(nodegetlocalname03.class); - sink.addTestSuite(nodegetnamespaceuri03.class); - // sink.addTestSuite(nodegetownerdocument01.class); - sink.addTestSuite(nodegetownerdocument02.class); - sink.addTestSuite(nodegetprefix03.class); - sink.addTestSuite(nodehasattributes01.class); - // sink.addTestSuite(nodehasattributes02.class); - sink.addTestSuite(nodehasattributes03.class); - sink.addTestSuite(nodehasattributes04.class); - // sink.addTestSuite(nodeissupported01.class); - // sink.addTestSuite(nodeissupported02.class); - // sink.addTestSuite(nodeissupported03.class); - // sink.addTestSuite(nodeissupported04.class); - // sink.addTestSuite(nodeissupported05.class); - // sink.addTestSuite(nodenormalize01.class); - sink.addTestSuite(nodesetprefix01.class); - sink.addTestSuite(nodesetprefix02.class); - sink.addTestSuite(nodesetprefix03.class); - // sink.addTestSuite(nodesetprefix04.class); - sink.addTestSuite(nodesetprefix05.class); - sink.addTestSuite(nodesetprefix06.class); - sink.addTestSuite(nodesetprefix07.class); - sink.addTestSuite(nodesetprefix08.class); - sink.addTestSuite(nodesetprefix09.class); - sink.addTestSuite(normalize01.class); - sink.addTestSuite(ownerDocument01.class); - sink.addTestSuite(ownerElement01.class); - sink.addTestSuite(ownerElement02.class); - sink.addTestSuite(prefix01.class); - sink.addTestSuite(prefix02.class); - sink.addTestSuite(prefix03.class); - sink.addTestSuite(prefix04.class); - sink.addTestSuite(prefix05.class); - sink.addTestSuite(prefix06.class); - sink.addTestSuite(prefix07.class); - // sink.addTestSuite(prefix08.class); - sink.addTestSuite(prefix09.class); - sink.addTestSuite(prefix10.class); - sink.addTestSuite(prefix11.class); - // sink.addTestSuite(publicId01.class); - // sink.addTestSuite(removeAttributeNS01.class); - // sink.addTestSuite(removeAttributeNS02.class); - sink.addTestSuite(removeNamedItemNS01.class); - sink.addTestSuite(removeNamedItemNS02.class); - sink.addTestSuite(removeNamedItemNS03.class); - sink.addTestSuite(setAttributeNS01.class); - sink.addTestSuite(setAttributeNS02.class); - //Test makes no sense w/o ER - // sink.addTestSuite(setAttributeNS03.class); - sink.addTestSuite(setAttributeNS04.class); - sink.addTestSuite(setAttributeNS05.class); - sink.addTestSuite(setAttributeNS06.class); - sink.addTestSuite(setAttributeNS07.class); - sink.addTestSuite(setAttributeNS09.class); - sink.addTestSuite(setAttributeNodeNS01.class); - //Test makes no sense w/o ER - // sink.addTestSuite(setAttributeNodeNS02.class); - sink.addTestSuite(setAttributeNodeNS03.class); - sink.addTestSuite(setAttributeNodeNS04.class); - sink.addTestSuite(setAttributeNodeNS05.class); - sink.addTestSuite(setNamedItemNS01.class); - sink.addTestSuite(setNamedItemNS02.class); - sink.addTestSuite(setNamedItemNS03.class); - //Test makes no sense w/o ER - // sink.addTestSuite(setNamedItemNS04.class); - sink.addTestSuite(setNamedItemNS05.class); - // sink.addTestSuite(systemId01.class); - - return sink; - - } - - /** - * Gets URI that identifies the test suite - * @return uri identifier of test suite - */ - public String getTargetURI() { - return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/alltests"; - } - - -} diff --git a/test/src/dom/detailed/w3c/ibmtests.java b/test/src/dom/detailed/w3c/ibmtests.java deleted file mode 100755 index d89006c..0000000 --- a/test/src/dom/detailed/w3c/ibmtests.java +++ /dev/null @@ -1,173 +0,0 @@ - -/* -This Java source file was generated by test-to-java.xsl -and is a derived work from the source document. -The source document contained the following notice: - - -Copyright (c) 2001 World Wide Web Consortium, -(Massachusetts Institute of Technology, Institut National de -Recherche en Informatique et en Automatique, Keio University). All -Rights Reserved. This program is distributed under the W3C's Software -Intellectual Property License. This program is distributed in the -hope that it will be useful, but WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. -See W3C License http://www.w3.org/Consortium/Legal/ for more details. - -*/ - -//package org.w3c.domts.level2.core; -package dom.detailed.w3c; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.w3c.domts.level2.core.*; - - - /** - * Test suite - * @author W3C DOM Test Working Group - **/ - public class ibmtests extends TestCase{ - - - - public static Test suite() { - TestSuite sink= new TestSuite(); - // sink.addTestSuite(attrgetownerelement01.class); - sink.addTestSuite(attrgetownerelement02.class); - sink.addTestSuite(attrgetownerelement03.class); - // sink.addTestSuite(attrgetownerelement04.class); - sink.addTestSuite(attrgetownerelement05.class); - sink.addTestSuite(documentcreateattributeNS01.class); - sink.addTestSuite(documentcreateattributeNS02.class); - sink.addTestSuite(documentcreateattributeNS03.class); - sink.addTestSuite(documentcreateattributeNS04.class); - sink.addTestSuite(documentcreateattributeNS05.class); - sink.addTestSuite(documentcreateattributeNS06.class); - sink.addTestSuite(documentcreateattributeNS07.class); - sink.addTestSuite(documentcreateelementNS01.class); - sink.addTestSuite(documentcreateelementNS02.class); - sink.addTestSuite(documentcreateelementNS05.class); - sink.addTestSuite(documentcreateelementNS06.class); - sink.addTestSuite(domimplementationcreatedocument03.class); - sink.addTestSuite(domimplementationcreatedocument04.class); - sink.addTestSuite(domimplementationcreatedocument05.class); - sink.addTestSuite(domimplementationcreatedocument07.class); - sink.addTestSuite(domimplementationcreatedocumenttype02.class); - sink.addTestSuite(domimplementationcreatedocumenttype04.class); - sink.addTestSuite(domimplementationhasfeature01.class); - sink.addTestSuite(domimplementationhasfeature02.class); - // sink.addTestSuite(documentgetelementbyid01.class); - sink.addTestSuite(documentgetelementsbytagnameNS01.class); - sink.addTestSuite(documentgetelementsbytagnameNS02.class); - sink.addTestSuite(documentgetelementsbytagnameNS03.class); - sink.addTestSuite(documentgetelementsbytagnameNS04.class); - sink.addTestSuite(documentgetelementsbytagnameNS05.class); - sink.addTestSuite(documentimportnode01.class); - // sink.addTestSuite(documentimportnode02.class); - sink.addTestSuite(documentimportnode03.class); - // sink.addTestSuite(documentimportnode04.class); - sink.addTestSuite(documentimportnode05.class); - sink.addTestSuite(documentimportnode06.class); - // sink.addTestSuite(documentimportnode07.class); - sink.addTestSuite(documentimportnode08.class); - sink.addTestSuite(documentimportnode09.class); - // sink.addTestSuite(documentimportnode10.class); - sink.addTestSuite(documentimportnode11.class); - sink.addTestSuite(documentimportnode12.class); - sink.addTestSuite(documentimportnode13.class); - sink.addTestSuite(documentimportnode14.class); - sink.addTestSuite(documentimportnode15.class); - sink.addTestSuite(documentimportnode17.class); - sink.addTestSuite(documentimportnode18.class); - // sink.addTestSuite(documentimportnode19.class); - // sink.addTestSuite(documentimportnode20.class); - // sink.addTestSuite(documentimportnode21.class); - // sink.addTestSuite(documentimportnode22.class); - // sink.addTestSuite(documenttypeinternalSubset01.class); - // sink.addTestSuite(documenttypepublicid01.class); - // sink.addTestSuite(documenttypesystemid01.class); - sink.addTestSuite(elementgetattributens02.class); - sink.addTestSuite(elementgetattributenodens01.class); - sink.addTestSuite(elementgetattributenodens02.class); - sink.addTestSuite(elementgetattributenodens03.class); - sink.addTestSuite(elementgetelementsbytagnamens02.class); - sink.addTestSuite(elementgetelementsbytagnamens04.class); - sink.addTestSuite(elementgetelementsbytagnamens05.class); - sink.addTestSuite(elementhasattribute01.class); - sink.addTestSuite(elementhasattribute02.class); - sink.addTestSuite(elementhasattribute03.class); - sink.addTestSuite(elementhasattribute04.class); - sink.addTestSuite(elementhasattributens01.class); - sink.addTestSuite(elementhasattributens02.class); - sink.addTestSuite(elementhasattributens03.class); - sink.addTestSuite(elementremoveattributens01.class); - sink.addTestSuite(elementsetattributens01.class); - sink.addTestSuite(elementsetattributens02.class); - sink.addTestSuite(elementsetattributens03.class); - sink.addTestSuite(elementsetattributens04.class); - sink.addTestSuite(elementsetattributens05.class); - sink.addTestSuite(elementsetattributens08.class); - sink.addTestSuite(elementsetattributenodens01.class); - sink.addTestSuite(elementsetattributenodens02.class); - sink.addTestSuite(elementsetattributenodens03.class); - sink.addTestSuite(elementsetattributenodens04.class); - sink.addTestSuite(elementsetattributenodens05.class); - sink.addTestSuite(elementsetattributenodens06.class); - sink.addTestSuite(namednodemapgetnameditemns01.class); - sink.addTestSuite(namednodemapgetnameditemns02.class); - sink.addTestSuite(namednodemapgetnameditemns03.class); - sink.addTestSuite(namednodemapgetnameditemns04.class); - sink.addTestSuite(namednodemapgetnameditemns05.class); - sink.addTestSuite(namednodemapgetnameditemns06.class); - sink.addTestSuite(namednodemapsetnameditemns01.class); - sink.addTestSuite(namednodemapsetnameditemns02.class); - sink.addTestSuite(namednodemapsetnameditemns03.class); - sink.addTestSuite(namednodemapsetnameditemns04.class); - sink.addTestSuite(namednodemapsetnameditemns05.class); - sink.addTestSuite(namednodemapsetnameditemns06.class); - sink.addTestSuite(namednodemapsetnameditemns07.class); - sink.addTestSuite(namednodemapsetnameditemns08.class); - sink.addTestSuite(namednodemapsetnameditemns09.class); - sink.addTestSuite(namednodemapsetnameditemns10.class); - sink.addTestSuite(namednodemapremovenameditemns01.class); - sink.addTestSuite(namednodemapremovenameditemns02.class); - sink.addTestSuite(namednodemapremovenameditemns03.class); - sink.addTestSuite(namednodemapremovenameditemns04.class); - sink.addTestSuite(namednodemapremovenameditemns05.class); - sink.addTestSuite(namednodemapremovenameditemns06.class); - sink.addTestSuite(namednodemapremovenameditemns07.class); - sink.addTestSuite(namednodemapremovenameditemns08.class); - sink.addTestSuite(namednodemapremovenameditemns09.class); - sink.addTestSuite(nodegetlocalname03.class); - sink.addTestSuite(nodegetnamespaceuri03.class); - sink.addTestSuite(nodegetownerdocument01.class); - sink.addTestSuite(nodegetownerdocument02.class); - sink.addTestSuite(nodegetprefix03.class); - sink.addTestSuite(nodesetprefix01.class); - sink.addTestSuite(nodesetprefix02.class); - sink.addTestSuite(nodesetprefix03.class); - sink.addTestSuite(nodesetprefix04.class); - sink.addTestSuite(nodesetprefix05.class); - sink.addTestSuite(nodesetprefix06.class); - sink.addTestSuite(nodesetprefix07.class); - sink.addTestSuite(nodesetprefix08.class); - sink.addTestSuite(nodesetprefix09.class); - sink.addTestSuite(nodehasattributes01.class); - sink.addTestSuite(nodehasattributes02.class); - sink.addTestSuite(nodehasattributes03.class); - sink.addTestSuite(nodehasattributes04.class); - sink.addTestSuite(nodeissupported01.class); - sink.addTestSuite(nodeissupported02.class); - sink.addTestSuite(nodeissupported03.class); - sink.addTestSuite(nodeissupported04.class); - sink.addTestSuite(nodeissupported05.class); - - return sink; - } - - -} diff --git a/test/src/misc/checkin/VersionTest.java b/test/src/misc/checkin/VersionTest.java deleted file mode 100644 index c3ae039..0000000 --- a/test/src/misc/checkin/VersionTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package misc.checkin; - -import org.apache.xmlbeans.XmlErrorCodes; -import org.apache.xmlbeans.XmlBeans; - -import junit.framework.Assert; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Map; -import java.util.Set; -import java.util.LinkedHashSet; -import java.util.Properties; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ArrayList; -import java.io.FileInputStream; -import java.io.InputStream; - -public class VersionTest extends TestCase -{ - - public VersionTest(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(VersionTest.class); - } - - // Test the getVersion API - public void testXBeansVersion() - { - try - { - String version = XmlBeans.getVersion(); - System.out.println("XmlBeans version:" + version); - assertNotNull(version); - } - catch(NullPointerException npe) - { - fail("NPE thrown for XmlBeans.getVersion()"); - } - } - -} diff --git a/test/src/misc/checkin/XMLBEANS412Test.java b/test/src/misc/checkin/XMLBEANS412Test.java deleted file mode 100644 index 096b255..0000000 --- a/test/src/misc/checkin/XMLBEANS412Test.java +++ /dev/null @@ -1,99 +0,0 @@ -package misc.checkin; - -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.impl.regex.ParseException; -import org.apache.xmlbeans.impl.regex.RegularExpression; - -import java.util.StringTokenizer; - -public class XMLBEANS412Test extends TestCase -{ - static String PassedPosCharGroups = "-,\\-,--,\\--,---,\\---,--\\-,\\--\\-,-\\--,\\-\\--,-a,\\-a,a-,"+ - "a\\-,a-b,a\\-b,a\\--,-a-z,\\-a-z,a-z-,a-z\\-,a-z\\-0-9,a\\-z-,a\\-z\\-,a\\-z\\-0-9,"+ - "-0-9,0-9-,0-9aaa,0-9a-,a-z\\--/,A-F0-9.+-,-A-F0-9.+,A-F0-9.+\\-,\\-A-F0-9.+"; - - static String FailedPosCharGroups = "[a--],[a-z-0-9],[a\\-z-0-9],[0-9--],[0-9a--],[0-9-a],[0-9-a-z]"; - static String MiscPassedPatterns = "([\\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(([a-zA-Z0-9_-])*\\.([a-zA-Z0-9_-])+)+"; - - public XMLBEANS412Test(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(XMLBEANS412Test.class); - } - - public void testPassedPosCharGroupPatterns() - { - StringTokenizer tok = new StringTokenizer(PassedPosCharGroups,","); - while (tok.hasMoreElements()) { - String pattern = "[" + tok.nextToken() + "]"; - try { - new RegularExpression(pattern, "X"); - } catch (ParseException e) { - Assert.fail("Pattern " + pattern + " failed due to " + e.getMessage()); - } - } - } - - public void testNegatedPassedPosCharGroupPatterns() - { - StringTokenizer tok = new StringTokenizer(PassedPosCharGroups,","); - while (tok.hasMoreElements()) { - String pattern = "[^" + tok.nextToken() + "]"; - try { - new RegularExpression(pattern, "X"); - } catch (ParseException e) { - Assert.fail("Pattern " + pattern + " failed due to " + e.getMessage()); - } - } - - - } - - public void testFailedPosCharGroupPatterns() - { - StringTokenizer tok = new StringTokenizer(FailedPosCharGroups,","); - while (tok.hasMoreElements()) { - String pattern = "[" + tok.nextToken() + "]"; - try { - new RegularExpression(pattern,"X"); - } catch (ParseException e) { - continue; - } - Assert.fail("Pattern " + pattern + " did not fail."); - } - } - - public void testNegatedFailedPosCharGroupPatterns() - { - StringTokenizer tok = new StringTokenizer(FailedPosCharGroups,","); - while (tok.hasMoreElements()) { - String pattern = "[^" + tok.nextToken() + "]"; - try { - new RegularExpression(pattern,"X"); - } catch (ParseException e) { - continue; - } - Assert.fail("Pattern " + pattern + " did not fail."); - } - } - - public void testMiscPassedPatterns() { - StringTokenizer tok = new StringTokenizer(MiscPassedPatterns,","); - while (tok.hasMoreElements()) { - String pattern = tok.nextToken(); - try { - new RegularExpression(pattern, "X"); - } catch (ParseException e) { - Assert.fail("Pattern " + pattern + " failed due to " + e.getMessage()); - } - } - - } -} diff --git a/test/src/misc/detailed/JiraRegressionTest101_150.java b/test/src/misc/detailed/JiraRegressionTest101_150.java deleted file mode 100644 index 0d4fe14..0000000 --- a/test/src/misc/detailed/JiraRegressionTest101_150.java +++ /dev/null @@ -1,99 +0,0 @@ -package misc.detailed; - -import junit.framework.Assert; - -import java.util.ArrayList; -import java.util.List; -import java.io.File; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.impl.tool.SchemaCompiler; -import misc.common.JiraTestBase; - -/** - * - */ -public class JiraRegressionTest101_150 extends JiraTestBase -{ - public JiraRegressionTest101_150(String name) - { - super(name); - } - - /** - * [XMLBEANS-103] XMLBeans - QName thread cache, cause memory leaks - * @throws Exception - */ - public void test_jira_xmlbeans102a() throws Exception{ - // set the parameters similar to those in the bug - SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setXsdFiles(new File[]{new File(JIRA_CASES + "xmlbeans_102.xsd")}); - params.setOutputJar(new File(outputroot+P+"xmlbeans_102.jar")); - File outputDir = new File(outputroot + P + "xmlbeans_102"); - outputDir.mkdirs(); - params.setClassesDir(outputDir); - params.setSrcDir(outputDir); - // compile schema - SchemaCompiler.compile(params); - // check for jar - compilation success - if(!(new File(outputroot + P + "xmlbeans_102.jar").exists()) ) - throw new Exception("Jar File was not found"); - //cleanup - deltree(outputroot); - } - - /* - * [XMLBEANS-102]: scomp - infinite loop during jar for specific xsd and params for netui_config.xsd - * - */ - public void test_jira_xmlbeans102b() { - //Assert.fail("test_jira_xmlbeans102: Infinite loop after completion of parsing" ); - - SchemaCompiler.Parameters params = new SchemaCompiler.Parameters(); - params.setOutputJar(new File(schemaCompOutputDirPath + "jira102.jar")); - params.setClassesDir(schemaCompClassesDir); - - params.setXsdFiles(new File[]{new File(scompTestFilesRoot + "xmlbeans_102_netui-config.xsd_")}); - List errors = new ArrayList(); - params.setErrorListener(errors); - params.setSrcDir(schemaCompSrcDir); - params.setClassesDir(schemaCompClassesDir); - - SchemaCompiler.compile(params); - if (printOptionErrMsgs(errors)) { - Assert.fail("test_jira_xmlbeans102() : Errors found when executing scomp"); - } - - } - - /** - * NPE while initializing a type system w/ a type that extends - * an a complex type from a different type system - * - * @throws Exception - */ - public void test_jira_xmlbeans105() throws Exception { - //run untyped parse - XmlObject obj = XmlObject.Factory.parse(new File(JIRA_CASES + "xmlbeans_105.xml")); - - //run Typed Parse - jira.xmlbeans105.ResourceUnknownFaultDocument rud = - jira.xmlbeans105.ResourceUnknownFaultDocument.Factory.parse(new File(JIRA_CASES + "xmlbeans_105.xml")); - - // / we know the instance is invalid - // make sure the error message is what is expected - rud.validate(xmOpts); - Assert.assertTrue("More Errors than expected", errorList.size() == 1); - Assert.assertTrue("Did not recieve the expected error code: " + ((XmlError) errorList.get(0)).getErrorCode(), - ((XmlError) errorList.get(0)).getErrorCode().compareToIgnoreCase("cvc-complex-type.2.4a") == 0); - - } - - - - - - - -} diff --git a/test/src/misc/detailed/LargeEnumTest.java b/test/src/misc/detailed/LargeEnumTest.java deleted file mode 100644 index ac14518..0000000 --- a/test/src/misc/detailed/LargeEnumTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package misc.detailed; - -import org.apache.xmlbeans.*; - -import java.util.*; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; - -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.Assert; -import xmlbeans307.*; - -/** - * This test was put together for: - * http://issues.apache.org/jira/browse/XMLBEANS-307 - * XMLBeans scomp throws error "code too large" - */ -public class LargeEnumTest extends TestCase { - - public LargeEnumTest(String name) { - super(name); - } - - public static Test suite() { - return new TestSuite(LargeEnumTest.class); - } - - /** - * These are tests for a enumeration type - * - * @throws Exception - */ - public void testEnumCount_closeToMax() throws Exception { - SchemaType mType = MaxAllowedEnumType.type; - assertTrue("Enumeration SchemaType was null", mType.getEnumerationValues() != null); - assertTrue("EnumerationValue was not 3665 as expected was" + mType.getEnumerationValues().length, - mType.getEnumerationValues().length == 3665); - - SchemaType mElem = MaxAllowedElementDocument.type; - assertTrue("Enumeration SchemaType was null", mElem.getEnumerationValues() == null); - - // Test that the Java type associated to this is an enum type - assertNotNull("This type does not correspond to a Java enumeration", mType.getStringEnumEntries()); - } - - - public void testEnumCount_greaterThanMax() throws Exception { - // TODO: verify if any xpath/xquery issues - SchemaType mType = MoreThanAllowedEnumType.type; - - assertNotNull("Enumeration should be null as type should be base type " + mType.getEnumerationValues(), - mType.getEnumerationValues()); - assertTrue("EnumerationValue was not 3678 as expected was " + mType.getEnumerationValues().length, - mType.getEnumerationValues().length == 3678); - System.out.println("GET BASE TYPE: " + mType.getBaseType()); - System.out.println("GET BASE TYPE: " + mType.getPrimitiveType()); - assertTrue("type should have been base type, was " + mType.getBaseType(), - mType.getBaseType().getBuiltinTypeCode() == XmlToken.type.getBuiltinTypeCode()); - - SchemaType mElem = GlobalMoreThanElementDocument.type; - assertTrue("Enumeration SchemaType was null", mElem.getBaseEnumType() == null); - - // Test that the Java type associated to this is not an enum type - assertNull("This type corresponds to a Java enumeration, even though it has too many enumeration values", - mType.getStringEnumEntries()); - } - - public void testEnumCount_validate_invalid_enum() throws Exception { - MoreThanAllowedEnumType mType = MoreThanAllowedEnumType.Factory.newInstance(); - - //This value dos not exist in the enumeration set - mType.setStringValue("12345AAA"); - ArrayList errors = new ArrayList(); - XmlOptions options = (new XmlOptions()).setErrorListener(errors); - mType.validate(options); - XmlError[] xErr = new XmlError[errors.size()]; - for (int i = 0; i < errors.size(); i++) { - System.out.println("ERROR: " + errors.get(i)); - xErr[i] = (XmlError)errors.get(i); - } - - Assert.assertTrue("NO Expected Errors after validating enumType after set", errors.size() ==1 ); - Assert.assertTrue("Expected ERROR CODE was not as expected", - xErr[0].getErrorCode().compareTo("cvc-enumeration-valid") ==0 ); - // string value '12345AAA' is not a valid enumeration value for MoreThanAllowedEnumType in - } - - - public void test_MoreEnum_Operations() throws Exception { - MoreThanAllowedEnumType mType = MoreThanAllowedEnumType.Factory.newInstance(); - - mType.setStringValue("AAA"); - ArrayList errors = new ArrayList(); - XmlOptions options = (new XmlOptions()).setErrorListener(errors); - mType.validate(options); - - for (int i = 0; i < errors.size(); i++) { - System.out.println("ERROR: " + errors.get(i)); - } - Assert.assertTrue("There were errors validating enumType after set", errors.size() == 0); - - GlobalMoreThanElementDocument mDoc = GlobalMoreThanElementDocument.Factory.newInstance(); - mDoc.setGlobalMoreThanElement("AAA"); - errors = null; - errors = new ArrayList(); - options = (new XmlOptions()).setErrorListener(errors); - mDoc.validate(options); - - for (int i = 0; i < errors.size(); i++) { - System.out.println("ERROR: " + errors.get(i)); - } - - Assert.assertTrue("There were errors validating enumDoc after set", errors.size() == 0); - - MoreThanAllowedComplexType mcType = MoreThanAllowedComplexType.Factory.newInstance(); - mcType.setComplexTypeMoreThanEnum("AAA"); - mcType.setSimpleString("This should work"); - errors = null; - errors = new ArrayList(); - mcType.validate(options); - for (int i = 0; i < errors.size(); i++) { - System.out.println("ERROR: " + errors.get(i)); - } - - Assert.assertTrue("There were errors validating complxType after set", errors.size() == 0); - } - - -} diff --git a/test/src/misc/detailed/SampleRunner.java b/test/src/misc/detailed/SampleRunner.java deleted file mode 100644 index 94138ee..0000000 --- a/test/src/misc/detailed/SampleRunner.java +++ /dev/null @@ -1,130 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package misc.detailed; - -import junit.framework.TestCase; - -import tools.ant.*; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Target; -import org.apache.tools.ant.BuildException; - -import java.io.File; -import java.io.FilenameFilter; -import java.util.ArrayList; - -/** - * Date: Feb 8, 2005 - * Time: 11:30:24 AM - */ -public class SampleRunner - extends TestCase -{ - - - protected void setUp() - throws Exception - { - proj = new Project(); - proj.setName("Samples Task Tests"); - XMLBEANS_HOME = proj.getBaseDir().getAbsolutePath(); - samples = new ArrayList(); - runSampleTest = new SamplesBuildFileTest("Sample Ant Task Wrapper"); - } - - public void testSamples() - throws Exception - { - loadSampleDirs(new File("./samples")); - ArrayList exceptions = new ArrayList(); - for (int i = 0; i < samples.size(); i++) - { - - runSampleTest.call_samples_task( - ((File) samples.get(i)).getAbsolutePath() - , "test"); - BuildException e; - if ((e = runSampleTest.getAnyExceptions()) != null) - { - exceptions.add(((File) samples.get(i)).getAbsolutePath()); - exceptions.add(e.getException()); - } - } - if (exceptions.size() != 0) - throw new RuntimeException(getMessageFromExceptions(exceptions)); - - } - - private String getMessageFromExceptions(ArrayList ex) - { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < ex.size(); i += 2) - { - sb.append("\n\nFILE:" + (String) ex.get(i)); - sb.append( - "\n **Error: " + ((BuildException) ex.get(i + 1)).getMessage()); - } - return sb.toString(); - } - - private void loadSampleDirs(File dir) - { - assert dir != null && dir.exists(); - File[] files = dir.listFiles(new BuildFilter()); - assert files.length == 1; - samples.add(files[0]); - - } - - private class BuildFilter - implements FilenameFilter - { - public boolean accept(File file, String name) - { - return name.equals("build.xml"); - } - } - - private class SamplesBuildFileTest - extends BuildFileTest - { - public SamplesBuildFileTest(String name) - { - super(name); - } - - public void call_samples_task(String projectPath, String taskName) - { - configureProject(projectPath); - Project proj = getProject(); - proj.setProperty("xmlbeans.home", XMLBEANS_HOME); - executeTarget(proj.getDefaultTarget()); - return; - } - - public BuildException getAnyExceptions() - throws Exception - { - return this.getBuildException(); - } - } - - ArrayList samples; - Project proj; - Target target; - String XMLBEANS_HOME; - SamplesBuildFileTest runSampleTest; - -} diff --git a/test/src/misc/detailed/SystemCacheClassloadersTest.java b/test/src/misc/detailed/SystemCacheClassloadersTest.java deleted file mode 100644 index 593d665..0000000 --- a/test/src/misc/detailed/SystemCacheClassloadersTest.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package misc.detailed; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.impl.common.SystemCache; - -import javax.xml.namespace.QName; -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; - -/* Test class loading using XmlBeans.getContextLoader() after changes to SystemCache.java (r240333) -* Now a custom implementation of the SystemCache can be provided -*/ -public class SystemCacheClassloadersTest extends TestCase -{ - public SystemCacheClassloadersTest(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(SystemCacheClassloadersTest.class); - } - - - public static void testSystemCacheAndThreadLocal() - { - Thread testThread = new SystemCacheThread("SchemTypeLoader Test Thread"); - - try { - testThread.start(); - } - catch (Exception e) { - e.printStackTrace(); - } - - finally { - try { - testThread.join(); - } - catch (InterruptedException ie) { - ie.printStackTrace(); - } - } - - } - - - public static void main(String[] args) throws Throwable - { - testSystemCacheAndThreadLocal(); - } - - public static class SystemCacheThread extends Thread - { - private String name; - - public SystemCacheThread(String threadName) - { - super(); - name = threadName; - } - - /** - */ - public void run() - { - System.out.println("Run Method of thread " + name); - - try { - - // test classloading from 2 different scomp jars using the default impl of SystemCache - testDefaultSystemCacheClassLoading(); - - } - catch (Throwable t) { - t.printStackTrace(); - } - } - - public void testDefaultSystemCacheClassLoading() - { - try { - // create classloaders here - String xbean_home = System.getProperty("xbean.rootdir"); - if (xbean_home == null) { - xbean_home = new File(".").getAbsolutePath(); - } - - File xbeanFile = new File(xbean_home + "/build/lib/xbean.jar"); - //File xbeanFile = new File(xbean_home + "/xbean.jar"); - if (!xbeanFile.exists()) { - throw new Exception("File " + xbeanFile + "does not exist"); - } - URL xbeanjar = xbeanFile.toURL(); - - File domFile = new File(xbean_home + "/build/test/lib/schemajars/dom.jar"); - if (!domFile.exists()) { - throw new Exception("File does not exist : " + domFile.toString()); - } - URL domjar = domFile.toURL(); - - File miscFile = new File(xbean_home + "/build/test/lib/schemajars/misc.jar"); - if (!miscFile.exists()) { - throw new Exception("File does not exist"); - } - URL miscjar = miscFile.toURL(); - - // dom.jar - URLClassLoader domTestsLoader = new URLClassLoader(new URL[]{xbeanjar, domjar}); - // misc.jar - URLClassLoader miscTestsLoader = new URLClassLoader(new URL[]{xbeanjar, miscjar}); - - System.out.println("Contents of domTestsLoader URL"); - URL[] urls = domTestsLoader.getURLs(); - for (int i = 0; i < urls.length; i++) { - System.out.println("URL:" + urls[i].toString()); - } - System.out.println("------------------"); - - System.out.println("Contents of miscTestsLoader URL"); - urls = miscTestsLoader.getURLs(); - for (int i = 0; i < urls.length; i++) { - System.out.println("URL:" + urls[i].toString()); - } - System.out.println("------------------"); - - - // define the Qnames of types to look for in the compiled xbeans after switching the class loaders - QName domTypeQName = new QName("http://xbean/dom/ComplexTypeTest", "elementT"); - QName miscPersonTypeQName = new QName("http://xbean/misc/SyscacheTests", "personType", "test"); - - setContextClassLoader(domTestsLoader); - //System.out.println("Testing elementT Type From dom tests complexTypeTest.xsd"); - SchemaTypeLoader initialDomLoader = XmlBeans.getContextTypeLoader(); - SchemaType domSchemaType = initialDomLoader.findType(domTypeQName); - assertNotNull(domSchemaType); - assertEquals("Invalid Type!", domSchemaType.getFullJavaImplName(), "xbean.dom.complexTypeTest.impl.ElementTImpl"); - - // -ve test, look for the person type from cases\misc\syscachetest.xsd - SchemaType personTypeFromMiscTests = initialDomLoader.findType(miscPersonTypeQName); - assertNull(personTypeFromMiscTests); - - // switch the SchemaTypeLoader - setContextClassLoader(miscTestsLoader); - //System.out.println("Testing Person Type From misc syscachetests.xsd"); - SchemaTypeLoader initialMiscSchemaLoader = XmlBeans.getContextTypeLoader(); - SchemaType miscPersonType = initialMiscSchemaLoader.findType(miscPersonTypeQName); - assertTrue(miscPersonType != null); - assertEquals("Invalid Type!", miscPersonType.getFullJavaImplName(), "xbean.misc.syscacheTests.impl.PersonTypeImpl"); - - // -ve test - SchemaType personTypeFromMisc = initialMiscSchemaLoader.findType(domTypeQName); - assertNull(personTypeFromMisc); - - // reload the original loader - setContextClassLoader(domTestsLoader); - SchemaTypeLoader secondDomLoader = XmlBeans.getContextTypeLoader(); - assertNotNull(secondDomLoader.findType(domTypeQName)); - assertTrue("SchemaTypeLoaders expected to be equal", initialDomLoader == secondDomLoader); - - setContextClassLoader(miscTestsLoader); - SchemaTypeLoader secondMiscLoader = XmlBeans.getContextTypeLoader(); - assertTrue("SchemaTypeLoaders expected to be equal", initialMiscSchemaLoader == secondMiscLoader); - - } - catch (Throwable t) { - t.printStackTrace(); - } - - } - - - } - -} diff --git a/test/src/misc/detailed/SystemCacheTestImpl.java b/test/src/misc/detailed/SystemCacheTestImpl.java deleted file mode 100644 index c71912a..0000000 --- a/test/src/misc/detailed/SystemCacheTestImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package misc.detailed; - -import org.apache.xmlbeans.impl.common.SystemCache; - -// This class provides an alternative implementation to the SystemCache that essentially does nothing special -// Used in testing the SystemCache.set() API to test an alternate implementation being picked up. Used in -// SystemCacheTests -public class SystemCacheTestImpl extends SystemCache -{ - private static int _accessed; - - public SystemCacheTestImpl() - { - System.out.println("constructor SystemCacheTestImpl"); - _accessed++; - } - - public String testCacheImpl() - { - return (this.getClass().getName()); - } - - public static final int getAccessed() - { - return _accessed; - } - -} - diff --git a/test/src/misc/detailed/SystemCacheTests.java b/test/src/misc/detailed/SystemCacheTests.java deleted file mode 100644 index 648e808..0000000 --- a/test/src/misc/detailed/SystemCacheTests.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package misc.detailed; - -import junit.framework.TestCase; -import common.Common; - -import java.util.Random; -import java.util.Collection; -import java.util.ArrayList; -import java.util.Iterator; -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.lang.reflect.Method; - -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.common.SystemCache; - -import javax.xml.namespace.QName; - -public class SystemCacheTests extends TestCase -{ - public void testSystemCacheImplFromAPITest() throws Throwable - { - try - { - // store the default SystemCache implementation before switch - SystemCache defaultImpl = SystemCache.get(); - - //assertEquals("org.apache.xmlbeans.impl.common.SystemCache",defaultImpl.getClass().getName()); - // The expected default impl does not get picked up as the test is not run from a single jvm - // when run from the test infrastructure. Hence compare against the actual impl that gets picked up - // The assert above commented out will hold good if this test is invoked as follows: - // ant run.junit -Dtest.area=misc -Dtest.spec=misc.detailed.SystemCacheTests - assertEquals("org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl$SchemaTypeLoaderCache",defaultImpl.getClass().getName()); - - // switch the Impl to the test Impl - SystemCacheTestImpl testImpl = new SystemCacheTestImpl(); - SystemCache.set(testImpl); - assertEquals("misc.detailed.SystemCacheTestImpl",testImpl.getClass().getName()); - assertEquals(testImpl.getAccessed(), 1); - - // switch back to default impl - SystemCache.set(defaultImpl); - System.out.println("Third 1:" + defaultImpl.getClass().getName()); - System.out.println("Third 2:" + defaultImpl.getClass().getName()); - //assertEquals("org.apache.xmlbeans.impl.common.SystemCache",defaultImpl.getClass().getName()); - assertEquals("org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl$SchemaTypeLoaderCache",defaultImpl.getClass().getName()); - } - catch(ExceptionInInitializerError err) - { - System.out.println(err.getMessage()); - throw new Exception("File does not exist"); - } - } - -} diff --git a/test/src/schemas/defaults.xsd b/test/src/schemas/defaults.xsd deleted file mode 100644 index 6de0224..0000000 --- a/test/src/schemas/defaults.xsd +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/test/src/scomp/attributes/detailed/LocalAttrFixedDefault.java b/test/src/scomp/attributes/detailed/LocalAttrFixedDefault.java deleted file mode 100644 index 2bc7176..0000000 --- a/test/src/scomp/attributes/detailed/LocalAttrFixedDefault.java +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package scomp.attributes.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.attribute.localAttrFixedDefault.LocalAttrFixedDefaultT; -import xbean.scomp.attribute.localAttrFixedDefault.LocalAttrFixedDefaultDocument; -import org.apache.xmlbeans.XmlErrorCodes; - -/** - * - * - * - */ -public class LocalAttrFixedDefault extends BaseCase { - /** - * Verify that a local attribute can add a fixed value but can not overwrite - * an existing fixed val - * inspired by Walmsley 13.6.2 - */ - //ensure default val is shadowed locally - //fixed can not be... - public void testDefault() throws Throwable{ - LocalAttrFixedDefaultT testDoc = - LocalAttrFixedDefaultDocument.Factory.newInstance() - .addNewLocalAttrFixedDefault(); - assertTrue(testDoc.validate()); - assertEquals(2,testDoc.getAttDefault().intValue()); - //second fixed value is ignored - testDoc.setAttFixed("NEWXBeanAttrStr"); - assertTrue(!testDoc.validate(validateOptions)); - showErrors(); - String[] errExpected = new String[]{ - XmlErrorCodes.ATTR_LOCALLY_VALID$FIXED - }; - assertTrue(compareErrorCodes(errExpected)); - - - testDoc.setAttFixed("XBeanAttrStr"); - try { - assertTrue(testDoc.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - - } -} diff --git a/test/src/scomp/contentType/complex/modelGroup/detailed/AllTest.java b/test/src/scomp/contentType/complex/modelGroup/detailed/AllTest.java deleted file mode 100644 index cfbfd19..0000000 --- a/test/src/scomp/contentType/complex/modelGroup/detailed/AllTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package scomp.contentType.complex.modelGroup.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.contentType.modelGroup.AllEltDocument; -import xbean.scomp.contentType.modelGroup.AllT; - -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlErrorCodes; - -/** - * - * - * - */ -public class AllTest extends BaseCase { - - /** - * Instance should be valid w/ child1 missing - */ - public void testChild1Optional() throws Throwable { - doc = AllEltDocument.Factory.newInstance(); - AllT elt = doc.addNewAllElt(); - elt.setChild2("doo"); - elt.setChild3(BigInteger.ONE); - try { - assertTrue(doc.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - - } - - /** - * All group doesn't care about field order - * - * @throws Throwable - */ - public void testOrder() throws Throwable { - String input = - "" + - "52bar" + - ""; - doc = AllEltDocument.Factory.parse(input); - try { - assertTrue(doc.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - - - } - - /** - * maxOccurs is always 1 - * - * @throws Throwable - */ - public void testIllegal() throws Throwable { - String input = - "" + - "52bar" + - ""; - doc = AllEltDocument.Factory.parse(input); - assertTrue(!doc.validate(validateOptions)); - showErrors(); - //$TODO: QUESTIONABLE ERRORS: if 2 is replaced by 2 - //all will be good: why 2 errors? - String[] errExpected = new String[]{ - XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_DIFFERENT_ELEMENT, - XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$ELEMENT_NOT_ALLOWED, - XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$EXPECTED_ELEMENT - }; - assertTrue(compareErrorCodes(errExpected)); - - } - - - private AllEltDocument doc; -} diff --git a/test/src/scomp/derivation/detailed/AbstractTest.java b/test/src/scomp/derivation/detailed/AbstractTest.java deleted file mode 100644 index 2175e90..0000000 --- a/test/src/scomp/derivation/detailed/AbstractTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package scomp.derivation.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.derivation.xabstract.EltAbstractDocument; -import xbean.scomp.derivation.xabstract.AbstractT; -import xbean.scomp.derivation.xabstract.EltConcreteDocument; - -import java.math.BigInteger; - -/** - * - * - * - */ -public class AbstractTest extends BaseCase{ - - /** - * This is an abstract element...no instance should ever be valid - * @throws Throwable - */ - - public void testElementAbstract() throws Throwable{ - EltAbstractDocument doc=EltAbstractDocument.Factory.newInstance(); - AbstractT elt=doc.addNewEltAbstract(); - elt.setAge(new BigInteger("15")); - elt.setName("Ben"); - assertTrue(elt!=null); - assertTrue (! elt.validate() ); - } - - public void testElementAbstractParse() throws Throwable{ - EltAbstractDocument doc=EltAbstractDocument.Factory.parse( - ""+ - " Bob25G" + - ""); - - assertTrue (! doc.validate(validateOptions) ); - showErrors(); - } - - public void testElementConcrete() throws Throwable{ - EltConcreteDocument doc=EltConcreteDocument.Factory.parse( - ""+ - " Bob25G" + - ""); - assertTrue (! doc.validate(validateOptions)); - showErrors(); - } - -} diff --git a/test/src/scomp/derivation/detailed/FinalTest.java b/test/src/scomp/derivation/detailed/FinalTest.java deleted file mode 100644 index afad8b2..0000000 --- a/test/src/scomp/derivation/detailed/FinalTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package scomp.derivation.detailed; - -/** - * - * - * - */ - -/** - * Testing final - * This is a compile time test, not a runtime one - * since final determines whether a type can be extended or not - */ -public class FinalTest { - - public void testFinalAll() throws Throwable { - } - - public void testFinalExtension() throws Throwable { - } - - public void testFinalRestriction() throws Throwable { - } - - //should be equivaluent to final="#all" - public void testFinalRE_ER() throws Throwable { - } - - public void testFinalFinalDefault() throws Throwable { - } - - public void testFinalNone() throws Throwable { - } - -} diff --git a/test/src/scomp/derivation/restriction/detailed/SubstitutionTest.java b/test/src/scomp/derivation/restriction/detailed/SubstitutionTest.java deleted file mode 100644 index e942b1f..0000000 --- a/test/src/scomp/derivation/restriction/detailed/SubstitutionTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package scomp.derivation.restriction.detailed; - -import xbean.scomp.contentType.modelGroup.ChoiceEltDocument; -import xbean.scomp.contentType.simpleType.PantSizeEltDocument; -import scomp.common.BaseCase; - -/** - * - */ -public class SubstitutionTest extends BaseCase - { - public void testSubstitution() throws Throwable{ - ChoiceEltDocument doc= - ChoiceEltDocument.Factory.parse( - "" + - "50" + - "" - ); - try { - assertTrue(doc.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - } - - public void testSimpleTypeSubstitution() throws Throwable{ - PantSizeEltDocument doc= - PantSizeEltDocument.Factory.parse( - ""+ - "8" + - "" - ); - try { - assertTrue(doc.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - } -} diff --git a/test/src/scomp/derivation/restriction/facets/detailed/FacetRestrictionTest.java b/test/src/scomp/derivation/restriction/facets/detailed/FacetRestrictionTest.java deleted file mode 100644 index 5bc107a..0000000 --- a/test/src/scomp/derivation/restriction/facets/detailed/FacetRestrictionTest.java +++ /dev/null @@ -1,279 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package scomp.derivation.restriction.facets.detailed; - -import org.apache.xmlbeans.XmlErrorCodes; -import xbean.scomp.derivation.facets.facetRestriction.*; -import scomp.common.BaseCase; - -import java.util.TimeZone; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.math.BigDecimal; - -/** - * - */ -public class FacetRestrictionTest extends BaseCase { - - public void testMinMaxInclusiveElt() throws Throwable { - MinMaxInclusiveEltDocument doc = - MinMaxInclusiveEltDocument.Factory.newInstance(); - doc.setMinMaxInclusiveElt(3); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MIN_INCLUSIVE_VALID}; - - doc.setMinMaxInclusiveElt(2); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - clearErrors(); - errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID}; - doc.setMinMaxInclusiveElt(10); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - } - public void testMinMaxInclusiveDateElt() throws Throwable { - MinMaxInclusiveDateEltDocument doc = - MinMaxInclusiveDateEltDocument.Factory.newInstance(); - TimeZone tz = TimeZone.getDefault(); - Calendar c = new GregorianCalendar(tz); - c.set(2003, 11, 22); - doc.setMinMaxInclusiveDateElt(c); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - c = new GregorianCalendar(2003, 11, 24); - doc.setMinMaxInclusiveDateElt(c); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MAX_INCLUSIVE_VALID}; - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - - - } - public void testMinMaxExclusiveElt() throws Throwable { - MinMaxExclusiveEltDocument doc = - MinMaxExclusiveEltDocument.Factory.newInstance(); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MIN_EXCLUSIVE_VALID}; - - doc.setMinMaxExclusiveElt(3); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - clearErrors(); - - doc.setMinMaxExclusiveElt(4); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - doc.setMinMaxExclusiveElt(8); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - - } - public void testMinMaxExclusiveDateElt() throws Throwable { - MinMaxExclusiveDateEltDocument doc = MinMaxExclusiveDateEltDocument.Factory.newInstance(); - Calendar c = new GregorianCalendar(2003, 11, 24); - doc.setMinMaxExclusiveDateElt(c); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MAX_EXCLUSIVE_VALID}; - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - clearErrors(); - c = new GregorianCalendar(2003, 11, 23); - doc.setMinMaxExclusiveDateElt(c); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - - - } - /* - public void testLengthElt() throws Throwable { - LengthEltDocument doc = LengthEltDocument.Factory.newInstance(); - doc.setLengthElt("foobar"); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_LENGTH_VALID$STRING}; - - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - doc.setLengthElt("fo"); - clearErrors(); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - doc.setLengthElt("f"); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - } - */ - public void testMinMaxLengthElt() throws Throwable { - MinMaxLengthEltDocument doc = MinMaxLengthEltDocument.Factory.newInstance(); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MAX_LENGTH_VALID$STRING}; - - doc.setMinMaxLengthElt("fooba"); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - doc.setMinMaxLengthElt("fo"); - errExpected = new String[]{ - XmlErrorCodes.DATATYPE_MIN_LENGTH_VALID$STRING}; - clearErrors(); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - doc.setMinMaxLengthElt("foo"); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - doc.setMinMaxLengthElt("foob"); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - - } - public void testDigitsElt() throws Throwable { - DigitsEltDocument doc = DigitsEltDocument.Factory.newInstance(); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_TOTAL_DIGITS_VALID}; - - doc.setDigitsElt(new BigDecimal("122.2")); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - doc.setDigitsElt(new BigDecimal("12.3")); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - clearErrors(); - errExpected = new String[]{ - XmlErrorCodes.DATATYPE_FRACTION_DIGITS_VALID}; - doc.setDigitsElt(new BigDecimal("2.45")); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - } - - public void testWSElt() throws Throwable { - - // whiteSpace="replace" case - WSReplaceEltDocument doc = WSReplaceEltDocument.Factory.parse("" + - " This is a test.\nThe resulting string should convert tabs \t, line feeds \n and carriage returns into a single space \n" + - ""); - - // whiteSpace="collapse " case - WSCollapseEltDocument doc2 = WSCollapseEltDocument.Factory.parse("" + - " This is a test.\nThe resulting string should convert tabs \t, line feeds \n and carriage returns into a single space \n" + - ""); - - try { - assertTrue(doc.validate(validateOptions)); - assertTrue(doc2.validate(validateOptions)); - } - catch (Throwable t) { - showErrors(); - throw t; - } - - String replaceExpected = " This is a test. The resulting string should convert tabs , line feeds and carriage returns into a single space "; - assertEquals(replaceExpected, doc.getWSReplaceElt()); - - String collapseExpected = "This is a test. The resulting string should convert tabs , line feeds and carriage returns into a single space"; - assertEquals(collapseExpected, doc2.getWSCollapseElt()); - - } - - public void testEnumElt() throws Throwable { - EnumEltDocument doc = EnumEltDocument.Factory.newInstance(); - doc.setEnumElt(EnumT.A); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - doc = EnumEltDocument.Factory.parse("" + - "b" + - ""); - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_ENUM_VALID}; - - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - } - - public void testPatternElt() throws Throwable { - - // base pattern is (a[^bc]d){3}, derived pattern is (a[^ef]d){3} - PatternEltDocument doc = PatternEltDocument.Factory.newInstance(); - doc.setPatternElt("axdaydazd"); - try { - assertTrue(doc.validate(validateOptions)); - } catch (Throwable t) { - showErrors(); - throw t; - } - String[] errExpected = new String[]{ - XmlErrorCodes.DATATYPE_VALID$PATTERN_VALID}; - - doc.setPatternElt("aedafdagd"); - assertTrue(!doc.validate(validateOptions)); - assertTrue(compareErrorCodes(errExpected)); - - - } -} diff --git a/test/src/scomp/elements/detailed/GlobalEltDefault.java b/test/src/scomp/elements/detailed/GlobalEltDefault.java deleted file mode 100644 index 0a7c6ca..0000000 --- a/test/src/scomp/elements/detailed/GlobalEltDefault.java +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package scomp.elements.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.element.globalEltDefault.GlobalEltDefaultIntDocument; -import xbean.scomp.element.globalEltDefault.GlobalEltDefaultStrDocument; - -/** - * - * - */ -public class GlobalEltDefault extends BaseCase { - //empty string is OK considered , so default value is ignored - public void testStringType()throws Throwable{ - GlobalEltDefaultStrDocument testDoc=GlobalEltDefaultStrDocument - .Factory.newInstance(); - assertEquals(null,testDoc.getGlobalEltDefaultStr()); -/*try{ - assertTrue(testDoc.validate(validateOptions)); -}catch(Throwable t){ - showErrors(); - throw t; -} */ - testDoc.setGlobalEltDefaultStr("foo"); - try{ - assertTrue(testDoc.validate(validateOptions)); - }catch(Throwable t){ - showErrors(); - throw t; - } - - } - - //default value is used - public void testIntType()throws Throwable{ - GlobalEltDefaultIntDocument testDoc - =GlobalEltDefaultIntDocument.Factory - .newInstance(); - assertEquals(0,testDoc.getGlobalEltDefaultInt()); - try{ - assertTrue(testDoc.validate(validateOptions)); -}catch(Throwable t){ - showErrors(); - throw t; -} - } -} diff --git a/test/src/scomp/elements/detailed/GlobalEltId.java b/test/src/scomp/elements/detailed/GlobalEltId.java deleted file mode 100644 index be3969e..0000000 --- a/test/src/scomp/elements/detailed/GlobalEltId.java +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package scomp.elements.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.element.globalEltDefault.IDElementDocument; - -/** - * - * - */ -public class GlobalEltId extends BaseCase{ - public void testRun()throws Throwable{ - IDElementDocument doc= - IDElementDocument.Factory.newInstance(); - doc.addNewIDElement().setID("IDAttr"); - try { - assertTrue( doc.validate(validateOptions)) ; - } - catch (Throwable t) { - showErrors(); - throw t; - } - } -} diff --git a/test/src/scomp/elements/detailed/NamedModelGroupsTest.java b/test/src/scomp/elements/detailed/NamedModelGroupsTest.java deleted file mode 100644 index 3c7eba4..0000000 --- a/test/src/scomp/elements/detailed/NamedModelGroupsTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package scomp.elements.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.element.namedModelGroup.EmployeePerformanceDocument; -import xbean.scomp.element.namedModelGroup.EmployeePerf; -import xbean.scomp.element.namedModelGroup.ManagerDocument; - -import java.util.GregorianCalendar; -import java.math.BigDecimal; -import java.math.BigInteger; - -/** - * - */ -public class NamedModelGroupsTest extends BaseCase{ - public void testValid() throws Throwable{ - EmployeePerformanceDocument doc= - EmployeePerformanceDocument.Factory.newInstance(); - EmployeePerf elt= doc.addNewEmployeePerformance(); - ManagerDocument.Manager m=elt.addNewManager(); - m.setDepartment("Marketing"); - m.setLastName("Smith"); - - elt.setComment("Horrible performance by employee Potatohead"); - elt.setDate(new GregorianCalendar(2004,8,12)); - elt.setGrade(new BigDecimal(new BigInteger("10"))); - elt.setManager(m); - try { - assertTrue( doc.validate(validateOptions)) ; - } - catch (Throwable t) { - showErrors(); - throw t; - } - } -} diff --git a/test/src/scomp/namespace/detailed/AttrFormDefault.java b/test/src/scomp/namespace/detailed/AttrFormDefault.java deleted file mode 100644 index 549cb61..0000000 --- a/test/src/scomp/namespace/detailed/AttrFormDefault.java +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package scomp.namespace.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.namespace.attributeFormDefault.AttributeFormDefaultEltDocument; -import xbean.scomp.namespace.attributeFormDefault.ElementT; -import org.apache.xmlbeans.XmlAnySimpleType; -import org.apache.xmlbeans.XmlErrorCodes; - -/** - * - */ -public class AttrFormDefault extends BaseCase { - public void testValid() throws Throwable { - AttributeFormDefaultEltDocument doc = - AttributeFormDefaultEltDocument.Factory.parse(""); - - try { - doc.validate(validateOptions); - } - catch (Throwable t) { - showErrors(); - throw t; - } - } - - public void testInvalid() throws Throwable { - AttributeFormDefaultEltDocument doc = - AttributeFormDefaultEltDocument.Factory.newInstance(); - ElementT elt=doc.addNewAttributeFormDefaultElt(); - XmlAnySimpleType val=XmlAnySimpleType.Factory.newInstance(); - val.setStringValue("345"); - elt.setLocalAttr(val); - try { - assertTrue( doc.validate(validateOptions) ); - } - catch (Throwable t) { - showErrors(); - throw t; - } - - doc = - AttributeFormDefaultEltDocument.Factory.parse(""); - assertTrue( ! doc.validate(validateOptions)); - showErrors(); - String[] errExpected = new String[]{ - XmlErrorCodes.ELEM_COMPLEX_TYPE_LOCALLY_VALID$NO_WILDCARD - }; - assertTrue(compareErrorCodes(errExpected)); - - } -} diff --git a/test/src/scomp/redefine/detailed/AttrGroupRedefine.java b/test/src/scomp/redefine/detailed/AttrGroupRedefine.java deleted file mode 100644 index 6006d6b..0000000 --- a/test/src/scomp/redefine/detailed/AttrGroupRedefine.java +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package scomp.redefine.detailed; - -import scomp.common.BaseCase; -import xbean.scomp.redefine.attrGroupRedefine.AttrGroupEltDocument; - - -import java.lang.reflect.Method; - -public class AttrGroupRedefine extends BaseCase{ - - /** - * test that fields from the old type def are not - * visible anymore - */ - public void testCodeGeneration(){ - AttrGroupEltDocument doc=AttrGroupEltDocument.Factory.newInstance(); - AttrGroupEltDocument.AttrGroupElt elt=doc.addNewAttrGroupElt(); - - try{ - elt.getClass().getDeclaredField("attr2"); - fail("field should be redefined"); - }catch(NoSuchFieldException e){} - - - try{ - elt.getClass().getDeclaredMethod("getAttr1",null); - elt.getClass().getDeclaredMethod("getAttr2A",null); - - Method m=elt.getClass().getDeclaredMethod("getAttr3A",null); - assertEquals(m.getReturnType(),Class.forName("java.lang.Integer.TYPE") ); - }catch(NoSuchMethodException e){ - fail("Fields not redefined"); - } catch (ClassNotFoundException e1){} - } -} diff --git a/test/src/scomp/redefine/detailed/SimpleRedefine.java b/test/src/scomp/redefine/detailed/SimpleRedefine.java deleted file mode 100644 index 58217df..0000000 --- a/test/src/scomp/redefine/detailed/SimpleRedefine.java +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package scomp.redefine.detailed; - -import xbean.scomp.redefine.simpleRedefined.NewSizeEltDocument; -import xbean.scomp.redefine.simpleRedefined.OldColorEltDocument; -import xbean.scomp.redefine.simpleRedefined.OldSizeEltDocument; -import scomp.common.BaseCase; - -/** - */ -public class SimpleRedefine extends BaseCase - { - - /** - * test that fields from the old type def are not - * visible anymore: only valid range for sizeT should be 3-20 - */ - public void testCodeGeneration() throws Throwable{ - NewSizeEltDocument doc=NewSizeEltDocument.Factory.newInstance(); - OldColorEltDocument doc1=OldColorEltDocument.Factory.newInstance(); - OldSizeEltDocument doc2=OldSizeEltDocument.Factory.newInstance(); - - doc.setNewSizeElt(3); - - try{ - assertTrue(doc.validate(validateOptions)); - }catch(Throwable t){ - showErrors(); - throw t; - } - doc.setNewSizeElt(21); - assertTrue( !doc.validate(validateOptions)); - showErrors(); - clearErrors(); - - doc2.setOldSizeElt(21); - assertTrue( !doc.validate(validateOptions)); - showErrors(); - clearErrors(); - - doc1.setOldColorElt("white"); - - try{ - assertTrue(doc1.validate(validateOptions)); - }catch(Throwable t){ - showErrors(); - throw t; - } - } -} diff --git a/test/src/tools/inst2xsd/checkin/Inst2XsdOptionsTest.java b/test/src/tools/inst2xsd/checkin/Inst2XsdOptionsTest.java deleted file mode 100644 index 1a0dac6..0000000 --- a/test/src/tools/inst2xsd/checkin/Inst2XsdOptionsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.inst2xsd.checkin; - -import tools.inst2xsd.common.Inst2XsdTestBase; -import tools.xml.XmlComparator; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; -import org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd; - - -import java.io.File; -import java.io.IOException; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -public class Inst2XsdOptionsTest extends Inst2XsdTestBase { - - public Inst2XsdOptionsTest(String name) { - super(name); - } - - /** Move tests from Detailed back once cursor bug gets fixed */ - public void test_move() throws Exception{ - System.out.println("Move tests from Detailed back once cursor bug gets fixed"); - } - - - - - - - - - - - - -} diff --git a/test/src/tools/inst2xsd/common/Inst2XsdCommon.java b/test/src/tools/inst2xsd/common/Inst2XsdCommon.java deleted file mode 100644 index c608c24..0000000 --- a/test/src/tools/inst2xsd/common/Inst2XsdCommon.java +++ /dev/null @@ -1,102 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.inst2xsd.common; - -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; - -public class Inst2XsdCommon { - - public static XmlOptions getXmlOptions(){ - XmlOptions xm = new XmlOptions(); - xm.setCompileDownloadUrls(); - xm.setSavePrettyPrintIndent(4); - xm.setSavePrettyPrintOffset(4); - xm.setSavePrettyPrint(); - return xm; - } - - public static Inst2XsdOptions getDefaultInstOptions(){ - Inst2XsdOptions initOpt = new Inst2XsdOptions(); - initOpt.setVerbose(true); - return initOpt; - } - - public static Inst2XsdOptions getRussianOptions() { - Inst2XsdOptions opt = getDefaultInstOptions(); - opt.setDesign(Inst2XsdOptions.DESIGN_RUSSIAN_DOLL); - return opt; - } - - public static Inst2XsdOptions getSalamiOptions() { - Inst2XsdOptions opt = getDefaultInstOptions(); - opt.setDesign(Inst2XsdOptions.DESIGN_SALAMI_SLICE); - return opt; - } - - public static Inst2XsdOptions getVenetianOptions() { - Inst2XsdOptions opt = getDefaultInstOptions(); - opt.setDesign(Inst2XsdOptions.DESIGN_VENETIAN_BLIND); - return opt; - } - - - public static String base = "" + - "abc" + - "123" + - "" + - ""; - public static String base_expected_russian = "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - - public static String base_expected_salami = "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - - public static String base_expected_venetian = "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - -} diff --git a/test/src/tools/inst2xsd/common/Inst2XsdTestBase.java b/test/src/tools/inst2xsd/common/Inst2XsdTestBase.java deleted file mode 100644 index 4fe16e1..0000000 --- a/test/src/tools/inst2xsd/common/Inst2XsdTestBase.java +++ /dev/null @@ -1,548 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.inst2xsd.common; - -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd; -import org.apache.xmlbeans.impl.inst2xsd.Inst2XsdOptions; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -import java.util.Collection; -import java.util.ArrayList; -import java.util.Iterator; - -import tools.xml.XmlComparator; -import common.Common; - -public class Inst2XsdTestBase extends Common { - - public static tools.inst2xsd.common.Inst2XsdCommon common; - public static boolean _verbose = true; - - public static final String fwroot = FWROOT; - public static String caseroot = XBEAN_CASE_ROOT; - //location of files under "cases folder" - public static String miscDir = caseroot + P + "tools"; - public static String inst2xsdDir = miscDir + P + "inst2xsd" + P; - public static String OPTION_CASES_DIR = inst2xsdDir + P + "options" + P; - public static String SCHEMA_CASES_DIR = inst2xsdDir + P + "schema" + P; - public static String VALIDATION_CASES_DIR = inst2xsdDir + P + "validation" + P; - public static final String BASEXML = OPTION_CASES_DIR + "base.xml"; - public static final String EXPBASEXML = OPTION_CASES_DIR + "base0.xsd"; - - - private static String base_start = ""; - private static String base_end = ""; - - private static String attr_base_start = ""; - - - public Inst2XsdTestBase(String name) { - super(name); - } - - public static final String test_getRootFilePath() throws IllegalStateException { - String root = System.getProperty("xbean.rootdir"); - log("xbean.rootdir: " + root); - if (root == null) - throw new IllegalStateException("xbean.rootdir system property not found"); - - return root; - } - - - public XmlObject getTypeXml(String val) throws Exception { - return XmlObject.Factory.parse(setTypeVal(val)); - } - - public String setTypeVal(String val) { - return base_start + val + base_end; - } - - public XmlObject getAttrTypeXml(String val) throws Exception { - return XmlObject.Factory.parse(setAttrVal(val)); - } - - public String setAttrVal(String val) { - return attr_base_start + val + attr_base_end; - } - - //attribute testing methods - public String getAttrTypeXmlVenetian(String primType, String derType) { - return "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - } - - public String getAttrTypeXmlVenetian(String type) { - return "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - } - - public String getAttrTypeXmlRDandSS(String primType, String derType) { - return "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - } - - public String getAttrTypeXmlRDandSS(String type) { - return "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - ""; - } - - public void runAttrTypeChecking(XmlObject act, String expType) throws Exception { - - log("=== Venetian options ==="); - runAttrTypeChecking(act, expType, Inst2XsdCommon.getVenetianOptions()); - log("=== Russian options ==="); - runAttrTypeChecking(act, expType, Inst2XsdCommon.getRussianOptions()); - log("=== Salami options ==="); - runAttrTypeChecking(act, expType, Inst2XsdCommon.getSalamiOptions()); - log("=== Default options ==="); - runAttrTypeChecking(act, expType, Inst2XsdCommon.getDefaultInstOptions()); - } - - public void runAttrTypeChecking(XmlObject act, String primType, String derType) throws Exception { - - log("=== Venetian options ==="); - runAttrTypeChecking(act, primType, derType, Inst2XsdCommon.getVenetianOptions()); - log("=== Russian options ==="); - runAttrTypeChecking(act, primType, derType, Inst2XsdCommon.getRussianOptions()); - log("=== Salami options ==="); - runAttrTypeChecking(act, primType, derType, Inst2XsdCommon.getSalamiOptions()); - log("=== Default options ==="); - runAttrTypeChecking(act, primType, derType, Inst2XsdCommon.getDefaultInstOptions()); - } - - private void runAttrTypeChecking(XmlObject act, String primType, String derType, Inst2XsdOptions opt) throws Exception { - SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); - checkLength(venetian, 1); - - if (opt.getDesign() == Inst2XsdOptions.DESIGN_RUSSIAN_DOLL || - opt.getDesign() == Inst2XsdOptions.DESIGN_SALAMI_SLICE) - compare(venetian[0], XmlObject.Factory.parse(getAttrTypeXmlRDandSS(primType, derType))); - else if (opt.getDesign() == Inst2XsdOptions.DESIGN_VENETIAN_BLIND) - compare(venetian[0], XmlObject.Factory.parse(getAttrTypeXmlVenetian(primType, derType))); - else - throw new Exception("Design style was not found"); - - checkInstance(venetian, new XmlObject[]{act}); - - } - - private void runAttrTypeChecking(XmlObject act, String expType, Inst2XsdOptions opt) throws Exception { - SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); - checkLength(venetian, 1); - - if (opt.getDesign() == Inst2XsdOptions.DESIGN_RUSSIAN_DOLL || - opt.getDesign() == Inst2XsdOptions.DESIGN_SALAMI_SLICE) - compare(venetian[0], XmlObject.Factory.parse(getAttrTypeXmlRDandSS(expType))); - else if (opt.getDesign() == Inst2XsdOptions.DESIGN_VENETIAN_BLIND) - compare(venetian[0], XmlObject.Factory.parse(getAttrTypeXmlVenetian(expType))); - else - throw new Exception("Design style was not found"); - - checkInstance(venetian, new XmlObject[]{act}); - - } - - //element value test methods - public void runTypeChecking(XmlObject act, String expType) throws Exception { - log("=== Venetian options ==="); - runTypeChecking(act, expType, Inst2XsdCommon.getVenetianOptions()); - log("=== Russian options ==="); - runTypeChecking(act, expType, Inst2XsdCommon.getRussianOptions()); - log("=== Salami options ==="); - runTypeChecking(act, expType, Inst2XsdCommon.getSalamiOptions()); - log("=== Default options ==="); - runTypeChecking(act, expType, Inst2XsdCommon.getDefaultInstOptions()); - } - - - private void runTypeChecking(XmlObject act, String expType, Inst2XsdOptions opt) throws Exception { - SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); - checkLength(venetian, 1); - log("actual: " + act); - log("expType: " + expType); - checkInstance(venetian, new XmlObject[]{act}); - compare(venetian[0], XmlObject.Factory.parse(getExpTypeXml(expType))); - } - - public String getExpTypeXml(String type) { - return "" + - "" + - ""; - } - - //type coercion/LCD test methods - public void runLCDTypeCheckTest(String val1, String val2, String expType) throws Exception { - log("=== Venetian options ==="); - runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getVenetianOptions()); - log("=== Russian options ==="); - runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getRussianOptions()); - log("=== Salami options ==="); - runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getSalamiOptions()); - log("=== Default options ==="); - runLCDTypeChecking(val1, val2, expType, Inst2XsdCommon.getDefaultInstOptions()); - } - - private void runLCDTypeChecking(String val1, String val2, String expType, Inst2XsdOptions opt) throws Exception { - XmlObject act = getTypeCoerceXml(val1, val2); - SchemaDocument[] venetian = (SchemaDocument[]) runInst2Xsd(act, opt); - checkLength(venetian, 1); - log("instance: " + act); - log("expType: " + expType); - checkInstance(venetian, new XmlObject[]{act}); - - if (opt.getDesign() == Inst2XsdOptions.DESIGN_VENETIAN_BLIND) - compare(venetian[0], getExpLCDXml_vb(expType)); - else if (opt.getDesign() == Inst2XsdOptions.DESIGN_SALAMI_SLICE) - compare(venetian[0], getExpLCDXml_ss(expType)); - else if (opt.getDesign() == Inst2XsdOptions.DESIGN_RUSSIAN_DOLL) - compare(venetian[0], getExpLCDXml_rd(expType)); - else - compare(venetian[0], getExpLCDXml_vb(expType)); - } - - public String getTypeCoerceXmlString(String val1, String val2) { - return "" + - " " + val1 + "" + - " " + val2 + "" + - ""; - } - - public XmlObject getTypeCoerceXml(String val1, String val2) throws XmlException { - return XmlObject.Factory.parse(getTypeCoerceXmlString(val1, val2)); - } - - - public XmlObject getExpLCDXml_vb(String type) throws XmlException { - return XmlObject.Factory.parse("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""); - } - - public XmlObject getExpLCDXml_ss(String type) throws XmlException { - return XmlObject.Factory.parse("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""); - } - - public XmlObject getExpLCDXml_rd(String type) throws XmlException { - return XmlObject.Factory.parse("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""); - } - - - public static XmlObject[] runInst2Xsd(String inst) throws XmlException { - return runInst2Xsd(new XmlObject[]{XmlObject.Factory.parse(inst, Inst2XsdCommon.getXmlOptions())}, - Inst2XsdCommon.getDefaultInstOptions()); - } - - public static XmlObject[] runInst2Xsd(XmlObject inst) { - return Inst2Xsd.inst2xsd(new XmlObject[]{inst}, Inst2XsdCommon.getDefaultInstOptions()); - } - - public static XmlObject[] runInst2Xsd(XmlObject[] inst) { - return Inst2Xsd.inst2xsd(inst, Inst2XsdCommon.getDefaultInstOptions()); - } - - public static XmlObject[] runInst2Xsd(XmlObject inst, Inst2XsdOptions options) { - return Inst2Xsd.inst2xsd(new XmlObject[]{inst}, options); - } - - public static XmlObject[] runInst2Xsd(XmlObject[] inst, Inst2XsdOptions options) { - return Inst2Xsd.inst2xsd(inst, options); - } - - - public static SchemaDocument[] getSchemaDoc(XmlObject[] inst) throws XmlException { - SchemaDocument[] docs = new SchemaDocument[inst.length]; - for (int i = 0; i < docs.length; i++) { - docs[i] = SchemaDocument.Factory.parse(inst[i].xmlText()); - } - return docs; - - } - - public static void runSchemaBuild(XmlObject inst, Inst2XsdOptions opts, XmlObject exp) throws Exception { - XmlObject[] genSchema = runInst2Xsd(inst, opts); - log(genSchema); - checkInstanceToAll(genSchema, inst, exp); - checkLength(genSchema, 1); - compare(genSchema[0], exp); - - } - - public static void runSchemaBuild(XmlObject inst, Inst2XsdOptions opts, XmlObject[] exp) throws Exception { - XmlObject[] genSchema = runInst2Xsd(inst, opts); - log(genSchema); - checkInstanceToAll(genSchema, new XmlObject[]{inst}, exp); - checkLength(genSchema, exp.length); - compare(genSchema, exp); - - } - - public static void runSchemaBuild(XmlObject[] inst, Inst2XsdOptions opts, XmlObject[] exp) throws Exception { - XmlObject[] genSchema = runInst2Xsd(inst, opts); - checkInstanceToAll(genSchema, inst, exp); - log(genSchema); - compare(genSchema, exp); - - } - - //TODO: Make this error narrowed - public static void checkLength(Object[] obj, int val) throws Exception { - log("Length = " + obj.length + " exp: " + val); - - if (obj.length == val) { - return; - } else if (obj.length < val) { - throw new Exception("Actual was smaller than expected"); - } else if (obj.length > val) { - throw new Exception("Actual was larger than expected"); - } else { - throw new Exception("Array Indexes did not compare correctly"); - } - - - } - - - public static void compare(XmlObject[] act, XmlObject[] exp) throws XmlException, Exception { - checkLength(act, exp.length); - //Arrays.sort(act); - //Arrays.sort(exp); - //if (Arrays.equals(act, exp)){ - // return; - //}else{ - for (int i = 0; i < act.length; i++) { - compare(act[i], exp[i]); - } - - } - - public static void compare(XmlObject act, XmlObject exp) - throws XmlException, Exception { - XmlComparator.Diagnostic diag = XmlComparator.lenientlyCompareTwoXmlStrings(act.xmlText(Inst2XsdCommon.getXmlOptions()), - exp.xmlText(Inst2XsdCommon.getXmlOptions())); - if (diag.hasMessage()) { - log("Expected: \n" + exp.xmlText(Inst2XsdCommon.getXmlOptions())); - log("Actual: \n" + act.xmlText(Inst2XsdCommon.getXmlOptions())); - throw new Exception("Xml Comparison Failed:\n" + diag.toString()); - } - } - - public static void log(XmlObject[] doc) { - if (_verbose) { - for (int i = 0; i < doc.length; i++) { - log("Schema[" + i + "] - " + doc[i].xmlText(Inst2XsdCommon.getXmlOptions())); - } - } - } - - public static void log(String msg) { - if (_verbose) - System.out.println(msg); - } - - public static void log(XmlObject obj) { - if (_verbose) - System.out.println(obj.xmlText(Inst2XsdCommon.getXmlOptions())); - } - - - public static boolean checkInstanceToAll(XmlObject[] actSchemaDoc, XmlObject inst, - XmlObject expSchemas) throws Exception { - return checkInstanceToAll(getSchemaDoc(actSchemaDoc), new XmlObject[]{inst}, getSchemaDoc(new XmlObject[]{expSchemas})); - } - - public static boolean checkInstanceToAll(XmlObject[] actSchemaDoc, XmlObject[] inst, - XmlObject[] expSchemas) throws Exception { - return checkInstanceToAll(getSchemaDoc(actSchemaDoc), inst, getSchemaDoc(expSchemas)); - } - - public static boolean checkInstanceToAll(XmlObject[] actSchemaDoc, XmlObject[] inst, - XmlObject expSchemas) throws Exception { - return checkInstanceToAll(getSchemaDoc(actSchemaDoc), inst, getSchemaDoc(new XmlObject[]{expSchemas})); - } - - public static boolean checkInstanceToAll(SchemaDocument[] actSchemaDoc, XmlObject inst, - SchemaDocument expSchemas) throws Exception { - return checkInstanceToAll(actSchemaDoc, new XmlObject[]{inst}, getSchemaDoc(new XmlObject[]{expSchemas})); - } - - public static boolean checkInstanceToAll(SchemaDocument[] actSchemaDoc, XmlObject inst, - SchemaDocument[] expSchemas) throws Exception { - return checkInstanceToAll(actSchemaDoc, new XmlObject[]{inst}, expSchemas); - } - - public static boolean checkInstanceToAll(SchemaDocument[] actSchemaDoc, XmlObject[] inst, - SchemaDocument[] expSchemas) throws Exception { - log("-= Comparing Actual to instance=-"); - if (checkInstance(actSchemaDoc, inst)) - log("-= Instance validated actual =-"); - - log("-= Comparing Expected to instance=-"); - if (checkInstance(expSchemas, inst)) - log("-= Instance validated Expected =-"); - - return true; - } - - public static boolean checkInstance(SchemaDocument[] sDocs, XmlObject[] inst) throws Exception { - if (validateInstances(sDocs, inst)) { - return true; - } else { - throw new Exception("Instance Failed to validate"); - } - } - - /** - * Copied from inst2Xsd as option may be removed - * - * @param sDocs - * @param instances - * @return - */ - public static boolean validateInstances(SchemaDocument[] sDocs, XmlObject[] instances) { - - SchemaTypeLoader sLoader; - Collection compErrors = new ArrayList(); - XmlOptions schemaOptions = new XmlOptions(); - schemaOptions.setErrorListener(compErrors); - try { - sLoader = XmlBeans.loadXsd(sDocs, schemaOptions); - } catch (Exception e) { - if (compErrors.isEmpty() || !(e instanceof XmlException)) { - e.printStackTrace(System.out); - } - System.out.println("Schema invalid"); - for (Iterator errors = compErrors.iterator(); errors.hasNext();) - System.out.println(errors.next()); - return false; - } - - boolean result = true; - - for (int i = 0; i < instances.length; i++) { - String instance = instances[i].toString(); - - XmlObject xobj; - - try { - xobj = sLoader.parse(instance, null, new XmlOptions().setLoadLineNumbers()); - } catch (XmlException e) { - System.out.println("Error:\n" + instance + " not loadable: " + e); - e.printStackTrace(System.out); - result = false; - continue; - } - - Collection errors = new ArrayList(); - - if (xobj.schemaType() == XmlObject.type) { - System.out.println(instance + " NOT valid. "); - System.out.println(" Document type not found."); - result = false; - } else if (xobj.validate(new XmlOptions().setErrorListener(errors))) - System.out.println("Instance[" + i + "] valid."); - else { - System.out.println("Instance[" + i + "] NOT valid."); - for (Iterator it = errors.iterator(); it.hasNext();) { - System.out.println(" " + it.next()); - } - result = false; - } - } - - return result; - } - -} diff --git a/test/src/xmlcursor/checkin/AddToSelectionTest.java b/test/src/xmlcursor/checkin/AddToSelectionTest.java deleted file mode 100755 index 7171d5c..0000000 --- a/test/src/xmlcursor/checkin/AddToSelectionTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.BasicCursorTestCase; - -import java.net.URL; - - -/** - * - * - */ -public class AddToSelectionTest extends BasicCursorTestCase -{ - - static String sXml = "0123456"; - - public AddToSelectionTest(String sName) - { - super(sName); - } - - public static Test suite() - { - return new TestSuite(AddToSelectionTest.class); - } - - public void testAddToSelectionEnd() - { - m_xc.toEndDoc(); - m_xc.addToSelection(); - assertEquals(1, m_xc.getSelectionCount()); - } - - public void testAddToSelectionStart() - { - m_xc.toStartDoc(); - m_xc.addToSelection(); - assertEquals(1, m_xc.getSelectionCount()); - } - - public void testAddToSelectionAll() throws Exception - { - sXml = ""; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - XmlCursor.TokenType tok; - m_xc.addToSelection(); - while ((tok = m_xc.toNextToken()) != XmlCursor.TokenType.NONE) { - System.err.println(tok); - m_xc.addToSelection(); - } - assertEquals(4, m_xc.getSelectionCount()); - - //check results - XmlCursor m_xc1 = XmlObject.Factory.parse(sXml).newCursor(); - m_xc.toSelection(0); //reset cursor - int i = m_xc.getSelectionCount(); - while ((tok = m_xc1.toNextToken()) != XmlCursor.TokenType.NONE) { - //assertEquals(true,m_xc.hasNextSelection()); - assertEquals(m_xc.toNextToken(), tok); - m_xc.toNextSelection(); - } - //second cursor should be at the end of selections too... - assertEquals(false, m_xc.toNextSelection()); - m_xc1.dispose(); - } - - public void testAddToSelectionSet() - { - //not set but bag semantics - int expRes = 100; - - m_xc.clearSelections(); - for (int i = 0; i < 100; i++) { - m_xc.toStartDoc(); - m_xc.addToSelection(); - } - assertEquals(expRes, m_xc.getSelectionCount()); - } - - public void testAddAfterDispose() - { - m_xc.dispose(); - boolean error = false; - try { - m_xc.addToSelection(); - } catch (Throwable e) { - error = true; - } - assertEquals(true, error); - - } - - - public void setUp() throws Exception - { - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - super.setUp(); - } - - public void tearDown() - { - if (m_xc == null) return; - try { - m_xc.clearSelections(); - super.tearDown(); - } catch (IllegalStateException e) { //cursor disposed - } catch (Exception e) { - - } - } -} - diff --git a/test/src/xmlcursor/checkin/AnnotationsTests.java b/test/src/xmlcursor/checkin/AnnotationsTests.java deleted file mode 100755 index 3ad5c46..0000000 --- a/test/src/xmlcursor/checkin/AnnotationsTests.java +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.checkin; - -import java.io.File; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import junit.framework.Assert; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; - -import xmlcursor.common.Common; - -public class AnnotationsTests extends TestCase -{ - public AnnotationsTests(String name) { super(name); } - public static Test suite() { return new TestSuite(AnnotationsTests.class); } - - static String[] _args; - static String _test; - - - - static class TestBookmark extends XmlCursor.XmlBookmark - { - } - - // - // Basic load up a file and iterate through it - // - - public void testBasicXml( ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); - - TestBookmark a1 = new TestBookmark(); - - c.setBookmark( a1 ); - - TestBookmark a2 = new TestBookmark(); - - c.toNextToken(); - c.toNextToken(); - - c.setBookmark( a2 ); - - c.toPrevToken(); - c.toPrevToken(); - - Assert.assertEquals( c.getBookmark( TestBookmark.class ), a1 ); - - c.toNextToken(); - c.toNextToken(); - - Assert.assertEquals( c.getBookmark( TestBookmark.class ), a2 ); - - c.toNextToken(); - - Assert.assertTrue( c.getBookmark( TestBookmark.class ) == null ); - } -} diff --git a/test/src/xmlcursor/checkin/BeginElementTest.java b/test/src/xmlcursor/checkin/BeginElementTest.java deleted file mode 100755 index 50b55eb..0000000 --- a/test/src/xmlcursor/checkin/BeginElementTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.Common; -import xmlcursor.common.BasicCursorTestCase; - -import java.net.URL; - - -/** - * - * - */ -public class BeginElementTest extends BasicCursorTestCase { - XmlCursor.TokenType tok; - - String sLocalName="localName"; - String sUri="fakeURI"; - String sDefaultPrefix=sUri.substring(0,3); //$BUGBUG:WHY??? - String sExpectedStart="<"+sDefaultPrefix+":localName xmlns:"+sDefaultPrefix+"=\"fakeURI\"/>"; - - String sInputDoc=Common.XML_FOO_DIGITS; - - - public BeginElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(BeginElementTest.class); - } - - - - public void testBeginElementStr()throws Exception { - //same for string API - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - m_xc.beginElement(sLocalName,sUri); - toPrevTokenOfType(m_xc, TokenType.START); - /*System.out.println(" SAW "+m_xc.xmlText()); - System.out.println(" Wanted "+sExpectedStart); - System.out.println(" Java Wanted "+new QName(sUri,sLocalName)); - */ - assertEquals(m_xc.xmlText(),sExpectedStart); - } - - public void testBeginElementQName() throws Exception{ - //Qname call - - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - //insert new under the first element - toNextTokenOfType(m_xc, TokenType.START); - QName qName=new QName(sUri,sLocalName); - m_xc.beginElement(qName); - checkResult(qName); - } - public void testBeginElementQNamePrefix() throws Exception{ - //Qname with prefix - String sPrefix="pre"; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - QName qName=new QName(sUri,sLocalName,sPrefix); - System.out.println("Java prefix Qname: "+qName); - m_xc.beginElement(qName); - checkResult(qName); - } - - //pre: cursor is not moved after beginElt call - private void checkResult(QName qName){ - tok=m_xc.toPrevToken(); - - assertEquals(m_xc.getName(),qName); - - } - - public void testBeginElementStartDoc(String sLocalName, String sUri)throws Exception { - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - m_xc.beginElement(sLocalName,sUri); - m_xc.toPrevToken(); - m_xc.toPrevToken(); - assertEquals(true,m_xc.isStartdoc()); - - } - - // - public static void main(String[] rgs){ - try{ - BeginElementTest test=(new BeginElementTest("")); - test.testBeginElementQNamePrefix(); - // test.testBeginElementQName(); - System.out.println("getName(): "+test.m_xc.getName()); - System.out.println("cmlText(): "+test.m_xc.xmlText()); - }catch (Exception e){ - - } - } -} diff --git a/test/src/xmlcursor/checkin/CopyTest.java b/test/src/xmlcursor/checkin/CopyTest.java deleted file mode 100755 index 9bd922a..0000000 --- a/test/src/xmlcursor/checkin/CopyTest.java +++ /dev/null @@ -1,236 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import tools.util.JarUtil; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; - -import javax.xml.namespace.QName; - - - -/** - * - * - */ -public class CopyTest extends BasicCursorTestCase { - public CopyTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CopyTest.class); - } - - public void testCopyToNull() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.copyXml(null); - fail( - "Expected IllegalArgumentException. Can't copy to foreign document"); - } - catch (IllegalArgumentException ise) { - } - } - - public void testCopyDifferentStoresLoadedByParse() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - XmlObject xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - XmlCursor xc1 = xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - toNextTokenOfType(xc1, TokenType.TEXT); - m_xc.copyXml(xc1); - xc1.toParent(); - // verify xc1 - assertEquals("01234text", xc1.getTextValue()); - xc1.dispose(); - // verify m_xc - assertEquals("01234", m_xc.getChars()); - } - - /** - * Method testCopyDifferentStoresLoadedFromFile - *

        - * Tests copy from document w/ namespaces to doc w/o - * - * @throws Exception - */ - public void testCopyDifferentStoresLoadedFromFile() throws Exception { - // load the documents and obtain a cursor - XmlObject xobj0 = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - XmlObject xobj1 = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - - XmlCursor xc0 = xobj0.newCursor(); - XmlCursor xc1 = xobj1.newCursor(); - - xc0.selectPath(Common.CLM_NS_XQUERY_DEFAULT + " .//Initial"); - xc0.toNextSelection(); - String sQuery= - "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "+ - ".//po:zip"; - xc1.selectPath( sQuery ); - xc1.toNextSelection(); - - xc0.copyXml(xc1); // should copy the GATX element plus the default namespace - xc1.toPrevSibling(); - // verify xc1 - String sExpected = "" + - "GATX"; - assertEquals(sExpected, xc1.xmlText()); - // verify xc0 - // should contain all the namespaces for the document - assertEquals( - "GATX", - xc0.xmlText()); - xc0.dispose(); - xc1.dispose(); - - } - - /** - * Method testCopyDifferentStoresLoadedFromFile2 - *

        - * Tests copy from document w/o namespaces to document with namespaces - * - * @throws Exception - */ - public void testCopyDifferentStoresLoadedFromFile2() throws Exception { - // load the documents and obtain a cursor - XmlObject xobj0 = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - XmlObject xobj1 = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - - XmlCursor xc0 = xobj0.newCursor(); - XmlCursor xc1 = xobj1.newCursor(); - - xc0.selectPath(Common.CLM_NS_XQUERY_DEFAULT + " .//Initial"); - xc0.toNextSelection(); - - String sQuery= - "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "+ - ".//po:zip"; - xc1.selectPath( sQuery ); - xc1.selectPath( sQuery ); - xc1.toNextSelection(); - - xc1.copyXml(xc0); // should copy the 90952 element - // verify xc1 - assertEquals( - "90952", - xc1.xmlText()); - // verify xc0 - // should contain all the namespaces for the document - xc0.toPrevSibling(); - // assertEquals("90952", xc0.xmlText()); - String sExpected = "" + - "90952"; - - assertEquals(sExpected, xc0.xmlText()); - xc0.dispose(); - xc1.dispose(); - - } - - public void testCopySameLocation() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - toNextTokenOfType(xc1, TokenType.TEXT); - m_xc.copyXml(xc1); - xc1.dispose(); - m_xc.toParent(); - assertEquals("0123401234", m_xc.getTextValue()); - } - - public void testCopyNewLocation() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "; - m_xc = m_xo.newCursor(); - XmlCursor xc1 = m_xo.newCursor(); - m_xc.selectPath(ns+" .//po:shipTo/po:city"); - m_xc.toNextSelection(); - xc1.selectPath(ns +" .//po:billTo/po:city"); - xc1.toNextSelection(); - m_xc.copyXml(xc1); - xc1.toPrevToken(); - xc1.toPrevToken(); - // verify xc1 - assertEquals("Mill Valley", xc1.getChars()); - xc1.dispose(); - // verify m_xc - assertEquals("Mill Valley", m_xc.getTextValue()); - - } - - public void testCopyElementToMiddleOfTEXT() throws Exception { - - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "; - String exp_ns="xmlns:po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = m_xo.newCursor(); - m_xc.selectPath(ns+" .//po:shipTo/po:city"); - m_xc.toNextSelection(); - xc1.selectPath(ns+" .//po:billTo/po:city"); - xc1.toNextSelection(); - xc1.toNextToken(); - xc1.toNextChar(4); // should be at 'T' in "Old Town" - m_xc.copyXml(xc1); // should be "Old Mill ValleyTown" - // verify xc1 - xc1.toPrevToken(); - assertEquals(TokenType.END, xc1.currentTokenType()); - xc1.toPrevToken(); - assertEquals("Mill Valley", xc1.getChars()); - xc1.toPrevToken(); - assertEquals(TokenType.START, xc1.currentTokenType()); - assertEquals(new QName("city").getLocalPart(), - xc1.getName().getLocalPart()); - xc1.toPrevToken(); - assertEquals("Old ", xc1.getChars()); - // verify m_xc - assertEquals("Mill Valley", m_xc.xmlText()); - } - - - -} - diff --git a/test/src/xmlcursor/checkin/CopyXmlContentsTest.java b/test/src/xmlcursor/checkin/CopyXmlContentsTest.java deleted file mode 100755 index 20f1724..0000000 --- a/test/src/xmlcursor/checkin/CopyXmlContentsTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlObject; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; - - - -/** - * - * - */ -public class CopyXmlContentsTest extends BasicCursorTestCase { - public CopyXmlContentsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CopyXmlContentsTest.class); - } - - public void testCopyToNull() throws Exception { - - m_xc = XmlObject.Factory.parse(Common.XML_FOO_DIGITS).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.copyXmlContents(null); - fail("Expected IllegalArgumentException. Can't copy to foreign document"); - } catch (IllegalArgumentException ise) { - } - } - public void testCopyDifferentStoresLoadedByParseInvalidDest() throws Exception { - String sDoc1=Common.XML_FOO_DIGITS; - String sDoc2=Common.XML_FOO_2ATTR_TEXT; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - toNextTokenOfType(xc1, TokenType.START); - try{ - xc1.dispose(); - m_xc.copyXmlContents(xc1); - fail("Expected IllegalStateException. Destination cursor was disposed "); - } catch (IllegalStateException ise) { - } - } - public void testCopyDifferentStoresLoadedByParse() throws Exception { - String sDoc1=Common.XML_FOO_DIGITS; - String sDoc2=Common.XML_FOO_2ATTR_TEXT; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - toNextTokenOfType(xc1, TokenType.TEXT); - m_xc.copyXmlContents(xc1); - xc1.toParent(); - // verify xc1 - assertEquals("01234text", xc1.getTextValue()); - xc1.dispose(); - - System.out.println("test "+m_xc.xmlText()); - // verify m_xc - toNextTokenOfType(m_xc, TokenType.TEXT); //get to the text - assertEquals("01234", m_xc.getChars()); - } - - /* the source is not a container*/ - public void testCopyDifferentStoresLoadedByParseInvalidSrc() throws Exception { - String sDoc1=Common.XML_FOO_DIGITS; - String sDoc2=Common.XML_FOO_2ATTR_TEXT; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - toNextTokenOfType(xc1, TokenType.START); - boolean result=m_xc.copyXmlContents(xc1); - assertEquals(false, result); - - } - - /*public void testCopyOntoItself() throws Exception { - String sDoc1=Common.XML_FOO_DIGITS; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - String sExpectedXml=m_xc.xmlText(); - boolean result=m_xc.copyXmlContents(m_xc); - - //cursor is left immediately before copied material - assertEquals(sExpectedXml,m_xc.getTextValue()); - - } - */ - public void testCopySelf() throws Exception { - String sDoc1=Common.XML_FOO_DIGITS; - m_xo = XmlObject.Factory.parse(sDoc1); - m_xc=m_xo.newCursor(); - - toNextTokenOfType(m_xc, TokenType.START); - String sExpectedXml="0123401234"; - boolean result=m_xc.copyXmlContents(m_xc); - - //cursor is left immediately before copied material - m_xc.toStartDoc(); - //assertEquals(sExpectedXml.length(),m_xc.xmlText().length()); - assertEquals(sExpectedXml,m_xc.xmlText()); - } - - - /** - Can't really copy the whole doc, so copy all the contents - into a false root */ - public void testCopyWholeDoc() throws Exception { - String sDoc1=Common.XML_FOO_BAR_WS_TEXT; - String sDoc2=""; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - XmlCursor xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); - xc1.toFirstChild(); - String sExpectedXml=m_xc.xmlText(); - boolean result=m_xc.copyXmlContents(xc1); - toPrevTokenOfType(xc1,TokenType.STARTDOC); - toNextTokenOfType(xc1,TokenType.START); - assertEquals(sExpectedXml,xc1.xmlText()); - - //namespaces are not copied - sDoc1=Common.XML_FOO_NS_PREFIX; - sDoc2=""; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); - sExpectedXml=m_xc.xmlText(); - xc1.toFirstChild(); - - result=m_xc.copyXmlContents(xc1); - toPrevTokenOfType(xc1,TokenType.STARTDOC); - assertEquals(false,sExpectedXml.equals(xc1.xmlText())); - - //attributes are not copied - sDoc1=Common.XML_FOO_2ATTR; - sDoc2=""; - m_xc = XmlObject.Factory.parse(sDoc1).newCursor(); - xc1 = XmlObject.Factory.parse(sDoc2).newCursor(); - sExpectedXml=m_xc.xmlText(); - xc1.toFirstChild(); - - result=m_xc.copyXmlContents(xc1); - toPrevTokenOfType(xc1,TokenType.STARTDOC); - assertEquals(false,sExpectedXml.equals(xc1.xmlText())); - - } - - public static void main(String[] rgs){ - try{ - // (new CopyXmlContentsTest("")).testCopyOntoItself(); - (new CopyXmlContentsTest("")).testCopyWholeDoc(); - }catch(Exception e){System.err.println(e.getMessage());} - } - -} diff --git a/test/src/xmlcursor/checkin/CurrentTokenTypeTest.java b/test/src/xmlcursor/checkin/CurrentTokenTypeTest.java deleted file mode 100755 index 8c45b00..0000000 --- a/test/src/xmlcursor/checkin/CurrentTokenTypeTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; - - - -/** - * - * - */ -public class CurrentTokenTypeTest extends BasicCursorTestCase { - - String sInputDoc; - - public CurrentTokenTypeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CurrentTokenTypeTest.class); - } - /** - ATTR - COMMENT - END - ENDDOC - NAMESPACE - NONE - PROCINST - START - STARTDOC - TEXT - */ - - public void testAttrType() throws XmlException{ - sInputDoc=Common.XML_FOO_2ATTR_TEXT; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - assertEquals(m_xc.currentTokenType(),XmlCursor.TokenType.STARTDOC); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.START); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.ATTR); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.ATTR); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.TEXT); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.END); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.ENDDOC); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.NONE); - } - public void testCommentType()throws XmlException{ - sInputDoc=Common.XML_FOO_COMMENT; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - assertEquals(m_xc.currentTokenType(),XmlCursor.TokenType.STARTDOC); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.COMMENT); - } - public void testEndType(){ - //tested by testAttrType - } - public void testEndDocType(){ - //tested by testAttrType - } - public void testNamespaceType()throws XmlException{ - sInputDoc=Common.XML_FOO_NS_PREFIX ; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - - assertEquals(m_xc.currentTokenType(),XmlCursor.TokenType.STARTDOC); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.START); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.NAMESPACE); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.COMMENT); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.TEXT); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.START); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.ATTR); - - } - public void testNoneType()throws XmlException{ - sInputDoc=""; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - m_xc.toEndDoc(); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.NONE); - } - public void testProcinstType()throws XmlException{ - sInputDoc=Common.XML_FOO_PROCINST; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - assertEquals(m_xc.currentTokenType(),XmlCursor.TokenType.STARTDOC); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.PROCINST); - - } - public void testStartType(){ - //tested by testAttrType - } - public void testStartdocType(){ - //tested by testAttrType - } - public void testTextType()throws XmlException{ - sInputDoc="blahtest and some more test"+"\u042F\u0436\n\r"; - m_xc= XmlObject.Factory.parse(sInputDoc).newCursor(); - assertEquals(m_xc.currentTokenType(),XmlCursor.TokenType.STARTDOC); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.START); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.TEXT); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.START); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.TEXT); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.END); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.TEXT); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.END); - assertEquals(m_xc.toNextToken(),XmlCursor.TokenType.ENDDOC); - - } - - public static void main(String[] rgs){ - try{ - (new CurrentTokenTypeTest("")).testAttrType(); - }catch (Exception e){ - System.err.println(e.getMessage()); - } - } -} diff --git a/test/src/xmlcursor/checkin/DisposeTest.java b/test/src/xmlcursor/checkin/DisposeTest.java deleted file mode 100755 index 2c4b0d7..0000000 --- a/test/src/xmlcursor/checkin/DisposeTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class DisposeTest extends BasicCursorTestCase { - public DisposeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(DisposeTest.class); - } - - public void testMultipleDispose() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO); - m_xc = m_xo.newCursor(); - m_xc.dispose(); - m_xc.dispose(); - assertEquals(true, true); - } -} - diff --git a/test/src/xmlcursor/checkin/GetObjectTest.java b/test/src/xmlcursor/checkin/GetObjectTest.java deleted file mode 100755 index 35d4b8d..0000000 --- a/test/src/xmlcursor/checkin/GetObjectTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlNMTOKEN; -import org.apache.xmlbeans.XmlObject; -import tools.util.JarUtil; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; - - -/** - * - * - */ -public class GetObjectTest extends BasicCursorTestCase { - public GetObjectTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(GetObjectTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } - - public void testGetObjectFromSTARTDOC() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - assertEquals(true, - m_xc.getObject() instanceof CarLocationMessageDocument); - } - - public void testGetObjectFromSTART() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.toFirstChild(); - assertEquals(true, - m_xc.getObject() instanceof CarLocationMessageDocument.CarLocationMessage); - } - - public void testGetObjectFromATTR() throws Exception { - m_xo = - XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - m_xc = m_xo.newCursor(); - String sQuery= - "declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\"; "+ - "$this//po:shipTo"; - m_xc.selectPath( sQuery ); - m_xc.toNextSelection(); - m_xc.toFirstAttribute(); - assertEquals(true, m_xc.getObject() instanceof XmlNMTOKEN); - } - - public void testGetObjectFromEND() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.END); - assertEquals(null, m_xc.getObject()); - } - - public void testGetObjectFromENDDOC() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.toEndDoc(); - assertEquals(null, m_xc.getObject()); - } - - public void testGetObjectFromNAMESPACE() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.NAMESPACE); - assertEquals(null, m_xc.getObject()); - } - - public void testGetObjectFromPROCINST() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.PROCINST); - assertEquals(null, m_xc.getObject()); - } - - public void testGetObjectFromCOMMENT() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_COMMENT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.COMMENT); - assertEquals(null, m_xc.getObject()); - } - - public void testGetObjectFromTEXT() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(null, m_xc.getObject()); - } -} - diff --git a/test/src/xmlcursor/checkin/InsertAttributeTest.java b/test/src/xmlcursor/checkin/InsertAttributeTest.java deleted file mode 100755 index 07126ce..0000000 --- a/test/src/xmlcursor/checkin/InsertAttributeTest.java +++ /dev/null @@ -1,302 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class InsertAttributeTest extends BasicCursorTestCase { - public InsertAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertAttributeTest.class); - } - - public void testInsertAttributeAtSTART() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - m_xc.insertAttributeWithValue("name", "uri", "value"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeAtATTR() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - m_xc.insertAttributeWithValue("name", null, "value"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeAt2ndATTR() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - toNextTokenOfType(m_xc, TokenType.ATTR); - m_xc.insertAttributeWithValue("name", null, "value"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeAtPROCINST() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.PROCINST); - m_xc.toNextToken(); - try { - m_xc.insertAttributeWithValue("name", null, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - assertEquals(true, true); - } - - public void testInsertAttributeAtSTARTwithEmptyStringName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - try { - m_xc.insertAttributeWithValue("", "uri", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeAtSTARTwithNullName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - try { - m_xc.insertAttributeWithValue(null, "uri", "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeWithNullQName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - try { - QName name = new QName(null); - m_xc.insertAttribute(name); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeAtSTARTwithEmptyStringUri() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - m_xc.insertAttributeWithValue("name", "", "value"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeAtSTARTwithNameXml() throws Exception { - /* -m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); -m_xc = m_xo.newCursor(); -toNextTokenOfType(m_xc, TokenType.TEXT); -try -{ -m_xc.insertAttributeWithValue("xml", null, "value"); -fail("Expected IllegalArgumentException"); -} -catch (IllegalArgumentException iae) -{ -} -assertEquals(true,true); - */ - - try { - m_xo = XmlObject.Factory.parse("text"); - m_xc = m_xo.newCursor(); - m_xc.insertAttributeWithValue("xml", null, "value"); - fail("Expected Exception"); - } catch (Exception e) { - } - - assertTrue(true); - } - - public void testInsertAttributeAtSTARTwithValueXml() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - m_xc.insertAttributeWithValue("name", null, "xml"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeAtSTARTwithLTcharInName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.insertAttributeWithValue("text", m_xc.xmlText()); - } - - public void testInsertAttributeAtSTARTwithAmpCharInValue() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - m_xc.insertAttributeWithValue("name", null, "&value"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeAtSTARTwithAmpCharInName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - try { - m_xc.insertAttributeWithValue("&bar", null, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - // tests below use the XMLName form of the parameter signature - - public void testInsertAttributeType2AtATTR() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - QName name = new QName("name"); - m_xc.insertAttributeWithValue(name, "value"); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeType2AfterSTART() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - QName name = new QName("name"); - m_xc.insertAttributeWithValue(name, null); - m_xc.toStartDoc(); - assertEquals("text", m_xc.xmlText()); - } - - public void testInsertAttributeType2WithXMLinName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - QName name = new QName(""); - try { - m_xc.insertAttributeWithValue(name, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeType2WithLeadingSpaceinName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - QName name = new QName(" any"); - try { - m_xc.insertAttributeWithValue(name, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeType2ContainingSpaceinName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - QName name = new QName("any any"); - try { - m_xc.insertAttributeWithValue(name, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeType2WithTrailingSpaceinName() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - QName name = new QName("any "); - try { - m_xc.insertAttributeWithValue(name, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } - - public void testInsertAttributeType2WithXMLinNameCase() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - QName name = new QName(""); - try { - m_xc.insertAttributeWithValue(name, "value"); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertEquals(true, true); - } -} - diff --git a/test/src/xmlcursor/checkin/IsAtSamePositionAsTest.java b/test/src/xmlcursor/checkin/IsAtSamePositionAsTest.java deleted file mode 100755 index 76c3607..0000000 --- a/test/src/xmlcursor/checkin/IsAtSamePositionAsTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ - -public class IsAtSamePositionAsTest extends BasicCursorTestCase{ - - static String sDoc=Common.XML_FOO_DIGITS; - - public IsAtSamePositionAsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(IsAtSamePositionAsTest.class); - } - public void testNormalCase(){ - XmlCursor m_xc1=m_xo.newCursor();; //parse - m_xc.toFirstChild(); - m_xc1.toFirstChild(); - assertEquals(true,m_xc.isAtSamePositionAs(m_xc1)); - } - - public void testSamePosDiffDoc()throws Exception{ - XmlCursor m_xc1=XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - m_xc1.toFirstChild(); - try{ - assertEquals(false,m_xc.isAtSamePositionAs(m_xc1)); - fail("Cursors are in different docs"); - }catch (IllegalArgumentException e){} - } - public void testDiffPosSameDoc()throws Exception{ - XmlCursor m_xc1=m_xo.newCursor(); - m_xc.toFirstChild(); - m_xc1.toFirstChild(); - m_xc1.toFirstAttribute(); - assertEquals(false,m_xc.isAtSamePositionAs(m_xc1)); - } - - public void testNull(){ - try { - assertEquals(false,m_xc.isAtSamePositionAs(null)); - fail("Other cursor is Null"); - }catch(Exception e){ - } - } - - public void testSelf(){ - m_xc.toFirstChild(); - assertEquals(true,m_xc.isAtSamePositionAs(m_xc)); - } - - public void setUp()throws Exception{ - m_xo=XmlObject.Factory.parse(sDoc); - m_xc=m_xo.newCursor(); - } - - public static void main(String[] rgs){ - try{ - IsAtSamePositionAsTest t=new IsAtSamePositionAsTest(""); - t.setUp(); - t.testNormalCase(); - }catch (Exception e){ - System.err.println("Error "+e.getMessage()); - e.printStackTrace(); - } - } - -} diff --git a/test/src/xmlcursor/checkin/PrevTokenTypeTest.java b/test/src/xmlcursor/checkin/PrevTokenTypeTest.java deleted file mode 100755 index 18b7dbd..0000000 --- a/test/src/xmlcursor/checkin/PrevTokenTypeTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class PrevTokenTypeTest extends BasicCursorTestCase { - - String sDoc=" 32.18"; - - public PrevTokenTypeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(PrevTokenTypeTest.class); - } - - public void testAllTokensTest(){ - m_xc.toEndDoc(); - assertEquals(true,m_xc.isEnddoc()); - assertEquals(true,m_xc.isFinish()); - assertEquals(TokenType.END,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isEnd()); - assertEquals(true,m_xc.isFinish()); - assertEquals(TokenType.END,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - - assertEquals(true,m_xc.isEnd()); - assertEquals(TokenType.TEXT,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isText()); - assertEquals(false,m_xc.isContainer()); - assertEquals(TokenType.ATTR,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isAttr()); - assertEquals(true,m_xc.isAnyAttr()); - assertEquals(TokenType.ATTR,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isAttr()); - assertEquals(true,m_xc.isAnyAttr()); - assertEquals(TokenType.START,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isStart()); - assertEquals(true,m_xc.isContainer()); - assertEquals(TokenType.TEXT,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isText()); - assertEquals(TokenType.COMMENT,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isComment()); - assertEquals(TokenType.PROCINST,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isProcinst()); - assertEquals(TokenType.NAMESPACE,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isNamespace()); - assertEquals(true,m_xc.isAnyAttr()); - assertEquals(false,m_xc.isAttr()); - assertEquals(TokenType.START,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isStart()); - assertEquals(true,m_xc.isContainer()); - assertEquals(TokenType.STARTDOC,m_xc.prevTokenType()); - m_xc.toPrevToken(); - - assertEquals(true,m_xc.isStartdoc()); - assertEquals(true,m_xc.isContainer()); - assertEquals(TokenType.NONE,m_xc.prevTokenType()); - //assert won't move further - assertEquals(TokenType.NONE,m_xc.toPrevToken()); - assertEquals(true,m_xc.isStartdoc()); - } - - - public void setUp() throws Exception{ - m_xc=XmlObject.Factory.parse(sDoc).newCursor(); - } -} diff --git a/test/src/xmlcursor/checkin/RemoveAttributeTest.java b/test/src/xmlcursor/checkin/RemoveAttributeTest.java deleted file mode 100755 index 753fd43..0000000 --- a/test/src/xmlcursor/checkin/RemoveAttributeTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class RemoveAttributeTest extends BasicCursorTestCase { - public RemoveAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(RemoveAttributeTest.class); - } - - public void testRemoveAttributeValidAttrFromSTART() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - QName name = new QName("attr1"); - assertEquals(true, m_xc.removeAttribute(name)); - assertEquals(null, m_xc.getAttributeText(name)); - } - - public void testRemoveAttributeInvalidAttrFromSTART() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - QName name = new QName("invalid"); - assertEquals(false, m_xc.removeAttribute(name)); - } - - public void testRemoveAttributeNullAttrFromSTART() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - QName name = new QName("dummy"); - try { - assertEquals(false, m_xc.removeAttribute(null)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - assertTrue(true); - } - - public void testRemoveAttributeFromPROCINST() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_PROCINST); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.PROCINST); - QName name = new QName("type"); - assertEquals(false, m_xc.removeAttribute(name)); - } - - public void testRemoveAttributeXMLNS() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_DIGITS); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - QName name = new QName("xmlns"); - assertEquals(false, m_xc.removeAttribute(name)); - } - - public void testRemoveAttributeFromEND() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.END); - QName name = new QName("attr1"); - assertEquals(false, m_xc.removeAttribute(name)); - } -} - diff --git a/test/src/xmlcursor/checkin/SelectPathTest.java b/test/src/xmlcursor/checkin/SelectPathTest.java deleted file mode 100755 index da15dcd..0000000 --- a/test/src/xmlcursor/checkin/SelectPathTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import xmlcursor.common.*; - -import tools.util.JarUtil; - - -/** - * - * - */ -public class SelectPathTest extends BasicCursorTestCase { - public SelectPathTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SelectPathTest.class); - } - - /** - *$BUGBUG: Eric's engine doesn't send to Jaxen appropriately - * - public void testSelectPathFromEND() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.XMLCASES_JAR, - Common.TRANXML_FILE_XMLCURSOR_PO)); - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.END); - m_xc.selectPath(ns+" $this//city"); - assertEquals(0, m_xc.getSelectionCount()); - } - - public void testSelectPathFromENDDOC() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.XMLCASES_JAR, - Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xc = m_xo.newCursor(); - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; - toNextTokenOfType(m_xc, TokenType.ENDDOC); - m_xc.selectPath(ns+" .//po:city"); - assertEquals(0, m_xc.getSelectionCount()); - } - */ - public void testSelectPathNamespace() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - String sLocalPath =".//FleetID"; - m_xc.selectPath(sLocalPath); - assertEquals(0, m_xc.getSelectionCount()); - m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - sLocalPath); - assertEquals(1, m_xc.getSelectionCount()); - } - - public void testSelectPathCaseSensitive() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xc = m_xo.newCursor(); - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\";"; - m_xc.selectPath(ns+" .//po:ciTy"); - assertEquals(0, m_xc.getSelectionCount()); - m_xc.selectPath(ns+" .//po:city"); - assertEquals(2, m_xc.getSelectionCount()); - } - - public void testSelectPathReservedKeyword() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xc = m_xo.newCursor(); - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\";"; - m_xc.selectPath(ns+" .//po:item"); - assertEquals(2, m_xc.getSelectionCount()); - } - - public void testSelectPathNull() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xc = m_xo.newCursor(); - // TODO: surround with appropriate t-c once ericvas creates the exception type - // see bugs 18009 and/or 18718 - try { - m_xc.selectPath(null); - fail("Expected RuntimeException"); - } catch (RuntimeException re) { - } - assertTrue(true); - } - - public void testSelectPathInvalidXPath() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xc = m_xo.newCursor(); - // TODO: surround with appropriate t-c once ericvas creates the exception type - // see bugs 18009 and/or 18718 - try { - m_xc.selectPath("&GARBAGE"); - assertEquals(0,m_xc.getSelectionCount()); - fail("Expected RuntimeException"); - } catch (RuntimeException re) { - } - assertTrue(true); - } - -} - diff --git a/test/src/xmlcursor/checkin/SetNameTest.java b/test/src/xmlcursor/checkin/SetNameTest.java deleted file mode 100755 index 0fa7208..0000000 --- a/test/src/xmlcursor/checkin/SetNameTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ - -public class SetNameTest extends BasicCursorTestCase{ - String sTestXml="text0"; - - - public SetNameTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SetNameTest.class); - } - - - public void testNormalCase(){ - m_xc.toFirstChild(); - QName newName=new QName("newBook"); - m_xc.setName(newName); - assertEquals(m_xc.getName(),newName); - - newName=new QName("uri:newUri","newBook"); - m_xc.setName(newName); - assertEquals(m_xc.getName(),newName); - - - newName=new QName("uri:newUri","newBook","prefix"); - m_xc.setName(newName); - assertEquals(m_xc.getName(),newName); - - //should work for attrs too... - m_xc.toFirstAttribute(); - newName=new QName("uri:newUri","newBook","prefix"); - m_xc.setName(newName); - assertEquals(m_xc.getName(),newName); - } - - public void testNoUri(){ - m_xc.toFirstChild(); - QName newName=new QName(null,"newBook"); - m_xc.setName(newName); - assertEquals(m_xc.getName().getLocalPart(),"newBook"); - } - - public void testNull(){ - m_xc.toFirstChild(); - try{ - m_xc.setName(null); - fail("QName null"); - }catch(Exception e){ - System.err.println(e.getMessage()); - } - - } - - public void setUp()throws Exception{ - m_xc=XmlObject.Factory.parse(sTestXml).newCursor(); - } - - - public static void main(String[]rgs){ - try{ - SetNameTest myTest=new SetNameTest(""); - myTest.setUp(); - myTest.testNormalCase(); - myTest.setUp(); - myTest.testNoUri(); - myTest.setUp(); - myTest.testNull(); - - }catch(Exception e){ - System.err.println(e.getMessage()); - } - } -} diff --git a/test/src/xmlcursor/checkin/StoreTests.java b/test/src/xmlcursor/checkin/StoreTests.java deleted file mode 100755 index 80ab820..0000000 --- a/test/src/xmlcursor/checkin/StoreTests.java +++ /dev/null @@ -1,2312 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlSaxHandler; -import org.apache.xmlbeans.XmlLineNumber; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.impl.common.XmlNameImpl; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.Iterator; -import java.util.TreeSet; -import javax.xml.namespace.QName; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.apache.xmlbeans.xml.stream.Attribute; -import org.apache.xmlbeans.xml.stream.AttributeIterator; -import org.apache.xmlbeans.xml.stream.ChangePrefixMapping; -import org.apache.xmlbeans.xml.stream.CharacterData; -import org.apache.xmlbeans.xml.stream.Comment; -import org.apache.xmlbeans.xml.stream.EndDocument; -import org.apache.xmlbeans.xml.stream.EndElement; -import org.apache.xmlbeans.xml.stream.EndPrefixMapping; -import org.apache.xmlbeans.xml.stream.StartDocument; -import org.apache.xmlbeans.xml.stream.StartElement; -import org.apache.xmlbeans.xml.stream.StartPrefixMapping; -import org.apache.xmlbeans.xml.stream.XMLEvent; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLName; - - -import xmlcursor.common.Common; - -public class StoreTests extends TestCase -{ - public StoreTests(String name) { super(name); } - public static Test suite() { return new TestSuite(StoreTests.class); } - - static String[] _args; - static String _test; - - - - private void streamTest ( String xml ) - throws Exception - { - XmlObject x1 = XmlObject.Factory.parse( xml ); - XmlObject x2 = XmlObject.Factory.parse( x1.newCursor().newXMLStreamReader() ); - - String x1Text = x1.xmlText(); - String x2Text = x2.xmlText(); - - Assert.assertTrue( x1Text.equals( x2Text ) ); - } - - public void testXMLStreamReader ( ) - throws Exception - { - streamTest( "" ); - streamTest( "" ); - streamTest( "foo" ); - streamTest( "foodsfdf" ); - streamTest( "" ); - streamTest( "xz" ); - streamTest( "moo" ); - streamTest( "asasdsdaazadsasd" ); - streamTest( "" ); - streamTest( "" ); - streamTest( "" ); - streamTest( "1" ); - streamTest( "" ); - streamTest( "abcde" ); - streamTest( "" ); - streamTest( "" ); - } - - public void testReplaceContents ( ) - throws Exception - { - XmlObject xDst = XmlObject.Factory.newInstance(); - XmlObject xSrc = XmlObject.Factory.parse( "" ); - XmlObject newDst = xDst.set( xSrc ); - Assert.assertTrue( newDst.xmlText().equals( "" ) ); - - xDst = XmlObject.Factory.parse( "" ); - xSrc = XmlObject.Factory.parse( "" ); - XmlCursor c = xDst.newCursor(); - c.toNextToken(); - xDst = c.getObject(); - xDst.set( xSrc ); - c.toStartDoc(); - xDst = c.getObject(); - Assert.assertTrue( xDst.xmlText().equals( "" ) ); - - xDst = XmlObject.Factory.parse( "" ); - xSrc = XmlObject.Factory.parse( "moo" ); - c = xDst.newCursor(); - c.toNextToken(); - c.toNextToken(); - xDst = c.getObject(); - xDst.set( xSrc ); - c.toStartDoc(); - xDst = c.getObject(); - Assert.assertTrue( xDst.xmlText().equals( "" ) ); - } - - public void testSniffing ( ) - throws Exception - { - XmlObject x; - - x = XmlObject.Factory.parse( "" ); - Assert.assertTrue( x.schemaType() == XmlBeans.NO_TYPE ); - - x = XmlObject.Factory.parse( - "" ); - Assert.assertTrue( - x.schemaType() == org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.type ); - - x = XmlObject.Factory.parse( - "" ); - Assert.assertTrue( x.schemaType() == XmlBeans.NO_TYPE ); - - x = XmlObject.Factory.parse( - "" ); - Assert.assertTrue( - x.schemaType() == org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.type ); - - x = org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Factory.parse( - "" ); - Assert.assertTrue( - x.schemaType() == org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.type ); - - try { - x = - org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Factory.parse( - "" ); - Assert.assertTrue( false ); - } - catch ( Throwable e ) { } - } - - public void testCursorStack ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "" ); - XmlCursor c = x.newCursor(); - c.push(); - c.toNextToken(); - c.push(); - c.toNextToken(); - Assert.assertTrue( c.isAttr() ); - c.pop(); - Assert.assertTrue( c.isStart() ); - c.pop(); - Assert.assertTrue( c.isStartdoc() ); - } - - public void testImplicitNamespaces ( ) - throws Exception - { - Map namespaces = new HashMap(); - namespaces.put( "foo", "foo.com" ); - namespaces.put( "bar", "bar.com" ); - namespaces.put( "", "default.com" ); - - XmlOptions options = new XmlOptions(); - options.put( XmlOptions.SAVE_IMPLICIT_NAMESPACES, namespaces ); - - XmlObject x = XmlObject.Factory.newInstance(); - XmlCursor c = x.newCursor(); - - c.toNextToken(); - - c.beginElement( "a", "foo.com" ); - c.beginElement( "b", "default.com" ); - c.beginElement( "c", "bar.com" ); - - Assert.assertTrue( - x.xmlText( options ).equals( "" ) ); - } - - private static class Content implements ContentHandler, LexicalHandler - { - public void startDocument ( ) throws SAXException - { - add( "START_DOCUMENT" ); - } - - public void endDocument ( ) throws SAXException - { - add( "END_DOCUMENT" ); - } - - public void startElement ( - String namespaceURI, String localName, - String qName, Attributes atts ) - throws SAXException - { - add( "START_ELEMENT" ); - add( " namespaceURI: " + namespaceURI ); - add( " localName: " + localName ); -// add( " qName: " + qName ); - - TreeSet sortedAttrs = new TreeSet(); - - for ( int i = 0 ; i < atts.getLength() ; i++ ) - { - String ln = atts.getLocalName( i ); - String uri = atts.getURI( i ); - String qname = atts.getQName( i ); - - if (ln.equals("xmlns")) - continue; - if (qname.startsWith("xmlns")) - continue; - -// if (ln.equals( "xmlns" )) -// ln = ""; -// -// if (uri.equals( "xmlns" )) -// uri = ""; - - sortedAttrs.add( - uri + "-" + ln + "-" + - atts.getQName( i ) + "-" + atts.getType( i ) + "-" + - atts.getValue( i ) ); - } - - for ( Iterator i = sortedAttrs.iterator() ; i.hasNext() ; ) - add( " Attr: " + i.next() ); - } - - public void endElement ( - String namespaceURI, String localName, String qName ) - throws SAXException - { - add( "END_ELEMENT" ); - add( " namespaceURI: " + namespaceURI ); - add( " localName: " + localName ); -// add( " qName: " + qName ); - } - - public void characters ( char ch[], int start, int length ) - throws SAXException - { - if (length > 0) - { - add( "CHARACTERS" ); - add( ch, start, length ); - } - } - - public void comment ( char ch[], int start, int length ) - throws SAXException - { - add( "COMMENT" ); - add( " Comment: ", ch, start, length ); - } - - public void processingInstruction ( String target, String data ) - throws SAXException - { - add( "PROCESSING_INSTRUCTION" ); - add( "target: " + target ); - add( "data: " + data ); - } - - public void ignorableWhitespace ( char ch[], int start, int length ) - throws SAXException - { - if (length > 0) - { - add( "IGNORABLE_WHITESPACE" ); - add( " whitespace: ", ch, start, length ); - } - } - - public void startPrefixMapping ( String prefix, String uri ) - throws SAXException - { - add( "START_PREFIX_MAPPING" ); -// add( " prefix: " + prefix ); - add( " uri: " + uri ); - } - - public void endPrefixMapping ( String prefix ) throws SAXException - { - add( "END_PREFIX_MAPPING" ); -// add( " prefix: " + prefix ); - } - - public void startCDATA ( ) throws SAXException - { - add( "START_CDATA" ); - } - - public void endCDATA ( ) throws SAXException - { - add( "END_CDATA" ); - } - - public void startDTD ( String name, String publicId, String systemId ) - throws SAXException - { - add( "START_DTD" ); - add( " name: " + name ); - add( " publicId: " + publicId ); - add( " systemId: " + systemId ); - } - - public void endDTD ( ) throws SAXException - { - add( "END_DTD" ); - } - - public void startEntity ( String name ) throws SAXException - { - add( "START_ENTITY" ); - add( " name: " + name ); - } - - public void endEntity ( String name ) throws SAXException - { - add( "END_ENTITY" ); - add( " name: " + name ); - } - - public void setDocumentLocator ( Locator locator ) - { - // add( "START_DOCUMENT_LOCATOR" ); - } - - public void skippedEntity ( String name ) throws SAXException - { - add( "SKIPPED_ENTITY" ); - add( " name: " + name ); - } - - private void add ( String s ) - { - _sb.append( s ); - _sb.append( "\n" ); - } - - private void add ( String s, char[] buf, int off, int cch ) - { - _sb.append( s ); - if (buf != null) - _sb.append( buf, off, cch ); - _sb.append( "\n" ); - } - - private void add ( char[] buf, int off, int cch ) - { - _sb.append( buf, off, cch ); - _sb.append( "\n" ); - } - - public boolean equals ( Object that ) - { - return toString().equals( that.toString() ); - } - - public String toString ( ) - { - return _sb.toString(); - } - - private StringBuffer _sb = new StringBuffer(); - } - - public void doTestSaxSaver ( String xml ) - throws Exception - { - // ME - - Content content2 = new Content(); - - XmlObject x = XmlObject.Factory.parse( xml ); - - x.save( content2, content2 ); - - // THEM - - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser sp = spf.newSAXParser(); - - XMLReader xr = sp.getXMLReader(); - - Content content1 = new Content(); - - xr.setProperty( "http://xml.org/sax/properties/lexical-handler", content1 ); - xr.setFeature( "http://xml.org/sax/features/namespace-prefixes", true ); - xr.setFeature( "http://xml.org/sax/features/namespaces", true ); - xr.setFeature( "http://xml.org/sax/features/validation", false ); - - xr.setContentHandler( content1 ); - - InputSource is = new InputSource( new StringReader( xml ) ); - - xr.parse( is ); - - - if (!content1.equals( content2 )) - { - System.err.println( "SAX save failure: " ); - System.err.println( xml ); - System.err.println(); - - System.err.println( "SAX: " ); - System.err.println( content1.toString() ); - System.err.println(); - - System.err.println( "ME: " ); - System.err.println( content2.toString() ); - System.err.println(); - - Assert.assertTrue( false ); - } - } - - public void testSaxSaver ( ) - throws Exception - { - doTestSaxSaver( "" ); - doTestSaxSaver( "xz" ); - doTestSaxSaver( "moo" ); - doTestSaxSaver( "asasdsdaazadsasd" ); - doTestSaxSaver( "" ); - doTestSaxSaver( "" ); - doTestSaxSaver( "" ); - } - - public void __testParsing ( ) - throws Exception - { - Random r = new Random( 1 ); - - for ( int i = 0 ; i < 100000 ; i++ ) - { - String xml = makeRandomDocument( r ); - -// System.err.println( "Starting..." ); -// -// System.err.println( xml ); - - try - { - XmlObject.Factory.parse( xml ); - } - catch ( Throwable e ) - { - System.err.println( "Failed parse test:" ); - e.printStackTrace(); - System.err.println( xml ); - - OutputStream os = new FileOutputStream( "c:\\ee.xml" ); - PrintStream ps = new PrintStream( os ); - ps.println( xml ); - ps.close(); - os.close(); - - throw (RuntimeException) e; - } - -// System.err.println( "Finished..." ); - } - } - - public void doTestLineNumbers ( String xml ) - throws Exception - { - int line = 1; - int col = 1; - - XmlCursor c = - XmlObject.Factory.parse( - xml, new XmlOptions().setLoadLineNumbers() ). - newCursor(); - - for ( int i = 0 ; i < xml.length() ; i++ ) - { - char ch = xml.charAt( i ); - - if (ch == '<' && Character.isLetter( xml.charAt( i + 1 ) ) ) - { - while (!c.currentTokenType().isStart()) - c.toNextToken(); - - Assert.assertTrue( c.currentTokenType().isStart() ); - - XmlLineNumber ln = - (XmlLineNumber) - c.getBookmark( XmlLineNumber.class ); - - Assert.assertTrue( ln != null ); - - Assert.assertTrue( ln.getLine() == -1 || ln.getLine() == line ); - Assert.assertTrue( ln.getColumn() == -1 || ln.getColumn() == col ); - Assert.assertTrue( ln.getOffset() == -1 || ln.getOffset() == i ); - - c.toNextToken(); - } - - if (ch == '\n') - { - line++; - col= 1; - } - else - col++; - } - } - - public void __testLineNumbers ( ) - throws Exception - { - Random r = new Random( 1 ); - - for ( int i = 0 ; i < 1000 ; i++ ) - { - String xml = makeRandomDocument( r ); - -// System.err.println( "Starting..." ); -// -// System.err.println( xml ); - - try - { - doTestLineNumbers( xml ); - } - catch ( Throwable e ) - { - System.err.println( "Failed line number test:" ); - System.err.println( xml ); - - OutputStream os = new FileOutputStream( "c:\\ee.xml" ); - PrintStream ps = new PrintStream( os ); - ps.println( xml ); - ps.close(); - os.close(); - - throw (RuntimeException) e; - } - -// System.err.println( "Finished..." ); - } - } - - private static class DocBuilder - { - Random r; - StringBuffer sb; - - DocBuilder ( Random _r, StringBuffer _sb ) - { - r = _r; - sb = _sb; - } - - void append ( char ch ) - { - sb.append( ch ); - } - - void append ( String s ) - { - sb.append( s ); - } - - public void whitespace ( ) - { - int p = r.nextInt( 100 ); - - if (p < 20) - append( '\t' ); - else if (p < 40) - append( '\n' ); - else - append( ' ' ); - } - - public void whitespaces ( ) - { - for ( int i = r.nextInt( 8 ) ; i > 0 ; i-- ) - whitespace(); - } - - public char makeLetter ( ) - { - return (char) (((int) 'a') + r.nextInt( 26 )); - } - - public void letter ( ) - { - append( makeLetter() ); - } - - public void charEntity ( ) - { - switch ( r.nextInt( 5 ) ) - { - case 0 : append( "<" ); break; - case 1 : append( ">" ); break; - case 2 : append( "&" ); break; - case 3 : append( "'" ); break; - case 4 : append( """ ); break; - } - } - - public void text ( ) - { - for ( int i = r.nextInt( 20 ) ; i > 0 ; i-- ) - { - int p = r.nextInt( 100 ); - - if (p < 70) - letter(); - else if (p < 74) - charEntity(); - else - whitespace(); - } - } - - public String makeNcName ( ) - { - StringBuffer name = new StringBuffer(); - - for ( ; ; ) - { - char ch = makeLetter(); - - if (ch == 'x' || ch == 'X') - continue; - - name.append( ch ); - - break; - } - - for ( int i = r.nextInt( 20 ) ; i > 0 ; i-- ) - name.append( makeLetter() ); - - return name.toString(); - } - - public void ncName ( ) - { - append( makeNcName() ); - } - - public void comment ( ) - { - append( "" ); - } - - public void procinst ( ) - { - append( "" ); - } - - public void whiteContent ( ) - { - for ( ; ; ) - { - int p = r.nextInt( 100 ); - - if (p < 20) - break; - else if (p < 50) - whitespaces(); - else if (p < 70) - comment(); - else - procinst(); - } - } - - public void xmlDecl ( ) - { - append( "" ); - } - - public void content ( int depth ) - { - for ( int i = r.nextInt( 10 ) ; i > 0 ; i-- ) - { - switch ( r.nextInt( 4 ) ) - { - case 0 : - elementContent( depth + 1 ); - break; - - case 1 : text(); break; - case 2 : comment(); break; - case 3 : procinst(); break; - } - } - } - - public void attribute ( ) - { - ncName(); - - if (r.nextInt( 100 ) == 0) - whitespaces(); - - append( '=' ); - - if (r.nextInt( 100 ) == 0) - whitespaces(); - - char q = r.nextInt( 2 ) == 0 ? '\'' : '"'; - - append( q ); - - text(); - - append( q ); - } - - public void elementContent ( int depth ) - { - // If depth == 0, guarantee an element, otherwise, as depth - // increases, the probablility we'll spit out an element - // gets smaller. - - if (r.nextInt( depth + 1 ) <= 1) - { - String name = makeNcName(); - - append( '<' ); - append( name ); - - if (r.nextInt( 100 ) == 0) - whitespaces(); - - HashMap attrs = new HashMap(); - - for ( int i = r.nextInt( 3 ) ; i > 0 ; i-- ) - { - append( ' ' ); - - String aname; - - for ( ; ; ) - { - aname = makeNcName(); - - if (!attrs.containsKey( aname )) - break; - } - - attrs.put( aname, null ); - - append( aname ); - - if (r.nextInt( 100 ) == 0) - whitespaces(); - - append( '=' ); - - if (r.nextInt( 100 ) == 0) - whitespaces(); - - char q = r.nextInt( 2 ) == 0 ? '\'' : '"'; - - append( q ); - - text(); - - append( q ); - - if (r.nextInt( 10 ) == 0) - whitespaces(); - } - - append( '>' ); - - content( depth ); - - append( "' ); - } - } - - public void document ( ) - { - if (r.nextInt( 2 ) == 0) - xmlDecl(); - - whiteContent(); - - elementContent( 0 ); - - whiteContent(); - } - } - - public String makeRandomDocument ( Random r ) - { - StringBuffer sb = new StringBuffer(); - - DocBuilder db = new DocBuilder( r, sb ); - - db.document(); - - return sb.toString(); - } - - /*public void testThatAssertIsOn ( ) - { - try - { - assert false; - - Assert.assertTrue( false ); - } - catch ( Throwable e ) - { - } - } - */ - static class MyMark extends XmlBookmark - { - } - - public void testBookmarks ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "abcdefgxy" ); - - XmlCursor c = x.newCursor(); - MyMark m1 = new MyMark(); c.setBookmark( m1 ); - - c.toNextToken(); - MyMark m2 = new MyMark(); c.setBookmark( m2 ); - - c.toNextToken(); - MyMark m3 = new MyMark(); c.setBookmark( m3 ); - - c.toNextToken(); - MyMark m4 = new MyMark(); c.setBookmark( m4 ); - - c.toNextChar( 1 ); - MyMark m5 = new MyMark(); c.setBookmark( m5 ); - - c.toNextChar( 3 ); - MyMark m6 = new MyMark(); c.setBookmark( m6 ); - - c.toNextToken(); - c.toNextToken(); - c.toNextToken(); - MyMark m7 = new MyMark(); c.setBookmark( m7 ); - - c.toNextToken(); - MyMark m8 = new MyMark(); c.setBookmark( m8 ); - - c.toStartDoc(); - - Assert.assertTrue( c.getBookmark ( MyMark.class ) == m1 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m2 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m3 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m4 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m5 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m6 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m7 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == m8 ); - Assert.assertTrue( c.toNextBookmark( MyMark.class ) == null ); - - c.toEndDoc(); - - Assert.assertTrue( c.getBookmark ( MyMark.class ) == m8 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m7 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m6 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m5 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m4 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m3 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m2 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == m1 ); - Assert.assertTrue( c.toPrevBookmark( MyMark.class ) == null ); - } - - public void testSetName( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "" ); - XmlCursor c = x.newCursor(); - c.toNextToken(); - c.setName( new QName( "bar" ) ); - c.toNextToken(); - c.setName( new QName( "y" ) ); - - Assert.assertTrue( x.xmlText().equals( "" ) ); - } - - // - // Basic load up a file and iterate through it - // - - - public void testBasicXml( ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); - - int n = 0; - - for ( ; ; ) - { - TokenType t = c.toNextToken(); - - n++; - - if (t == TokenType.NONE) - break; - } - - Assert.assertTrue( n == 6 ); - } - - // - // Make sure the tokens going forward the the reverse of the tokens - // going backward - // - - public void testConsistentTokenOrder( ) - throws Exception - { - ArrayList l = new ArrayList(); - - XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); - - - for ( ; ; ) - { - // System.err.println(c.currentTokenType()); - l.add(c.currentTokenType()); - - if (c.toNextToken() == TokenType.NONE) - break; - } - - c.toEndDoc(); - // System.err.println("Reversing"); - - for ( int i = l.size() - 1 ; ; i-- ) - { - // System.err.println(c.currentTokenType()); - Assert.assertEquals(l.get(i), c.currentTokenType()); - - if (c.toPrevToken() == TokenType.NONE) - break; - } - } - - // - // Make sure you can't insert text before the doc begin - // going backward - // - - public void testIllegalTextInsert( ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); - - - try - { - c.insertChars( "Ho ho ho" ); - } - catch (IllegalStateException e) - { - return; - } - - Assert.assertTrue("Did not catch IllegalStateException", false); - } - - // - // Make sure getText works in a basic way - // - - public void testgetText( ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse(Common.XML_ATTR_TEXT, null).newCursor(); - - - Assert.assertTrue( c.getTextValue().equals( "ab" ) ); // Doc node - - c.toNextToken(); - Assert.assertTrue( c.getTextValue().equals( "ab" ) ); // Doc elem - - c.toNextToken(); - Assert.assertTrue( c.getTextValue().equals( "y" ) ); // Attr x - - c.toNextToken(); - Assert.assertTrue( c.getChars().equals( "ab" ) ); // Text - - c.toNextChar( 1 ); - Assert.assertTrue( c.getChars().equals( "b" ) ); // Text - - c.toNextToken(); - Assert.assertTrue( c.getChars().length() == 0 ); // End tag - - c.toNextToken(); - Assert.assertTrue( c.getChars().length() == 0 ); // End doc - } - - // - // Text XMLInputStream support - // - - private void assertName ( - XMLName name, String uri, String local, String prefix ) - { - Assert.assertTrue( local != null ); - - String nameUri = name.getNamespaceUri(); - String nameLocal = name.getLocalName(); - String namePrefix = name.getPrefix(); - - if (uri == null) - Assert.assertTrue( nameUri == null ); - else - Assert.assertTrue( nameUri.equals( uri ) ); - - if (local == null) - Assert.assertTrue( nameLocal == null ); - else - Assert.assertTrue( nameLocal.equals( local ) ); - - if (prefix == null) - Assert.assertTrue( namePrefix == null ); - else - Assert.assertTrue( namePrefix.equals( prefix ) ); - - if (prefix != null) - { - String qName = prefix + ":" + local; - Assert.assertTrue( name.getQualifiedName().equals( qName ) ); - } - else - Assert.assertTrue( name.getQualifiedName().equals( local ) ); - } - - private void doXmlStreamTest ( String xml ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse( xml ).newCursor(); - XMLInputStream xmlStream = c.newXMLInputStream(); - XmlObject o = XmlObject.Factory.parse( xmlStream ); - Assert.assertTrue( o.xmlText().equals( xml ) ); - } - - private void doSaverTest ( String xml ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse( xml ).newCursor(); - Assert.assertEquals( xml, c.xmlText() ); - } - - private void doSaveTest ( String xml ) - throws Exception - { - doSaverTest( xml ); - } - - public void testCDATA() throws Exception - { - // https://issues.apache.org/jira/browse/XMLBEANS-404 - String xml = "Unable to render embedded object: >>>>>>><<<<<<<<<<<]]>"; - String expected = ">>>>>>><<<<<<<<<<<]]>"; - XmlOptions options = new XmlOptions().setSaveCDataLengthThreshold(0); - XmlCursor c = XmlObject.Factory.parse(xml, options).newCursor(); - Assert.assertEquals( expected, c.xmlText(options) ); - } - - public void testSaving ( ) - throws Exception - { - doSaveTest( "1" ); - doSaveTest( "" ); - doSaveTest( "abcde" ); - doSaveTest( "" ); - doSaveTest( "" ); - - String s = "aaabbb"; - s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s; - s = "xxxx" + s + ""; - - doSaveTest( s ); - - XmlObject x = - XmlObject.Factory.parse( "" ); - - XmlCursor c = x.newCursor(); - - c.toFirstChild(); - c.toFirstChild(); - - Assert.assertTrue( c.xmlText().equals( "" ) ); - - x = XmlObject.Factory.parse( "" ); - - c = x.newCursor(); - - c.toFirstChild(); - c.toFirstChild(); - - Assert.assertTrue( c.xmlText().equals( "" ) ); - } - - - private XmlCursor navDoc ( XmlObject x, String dirs ) - { - return navCursor( x.newCursor(), dirs ); - } - - private XmlCursor navNewCursor ( XmlCursor c, String dirs ) - { - return navCursor( c.newCursor(), dirs ); - } - - // - // Format: - // - // ( [-][N] type ) * - // - // type: - // - // c - character - // t - token - // p - parent element - // s - sibling element - // d - descendent (child) element - // r - end of the doc (root) - // b - begin of the doc - // - - private XmlCursor navCursor ( XmlCursor c, String dirs ) - { - int n = 0; - boolean prev = false; - - for ( int i = 0 ; i < dirs.length() ; i++ ) - { - char ch = dirs.charAt( i ); - - if (ch == '-') - { - prev = ! prev; - continue; - } - else if (ch >= '0' && ch <= '9') - { - n = n * 10 + (ch - '0'); - continue; - } - - if (n == 0) - n = 1; - - if (ch == 'c') - { - if (prev) - Assert.assertTrue( c.toPrevChar( n ) == n ); - else - Assert.assertTrue( c.toNextChar( n ) == n ); - } - else if (ch == 't') - { - while ( n-- > 0 ) - { - if (prev) - Assert.assertTrue( c.toPrevToken() != TokenType.NONE ); - else - Assert.assertTrue( c.toNextToken() != TokenType.NONE ); - } - } - else if (ch == 'p') - { - Assert.assertTrue( ! prev ); - - while ( n-- > 0 ) - Assert.assertTrue( c.toParent() ); - } - else if (ch == 'r') - { - Assert.assertTrue( ! prev ); - Assert.assertTrue( n == 1 ); - - c.toEndDoc(); - } - else if (ch == 'b') - { - Assert.assertTrue( ! prev ); - Assert.assertTrue( n == 1 ); - - c.toStartDoc(); - } - else if (ch == 's') - { - while ( n-- > 0 ) - { - if (prev) - Assert.assertTrue( c.toPrevSibling() ); - else - Assert.assertTrue( c.toNextSibling() ); - } - } - else if (ch == 'd') - { - Assert.assertTrue( ! prev ); - - while ( n-- > 0 ) - Assert.assertTrue( c.toFirstChild() ); - } - else - { - Assert.assertTrue( false ); - } - - n = 0; - prev = false; - } - - return c; - } - - public void testOps ( ) - throws Exception - { - XmlObject x, x2, y; - XmlCursor cFrom, cTo, cTemp, cTemp2, c, d; - XmlBookmark anno; - - // - - x = XmlObject.Factory.parse( "abcdef" ); - cFrom = navDoc( x, "d" ); - cTo = navNewCursor( cFrom, "" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - XmlOptions options = new XmlOptions(); - - options.put( - XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT, - new QName( null, "bar" ) ); - - Assert.assertTrue( - x.xmlText( options ).equals( "[TO]abcdef[FROM]" ) || - x.xmlText( options ).equals( "[FROM]abcdef[TO]" ) ); - - // - - x = XmlObject.Factory.parse( "abcdef" ); - - cFrom = navDoc( x, "d" ); - cTo = navNewCursor( cFrom, "ttt" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText( options ).equals( "abcdef[FROM][TO]" ) || - x.xmlText( options ).equals( "abcdef[TO][FROM]" ) ); - - // - - x = XmlObject.Factory.parse( "abcdef" ); - - cFrom = navDoc( x, "d" ); - cTo = navNewCursor( cFrom, "t3c" ); - Assert.assertTrue( !cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText( options ).equals( "[FROM]abc[TO]def" ) ); - - // - - x = XmlObject.Factory.parse( "xyzpqr" ); - - cFrom = navDoc( x, "dd" ); - cTo = navNewCursor( cFrom, "r-1t" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( "[FROM]pqrxyz[TO]" ) ); - - // - - x = XmlObject.Factory.parse( "xyzpqrAB" ); - - cFrom = navDoc( x, "dd" ); - cTo = navNewCursor( cFrom, "r-1t-1c" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( "[FROM]pqrAxyz[TO]B" ) ); - - // - - x = XmlObject.Factory.parse( "xyzpqrAB" ); - - cFrom = navDoc( x, "dd" ); - cTo = navNewCursor( cFrom, "stc" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( "[FROM]pxyz[TO]qrAB" ) ); - - // - - x = XmlObject.Factory.parse( "xyzpqrAB" ); - - cFrom = navDoc( x, "dd" ); - cTo = navDoc( x, "d" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - testTextFrag( x.xmlText(), "xyz[TO][FROM]pqrAB" ); - - // - - x = XmlObject.Factory.parse( "xyzpqrAB" ); - - cFrom = navDoc( x, "dd" ); - cTo = navDoc( x, "r" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText( options ).equals( "[FROM]pqrABxyz[TO]" ) ); - - // - - x = XmlObject.Factory.parse( "xyz" ); - x2 = XmlObject.Factory.parse( "" ); - - cFrom = navDoc( x, "dd" ); - cTo = navDoc( x2, "dt" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( x.xmlText().equals( "[FROM]" ) ); - Assert.assertTrue( x2.xmlText().equals( "xyz[TO]" ) ); - - // - - x = XmlObject.Factory.parse( "pq" ); - - cFrom = navDoc( x, "dd" ); - cTo = navDoc( x, "ddst" ); - cTemp = navDoc( x, "ddt1c" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - cTemp.insertChars( "[TEMP]" ); - - Assert.assertTrue( - x.xmlText().equals( "[FROM][TEMP]pq[TO]" ) ); - - // - - x = XmlObject.Factory.parse( "abcdef" ); - - cFrom = navDoc( x, "2t2c" ); - cTo = navNewCursor( cFrom, "-1c" ); - cFrom.moveChars( 2, cTo ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( "acd[TO]b[FROM]ef" ) ); - - // - - x = XmlObject.Factory.parse( "abcdef" ); - - cFrom = navDoc( x, "2t2c" ); - cTo = navNewCursor( cFrom, "3c" ); - cFrom.moveChars( 2, cTo ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( "ab[FROM]ecd[TO]f" ) ); - - // - - x = XmlObject.Factory.parse( "abcdef123456" ); - - cFrom = navDoc( x, "3t2c" ); - cTo = navNewCursor( cFrom, "3t3c" ); - cFrom.moveChars( 2, cTo ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( - "ab[FROM]ef123cd[TO]456" ) ); - - // - - x = XmlObject.Factory.parse( "abcdef123456" ); - - cFrom = navDoc( x, "2d" ); - cTo = navDoc( x, "2dst2c" ); - Assert.assertTrue( cFrom.copyXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( - "[FROM]abcdef12" + - "abcdef[TO]3456" ) ); - - // - - x = XmlObject.Factory.parse( "xyz" ); - x2 = XmlObject.Factory.parse( "" ); - - cFrom = navDoc( x, "dd" ); - cTo = navDoc( x2, "dt" ); - Assert.assertTrue( cFrom.copyXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( x.xmlText().equals( "[FROM]xyz" ) ); - Assert.assertTrue( x2.xmlText().equals( "xyz[TO]" ) ); - - // - - x = XmlObject.Factory.parse( - "abcdefblah123456" ); - - cFrom = navDoc( x, "2d" ); - cTo = navDoc( x, "2dst2c" ); - Assert.assertTrue( cFrom.copyXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( - "[FROM]abcdefblah12" + - "abcdef[TO]3456" ) ); - - // - - x = XmlObject.Factory.parse( - "abcdef1234567890" ); - - cFrom = navDoc( x, "2dt" ); - cTo = navDoc( x, "2dst" ); - cTemp = navDoc( x, "2dst3c" ); - cTemp2 = navDoc( x, "2ds3t2c" ); - Assert.assertTrue( cFrom.copyXml( cTo ) ); - cTemp.insertChars( "[TEMP]" ); - cTemp2.insertChars( "[TEMP2]" ); - - Assert.assertTrue( - x.xmlText().equals( - "abcdef" + - "123[TEMP]45678[TEMP2]90" ) ); - - // - - x = XmlObject.Factory.parse( - "xyabcdefpqr123456" ); - - cFrom = navDoc( x, "2d" ); - cTo = navDoc( x, "2ds-2c" ); - - Assert.assertTrue( cFrom.removeXml() ); - - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( - "xy[FROM]p[TO]qr123456" ) ); - - // - - x = XmlObject.Factory.parse( - "xyabcdefpqr123456" ); - - cFrom = navDoc( x, "2d2t2c" ); - cTo = navDoc( x, "2d2t5c" ); - - cFrom.removeChars( 2 ); - - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( - x.xmlText().equals( - "xyab[FROM]e[TO]f" + - "pqr123456" ) ); - - // - - x = XmlObject.Factory.parse( "abc" ); - - cFrom = navDoc( x, "tt" ); - cTo = navDoc( x, "tttc" ); - - Assert.assertTrue( cFrom.removeXml() ); - - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - - Assert.assertTrue( x.xmlText().equals( "[FROM]a[TO]bc" ) ); - - // - - x = XmlObject.Factory.newInstance(); - - cTo = navDoc( x, "t" ); - cTo.insertElement( "boo" ); - cTo.toPrevToken(); - cTo.insertElement( "moo" ); - cTo.toPrevToken(); - cTo.insertElement( "goo" ); - - Assert.assertTrue( x.xmlText().equals( - "" ) ); - - // - - x = XmlObject.Factory.newInstance(); - - cTo = navDoc( x, "t" ); - cTo.insertElement( "boo" ); - cTo.toPrevToken(); - cTo.insertElement( "moo" ); - cTo.toPrevToken(); - cTo.insertAttributeWithValue( "x", "y" ); - - Assert.assertTrue( x.xmlText().equals( - "" ) ); - - // - - x = XmlObject.Factory.parse( "abc" ); - cTo = navDoc( x, "tt" ); - cTo.insertAttributeWithValue( "p", "q" ); - - Assert.assertTrue( x.xmlText().equals( - "abc" ) ); - - // Text XmlBookmark - - x = XmlObject.Factory.parse( "abc" ); - cFrom = navDoc( x, "tt" ); - anno = new Anno(); - cFrom.setBookmark( anno ); - cTo = navDoc( x, "6t" ); - Assert.assertTrue( cFrom.moveXml( cTo ) ); - cFrom.insertChars( "[FROM]" ); - cTo.insertChars( "[TO]" ); - anno.createCursor().insertChars( "[ANNO]" ); - - Assert.assertTrue( x.xmlText().equals( - "[FROM][ANNO]abc[TO]" ) ); - - // Test content ops - - x = XmlObject.Factory.parse( "abc" ); - y = XmlObject.Factory.newInstance(); - d = y.newCursor(); - d.toNextToken(); - x.newCursor().moveXmlContents( d ); - Assert.assertTrue( y.xmlText().equals( "abc" ) ); - - x = XmlObject.Factory.parse( "abc" ); - y = XmlObject.Factory.newInstance(); - c = x.newCursor(); - c.toNextToken(); - d = y.newCursor(); - d.toNextToken(); - c.moveXmlContents( d ); - Assert.assertTrue( y.xmlText().equals( "abc" ) ); - - x = XmlObject.Factory.parse( "abc" ); - c = x.newCursor(); - c.toNextToken(); - c.removeXmlContents(); - Assert.assertTrue( x.xmlText().equals( "" ) ); - - x = XmlObject.Factory.parse( "abc" ); - y = XmlObject.Factory.newInstance(); - d = y.newCursor(); - d.toNextToken(); - x.newCursor().copyXmlContents( d ); - Assert.assertTrue( y.xmlText().equals( "abc" ) ); - } - - public static class Anno extends XmlBookmark - { - } - - public void testSave ( ) - throws Exception - { - XmlObject x; - XmlCursor cTo; - - // - - x = XmlObject.Factory.parse( "abcdef" ); - - Assert.assertTrue( x.xmlText().equals( "abcdef" ) ); - - // - - x = XmlObject.Factory.parse( "a<b&c" ); - - Assert.assertTrue( x.xmlText().equals( "a<b&c" ) ); - - // - - x = XmlObject.Factory.parse( "" ); - - cTo = navDoc( x, "dt" ); - cTo.insertChars( "&<" ); - - Assert.assertTrue( x.xmlText().equals( "&<" ) ); - - // - - x = XmlObject.Factory.parse( "bar" ); - - cTo = navDoc( x, "dt" ); - - Assert.assertTrue( cTo.xmlText().equals( "bar" ) ); - - // - - x = XmlObject.Factory.parse( "bar" ); - - cTo = navDoc( x, "dt" ); - - Assert.assertTrue( cTo.xmlText().equals( "bar" ) ); - - // Tests fragment saving and loading - - x = XmlObject.Factory.parse( "Eric" ); - - cTo = navDoc( x, "dt" ); - - x = XmlObject.Factory.parse( cTo.xmlText() ); - - cTo = navDoc( x, "" ); - - Assert.assertTrue( cTo.getTextValue().equals( "Eric" ) ); - - // test save where I replace the name of an element - - x = XmlObject.Factory.parse( "Eric" ); - - cTo = navDoc( x, "d" ); - - XmlOptions options = new XmlOptions(); - - options.put( - XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT, - new QName( null, "bar" ) ); - - x = XmlObject.Factory.parse( cTo.xmlText( options ) ); - - cTo = navDoc( x, "" ); - - Assert.assertTrue( cTo.xmlText().equals( "Eric" ) ); - - // test save where I replace the name of the document - - x = XmlObject.Factory.parse( "Eric" ); - - cTo = navDoc( x, "" ); - - options = new XmlOptions(); - - options.put( - XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT, - new QName( null, "bar" ) ); - - x = XmlObject.Factory.parse( cTo.xmlText( options ) ); - - cTo = navDoc( x, "" ); - - Assert.assertTrue( - cTo.xmlText().equals( "Eric" ) ); - - // - // - // - - x = XmlObject.Factory.parse( "" ); - - XmlCursor c = x.newCursor(); - - c.toFirstContentToken(); - c.toFirstContentToken(); - - c.insertElement( "b" ); - c.toPrevSibling(); - Assert.assertTrue( c.getName().getLocalPart().equals( "b" ) ); - Assert.assertTrue( c.getName().getNamespaceURI().length() == 0 ); - - x = XmlObject.Factory.parse( x.xmlText() ); - - c = x.newCursor(); - - c.toFirstContentToken(); - c.toFirstContentToken(); - - Assert.assertTrue( c.getName().getLocalPart().equals( "b" ) ); - Assert.assertTrue( c.getName().getNamespaceURI().length() == 0 ); - } - - private void testTextFrag ( String actual, String expected ) - { - String pre = ""; - - String post = ""; - - Assert.assertTrue( actual.startsWith( pre ) ); - Assert.assertTrue( actual.endsWith( post ) ); - - Assert.assertTrue( - expected.equals( - actual.substring( - pre.length(), actual.length() - post.length() ) ) ); - } - - public void testSaveFrag ( ) - throws Exception - { - XmlObject x; - XmlCursor c; - - x = XmlObject.Factory.newInstance(); - - c = x.newCursor(); - - c.toNextToken(); - - c.insertChars( "Eric" ); - - testTextFrag( x.xmlText(), "Eric" ); - - // - - x = XmlObject.Factory.newInstance(); - - c = x.newCursor(); - - c.toNextToken(); - - c.insertComment( "" ); - c.insertChars( "x" ); - - testTextFrag( x.xmlText(), "x" ); - - // - - x = XmlObject.Factory.newInstance(); - - c = x.newCursor(); - - c.toNextToken(); - - c.insertElement( "foo" ); - c.insertChars( "x" ); - - testTextFrag( x.xmlText(), "x" ); - - // - - x = XmlObject.Factory.newInstance(); - - c = x.newCursor(); - - c.toNextToken(); - - c.insertElement( "foo" ); - c.insertElement( "bar" ); - - testTextFrag( x.xmlText(), "" ); - } - - public void testLoad ( ) - throws Exception - { - XmlObject x; - - XmlOptions options = new XmlOptions(); - - options.put( XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT, null ); - - x = - XmlObject.Factory.parse( - "abxycd", options ); - - XmlCursor c = navDoc( x, "t" ); - - assertTrue( c.currentTokenType() == TokenType.ATTR ); - - String open = "xmlns:open='http://www.openuri.org/fragment'"; - - x = - XmlObject.Factory.parse( - "abxycd" ); - - c = navDoc( x, "t" ); - - assertTrue( c.currentTokenType() == TokenType.ATTR ); - } - - public void testCompare ( ) - throws Exception - { - XmlObject x; - XmlCursor cFrom, cTo; - - // Forward navigation - - x = XmlObject.Factory.parse( "abxycd" ); - - cFrom = navDoc( x, "" ); - cTo = navDoc( x, "" ); - - for ( ; ; ) - { - Assert.assertTrue( cFrom.comparePosition( cTo ) == 0 ); - Assert.assertTrue( cFrom.isAtSamePositionAs( cTo ) ); - - TokenType tt = cFrom.currentTokenType(); - - if (tt == TokenType.ENDDOC) - { - break; - } - else if (tt == TokenType.TEXT) - { - cFrom.toNextChar( 1 ); - cTo.toNextChar( 1 ); - } - else - { - cFrom.toNextToken(); - cTo.toNextToken(); - } - } - - // Backward navigation - - x = XmlObject.Factory.parse( "abxycd" ); - - cFrom = navDoc( x, "r" ); - cTo = navDoc( x, "r" ); - - for ( ; ; ) - { - Assert.assertTrue( cFrom.comparePosition( cTo ) == 0 ); - Assert.assertTrue( cFrom.isAtSamePositionAs( cTo ) ); - - if (cFrom.toPrevChar( 1 ) == 1) - cTo.toPrevChar( 1 ); - else if (cFrom.toPrevToken() != TokenType.NONE) - cTo.toPrevToken(); - else - break; - } - - // - - x = XmlObject.Factory.parse( - "abxycxyd" ); - - cFrom = navDoc( x, "" ); - - for ( ; ; ) - { - boolean passed = false; - - cTo = navDoc( x, "" ); - - for ( ; ; ) - { - if (cTo.isAtSamePositionAs( cFrom )) - { - Assert.assertTrue( !passed ); - passed = true; - } - else if (cTo.isLeftOf( cFrom )) - { - Assert.assertTrue( !passed ); - } - else - { - Assert.assertTrue( passed ); - Assert.assertTrue( cTo.isRightOf( cFrom ) ); - } - - if (cTo.toNextChar( 1 ) != 1) - if (cTo.toNextToken() == TokenType.ENDDOC) - break; - } - - if (cFrom.toNextChar( 1 ) != 1) - if (cFrom.toNextToken() == TokenType.ENDDOC) - break; - } - } - - static class MyAnno extends XmlBookmark - { - } - - - public void testAttrSetter ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "" ); - XmlCursor c = x.newCursor(); - c.toNextToken(); - c.setAttributeText( new QName( null, "x" ), "hardehar" ); - Assert.assertTrue( x.xmlText().equals( "" ) ); - } - - public void testNavigation ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "" ); - XmlCursor c = x.newCursor(); - Assert.assertTrue( c.toNextSibling() == false ); - Assert.assertTrue( c.toPrevSibling() == false ); - Assert.assertTrue( c.toFirstAttribute() == false ); - Assert.assertTrue( c.toLastAttribute() == false ); - c.toNextToken(); - c.toNextToken(); - Assert.assertTrue( c.toNextSibling() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "y" ) ); - Assert.assertTrue( c.toNextSibling() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "z" ) ); - Assert.assertTrue( c.toNextSibling() == false ); - - x = XmlObject.Factory.parse( "" ); - c = x.newCursor(); - c.toNextToken(); - c.toNextToken(); - Assert.assertTrue( c.currentTokenType().isAttr() ); - Assert.assertTrue( c.toPrevSibling() == false ); - Assert.assertTrue( c.currentTokenType().isAttr() ); - Assert.assertTrue( c.toNextSibling() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "x" ) ); - - c.toEndDoc(); - c.toPrevToken(); - Assert.assertTrue( c.toPrevSibling() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "z" ) ); - Assert.assertTrue( c.toPrevSibling() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "y" ) ); - Assert.assertTrue( c.toPrevSibling() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "x" ) ); - Assert.assertTrue( c.toPrevSibling() == false ); - - c.toEndDoc(); - c.toPrevToken(); - Assert.assertTrue( c.toParent() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "a" ) ); - - c.toEndDoc(); - Assert.assertTrue( c.toParent() == true ); - Assert.assertTrue( c.currentTokenType().isStartdoc() ); - - x = XmlObject.Factory.parse( "moofoo" ); - c = x.newCursor(); - c.toStartDoc(); - c.toNextToken(); - c.toNextToken(); - c.toNextToken(); - Assert.assertTrue( c.toParent() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "a" ) ); - - c.toStartDoc(); - c.toNextToken(); - c.toNextToken(); - c.toNextToken(); - c.toNextToken(); - Assert.assertTrue( c.toParent() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "a" ) ); - - c.toStartDoc(); - c.toNextToken(); - c.toNextToken(); - c.toNextToken(); - c.toNextToken(); - c.toNextChar( 2 ); - Assert.assertTrue( c.toParent() == true ); - Assert.assertTrue( c.getName().getLocalPart().equals( "a" ) ); - - x = XmlObject.Factory.parse( "earlytextzap" ); - c = x.newCursor(); - c.toNextToken(); - c.toNextToken(); - Assert.assertTrue( c.toFirstChild() == true ); - Assert.assertTrue( c.getTextValue().equals( "zap" ) ); - } - - public void testGetName ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "eric" ); - XmlCursor c = x.newCursor(); - Assert.assertTrue( c.getName() == null ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName().getLocalPart().equals( "a" ) ); - Assert.assertTrue( c.getName().getNamespaceURI().length() == 0 ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName().getLocalPart().equals( "x" ) ); - Assert.assertTrue( c.getName().getNamespaceURI().length() == 0 ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName() == null ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName() == null ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName().getLocalPart().equals( "moo" ) ); - Assert.assertTrue( c.getName().getNamespaceURI().length() == 0 ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName() == null ); - Assert.assertTrue( !c.toNextToken().isNone() ); - Assert.assertTrue( c.getName() == null ); - Assert.assertTrue( c.toNextToken().isNone() ); - } - - public void testGetChars ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "abcdefghijkl" ); - XmlCursor c = x.newCursor(); - c.toNextToken(); - c.toNextToken(); - c.toNextChar( 2 ); - - char[] buf = new char[ 3 ]; - int n = c.getChars( buf, 0, 400 ); - - Assert.assertTrue( n == 3 ); - Assert.assertTrue( buf[0] == 'c' ); - Assert.assertTrue( buf[1] == 'd' ); - Assert.assertTrue( buf[2] == 'e' ); - } - - public void testNamespaceSubstitution ( ) - throws Exception - { - HashMap subs = new HashMap(); - subs.put( "foo", "moo" ); - subs.put( "a", "b" ); - - XmlOptions options = new XmlOptions(); - options.put( XmlOptions.LOAD_SUBSTITUTE_NAMESPACES, subs ); - - XmlObject x = - XmlObject.Factory.parse( - "", - options ); - - XmlCursor c = x.newCursor(); - - c.toNextToken(); - Assert.assertTrue( c.getName().getNamespaceURI().equals( "moo" ) ); - - c.toNextToken(); - Assert.assertTrue( c.getName().getNamespaceURI().equals( "moo" ) ); - - c.toNextToken(); - Assert.assertTrue( c.getName().getNamespaceURI().equals( "b" ) ); - - c.toNextToken(); - Assert.assertTrue( c.getName().getNamespaceURI().equals( "b" ) ); - } - - public void testNamespaceInsertion ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.newInstance(); - - XmlCursor c = x.newCursor(); - - c.toNextToken(); - c.insertElement( "foo", "http://p.com" ); - c.toPrevToken(); - c.insertNamespace( "p", "http://p.com" ); - - Assert.assertTrue( - x.xmlText().equals( "" ) ); - } - - private void dotestParser ( String xml, String xmlResult ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( xml ); - String result = x.xmlText(); - Assert.assertTrue( xmlResult.equals( result ) ); - } - - private void dotestParserErrors ( String xml ) - { - try - { - XmlObject.Factory.parse( xml ); - } - catch ( Throwable t ) - { - return; - } - - Assert.assertTrue( false ); - } - - public void testNil ( ) - throws Exception - { - XmlObject x = noNamespace.CanBeNilDocument.Factory.parse( "" ); - XmlCursor c = x.newCursor(); - c.toFirstChild(); - XmlObject fc = c.getObject(); - Assert.assertTrue( ! fc.isNil() ); - fc.setNil(); - Assert.assertTrue( fc.isNil() ); - Assert.assertTrue( x.xmlText().equals( "" ) ); - c.toNextToken(); - Assert.assertTrue( c.isAttr() ); - c.removeXml(); - Assert.assertTrue( x.xmlText().equals( "" ) ); - Assert.assertTrue( ! fc.isNil() ); - } - - - public void testParser ( ) - throws Exception - { - dotestParserErrors( "66" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( " " ); - - dotestParserErrors( "har" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); - dotestParserErrors( "" ); -// Fix the parser to make these work -// dotestParserErrors( "" ); -// dotestParserErrors( "" ); - - dotestParser( "", "" ); - } - - public void testSaxParser ( ) - throws Exception - { - String xml = "xz"; - - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser sp = spf.newSAXParser(); - XMLReader xr = sp.getXMLReader(); - InputSource is = new InputSource( new StringReader( xml ) ); - XmlSaxHandler sh = XmlObject.Factory.newXmlSaxHandler(); - - xr.setFeature( - "http://xml.org/sax/features/namespace-prefixes", - true ); - - xr.setFeature( - "http://xml.org/sax/features/namespaces", true ); - - xr.setFeature( - "http://xml.org/sax/features/validation", false ); - - xr.setContentHandler( sh.getContentHandler() ); - - xr.setProperty( - "http://xml.org/sax/properties/lexical-handler", - sh.getLexicalHandler() ); - - xr.parse( is ); - - XmlObject x1 = sh.getObject(); - - XmlObject x2 = XmlObject.Factory.parse( xml ); - - Assert.assertTrue( x1.xmlText().equals( x2.xmlText() ) ); - } - - public void testAdditionalNamespaces() - throws Exception - { - String xml = ""; - - Map map = new java.util.LinkedHashMap(); - map.put("b", "bNS"); - map.put("c", "cNS"); - map.put("a", "not-aNS"); - - XmlOptions options = new XmlOptions(); - options.setLoadAdditionalNamespaces(map); - - XmlObject x = XmlObject.Factory.parse(xml, options); - - // 'a' prefix namespace is not remapped - String expect = ""; - - xml = ""; - - map = new java.util.LinkedHashMap(); - map.put("b", "bNS"); - map.put("c", "cNS"); - map.put("", "not-aNS"); - - options = new XmlOptions(); - options.setLoadAdditionalNamespaces(map); - - x = XmlObject.Factory.parse(xml, options); - - // default namespace is not remapped - expect = ""; - Assert.assertEquals( expect, x.xmlText() ); - - } - - -} diff --git a/test/src/xmlcursor/checkin/ToCursorTest.java b/test/src/xmlcursor/checkin/ToCursorTest.java deleted file mode 100755 index ecc87b4..0000000 --- a/test/src/xmlcursor/checkin/ToCursorTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToCursorTest extends BasicCursorTestCase { - public ToCursorTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToCursorTest.class); - } - - public void testToCursorMoves() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - XmlCursor xc0 = m_xc.newCursor(); - xc0.toEndDoc(); - try { - assertEquals(true, m_xc.toCursor(xc0)); - assertEquals(true, xc0.isAtSamePositionAs(m_xc)); - } finally { - xc0.dispose(); - } - } - - /** - * FIXED: toCursor(null) does not return a boolean but throws an exception. - */ - public void testToCursorNull() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - m_xc.toFirstChild(); - String s = m_xc.xmlText(); - boolean caught = false; - try { - m_xc.toCursor(null); - } catch (java.lang.IllegalArgumentException e) { - caught = true; - } - assertTrue("toCursor(null) did not throw IllegalArgumentException", caught); - assertEquals(s, m_xc.xmlText()); - } - - public void testToCursorDifferentDocs() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - XmlCursor xc0 = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - String s = m_xc.xmlText(); - toNextTokenOfType(xc0, TokenType.TEXT); - try { - assertEquals(false, m_xc.toCursor(xc0)); - assertEquals(s, m_xc.xmlText()); - } finally { - xc0.dispose(); - } - } - - public void testToCursorThis() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - m_xc.toFirstChild(); - String s = m_xc.xmlText(); - assertEquals(true, m_xc.toCursor(m_xc)); - assertEquals(s, m_xc.xmlText()); - } - -} - diff --git a/test/src/xmlcursor/checkin/ToFirstAttributeTest.java b/test/src/xmlcursor/checkin/ToFirstAttributeTest.java deleted file mode 100755 index 0d1533c..0000000 --- a/test/src/xmlcursor/checkin/ToFirstAttributeTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToFirstAttributeTest extends BasicCursorTestCase { - public ToFirstAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToFirstAttributeTest.class); - } - - public void testToFirstAttrSTARTDOC() throws Exception { - m_xc = XmlObject.Factory.parse("text").newCursor(); - m_xc.toFirstChild(); - m_xc.insertAttributeWithValue("attr0", "val0"); - m_xc.toStartDoc(); - assertEquals(true, m_xc.toFirstAttribute()); - assertEquals("val0", m_xc.getTextValue()); - } - - public void testToFirstAttrSTARTmoreThan1ATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(true, m_xc.toFirstAttribute()); - assertEquals("val0", m_xc.getTextValue()); - } - - public void testToFirstAttrFrom2ndATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(false, m_xc.toFirstAttribute()); - } - - public void testToFirstAttrZeroATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(false, m_xc.toFirstAttribute()); - } - - public void testToFirstAttrFromTEXT() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(TokenType.TEXT, m_xc.currentTokenType()); - assertEquals("text", m_xc.getChars()); - assertEquals(false, m_xc.toFirstAttribute()); - } - - public void testToFirstAttrWithXMLNS() throws Exception { - m_xc = XmlObject.Factory.parse("text").newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(false, m_xc.toFirstAttribute()); - } -} - diff --git a/test/src/xmlcursor/checkin/ToFirstChildElementTest.java b/test/src/xmlcursor/checkin/ToFirstChildElementTest.java deleted file mode 100755 index 3a9def3..0000000 --- a/test/src/xmlcursor/checkin/ToFirstChildElementTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToFirstChildElementTest extends BasicCursorTestCase { - public ToFirstChildElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToFirstChildElementTest.class); - } - - public void testToFirstChildElemSTARTnested() throws Exception { - m_xc = XmlObject.Factory.parse("earlytext").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(true, m_xc.toFirstChild()); - assertEquals("text", m_xc.getTextValue()); - } - - public void testToFirstChildElemFromLastChild() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(false, m_xc.toFirstChild()); - assertEquals("text", m_xc.getTextValue()); - } - - public void testToFirstChildElemFromTEXTnested() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals("early", m_xc.getChars()); - assertEquals(true, m_xc.toFirstChild()); - assertEquals("zap", m_xc.getTextValue()); - } - - public void testToFirstChildElemFromATTRnested() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals("val0", m_xc.getTextValue()); - assertEquals(true, m_xc.toFirstChild()); - } - - public void testToFirstChildElemFromSTARTnoChild() throws Exception { - m_xc = XmlObject.Factory.parse("early").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(false, m_xc.toFirstChild()); - } - - public void testToFirstChildElemFromSTARTDOC() throws Exception { - m_xc = XmlObject.Factory.parse("early").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(TokenType.START, m_xc.currentTokenType()); - } -} - diff --git a/test/src/xmlcursor/checkin/ToLastAttributeTest.java b/test/src/xmlcursor/checkin/ToLastAttributeTest.java deleted file mode 100755 index 909c6ab..0000000 --- a/test/src/xmlcursor/checkin/ToLastAttributeTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToLastAttributeTest extends BasicCursorTestCase { - public ToLastAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToLastAttributeTest.class); - } - - public void testToLastAttrSTARTDOC() throws Exception { - m_xc = XmlObject.Factory.parse("text").newCursor(); - m_xc.toLastChild(); - m_xc.insertAttributeWithValue("attr0", "val0"); - m_xc.insertAttributeWithValue("attr1", "val1"); - m_xc.toStartDoc(); - assertEquals(true, m_xc.toLastAttribute()); - assertEquals("val1", m_xc.getTextValue()); - } - - public void testToLastAttrSTARTmoreThan1ATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(true, m_xc.toLastAttribute()); - assertEquals("val1", m_xc.getTextValue()); - } - - public void testToLastAttrFrom1stATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(false, m_xc.toLastAttribute()); - } - - public void testToLastAttrZeroATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(false, m_xc.toLastAttribute()); - } - - public void testToLastAttrFromTEXT() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(false, m_xc.toLastAttribute()); - } - - public void testToLastAttrWithXMLNS() throws Exception { - m_xc = XmlObject.Factory.parse("text").newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(false, m_xc.toLastAttribute()); - } -} - diff --git a/test/src/xmlcursor/checkin/ToLastChildElementTest.java b/test/src/xmlcursor/checkin/ToLastChildElementTest.java deleted file mode 100755 index 68116ba..0000000 --- a/test/src/xmlcursor/checkin/ToLastChildElementTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToLastChildElementTest extends BasicCursorTestCase { - public ToLastChildElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToLastChildElementTest.class); - } - - public void testToLastChildElemSTARTnestedSiblings() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzap").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(true, m_xc.toLastChild()); - assertEquals("zap", m_xc.getTextValue()); - } - - public void testToLastChildElemSTARTnestedSiblingsTwice() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(true, m_xc.toLastChild()); - assertEquals(true, m_xc.toLastChild()); - assertEquals("yap", m_xc.getTextValue()); - } - - public void testToLastChildElemFromTEXTnested() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzapyap").newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals("early", m_xc.getChars()); - XmlCursor xc0 = m_xc.newCursor(); - xc0.toNextSibling(); - try { - assertEquals("textzapyap", xc0.getTextValue()); - xc0.toLastChild(); - assertEquals("yap", xc0.getTextValue()); - assertEquals(true, m_xc.toLastChild()); - assertEquals("yap", m_xc.getTextValue()); - } finally { - xc0.dispose(); - } - } - - public void testToLastChildElemFromATTRnested() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzapyap").newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals("val0", m_xc.getTextValue()); - assertEquals(true, m_xc.toLastChild()); - } - - public void testToLastChildElemFromSTARTnoChild() throws Exception { - m_xc = XmlObject.Factory.parse("early").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(false, m_xc.toLastChild()); - } - - public void testToLastChildElemFromSTARTDOC() throws Exception { - m_xc = XmlObject.Factory.parse("early").newCursor(); - assertEquals(true, m_xc.toLastChild()); - assertEquals(TokenType.START, m_xc.currentTokenType()); - } -} - diff --git a/test/src/xmlcursor/checkin/ToNextAttributeTest.java b/test/src/xmlcursor/checkin/ToNextAttributeTest.java deleted file mode 100755 index 16bc497..0000000 --- a/test/src/xmlcursor/checkin/ToNextAttributeTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToNextAttributeTest extends BasicCursorTestCase { - public ToNextAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToNextAttributeTest.class); - } - - public void testToNextAttrFromSTART() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(false, m_xc.toNextAttribute()); - } - - public void testToNextAttrFromSingleATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(false, m_xc.toNextAttribute()); - assertEquals("val0", m_xc.getTextValue()); - } - - public void testToNextAttrWithSiblings() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(true, m_xc.toNextAttribute()); - assertEquals("val1", m_xc.getTextValue()); - } - - public void testToNextAttrFromLastSibling() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(false, m_xc.toNextAttribute()); - assertEquals("val1", m_xc.getTextValue()); - } - - public void testToNextAttrWithXMLNS() throws Exception { - m_xc = XmlObject.Factory.parse("text").newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals("val0", m_xc.getTextValue()); - assertEquals(true, m_xc.toNextAttribute()); - assertEquals("val1", m_xc.getTextValue()); - assertEquals(false, m_xc.toNextAttribute()); - } - - public void testToNextAttrFromTEXT() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(false, m_xc.toNextAttribute()); - } - -} - diff --git a/test/src/xmlcursor/checkin/ToNextElementTest.java b/test/src/xmlcursor/checkin/ToNextElementTest.java deleted file mode 100755 index 64a54ac..0000000 --- a/test/src/xmlcursor/checkin/ToNextElementTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToNextElementTest extends BasicCursorTestCase { - public ToNextElementTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToNextElementTest.class); - } - - public void testToNextElementFromSTARTDOC() throws Exception { - m_xc = XmlObject.Factory.parse("earlytext").newCursor(); - assertEquals(false, m_xc.toNextSibling()); - assertEquals(TokenType.STARTDOC, m_xc.currentTokenType()); - } - - public void testToNextElementSiblings() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); - assertEquals(true, m_xc.toFirstChild()); - assertEquals(true, m_xc.toFirstChild()); - assertEquals("text", m_xc.getTextValue()); - assertEquals(true, m_xc.toNextSibling()); - assertEquals("zapwapyap", m_xc.getTextValue()); - assertEquals(false, m_xc.toNextSibling()); - } - - public void testToNextElementFromATTR() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals("val0", m_xc.getTextValue()); - assertEquals(true, m_xc.toNextSibling()); - } - - public void testToNextElementFromTEXT() throws Exception { - m_xc = XmlObject.Factory.parse("earlytextzapwapyap").newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals("early", m_xc.getChars()); - assertEquals(true, m_xc.toNextSibling()); - assertEquals("text", m_xc.getTextValue()); - } -} - diff --git a/test/src/xmlcursor/checkin/ToNextSelectionTest.java b/test/src/xmlcursor/checkin/ToNextSelectionTest.java deleted file mode 100755 index 5f89084..0000000 --- a/test/src/xmlcursor/checkin/ToNextSelectionTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToNextSelectionTest extends BasicCursorTestCase { - public ToNextSelectionTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToNextSelectionTest.class); - } - - public void testToNextSelectionMultipleReturns() throws Exception { - String sXml = "0123456"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - m_xc.selectPath("$this//b"); - m_xc.toNextSelection(); - for (int i = 0; i < 6; i++) { - assertEquals("" + i, m_xc.getTextValue()); - assertEquals(true, m_xc.toNextSelection()); - } - assertEquals("6", m_xc.getTextValue()); - assertEquals(false, m_xc.toNextSelection()); - } - - public void testToNextSelectionAfterClear() throws Exception { - String sXml = "0123456"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - m_xc.selectPath("$this//b"); - m_xc.toNextSelection(); - for (int i = 0; i < 3; i++) { - assertEquals("" + i, m_xc.getTextValue()); - assertEquals(true, m_xc.toNextSelection()); - } - m_xc.clearSelections(); - assertEquals("3", m_xc.getTextValue()); - assertEquals(false, m_xc.toNextSelection()); - } - - public void testToNextSelectionBeforeSelect() throws Exception { - String sXml = "0123456"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - assertEquals(false, m_xc.toNextSelection()); - m_xc.selectPath("$this//b"); - m_xc.toNextSelection(); - for (int i = 0; i < 6; i++) { - assertEquals("" + i, m_xc.getTextValue()); - assertEquals(true, m_xc.toNextSelection()); - } - assertEquals("6", m_xc.getTextValue()); - assertEquals(false, m_xc.toNextSelection()); - } - - public void testToNextSelectionOtherCursor() throws Exception { - String sXml = "0123456"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - XmlCursor xc0 = m_xc.newCursor(); - try { - m_xc.selectPath("$this//b"); - assertEquals(false, xc0.toNextSelection()); - } finally { - xc0.dispose(); - } - } - - public void testToNextSelectionTwoCursorsDifferentSelections() throws Exception { - String sXml = "X0Y1Z2"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - XmlCursor xc0 = m_xc.newCursor(); - try { - xc0.selectPath("$this//a"); - xc0.toNextSelection(); - assertEquals(3, xc0.getSelectionCount()); - m_xc.selectPath("$this//b"); - m_xc.toNextSelection(); - assertEquals(3, m_xc.getSelectionCount()); - assertEquals(true, xc0.toNextSelection()); - assertEquals("Y", xc0.getTextValue()); - assertEquals(true, m_xc.toNextSelection()); - assertEquals("1", m_xc.getTextValue()); - } finally { - xc0.dispose(); - } - } - - public void testToNextSelectionTwoCursorsSameSelections() throws Exception { - String sXml = "X0Y1Z2"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - XmlCursor xc0 = m_xc.newCursor(); - try { - xc0.selectPath("$this//b"); - xc0.toNextSelection(); - assertEquals(3, xc0.getSelectionCount()); - m_xc.selectPath("$this//b"); - m_xc.toNextSelection(); - assertEquals(3, m_xc.getSelectionCount()); - assertEquals(true, xc0.toNextSelection()); - assertEquals("1", xc0.getTextValue()); - assertEquals(true, m_xc.toNextSelection()); - assertEquals("1", m_xc.getTextValue()); - assertEquals(true, xc0.toNextSelection()); - assertEquals("2", xc0.getTextValue()); - assertEquals(true, m_xc.toNextSelection()); - assertEquals("2", m_xc.getTextValue()); - assertEquals(false, xc0.toNextSelection()); - assertEquals(false, m_xc.toNextSelection()); - } finally { - xc0.dispose(); - } - } -} - diff --git a/test/src/xmlcursor/checkin/ToPrevAttributeTest.java b/test/src/xmlcursor/checkin/ToPrevAttributeTest.java deleted file mode 100755 index b0932b2..0000000 --- a/test/src/xmlcursor/checkin/ToPrevAttributeTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.checkin; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToPrevAttributeTest extends BasicCursorTestCase { - public ToPrevAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToPrevAttributeTest.class); - } - - public void testtoPrevAttrFromSTART() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.START); - assertEquals(false, m_xc.toPrevAttribute()); - } - - public void testtoPrevAttrFromSingleATTR() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(false, m_xc.toPrevAttribute()); - assertEquals("val0", m_xc.getTextValue()); - } - - public void testtoPrevAttrWithSiblings() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals("val1", m_xc.getTextValue()); - assertEquals(true, m_xc.toPrevAttribute()); - assertEquals("val0", m_xc.getTextValue()); - } - - public void testtoPrevAttrFromFirstSibling() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals(false, m_xc.toPrevAttribute()); - assertEquals("val0", m_xc.getTextValue()); - } - - public void testtoPrevAttrWithXMLNS() throws Exception { - m_xc = XmlObject.Factory.parse("text").newCursor(); - toNextTokenOfType(m_xc, TokenType.ATTR); - toNextTokenOfType(m_xc, TokenType.ATTR); - assertEquals("val1", m_xc.getTextValue()); - assertEquals(true, m_xc.toPrevAttribute()); - assertEquals("val0", m_xc.getTextValue()); - assertEquals(false, m_xc.toPrevAttribute()); - } - - public void testtoPrevAttrFromTEXT() throws Exception { - m_xc = XmlObject.Factory.parse(Common.XML_FOO_2ATTR_TEXT).newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(false, m_xc.toPrevAttribute()); - } -} diff --git a/test/src/xmlcursor/common/BasicCursorTestCase.java b/test/src/xmlcursor/common/BasicCursorTestCase.java deleted file mode 100755 index 69f6902..0000000 --- a/test/src/xmlcursor/common/BasicCursorTestCase.java +++ /dev/null @@ -1,142 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -package xmlcursor.common; - -import junit.framework.*; -import junit.framework.Assert.*; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlError; - -import javax.xml.namespace.QName; -import java.util.*; - -/** - * - */ -public class BasicCursorTestCase extends TestCase { - protected XmlObject m_xo; - protected XmlCursor m_xc; - - public BasicCursorTestCase(String sName) { - super(sName); - } - - protected void setUp() throws Exception { - } - - protected void tearDown() throws Exception - { - super.tearDown(); - m_xo = null; - if (m_xc != null) { - m_xc.dispose(); - m_xc = null; - } - } - - /* - public void testRuntimeClassPath() throws Exception - { - fail(System.getProperty("java.class.path")); - } - */ - - /** - * Method testFilesInClassPath - * - * tests for files directory in local environment: - * ${cajun.dir}/knex/test/local/files - * or automation environment: - * ${install.tempdir}/testcase/files - * - * If these directories are not in runtime classpath, locating files - * using getSystemResource() will fail causing false test failures. - * - * TODO: we should really make these identical as the test isn't foolproof - * - * @throws Exception - * - */ - public void testForFilesInClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf("schemajars"); - if (i < 0) { - fail("files directory not found in runtime classpath. Ant script error!"); - } - assertTrue(true); - } - - public void toNextTokenOfType(XmlCursor xc, TokenType tt) throws IllegalArgumentException { - if (xc == null) { - throw new IllegalArgumentException("Invalid argument: null XmlCursor"); - } else if (tt == null) { - throw new IllegalArgumentException("Invalid argument: null TokenType"); - } - - while (xc.toNextToken() != tt) { - if (xc.currentTokenType() == TokenType.ENDDOC) - fail("Expected Token not found! " + tt.toString()); - } - assertEquals(tt, xc.currentTokenType()); - } - - public void toPrevTokenOfType(XmlCursor xc, TokenType tt) - throws IllegalArgumentException { - if (xc == null) { - throw new IllegalArgumentException("Invalid argument: null XmlCursor"); - } else if (tt == null) { - throw new IllegalArgumentException("Invalid argument: null TokenType"); - } - - while (xc.toPrevToken() != tt) { - if (xc.currentTokenType() == TokenType.STARTDOC) - fail("Expected Token not found! " + tt.toString()); - } - assertEquals(tt, xc.currentTokenType()); - } - - /** - * Method compareDocTokens - * - * TODO: should really compare values also. - * - * @param tc a TestCase - * @param a a XmlCursor - * @param b a XmlCursor - * - * - */ - public void compareDocTokens(XmlCursor a, XmlCursor b) { - while (a.hasNextToken() && b.hasNextToken()) { - TokenType ttOrig = a.currentTokenType(); - TokenType ttRoundTrip = b.currentTokenType(); - if (ttOrig != ttRoundTrip) { - fail("Round trip failed. Original Cursor TokenType = " - + ttOrig + " Roundtrip Cursor TokenType = " - + ttRoundTrip); - - } - a.toNextToken(); - b.toNextToken(); - } - } - -} - diff --git a/test/src/xmlcursor/common/Common.java b/test/src/xmlcursor/common/Common.java deleted file mode 100755 index b4726c5..0000000 --- a/test/src/xmlcursor/common/Common.java +++ /dev/null @@ -1,85 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -package xmlcursor.common; - - - -/** - * - */ -public class Common { - public final static String XMLFRAG_BEGINTAG = ""; - public final static String XMLFRAG_ENDTAG = ""; - - public final static String XML_FOO = ""; - public final static String XML_FOO_1ATTR = ""; - public final static String XML_FOO_TEXT = "text"; - public final static String XML_FOO_1ATTR_TEXT = "text"; - public final static String XML_FOO_2ATTR = ""; - public final static String XML_FOO_2ATTR_TEXT = "text"; - public final static String XML_FOO_5ATTR_TEXT = "text"; - public final static String XML_FOO_BAR = ""; - public final static String XML_FOO_BAR_TEXT = "text"; - public final static String XML_FOO_BAR_TEXT_EXT = "textextended"; - public final static String XML_FOO_BAR_WS_TEXT = " text ws \\r\\n "; - public final static String XML_FOO_BAR_WS_ONLY = " "; - public final static String XML_FOO_NS = ""; - public final static String XML_FOO_NS_PREFIX = " 32.18"; - public final static String XML_FOO_BAR_SIBLINGS = "text0text1"; - public final static String XML_FOO_BAR_NESTED_SIBLINGS = "text0nested0text1nested1"; - public final static String XML_FOO_PROCINST = "text"; - public final static String XML_FOO_COMMENT = "text"; - public final static String XML_FOO_DIGITS = "01234"; - public final static String XML_TEXT_MIDDLE = "textextendedtext1"; - - public final static String XML_ATTR_TEXT = "ab "; - - - - public final static String TRANXML_DIR = "tranxml/Version4.0/"; - public final static String TRANXML_SCHEMAS_DIR = TRANXML_DIR + "schemas/StandAlone/"; - public final static String TRANXML_EXAMPLEDOCS_DIR = TRANXML_DIR + "ExampleDocs/"; - public final static String CLM_NS = "http://www.tranxml.org/TranXML/Version4.0"; - public final static String CLM_XSI_NS = "xmlns:xsi=\"http://www.w3.org/2000/10/XMLSchema-instance\""; - public final static String CLM_NS_XQUERY_DEFAULT = "declare default element namespace \"" + CLM_NS + "\"; "; - - public final static String TRANXML_FILE_CLM = TRANXML_EXAMPLEDOCS_DIR + "CarLocationMessage.xml"; - public final static String TRANXML_FILE_RBL = TRANXML_EXAMPLEDOCS_DIR + "RailBillOfLading.xml"; - public final static String TRANXML_FILE_SRCWBI = TRANXML_EXAMPLEDOCS_DIR + "SimpleRailCarrierWaybillInterchange.xml"; - public final static String TRANXML_FILE_TOAIRA = TRANXML_EXAMPLEDOCS_DIR + "TerminalOperationsAndIntermodalRampActivity.xml"; - public final static String TRANXML_FILE_XMLCURSOR_PO = "xbean/xmlcursor/po.xml"; - - - public final static String XML_SCHEMA_TYPE_SUFFIX = "http://www.w3.org/2001/XMLSchema"; - public final static String TRANXML_SCHEMA_TYPE_SUFFIX = CLM_NS; - - public static final String XMLCASES_JAR = "xmlcases.jar"; - public static final String XSDCASES_JAR = "xsdcases.jar"; - - public static final String XMLCURSOR_JAR = "xmlcursor.jar"; - public static final String CARLOCATIONMESSAGE_JAR = "CarLocationMessage_40_LX.xsd.jar"; - public static final String RAILBILLOFLADING_JAR = "RailBillOfLading_V40_LX.xsd.jar"; - public static final String SIMPLERAILCARRIERWAYBILLINTERCHANGE_JAR = "SimpleRailCarrierWaybillInterchange_V40_LX.xsd.jar"; - public static final String TERMINALOPERATIONSANDINTERMODALRAMPACTIVITY_JAR = "TerminalOperationsAndIntermodalRampActivity_V40_LX.xsd.jar"; - - public static String wrapInXmlFrag(String text) { - return XMLFRAG_BEGINTAG + text + XMLFRAG_ENDTAG; - } - -} - diff --git a/test/src/xmlcursor/detailed/CopyTest.java b/test/src/xmlcursor/detailed/CopyTest.java deleted file mode 100644 index ab8a8b5..0000000 --- a/test/src/xmlcursor/detailed/CopyTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.detailed; - -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import junit.framework.TestCase; - -/** - */ -public class CopyTest extends TestCase{ - -//this is per CR128353 - public void testCopyNamespaceMigration()throws XmlException{ - String s1="123"; - String s2=" ... [some content] ... "; - XmlCursor xc1=XmlObject.Factory.parse(s1).newCursor(); - xc1.toFirstContentToken(); - xc1.toFirstChild(); - XmlCursor xc2=XmlObject.Factory.parse(s2).newCursor(); - assertEquals(XmlCursor.TokenType.START,xc2.toFirstContentToken()); - xc2.toNextToken(); - xc1.copyXml(xc2); - xc2.toStartDoc(); - assertEquals("" + - "123" + - " ... [some content] ... ",xc2.xmlText()); - xc1.dispose(); - xc2.dispose(); - } - -} diff --git a/test/src/xmlcursor/detailed/CursorGeneratedTypedObjectTest.java b/test/src/xmlcursor/detailed/CursorGeneratedTypedObjectTest.java deleted file mode 100755 index 2b32c3b..0000000 --- a/test/src/xmlcursor/detailed/CursorGeneratedTypedObjectTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.detailed; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import tools.util.JarUtil; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.CodeList309; -import org.tranxml.tranXML.version40.GeographicLocationDocument; -import org.tranxml.tranXML.version40.LocationIdentifierDocument; -import person.Person; -import person.PersonDocument; -import test.xbean.xmlcursor.location.LocationDocument; - -import javax.xml.namespace.QName; - - -/** - * - * - */ -public class CursorGeneratedTypedObjectTest extends TestCase { - public CursorGeneratedTypedObjectTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CursorGeneratedTypedObjectTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } - - public void testGetObjectValidateLocation() throws Exception { - String sNamespace = "xmlns:loc=\"http://xbean.test/xmlcursor/Location\""; - String sXml = - "" + - "DALLAS" + - "TX" + - ""; - LocationDocument locDoc = LocationDocument.Factory.parse(sXml); - XmlCursor xc = locDoc.newCursor(); - xc.toFirstChild(); - LocationDocument.Location loc = (LocationDocument.Location) xc.getObject(); - assertEquals(true, loc.validate()); - XmlCursor xc0 = xc.newCursor(); - - xc0.toEndDoc(); - xc0.toPrevToken(); - // xc0.insertElementWithText("SubdivisionCode", "xyz"); - xc0.insertElementWithText( - new QName("http://xbean.test/xmlcursor/Location","SubdivisionCode","loc"), - "xyz"); - xc0.toCursor(xc); - - - String sExpectedXML = - "" + - "DALLAS" + - "TX" + - "xyz" + - ""; - - String sOExpectedXML = - "" + - "DALLAS" + - "TX" + - "xyz" + - ""; - XmlOptions map = new XmlOptions(); - //map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); - //map.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(-1)); - try { - assertEquals(sExpectedXML, xc0.xmlText(map)); - loc = (LocationDocument.Location) xc0.getObject(); - assertEquals(sOExpectedXML, loc.xmlText()); - assertEquals(true, loc.validate()); - assertEquals("DALLAS", loc.getCityName()); - assertEquals("TX", loc.getStateCode()); - assertEquals("xyz", loc.getSubdivisionCode()); - } - finally { - xc.dispose(); - xc0.dispose(); - } - - } - - public void testGetObjectGL() throws Exception { - String sNamespace = "xmlns=\"http://www.tranxml.org/TranXML/Version4.0\" xmlns:xsi=\"http://www.w3.org/2000/10/XMLSchema-instance\""; - CarLocationMessageDocument clm = CarLocationMessageDocument.Factory.parse( - JarUtil.getResourceFromJar( - Common.TRANXML_FILE_CLM)); - XmlCursor xc = clm.newCursor(); - xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//GeographicLocation"); - xc.toNextSelection(); - - GeographicLocationDocument.GeographicLocation gl0 = (GeographicLocationDocument.GeographicLocation) xc.getObject(); - assertEquals(true, gl0.validate()); - - XmlCursor xc0 = xc.newCursor(); - try { - xc0.toLastChild(); - assertEquals("TX", xc0.getTextValue()); - xc0.toNextToken(); - xc0.toNextToken(); - xc0.toNextToken(); - xc0.toNextToken(); - assertEquals(TokenType.END, xc0.currentTokenType()); - - xc0.beginElement("LocationIdentifier", - "http://www.tranxml.org/TranXML/Version4.0"); - xc0.insertAttributeWithValue("Qualifier", "FR"); - xc0.toEndToken(); - xc0.toNextToken();//move past the end token - xc0.insertElementWithText("CountrySubdivisionCode", - "http://www.tranxml.org/TranXML/Version4.0", "xyz"); - xc0.toCursor(xc); - - String sExpectedXML = - "\n" + - "\t\t\tDALLAS\n" + - "\t\t\tTX\n"+ - "\t\txyz" + - ""; - - XmlOptions map = new XmlOptions(); - // map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); - // map.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(-1)); - assertEquals(sExpectedXML, xc0.xmlText()); - - String sOExpectedXML = - "\n" + - "\t\t\t" + - "DALLAS\n" + - "\t\t\t" + - "TX\n" + - "\t\t" + - "xyz" + - ""; - - GeographicLocationDocument.GeographicLocation gl = (GeographicLocationDocument.GeographicLocation) xc0.getObject(); - assertEquals(sOExpectedXML, gl.xmlText(map)); - assertEquals(true, gl.validate()); - - - assertEquals("DALLAS", gl.getCityName().getStringValue()); - assertEquals("TX", gl.getStateOrProvinceCode()); - LocationIdentifierDocument.LocationIdentifier li = gl.getLocationIdentifier(); - assertNotNull("LocationIdentifier unexpectedly null", li); - assertEquals(CodeList309.FR, - gl.getLocationIdentifier().getQualifier()); - assertEquals("xyz", gl.getCountrySubdivisionCode()); - } - finally { - xc.dispose(); - xc0.dispose(); - } - } - - - /** - * Method testGetObjectPerson - * - * @throws Exception - */ - public void testGetObjectPerson() throws Exception { - String sFF = "FredFlintstone"; - String sXml = "" + sFF + - ""; - XmlCursor xc = XmlObject.Factory.parse(sXml).newCursor(); - PersonDocument pdoc = (PersonDocument) xc.getObject(); - - xc.toFirstChild(); - XmlCursor xcPlaceHolder = xc.newCursor(); - - try { - Person p = (Person) xc.getObject(); - assertEquals(true, p.validate()); - // move to - xc.toEndToken(); - - xc.insertElement("Sibling", "person"); - xc.toPrevToken(); - xc.insertElement("Name", "person"); - xc.toPrevToken(); - xc.insertElementWithText("First", "person", "Barney"); - xc.insertElementWithText("Last", "person", "Rubble"); - - p = (Person) xcPlaceHolder.getObject(); - assertEquals(true, p.validate()); - - assertEquals("Fred", p.getName().getFirst()); - assertEquals("Flintstone", p.getName().getLast()); - Person[] ap = p.getSiblingArray(); - assertEquals(1, ap.length); - assertEquals("Barney", ap[0].getName().getFirst()); - assertEquals("Rubble", ap[0].getName().getLast()); - } - finally { - xc.dispose(); - xcPlaceHolder.dispose(); - } - } - - -} - diff --git a/test/src/xmlcursor/detailed/CursorLocations.java b/test/src/xmlcursor/detailed/CursorLocations.java deleted file mode 100755 index ab0b8b0..0000000 --- a/test/src/xmlcursor/detailed/CursorLocations.java +++ /dev/null @@ -1,352 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.detailed; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlObject; -import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; -import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderType; -import test.xbean.xmlcursor.purchaseOrder.USAddress; -import tools.util.JarUtil; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; - -import java.math.BigDecimal; - -/** - * - * - */ -public class CursorLocations extends BasicCursorTestCase { - - private Bookmark0 _theBookmark0 = new Bookmark0("value0"); - - public CursorLocations(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CursorLocations.class); - } - - public void testLocation() throws Exception { - XmlCursor xc1, xc2, xc3, xc4; - XmlObject m_xo1; - - - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - m_xo1 = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); - - - xc1 = m_xo.newCursor(); - xc2 = m_xo.newCursor(); - xc3 = m_xo1.newCursor(); - - - toNextTokenOfType(xc2, TokenType.END); - toNextTokenOfType(xc3, TokenType.START); - - - //start w/ xc1 at beg of doc - //xc2 at end of first elt (po:name) - while (xc1.isLeftOf(xc2)) { - assertEquals(false, xc1.isRightOf(xc2)); - assertEquals(true, xc2.isRightOf(xc1)); - assertEquals(true, xc1.isInSameDocument(xc2)); - assertEquals(false, xc2.isAtSamePositionAs(xc1)); - assertEquals(false, xc1.isAtSamePositionAs(xc2)); - assertEquals(1, xc2.comparePosition(xc1)); - assertEquals(-1, xc1.comparePosition(xc2)); - // System.out.println(xc1.currentTokenType() + " " + xc2.currentTokenType()); - xc1.toNextToken(); - xc2.toPrevToken(); - } - //xc1 & xc2 @ shipTo - toNextTokenOfType(xc1,TokenType.TEXT); - toNextTokenOfType(xc2,TokenType.TEXT); - assertEquals("Current Token Type ", - xc1.currentTokenType(), - xc2.currentTokenType()); - //both @ Alice Smith - toNextTokenOfType(xc1,TokenType.TEXT); - toNextTokenOfType(xc2,TokenType.TEXT); - assertEquals(XmlCursor.TokenType.TEXT, - xc1.currentTokenType()); - //these are only equivalent if the cursor is on a TEXT token - assertEquals(xc1.getChars(), xc1.getTextValue()); - assertEquals(xc1.getChars(), xc2.getTextValue()); - - assertEquals(true, xc1.isAtSamePositionAs(xc2)); - xc2.toNextChar(10); - - -//comparing two cursors in the middle of text - - assertEquals(xc2.toPrevChar(4), xc1.toNextChar(4)); - assertEquals(true, xc2.isRightOf(xc1)); - assertEquals(false, xc1.isRightOf(xc2)); - assertEquals(false, xc2.isLeftOf(xc1)); - assertEquals(false, xc1.isAtSamePositionAs(xc2)); - assertEquals(1, xc2.comparePosition(xc1)); - assertEquals(true, xc1.isInSameDocument(xc2)); - xc1.toNextChar(2); - assertEquals(0, xc2.comparePosition(xc1)); - assertEquals(xc1.currentTokenType(), xc2.currentTokenType()); - -//Comparing the same cursor to itself - xc1.toNextChar(1); - assertEquals(false, xc1.isRightOf(xc1)); - assertEquals(0, xc2.comparePosition(xc2)); - assertEquals(true, xc2.isInSameDocument(xc2)); - assertEquals(true, xc2.isAtSamePositionAs(xc2)); - - xc2.toPrevToken(); - //xc2 on Alice - assertEquals(TokenType.TEXT, xc2.toPrevToken()); - //put the bookmark on S*mith - xc1.setBookmark(_theBookmark0); - - //moving xml and bookmark to a - // different location - assertEquals(true, xc1.moveXml(xc3)); - xc4 = _theBookmark0.createCursor(); - - XmlCursor debug=xc4.newCursor(); - XmlCursor debug1=xc1.newCursor(); - - toPrevTokenOfType(debug1,TokenType.START); - assertEquals(true, xc4.isInSameDocument(xc3)); - assertEquals(-1, xc4.comparePosition(xc3)); - // assertEquals(TokenType.TEXT, xc3.toPrevToken()); - assertEquals(4,xc3.toPrevChar(4)); - assertEquals(0, xc4.comparePosition(xc3)); - -//comparing in two different documents - assertEquals(false, xc2.isInSameDocument(xc3)); - - - try { - xc4.isLeftOf(xc2); - fail("Expecting Illegal Argument Exception"); - } - catch (IllegalArgumentException ie) { - } - - xc1.dispose(); - xc2.dispose(); - xc3.dispose(); - xc4.dispose(); - - } - - public void testLocationATTR() throws Exception { - XmlCursor xc1, xc2; - m_xo = XmlObject.Factory.parse(Common.XML_FOO_5ATTR_TEXT); - - xc1 = m_xo.newCursor(); - xc2 = m_xo.newCursor(); - - toNextTokenOfType(xc1, TokenType.ATTR); - toNextTokenOfType(xc2, TokenType.ATTR); - - int i = 0; - while (xc2.currentTokenType() == TokenType.ATTR) { - xc2.toNextToken(); - ++i; - } - - assertEquals(5, i); - xc2.toPrevToken(); - -//moving betweenAttributes. one cursor is at the last ATTR and other is at first ATTR. - while (xc1.isLeftOf(xc2)) { - assertEquals(false, xc1.isRightOf(xc2)); - assertEquals(true, xc2.isRightOf(xc1)); - assertEquals(true, xc1.isInSameDocument(xc2)); - assertEquals(false, xc2.isAtSamePositionAs(xc1)); - assertEquals(false, xc1.isAtSamePositionAs(xc2)); - assertEquals(1, xc2.comparePosition(xc1)); - assertEquals(-1, xc1.comparePosition(xc2)); - // System.out.println(xc1.currentTokenType() + " " + xc2.currentTokenType()); - xc1.toNextToken(); - xc2.toPrevToken(); - } - assertEquals(true, xc1.isAtSamePositionAs(xc2)); - -//inserting and then comparing to make sure cursors move properly. - xc2.insertAttributeWithValue("attr5", "val5"); - assertEquals(0, xc1.comparePosition(xc2)); - - xc2.toPrevToken(); - assertEquals("val5", xc2.getTextValue()); - - xc1.dispose(); - xc2.dispose(); - - } - - public void testLocationTEXTMiddle() throws Exception { - XmlCursor xc1, xc2, xc3; - m_xo = XmlObject.Factory.parse(Common.XML_TEXT_MIDDLE); - - xc1 = m_xo.newCursor(); - xc2 = m_xo.newCursor(); - xc3 = m_xo.newCursor(); - - - // while(xc2.currentTokenType() != TokenType.ENDDOC) - // { - // System.out.println(xc2.currentTokenType()); - // xc2.toNextToken(); - // } - -//moving cursor to right locations. one is in middle of mixed content. the others is in middle of text of first node and last node - - toNextTokenOfType(xc1, TokenType.TEXT); - toNextTokenOfType(xc2, TokenType.TEXT); - toNextTokenOfType(xc3, TokenType.START); - toNextTokenOfType(xc2, TokenType.TEXT); - xc1.toNextChar(4); - xc2.toNextChar(5); - xc3.toEndToken(); - xc3.toPrevToken(); - xc3.toPrevChar(3); -//comparing positions - assertEquals(-1, xc2.comparePosition(xc3)); - assertEquals(true, xc2.isRightOf(xc1)); - assertEquals(true, xc1.isInSameDocument(xc2)); - assertEquals(false, xc2.isAtSamePositionAs(xc3)); - -//moving cursors - xc3.toPrevChar(2); - xc2.toNextChar(1); -//comparing position once again - assertEquals(-1, xc2.comparePosition(xc3)); - assertEquals(true, xc2.isRightOf(xc1)); - assertEquals(true, xc1.isInSameDocument(xc2)); - assertEquals(false, xc2.isAtSamePositionAs(xc3)); - -//moving and bringing them to identical positions - xc3.toPrevToken(); - xc2.toNextChar(2); - assertEquals(true, xc2.isAtSamePositionAs(xc3)); - - xc1.dispose(); - xc2.dispose(); - xc3.dispose(); - - - } - - - public void testXmlObjectUsingCursor() throws Exception { - XmlCursor xc1, xc2, xc3; - - PurchaseOrderDocument pod = PurchaseOrderDocument.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO)); - xc1 = pod.newCursor(); - xc2 = pod.newCursor(); - xc3 = pod.newCursor(); - - - //moving cursor location so that it comes to zip under shipto - - toNextTokenOfType(xc1, TokenType.START); - toNextTokenOfType(xc1, TokenType.START); - toNextTokenOfType(xc2, TokenType.START); - toNextTokenOfType(xc2, TokenType.START); - toNextTokenOfType(xc3, TokenType.START); - toNextTokenOfType(xc3, TokenType.START); - - xc1.toEndToken(); - xc2.toEndToken(); - xc3.toEndToken(); - - toPrevTokenOfType(xc1, TokenType.TEXT); - toPrevTokenOfType(xc1, TokenType.TEXT); - toPrevTokenOfType(xc2, TokenType.TEXT); - toPrevTokenOfType(xc2, TokenType.TEXT); - toPrevTokenOfType(xc3, TokenType.TEXT); - toPrevTokenOfType(xc3, TokenType.TEXT); - //all cursors are now at: 90952 - assertEquals(xc1.getChars(), xc2.getChars(), xc3.getChars()); - //at 52 - xc2.toNextChar(3); - //after 90952 - xc3.toNextChar(5); - assertEquals(false, xc2.isAtSamePositionAs(xc3)); - assertEquals(false, xc3.isAtSamePositionAs(xc1)); - - - //setting zip value through the object . - // once the set occurs comparing postions of cursors. - PurchaseOrderType pt = pod.getPurchaseOrder(); - USAddress usa = pt.getShipTo(); - usa.setZip(new BigDecimal(500)); - - assertEquals(500,usa.getZip().intValue()); - //Any cursors in the value of an Element/attr should be positioned - // at the end of the elem/attr after the strong setter - assertEquals(true, xc2.isAtSamePositionAs(xc3)); - assertEquals(true, xc3.isAtSamePositionAs(xc1)); - - assertEquals(TokenType.END,xc1.currentTokenType()); - - -//inserting an element through the cursor under zip and then doing a set of a valid value through object.. - - xc1.insertElementWithText("foo", "text"); - toPrevTokenOfType(xc1, TokenType.START); - toPrevTokenOfType(xc1, TokenType.START); - //System.out.println("here" + xc1.getTextValue()); - - toNextTokenOfType(xc1, TokenType.START); - - xc1.toNextChar(2); - usa.setZip(new BigDecimal(90852)); - - assertEquals(true, xc2.isAtSamePositionAs(xc3)); - assertEquals(true, xc3.isAtSamePositionAs(xc1)); - //cursors at the end of element - xc1.toPrevToken(); - //assertEquals(5,xc1.toPrevChar(5)); - assertEquals("90852", xc1.getChars()); - - - xc1.dispose(); - xc2.dispose(); - xc3.dispose(); - - - } - - - public class Bookmark0 extends XmlCursor.XmlBookmark { - public String text; - - public Bookmark0(String text) { - this.text = text; - } - } - - -} - diff --git a/test/src/xmlcursor/detailed/CursorVsObjectAttributeTest.java b/test/src/xmlcursor/detailed/CursorVsObjectAttributeTest.java deleted file mode 100755 index 2e9ffb7..0000000 --- a/test/src/xmlcursor/detailed/CursorVsObjectAttributeTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.detailed; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import tools.util.JarUtil; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.CarLocationMessageDocument.CarLocationMessage; - -import javax.xml.namespace.QName; - - -/** - * - * - */ -public class CursorVsObjectAttributeTest extends TestCase { - public CursorVsObjectAttributeTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CursorVsObjectAttributeTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } - - public void testAttributeSet() throws Exception { - CarLocationMessageDocument clmDoc = CarLocationMessageDocument.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - XmlCursor xc = clmDoc.newCursor(); - xc.toFirstChild(); - CarLocationMessage clm = (CarLocationMessage) xc.getObject(); - - clm.setVersion("XyZ"); - QName name = new QName("Version"); - assertEquals("XyZ", xc.getAttributeText(name)); - xc.setAttributeText(name, "012"); - assertEquals("012", clm.getVersion()); - } - - public void testAttributeUnsetRemove() throws Exception { - CarLocationMessageDocument clmDoc = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - XmlCursor xc = clmDoc.newCursor(); - xc.toFirstChild(); - CarLocationMessage clm = (CarLocationMessage) xc.getObject(); - QName name = new QName("Version"); - assertEquals("CLM", xc.getAttributeText(name)); - clm.unsetVersion(); - assertEquals(null, xc.getAttributeText(name)); - xc.setAttributeText(name, "012"); - assertEquals("012", clm.getVersion()); - xc.removeAttribute(name); - assertEquals(null, clm.getVersion()); - } - - public void testAttributeInsert() throws Exception { - XmlOptions map = new XmlOptions(); - map.put(XmlOptions.LOAD_STRIP_WHITESPACE, ""); - - CarLocationMessageDocument clmDoc = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM), map); - XmlCursor xc = clmDoc.newCursor(); - xc.toFirstChild(); - CarLocationMessage clm = (CarLocationMessage) xc.getObject(); - QName name = new QName("Version"); - assertEquals("CLM", xc.getAttributeText(name)); - clm.unsetVersion(); - assertEquals(null, xc.getAttributeText(name)); - xc.toFirstChild(); - assertEquals(TokenType.START, xc.currentTokenType()); - xc.insertAttributeWithValue(name, "012"); - assertEquals("012", clm.getVersion()); - } - -} - diff --git a/test/src/xmlcursor/detailed/InsertAttributeTest2.java b/test/src/xmlcursor/detailed/InsertAttributeTest2.java deleted file mode 100755 index 7285fa5..0000000 --- a/test/src/xmlcursor/detailed/InsertAttributeTest2.java +++ /dev/null @@ -1,202 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.detailed; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class InsertAttributeTest2 extends BasicCursorTestCase { - - - static String sDoc=Common.XML_FOO_TEXT; - - public InsertAttributeTest2(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(InsertAttributeTest2.class); - } - - - - public void testNormalCase(){ - for (int i=0;i<50;i++){ - m_xc.insertAttribute("at"+i,"com.bea.foo"); - //System.out.println(i); - } - toPrevTokenOfType(m_xc, TokenType.ATTR); - - int i=0; - do{ - i++; - //System.out.println(m_xc.xmlText()); - }while(m_xc.toPrevAttribute()); - - assertEquals(i,50); - } - - public void testIllegalCursorPos(){ - //position curor at text - toNextTokenOfType(m_xc,XmlCursor.TokenType.END); - try{ - m_xc.insertAttribute("at","com.bea.foo"); - fail("Shoild not be able to insert at attr here "); - }catch(Exception e){} - } - /** - No xml tag can contain 2 attrib such that: - 1. have identical names, or - 2. have qualified names with the same local part and with prefixes which have been bound to namespace names that are identical. - - ** According to Eric he will perform the insert but - * check upon serialization that only the first token with a given name is printed - */ - public void testLocalNameCollision(){ - m_xc.insertAttributeWithValue("at","v1"); - m_xc.insertAttributeWithValue("at","v2"); - toPrevTokenOfType(m_xc,TokenType.START); - m_xc.toFirstAttribute(); - assertEquals(m_xc.getName().getLocalPart(),"at"); - assertEquals(true, m_xc.toNextAttribute()); - assertEquals(m_xc.getName().getLocalPart(),"at"); - - - } - - /** - * The idea was to try to force the following: - * - * which would be illegal - * This test case is not necessary: The implementation re-writes this as - * xmlns:com="..." and com:at0, com:at1 - * it seems impossible to force a binding of the same URI with two - * different prefixes - */ - /* - public void testUriCollision(){ - m_xc.insertAttribute("at0","com.bea.foo"); - try{ - m_xc.insertAttribute("at1","com.bea.foo"); - toPrevTokenOfType(m_xc,TokenType.START); - System.out.println(m_xc.xmlText()); - fail("Should not be able to insert at attr with colliding name "); - }catch(Exception e){} - } - */ - public void testUriLocalNameOK(){ - m_xc.insertAttribute("at",""); - m_xc.insertAttribute("at","com.bea.foo"); - toPrevTokenOfType(m_xc,XmlCursor.TokenType.START); - m_xc.toFirstAttribute(); - int i=1; -// System.out.println(m_xc.xmlText()); - while(m_xc.toNextAttribute()) i++; - assertEquals(i,2); - } - - public void testUriNull(){ - m_xc.insertAttribute("at",null); - toPrevTokenOfType(m_xc, TokenType.ATTR); - assertEquals(m_xc.getName(),new QName("at")); - } - public void testLocalnameNull(){ - try{ - m_xc.insertAttribute(null,""); - fail("Null Localname"); - }catch(Exception e){} - } - public void testUriEmpty(){ - m_xc.insertAttribute("myat",""); - toPrevTokenOfType(m_xc, TokenType.START); - m_xc.toFirstAttribute(); - assertEquals(m_xc.getName(),new QName(null,"myat")); - } - public void testLocalnameEmpty(){ - try{ - m_xc.insertAttribute("",""); - fail("No Localname"); - }catch(Exception e){} - } - - public void testInsertAttributeWithValue(){ - StringBuffer sb=new StringBuffer(); - String value0="test"+"\n\t\r"; - String value1="'QuotedText'"; - String value2="\"QuotedText2\""; - - int nStressBound=20000;//Integer.MAX_VALUE - for (int i=0;i= 0); - } - - public void testMultipleCopy() throws Exception { - CarLocationMessageDocument clm = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - assertNotNull(clm); - XmlCursor xc = clm.newCursor(); - XmlCursor[] aCursors = new XmlCursor[3]; - try { - xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//GeographicLocation"); - xc.toNextSelection(); - for (int i = 0; i < 3; i++) { - aCursors[i] = xc.newCursor(); - xc.toNextSelection(); - } - xc.toStartDoc(); - xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//GeographicLocation"); - assertTrue( xc.getSelectionCount() > 0 ); - assertTrue( xc.toNextSelection()); - aCursors[0].toLastChild(); - assertEquals("TX", aCursors[0].getTextValue()); - - aCursors[0].toNextToken(); - aCursors[0].toNextToken(); - aCursors[0].toNextToken(); - aCursors[0].toNextToken(); - assertEquals(TokenType.END, aCursors[0].currentTokenType()); - - aCursors[0].beginElement("LocationIdentifier", - "http://www.tranxml.org/TranXML/Version4.0"); - aCursors[0].insertAttributeWithValue("Qualifier", "FR"); - aCursors[0].toEndToken(); - aCursors[0].toNextToken();//move past the end token - aCursors[0].insertElementWithText("CountrySubdivisionCode", - "http://www.tranxml.org/TranXML/Version4.0", - "xyz"); - aCursors[0].toCursor(xc); - GeographicLocation gl = (GeographicLocation) aCursors[0].getObject(); - XmlOptions validateOptions=new XmlOptions(); - ArrayList errors=new ArrayList(); - validateOptions.setErrorListener(errors); - try{ - assertEquals(true, gl.validate(validateOptions)); - }catch (Throwable t){ - StringBuffer sb=new StringBuffer(); - for (int i = 0; i < errors.size(); i++) { - XmlError error = (XmlError) errors.get(i); - - sb.append("Message: " + error.getMessage() + "\n"); - if (error.getCursorLocation() != null) - System.out.println("Location of invalid XML: " + - error.getCursorLocation().xmlText() + "\n"); - } - throw new Exception(" Validation failed "+sb.toString()); - } - - assertEquals("DALLAS", gl.getCityName().getStringValue()); - assertEquals("TX", gl.getStateOrProvinceCode()); - LocationIdentifier li = gl.getLocationIdentifier(); - assertNotNull("Cursor0: LocationIdentifier unexpectedly null", li); - assertEquals(CodeList309.FR, gl.getLocationIdentifier().getQualifier()); - assertEquals("xyz", gl.getCountrySubdivisionCode()); - - - for (int i = 1; i < 3; i++) { - aCursors[i].removeXml(); - aCursors[0].copyXml(aCursors[i]); - // must move to PrevElement to get to the START of the copied section. - aCursors[i].toPrevSibling(); - - gl = (GeographicLocation) aCursors[i].getObject(); - - assertEquals("DALLAS", gl.getCityName().getStringValue()); - assertEquals("TX", gl.getStateOrProvinceCode()); - li = gl.getLocationIdentifier(); - assertNotNull("Cursor " + i + ": LocationIdentifier unexpectedly null", li); - assertEquals(CodeList309.FR, gl.getLocationIdentifier().getQualifier()); - assertEquals("xyz", gl.getCountrySubdivisionCode()); - } - - } finally { - xc.dispose(); - for (int i = 0; i < 3; i++) { - aCursors[i].dispose(); - } - } - } -} - - diff --git a/test/src/xmlcursor/detailed/ObjectCursorInteractionTest.java b/test/src/xmlcursor/detailed/ObjectCursorInteractionTest.java deleted file mode 100755 index e903ec3..0000000 --- a/test/src/xmlcursor/detailed/ObjectCursorInteractionTest.java +++ /dev/null @@ -1,196 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.detailed; - -import junit.framework.*; - -import xmlcursor.common.Common; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; - -import test.xbean.xmlcursor.location.LocationDocument.Location; -import test.xbean.xmlcursor.location.LocationDocument; - - -/** - * - * - */ -public class ObjectCursorInteractionTest extends TestCase { - public ObjectCursorInteractionTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ObjectCursorInteractionTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } - - public void testObjectNullEffectOnCursor() throws Exception { - String sNamespace = ""; - String sXml = - "DALLASTX" + - ""; - - // LocationDocument locDoc = (LocationDocument) XmlObject.Factory.parse(sXml); - LocationDocument locDoc = LocationDocument.Factory.parse(sXml); - Location loc = locDoc.getLocation(); - XmlCursor xc0 = loc.newCursor(); - assertEquals("DALLAS", loc.getCityName()); - loc = null; - System.gc(); - try { - Thread.sleep(1000); - xc0.toFirstChild(); - assertEquals("DALLAS", xc0.getTextValue()); - } - catch (InterruptedException e) { - } - finally { - xc0.dispose(); - } - } - - public void testCursorDisposalEffectOnObject() throws Exception { - String sNamespace = "xmlns:loc=\"http://xbean.test/xmlcursor/Location\""; - String sXml = "" + - "DALLASTX"; - LocationDocument locDoc = LocationDocument.Factory.parse( - sXml); - assertEquals(true, locDoc.validate()); - Location loc0 = locDoc.getLocation(); - Location loc1 = locDoc.getLocation(); - XmlCursor xc0 = loc0.newCursor(); - XmlCursor xc1 = loc1.newCursor(); - - xc0.toFirstChild(); - xc1.toFirstChild(); - xc0.setTextValue("AUSTIN"); - try { - assertEquals("AUSTIN", loc0.getCityName()); - loc1.setCityName("SAN ANTONIO"); - xc0.dispose(); - assertEquals("SAN ANTONIO", xc1.getTextValue()); - xc1.setTextValue("HOUSTON"); - xc1.dispose(); - assertEquals("HOUSTON", loc0.getCityName()); - } - finally { - xc0.dispose(); - xc1.dispose(); - } - } - - public void testObjectRefAssignmentEffectOnCursor() throws Exception { - String sXml0 = - "" + - "DALLAS" + - "TX" + - ""; - String sXml1 = - "" + - "90210" + - "US" + - ""; - LocationDocument locDoc0 = LocationDocument.Factory.parse( - sXml0); - Location loc0 = locDoc0.getLocation(); - XmlCursor xc0 = loc0.newCursor(); - - LocationDocument locDoc1 = (LocationDocument) XmlObject.Factory.parse( - sXml1); - Location loc1 = locDoc1.getLocation(); - - assertEquals("DALLAS", loc0.getCityName()); - assertEquals("TX", loc0.getStateCode()); - assertEquals(null, loc0.getPostalCode()); - assertEquals(null, loc0.getCountryCode()); - - loc0 = loc1; - - assertEquals(null, loc0.getCityName()); - assertEquals(null, loc0.getStateCode()); - assertEquals("90210", loc0.getPostalCode()); - assertEquals("US", loc0.getCountryCode()); - - try { - assertEquals(sXml0, xc0.xmlText()); - xc0 = loc0.newCursor(); - assertEquals(sXml1, xc0.xmlText()); - } - finally { - xc0.dispose(); - } - } - - public void testCursorRefAssignmentEffectOnObject() throws Exception { - String sXml0 = - "" + - "DALLAS" + - "TX" + - ""; - LocationDocument locDoc0 = LocationDocument.Factory.parse( - sXml0); - Location loc0 = locDoc0.getLocation(); - XmlCursor xc0 = loc0.newCursor(); - - String sXml1 = - "" + - "90210" + - "US" + - ""; - LocationDocument locDoc1 = LocationDocument.Factory.parse( - sXml1); - Location loc1 = locDoc1.getLocation(); - XmlCursor xc1 = loc1.newCursor(); - - try { - assertEquals("DALLAS", loc0.getCityName()); - assertEquals("TX", loc0.getStateCode()); - assertEquals(null, loc0.getPostalCode()); - assertEquals(null, loc0.getCountryCode()); - - xc0 = xc1; - - assertEquals("DALLAS", loc0.getCityName()); - assertEquals("TX", loc0.getStateCode()); - assertEquals(null, loc0.getPostalCode()); - assertEquals(null, loc0.getCountryCode()); - - loc0 = (Location) xc0.getObject(); - - assertEquals(null, loc0.getCityName()); - assertEquals(null, loc0.getStateCode()); - assertEquals("90210", loc0.getPostalCode()); - assertEquals("US", loc0.getCountryCode()); - - } - finally { - xc0.dispose(); - xc1.dispose(); - } - } - -} - diff --git a/test/src/xmlcursor/detailed/PushPopTest.java b/test/src/xmlcursor/detailed/PushPopTest.java deleted file mode 100755 index 8ab0414..0000000 --- a/test/src/xmlcursor/detailed/PushPopTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.detailed; - - -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; - -import xmlcursor.common.*; - - -/** - * - * - */ -public class PushPopTest extends BasicCursorTestCase { - - String sDoc=" 32.18 "; - - public PushPopTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(PushPopTest.class); - } - - public void testPopEmpty(){ - assertEquals(false,m_xc.pop()); - } - - public void testPushNTimes(){ - int nCount=100; - for (int i=0;i3456"; - - public SelectionsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SelectionsTest.class); - } - - //average case test - public void testNormalCase()throws Exception{ - XmlCursor m_xc1=m_xo.newCursor(); - int nSelectionsCount=7; - m_xc.selectPath("$this//a"); - assertEquals(false, m_xc.hasNextSelection()); - assertEquals(false, m_xc.toNextSelection()); - assertEquals(0, m_xc.getSelectionCount()); - - m_xc.selectPath("$this//b"); - m_xc1.toFirstChild(); - m_xc1.toFirstChild(); - do{ - m_xc1.addToSelection(); - }while(m_xc1.toNextSibling()); - assertEquals(nSelectionsCount, m_xc.getSelectionCount()); - int i=0; - while(m_xc.hasNextSelection()){ - m_xc.toNextSelection(); - assertEquals("" + i, m_xc.getTextValue()); - i++; - } - int j=0; - while(m_xc1.hasNextSelection()){ - m_xc1.toSelection(j); - assertEquals("" + j, m_xc1.getTextValue()); - j++; - } - assertEquals(nSelectionsCount,j); - assertEquals(nSelectionsCount,i); - } - - public void testToSelectionIllegalIndex(){ - m_xc.selectPath("$this//b"); - int i=0; - boolean result=false; - result=m_xc.toSelection(-1); - assertEquals(result,false); - - try{ - result=m_xc.toSelection(m_xc.getSelectionCount()+1); - if (result) - fail(" Index > num selections"); - }catch(IllegalStateException e){} - - if (result && (i>0)) fail(" Index <0 "); - - } - - public void testClearSelections(){ - - int nSelectionsCount=7; - m_xc.selectPath("$this//b"); - m_xc.toSelection(0); - m_xc.clearSelections(); - assertEquals("0",m_xc.xmlText()); - - } - - public void testCR196679() throws Exception - { - TestDocument testDoc = null; - String input="\n" + - " myTest" + - " 5" + - " "; - testDoc = TestDocument.Factory.parse(input); - TestType test = testDoc.getTest(); - - String queryName = - "declare namespace ns='http://xbean.test/xmlcursor/CR196679'" + - "$this/ns:name"; - - String queryValue = - "declare namespace ns='http://xbean.test/xmlcursor/CR196679'" + - "$this/ns:value"; - - XmlCursor cursor = test.newCursor(); - cursor.push(); - cursor.selectPath(queryName); - cursor.toNextSelection(); - - assertEquals("myTest",cursor.getTextValue()); - - cursor.pop(); - cursor.selectPath(queryValue); - cursor.toNextSelection(); - - assertEquals("5",cursor.getTextValue());//expected output is value=5 - - cursor.dispose(); - - } - public void setUp()throws Exception{ - m_xo=XmlObject.Factory.parse(sXml); - m_xc= m_xo.newCursor(); - } -} diff --git a/test/src/xmlcursor/detailed/ToChildTest.java b/test/src/xmlcursor/detailed/ToChildTest.java deleted file mode 100755 index e5eae37..0000000 --- a/test/src/xmlcursor/detailed/ToChildTest.java +++ /dev/null @@ -1,321 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.detailed; - -import org.apache.xmlbeans.XmlOptions; -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - - -/** - * - * - */ -public class ToChildTest extends BasicCursorTestCase { - - String sDoc="earlytextzapwapyap"; - - int nChildCount=2; //num children if TEXT is a child - public ToChildTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ToChildTest.class); - } - /** - * Testing toChild(String) - * Cases: - * non-existing name - * 2 children with same name - * nested child with same name - * Child of TEXT - */ - - public void testToChildNonExisting()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - assertEquals(false,m_xc.toChild("yana")); - } - public void testToChildInvalidName()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - try{ - m_xc.toChild(""); - fail(" Name is invalid"); - }catch (java.lang.IllegalArgumentException e){} - - } - - public void testToChildNull()throws Exception{ - String sNull=null; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - try{ - assertEquals(false,m_xc.toChild(sNull)); - fail("toChild with Null localName"); - }catch (IllegalArgumentException e){} - } - - public void testNameCollision()throws Exception{ - sDoc="txt0txt1"; - String sExpectedValue="txt0"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("bar")); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - public void testSameNameDescendant()throws Exception{ - sDoc="txt0txt1"; - String sExpectedValue="txt0"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("bar")); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - public void testTextChild()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - toNextTokenOfType(m_xc,TokenType.TEXT); - assertEquals(false,m_xc.toChild("bar")); - } - - /** - * toChild(String,String) - * Cases: - * non-existing ns, existing name - * non-existing name, existing ns - * 2 children with same name - * 2 children with same name, diff ns - * 2 children with diff name, same ns - * nested child with same name & ns - */ - - - public void testNullNS()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - String sExpectedResult="text"; - assertEquals(true,m_xc.toChild(null,"bar")); - assertEquals(sExpectedResult,m_xc.xmlText()); - } - - public void testNullName()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - try{ - assertEquals(false,m_xc.toChild("uri:foo.org",null)); - fail("toChild(uri,localname) with Null localName"); - }catch (IllegalArgumentException e){} - } - - public void testNamespaceOKNameInvalid()throws Exception{ - sDoc="txt0txt1"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(false,m_xc.toChild("fo","test")); - } - - public void testNamespaceInvalidNameOK()throws Exception{ - sDoc="txt0txt1"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - String sExpectedResult="text"; - assertEquals(false,m_xc.toChild("bar","bar")); - } - - public void testNormalCase()throws Exception{ - sDoc="txt0txt1"; - String sExpectedResult="txt0"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("uri:foo.org","bar")); - assertEquals(sExpectedResult,m_xc.xmlText()); - } - - public void testUriNameCollision()throws Exception{ - sDoc="txt0txt1"; - String sExpectedValue="txt0"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("uri:foo.org","bar")); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - - - //same URI diff names - public void testFakeNameCollision()throws Exception{ - sDoc="txt0txt1"; - String sExpectedValue="txt1"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("uri:foo.org","bar")); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - //diff URI same names - public void testFakeNameCollision3()throws Exception{ - sDoc="txt0txt1"; - String sExpectedValue="txt0"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("uri:foo.org","bar")); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - - public void testSameNameDescendant1()throws Exception{ - sDoc="txt0txt1"; - - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(false,m_xc.toChild("uri:foo.org","bar")); - } - - public void testSameNameDescendant2()throws Exception{ - sDoc="txt0txt1txt1"; - String sExpectedValue="txt1"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild("uri:foo.org","bar")); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - - /** - * toChild(int) - * Cases: - * i<0 - * i>numChildren - * i=0, numChildren=0 - */ - - public void testNegativeIndex()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - assertEquals(false,m_xc.toChild(-1)); - } - - public void testIndexOKFirst()throws Exception{ - String sExpectedValue="text"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild(0));//text is not children - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - public void testIndexOKLast()throws Exception{ - String sExpectedValue="zapwapyap"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild(nChildCount-1)); - assertEquals(sExpectedValue,m_xc.xmlText()); - m_xc.toParent(); - m_xc.toLastChild(); - assertEquals(sExpectedValue,m_xc.xmlText()); - } - - public void testLargeIndex()throws Exception{ - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(false,m_xc.toChild(20)); - - } - public void testInd0Count0()throws Exception{ - sDoc=""; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(false,m_xc.toChild(0)); - } - - - /** - * toChild(QName,int) - * Cases: - * QName dne, - * QName OK, i OK;i >numChildren;i<0 - * Name collision, i=1;i>numChildren - * Siblings and a child with same qname, ask for 2nd sibling - */ - - public void testToChildQNameDNE0()throws Exception{ - QName searchVal=new QName("fake:uri","bar"); - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(false,m_xc.toChild(searchVal,1)); - } - - public void testToChildQNameDNE1()throws Exception{ - sDoc="txt0txt1"; - QName searchVal=new QName("uri:foo.org","bar","pre"); - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(false,m_xc.toChild(searchVal,1)); - } - - public void testToChildQNameOKIndexOK()throws Exception{ - sDoc="txt0txt1"; - QName searchVal=new QName("uri:foo.org","bar","fo"); - String sExpectedValue="txt1"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild(searchVal,0)); - assertEquals(sExpectedValue,m_xc.xmlText()); - assertEquals(false,m_xc.toChild(searchVal,1)); - assertEquals(false,m_xc.toChild(searchVal,-1)); - } - - public void testQNameNameCollision()throws Exception{ - sDoc="txt0txt1"; - nChildCount=2; - QName searchVal=new QName("uri:foo.org","bar","fo"); - String sExpectedValue="txt1"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - assertEquals(true,m_xc.toChild(searchVal,0)); - assertEquals(sExpectedValue,m_xc.xmlText()); - int nInvalidCount=2; - if(nInvalidCount>=nChildCount) - assertEquals(false,m_xc.toChild(searchVal,nInvalidCount)); - else fail("Broken Test"); - } - - - public void testFakeQNameCollision()throws Exception{ - sDoc="txt0txt1"; - String sExpectedValue="txt0"; - m_xc = XmlObject.Factory.parse(sDoc).newCursor(); - m_xc.toFirstChild(); - QName searchVal=new QName("uri:foo.org","bar","fo"); - assertEquals(true,m_xc.toChild(searchVal,0)); - assertEquals(sExpectedValue,m_xc.xmlText()); - } -} diff --git a/test/src/xmlcursor/detailed/XmlLineNumberTest.java b/test/src/xmlcursor/detailed/XmlLineNumberTest.java deleted file mode 100644 index 6709bbf..0000000 --- a/test/src/xmlcursor/detailed/XmlLineNumberTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* Copyright 2005 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.detailed; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlLineNumber; -import org.apache.xmlbeans.XmlOptions; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import common.Common; - -public class XmlLineNumberTest extends Common -{ - public static final String xml = - "\n" + - " \n" + - "\t\tAlan\n" + - "\t\tTuring\n" + - "\n" + - ""; - - public static final String xmlFile = - XBEAN_CASE_ROOT + P + "xmlcursor" + P + "Employees.xml"; - - public XmlLineNumberTest(String name) - { - super(name); - } - - /** test obtaining XmlLineNumber bookmark with option - XmlOptions.setLoadLineNumbers() */ - public void testGetBookmark1() throws Exception - { - File f = new File(xmlFile); - XmlOptions opt = new XmlOptions(); - opt.setLoadLineNumbers(); - XmlObject xo = XmlObject.Factory.parse(f, opt); - XmlCursor c = xo.newCursor(); - c.toFirstChild(); - assertEquals(XmlCursor.TokenType.START, c.currentTokenType()); - XmlLineNumber ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertTrue(ln != null); - assertEquals(1, ln.getLine()); - c.toFirstChild(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(2, ln.getLine()); - c.toEndToken(); - assertEquals(XmlCursor.TokenType.END, c.currentTokenType()); - ln =(XmlLineNumber) c.getBookmark(XmlLineNumber.class); - // no bookmark at END - assertEquals(null, ln); - } - - /** test obtaining XmlLineNumber bookmark with option - XmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT) - */ - public void testGetBookmark2() throws Exception - { - File f = new File(xmlFile); - XmlOptions opt = new XmlOptions(); - opt.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT); - XmlObject xo = XmlObject.Factory.parse(f, opt); - XmlCursor c = xo.newCursor(); - c.toFirstChild(); - assertEquals(XmlCursor.TokenType.START, c.currentTokenType()); - XmlLineNumber ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertTrue(ln != null); - assertEquals(1, ln.getLine()); - c.toFirstChild(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(2, ln.getLine()); - c.toEndToken(); - assertEquals(XmlCursor.TokenType.END, c.currentTokenType()); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - // there is a bookmark at END - assertTrue(ln != null); - assertEquals(19, ln.getLine()); - } - - /** test using XmlLineNumber to get line number, column, and offset - - parsing xml from string */ - public void testLineNumber1() throws Exception - { - XmlOptions opt = new XmlOptions().setLoadLineNumbers(); - XmlObject xo = XmlObject.Factory.parse(xml, opt); - XmlCursor c = xo.newCursor(); - c.toFirstContentToken(); - c.toFirstChild(); - XmlLineNumber ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(1, ln.getLine()); - //assertEquals(8, ln.getColumn()); // actual: 10 - assertTrue(8 <= ln.getColumn() && ln.getColumn() <= 10); - // offset is not implemented - assertEquals(-1, ln.getOffset()); - c.toFirstChild(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(2, ln.getLine()); - //assertEquals(4, ln.getColumn()); // actual: 6 - assertTrue(4 <= ln.getColumn() && ln.getColumn() <= 6); - c.toFirstChild(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(3, ln.getLine()); - // tabs count as having single column width - //assertEquals(2, ln.getColumn()); // actual: 4 - assertTrue(2 <= ln.getColumn() && ln.getColumn() <= 4); - } - - /** test using XmlLineNumber to get line number, column, and offset - - parsing xml from file */ - public void testLineNumber2() throws Exception - { - File f = new File(xmlFile); - XmlOptions opt = new XmlOptions(); - opt.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT); - XmlObject xo = XmlObject.Factory.parse(f, opt); - XmlCursor c = xo.newCursor(); - c.toFirstContentToken(); - c.toFirstChild(); - XmlLineNumber ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(2, ln.getLine()); - assertTrue(2 <= ln.getColumn() && ln.getColumn() <= 4); - assertEquals(-1, ln.getOffset()); - c.toFirstChild(); - c.push(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(3, ln.getLine()); - assertTrue(4 <= ln.getColumn() && ln.getColumn() <= 6); - c.toEndToken(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(3, ln.getLine()); - assertTrue(23 <= ln.getColumn() && ln.getColumn() <= 25); - c.pop(); - c.toNextSibling(); //address - c.toEndToken(); - ln = (XmlLineNumber) c.getBookmark(XmlLineNumber.class); - assertEquals(9, ln.getLine()); - assertTrue(4 <= ln.getColumn() && ln.getColumn() <= 6); - assertEquals(-1, ln.getOffset()); - } - - public static Test suite() - { - TestSuite suite = new TestSuite(XmlLineNumberTest.class); - return suite; - } - - public static void main(String args[]) - { - junit.textui.TestRunner.run(suite()); - } -} diff --git a/test/src/xmlcursor/jsr173/common/AttributeTest.java b/test/src/xmlcursor/jsr173/common/AttributeTest.java deleted file mode 100755 index 55e35a7..0000000 --- a/test/src/xmlcursor/jsr173/common/AttributeTest.java +++ /dev/null @@ -1,352 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.jsr173.common; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.XmlOptions; - -import junit.framework.*; -import junit.framework.Assert.*; - -/** - * - * - */ -public abstract class AttributeTest extends TestCase { - - int indexMethods=6; - public abstract XMLStreamReader getStream(XmlCursor c)throws Exception; - public AttributeTest(String s) { - super(s); - } - - public void testAttrEvent() throws Exception { - cur.toNextToken(); - m_stream =getStream(cur); - assertEquals( XMLStreamConstants.ATTRIBUTE, m_stream.getEventType() ); - assertEquals(1, m_stream.getAttributeCount()); - assertEquals(m_stream.getAttributeValue(0), - m_stream.getAttributeValue("foo.org", "at0")); - - assertFalse(m_stream.hasNext()); - - } - public void testAttrMethodsAtAttr() throws Exception{ - - //2 attrs under the doc -// assertEquals(2, m_stream.getAttributeCount()); - - cur.toNextToken(); - m_stream= getStream(cur);; - //move 2 first attr - assertEquals( XMLStreamConstants.ATTRIBUTE, m_stream.getEventType() ); - assertEquals(1, m_stream.getAttributeCount()); - - assertEquals(m_stream.getAttributeValue(0), - m_stream.getAttributeValue("foo.org", "at0")); - - //Below methods tested at index 0 and last at index tests - //getAttributeLocalName(int) - //getAttributeName(int) - //getAttributeNamespace(int) - //getAttributePrefix(int) - //getAttributeType(int) - //getAttributeValue(int) - - - } - - public void testAttrMethodsAtStartElt() throws Exception{ - cur.toFirstChild(); - cur.toNextSibling(); - m_stream = getStream(cur); - assertEquals(1, m_stream.getAttributeCount()); - assertTrue(m_stream.isStartElement()); - assertEquals(new QName("foo.org", "foo", ""), m_stream.getName()); - assertEquals(m_stream.getAttributeValue(0), ""); - assertEquals(m_stream.getAttributeValue(0), - m_stream.getAttributeValue("", "localName")); - } - - private void assertIllegalState1() { - try { - m_stream.getAttributeCount(); - fail("Illegal State"); - } - catch (java.lang.IllegalStateException e) { - } - } - - private void assertIllegalState2() { - try { - m_stream.getAttributeValue(0); - fail("Illegal State"); - } - catch (java.lang.IllegalStateException e) { - } - } - - public void testAttrMethodsAtNamespace() throws Exception { - cur.toNextToken(); - cur.toNextToken(); - assertEquals (XmlCursor.TokenType.NAMESPACE, cur.toNextToken()); - m_stream = getStream(cur); - - assertIllegalState1(); - assertIllegalState2(); -// assertEquals(1,m_stream.getNamespaceCount()); -// assertEquals("foons.bar.org",m_stream.getNamespaceURI(0)); -// assertEquals(m_stream.getNamespaceURI(0),m_stream.getAttributeValue("","localName")); -// - } - -// -// java.lang.IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE -// - - public void testAttrMethodsAtEndElt()throws Exception { - cur.toFirstChild(); - cur.toNextSibling(); - cur.toNextToken(); - cur.toNextToken(); - assertEquals(XmlCursor.TokenType.END, cur.toNextToken()); //toEnd - m_stream = getStream(cur); - assertIllegalState1(); - assertIllegalState2(); - } - - public void testAttrMethodsAtEndDoc() throws Exception { - cur.toFirstChild(); - cur.toNextSibling(); - cur.toNextToken(); - cur.toNextToken(); - cur.toNextToken(); - cur.toNextToken(); - assertEquals(XmlCursor.TokenType.ENDDOC, cur.toNextToken()); - m_stream = getStream(cur); - assertIllegalState1(); - assertIllegalState2(); - } - - public void testAttrMethodstAtText() throws Exception { - cur.toFirstChild(); - cur.toNextSibling(); - cur.toNextToken(); - assertEquals(XmlCursor.TokenType.TEXT, cur.toNextToken()); //text - m_stream = getStream(cur); - assertIllegalState1(); - assertIllegalState2(); - } - - public void testAttrMethodstAtPI() throws Exception { - cur.toFirstChild(); - cur.toNextSibling(); - cur.toNextToken(); - cur.toNextToken(); - cur.toNextToken(); - assertEquals(XmlCursor.TokenType.PROCINST, cur.toNextToken()); - m_stream = getStream(cur); - assertIllegalState1(); - assertIllegalState2(); - } - - /** - * verify index correctness for all index methods - * tested w/ cursor positioned at first attr - * //getAttributeLocalName(int) - * //getAttributeName(int) - * //getAttributeNamespace(int) - * //getAttributePrefix(int) - * //getAttributeType(int) - * //getAttributeValue(int) - */ - - public void testAttrMethodsNegIndex() throws Exception { - - int cnt = 0; - try { - m_stream.getAttributeLocalName(-1); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeName(-1); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeNamespace(-1); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributePrefix(-1); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeType(-1); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeValue(-1); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - - assertEquals( "A negative error wasn't thrown", indexMethods , cnt); - } - - public void testAttrMethodsLargeIndex() - throws XMLStreamException { - - int cnt = 0; - int pos=-1; - try { - m_stream.next(); - pos=m_stream.getAttributeCount(); - m_stream.getAttributeLocalName(pos); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeName(pos); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeNamespace(pos); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributePrefix(pos); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeType(pos); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - try { - m_stream.getAttributeValue(pos); - } - catch (java.lang.IndexOutOfBoundsException e) { - cnt++; - } - - assertEquals( "A negative error wasn't thrown", indexMethods, cnt); - } - - public void testAttrMethods0Index() throws Exception{ - assertEquals( XMLStreamConstants.START_DOCUMENT, m_stream.getEventType() ); - - assertEquals( XMLStreamConstants.ATTRIBUTE, m_stream.next() ); - assertEquals(1, m_stream.getAttributeCount()); - - assertEquals("val0", m_stream.getAttributeValue(0)); - - assertEquals( XMLStreamConstants.ATTRIBUTE, m_stream.next() ); - - assertEquals("val1", m_stream.getAttributeValue(0)); - //why does this crash here???? - assertEquals( XMLStreamConstants.NAMESPACE,m_stream.next()); //ns - m_stream.next(); //elt - assertEquals("", m_stream.getAttributeValue(0)); - - } - - //NOTHING to do; eric always emits one event per attr=> - //getAttributeCount is always 1 - public void testAttrMethodsLastIndex() { - - } - public void testIsAttributeSpecified() throws Exception { - assertEquals( XMLStreamConstants.START_DOCUMENT, - m_stream.getEventType() ); - try{ - m_stream.isAttributeSpecified(0); - fail("Bad state"); - }catch (IllegalStateException e){} - - assertEquals( XMLStreamConstants.ATTRIBUTE, m_stream.next() ); - assertEquals(false, m_stream.isAttributeSpecified(0)); - - try{ - m_stream.isAttributeSpecified(-1); - fail("Bad state"); - }catch (java.lang.IndexOutOfBoundsException e){} - - try{ - m_stream.isAttributeSpecified(2); - fail("Bad state"); - }catch (java.lang.IndexOutOfBoundsException e){} - - } - - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - - cur.insertAttributeWithValue(new QName("foo.org", "at0", "pre"), - "val0"); - cur.insertAttributeWithValue(new QName("", "at1", "pre"), "val1"); - cur.insertNamespace("pre", "foons.bar.org"); - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertAttribute("localName"); - cur.insertChars("some text"); - cur.toNextToken(); - cur.toNextToken();//end elt - cur.insertProcInst("xml-stylesheet", "http://foobar"); - - cur.toStartDoc(); - m_stream=getStream(cur); - //cur.newXMLStreamReader(); - - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - XMLStreamReader m_stream; - XmlCursor cur; - -} \ No newline at end of file diff --git a/test/src/xmlcursor/jsr173/common/CharactersTest.java b/test/src/xmlcursor/jsr173/common/CharactersTest.java deleted file mode 100755 index 58f48c4..0000000 --- a/test/src/xmlcursor/jsr173/common/CharactersTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.jsr173.common; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.namespace.QName; - - -import junit.framework.*; - - -// - -/** - * Methods tested - * getText - * getTextCharacters x 2 - * getTextLength - * getTextStart - * hasText - * Token Types should be DTD, ER, Chars, Comment, Space - * currently DTD and ER are Not Impl - */ -public abstract class CharactersTest extends TestCase { - - public abstract XMLStreamReader getStream(XmlCursor c) throws Exception; - - public void testHasText() throws Exception { - assertEquals(XMLStreamConstants.START_DOCUMENT, - m_stream.getEventType()); - - // assertEquals( XMLStreamConstants.ATTRIBUTE, m_stream.next() ); - // assertFalse( m_stream.hasText() ); - - assertEquals(XMLStreamConstants.COMMENT, m_stream.next()); - assertTrue(m_stream.hasText()); - - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertFalse(m_stream.hasText()); - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - assertTrue(m_stream.hasText()); - - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertFalse(m_stream.hasText()); - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertFalse(m_stream.hasText()); - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertFalse(m_stream.hasText()); - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); -// assertTrue( m_stream.isWhiteSpace()); - assertTrue(m_stream.hasText()); - } - - //also testing getTextStart and getTextLength - public void testGetTextCharacters() throws Exception { - try { - assertEquals(XMLStreamConstants.START_DOCUMENT, m_stream.getEventType()); - m_stream.getTextLength(); - fail("Illegal State"); - } catch (IllegalStateException e) { - } - - assertEquals(XMLStreamConstants.COMMENT, m_stream.next()); - char[] result = m_stream.getTextCharacters(); - assertEquals(" some comment ", new String(result).substring(m_stream.getTextStart(), - m_stream.getTextLength())); - - try { - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - m_stream.getTextLength(); - fail("Illegal State"); - } catch (IllegalStateException e) { - } - - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - result = m_stream.getTextCharacters(); - assertEquals("some text", new String(result).substring(m_stream.getTextStart(), - m_stream.getTextLength())); - - m_stream.next(); - m_stream.next();//skip empty elt - m_stream.next(); //end foo - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - result = m_stream.getTextCharacters(); - assertEquals("\t", new String(result).substring(m_stream.getTextStart(), - m_stream.getTextLength())); - try { - m_stream.next(); - m_stream.getTextLength(); - fail("Illegal State"); - } catch (IllegalStateException e) { - } - } - - - public void testGetTextCharactersBufferNegStart() throws Exception { - m_stream.next(); - try { - m_stream.getTextCharacters(-1, new char[10], 12, 12); - fail(" java.lang.IndexOutOfBoundsException - if " + - "length < 0 or targetStart + length > length of target "); - } catch (java.lang.IndexOutOfBoundsException e) { - } - } - - public void testGetTextCharactersBufferNull() throws Exception { - m_stream.next(); - try { - m_stream.getTextCharacters(0, null, 12, 12); - fail(" java.lang.NullPointerException - is if target is null "); - } catch (java.lang.NullPointerException e) { - } - - } - - public void testGetTextCharactersLargeSrcOff() throws Exception { - m_stream.next(); - try { - m_stream.getTextCharacters(110, new char[10], 0, 9); - fail(" java.lang.IndexOutOfBoundsException - if " + - "length < 0 or targetStart + length > length of target "); - } catch (java.lang.IndexOutOfBoundsException e) { - } - } - - public void testGetTextCharactersLargeTrgOff() throws Exception { - m_stream.next(); - try { - m_stream.getTextCharacters(110, new char[10], 10, 9); - fail(" java.lang.IndexOutOfBoundsException - if " + - "length < 0 or targetStart + length > length of target "); - } catch (java.lang.IndexOutOfBoundsException e) { - } - } - - public void testGetTextCharactersLargeLen() throws Exception { - m_stream.next(); - char[] buff = new char[9]; - try { - int nCopied = m_stream.getTextCharacters(0, buff, 0, 30); - assertEquals(nCopied, buff.length); - fail(" java.lang.IndexOutOfBoundsException - if " + - "length < 0 or targetStart + length > length of target "); - } catch (java.lang.IndexOutOfBoundsException e) { - } - - } - - //off+len past end - public void testGetTextCharactersLargeSum() throws Exception { - m_stream.next(); - char[] buff = new char[9]; - try { - int nCopied = m_stream.getTextCharacters(0, buff, 3, 10); - fail(" java.lang.IndexOutOfBoundsException - if " + - "length < 0 or targetStart + length > length of target "); - } catch (java.lang.IndexOutOfBoundsException e) { - } - - } - - - public void testGetText() throws Exception { - try { - assertEquals(XMLStreamConstants.START_DOCUMENT, m_stream.getEventType()); - m_stream.getText(); - fail("Illegal State"); - } catch (IllegalStateException e) { - } - - assertEquals(XMLStreamConstants.COMMENT, m_stream.next()); - String result = m_stream.getText(); - assertEquals(" some comment ", result); - - try { - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - m_stream.getText(); - fail("Illegal State"); - } catch (IllegalStateException e) { - } - - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - result = m_stream.getText(); - assertEquals("some text", result); - - m_stream.next(); - m_stream.next();//skip empty elt - m_stream.next(); //end foo - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - result = m_stream.getText(); - assertEquals("\t", result); - try { - m_stream.next(); - m_stream.getText(); - fail("Illegal State"); - } catch (IllegalStateException e) { - } - } - - - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - - // cur.insertAttributeWithValue(new QName("foo.org", "at0", "pre"), "val0"); - cur.insertComment(" some comment "); - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertAttribute("localName"); - cur.insertChars("some text"); - cur.insertElement("foo2"); - cur.toNextToken(); //close foo elt - cur.insertChars("\t"); - - - cur.toStartDoc(); - m_stream = getStream(cur); - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - private XMLStreamReader m_stream; - private XmlCursor cur; -} \ No newline at end of file diff --git a/test/src/xmlcursor/jsr173/common/ElementTest.java b/test/src/xmlcursor/jsr173/common/ElementTest.java deleted file mode 100755 index ba1ebe3..0000000 --- a/test/src/xmlcursor/jsr173/common/ElementTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlcursor.jsr173.common; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamConstants; - -import junit.framework.*; -import junit.framework.Assert.*; - -/** - * - * - */ -public abstract class ElementTest extends TestCase { - - public abstract XMLStreamReader getStream(XmlCursor c)throws Exception; - public void testGetElementText() throws Exception { - cur.toFirstChild(); //first element? - m_stream = getStream(cur); - - assertEquals("some text", m_stream.getElementText()); - } - - public void testGetElementTextEmptyElt() throws Exception { - cur.toFirstChild(); //first element? - cur.toNextSibling(); - m_stream = getStream( cur ); - - assertEquals("", m_stream.getElementText()); - } - - public void testGetElementTextMixedContent() throws Exception { - cur.toFirstChild(); //first element? - cur.toNextSibling(); - cur.toNextSibling(); - m_stream =getStream( cur ); - assertEquals(new QName("foo.org", "foo", ""), m_stream.getName()); - try { - assertEquals("\thooa", m_stream.getElementText()); - fail("Mixed content needs exception"); - } - catch (javax.xml.stream.XMLStreamException e) { - } - - //mixed content txt1, PI, COMMENT,txt2: - //should coalesce txt1 & txt2 - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - cur.beginElement("foo"); - cur.insertChars(" \n "); - cur.insertComment("My comment"); - cur.insertProcInst("xml-stylesheet", "http://foobar"); - cur.insertChars("txt1\t"); - cur.toStartDoc(); - m_stream = getStream( cur ); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next() ); - assertEquals(" \n txt1\t", m_stream.getElementText()); - - - } - - public void testGetNameAtStartElt() throws Exception { - cur.toFirstChild(); //first element - m_stream = getStream( cur ); - assertEquals(new QName("foo.org", "foo", ""), m_stream.getName()); - - } - - public void testGetNameAtEndElt() throws Exception { - cur.toFirstChild(); - m_stream = getStream( cur ); - m_stream.next(); - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertEquals(new QName("foo.org", "foo", ""), m_stream.getName()); - } - - public void testHasName() throws Exception{ - - m_stream = getStream( cur ); - m_stream.next(); - m_stream.next(); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertTrue( m_stream.hasName() ); - - } - - //call at a bad place..here just attr but should exhaust all - public void testGetNameIllegal() throws Exception{ - cur.toNextToken(); //attr - m_stream = getStream( cur ); - try { - m_stream.getName(); - fail("getName illegal pos"); - } - catch (java.lang.IllegalStateException e) { - } - - assertFalse( m_stream.hasName() ); - } - - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - - cur.insertAttributeWithValue(new QName("foo.org", "at0", "pre"), - "val0"); - cur.insertNamespace("pre", "foons.bar.org"); - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertAttribute("localName"); - cur.insertChars("some text"); - cur.toNextToken(); - cur.toNextToken();//end elt - cur.insertElement("foo1"); - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertChars("\t"); - cur.insertElement("foo2"); - cur.insertChars("hooa"); - - cur.toStartDoc(); - - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - private XMLStreamReader m_stream; - private XmlCursor cur; -} \ No newline at end of file diff --git a/test/src/xmlcursor/jsr173/common/GeneralMethodsTest.java b/test/src/xmlcursor/jsr173/common/GeneralMethodsTest.java deleted file mode 100755 index 9ad90c4..0000000 --- a/test/src/xmlcursor/jsr173/common/GeneralMethodsTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.jsr173.common; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlDocumentProperties; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.*; -import javax.xml.stream.XMLStreamException; -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamConstants; - -import junit.framework.*; - - -// - -/** - * Methods tested - * close() - * getCharacterEncodingScheme() - * getEncoding() - * getLocation - * getProperty - * getVersion - * isStandalone - * require - * standaloneSet - * - * - * - */ -public abstract class GeneralMethodsTest extends TestCase { - - public abstract XMLStreamReader getStream(XmlCursor c) - throws Exception; - public void testClose() throws Exception { - m_stream.close(); - - - m_stream.next(); - - - } - - public void testAll() throws Exception { - m_stream.next(); - m_stream.next(); - assertEquals("utf-8", m_stream.getCharacterEncodingScheme()); - // Eric says this refers to actual encoding, not xml def - // assertEquals("utf-8", m_stream.getEncoding()); - - assertEquals(null, m_stream1.getCharacterEncodingScheme()); - assertEquals(null, m_stream1.getEncoding()); - //TODO: why is this still -1??? - Location l = m_stream.getLocation(); - assertEquals(-1, l.getCharacterOffset()); - assertEquals(-1, l.getColumnNumber()); - assertEquals(-1, l.getLineNumber()); - assertEquals(null, l.getPublicId()); - assertEquals(null, l.getSystemId()); - - - // m_stream.getProperty(""); - m_stream.getVersion(); -// m_stream.isStandalone(); - assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.getEventType() ); - //only elements can have localnames - try{ - m_stream.require(10, "", "at1"); - fail("IllegalStateException needed here"); - }catch (IllegalStateException e){} - - - m_stream.next(); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next() ) ; - m_stream.require(1, "foo.org", "foo"); - try{ - m_stream.require(10, "", ""); - fail("XMLStreamException needed here"); - }catch (XMLStreamException e){} - - -// m_stream.standaloneSet(); - } - - - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - - cur.insertAttributeWithValue(new QName("foo.org", "at0", "pre"), - "val0"); - cur.insertAttributeWithValue(new QName("", "at1", "pre"), "val1"); - cur.insertNamespace("pre", "foons.bar.org"); - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertAttribute("localName"); - cur.insertChars("some text"); - cur.toNextToken(); - cur.toNextToken();//end elt - cur.insertProcInst("xml-stylesheet", "http://foobar"); - - cur.toStartDoc(); - XmlDocumentProperties opt=cur.documentProperties(); - - m_stream1 = getStream( cur ); - - opt.setEncoding("utf-8"); - m_stream= getStream( cur ); - - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - private XMLStreamReader m_stream; - private XMLStreamReader m_stream1; - private XmlCursor cur; - private XmlOptions opt; - - -} \ No newline at end of file diff --git a/test/src/xmlcursor/jsr173/common/IsXXXTest.java b/test/src/xmlcursor/jsr173/common/IsXXXTest.java deleted file mode 100755 index d1b0f78..0000000 --- a/test/src/xmlcursor/jsr173/common/IsXXXTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.jsr173.common; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamConstants; - -import junit.framework.*; -import junit.framework.Assert.*; - -/** - * This class tests next, hasNext, nextTag,getEventType and isXXX methods - * - * - * - */ -public abstract class IsXXXTest extends TestCase { - - public abstract XMLStreamReader getStream(XmlCursor c) throws Exception; - - public void testAll() throws Exception { - assertEquals(XMLStreamConstants.START_DOCUMENT, - m_stream.getEventType()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.next()); - assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.getEventType()); - assertFalse(m_stream.isAttributeSpecified(0)); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.next()); - assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.getEventType()); - assertFalse(m_stream.isAttributeSpecified(0)); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.getEventType()); - assertFalse(m_stream.isCharacters()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.getEventType()); - assertTrue(m_stream.isStartElement()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.getEventType()); - assertTrue(m_stream.isCharacters()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.getEventType()); - assertTrue(m_stream.isEndElement()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.PROCESSING_INSTRUCTION, - m_stream.next()); - assertEquals(XMLStreamConstants.PROCESSING_INSTRUCTION, - m_stream.getEventType()); - - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.getEventType()); - assertTrue(m_stream.isCharacters()); -// assertTrue(m_stream.isWhiteSpace()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.COMMENT, m_stream.next()); - assertEquals(XMLStreamConstants.COMMENT, m_stream.getEventType()); - assertFalse(m_stream.isCharacters()); - - assertTrue(m_stream.hasNext()); - assertEquals(XMLStreamConstants.END_DOCUMENT, m_stream.next()); - assertEquals(XMLStreamConstants.END_DOCUMENT, m_stream.getEventType()); -// assertFalse(m_stream.isWhiteSpace()); - - assertFalse(m_stream.hasNext()); - } - - /** - * Not Impl - * public void testNextTag() throws Exception { - * try{ - * m_stream.nextTag(); - * fail("shouldn't jump to next tag"); - * }catch (IllegalStateException e){} - *

        - * cur = Public2.newStore(); - * cur.toNextToken(); - *

        - * cur.insertComment("cmt"); - * cur.beginElement("foobar"); - * cur.insertChars(" \n"); - * cur.toNextToken(); - * cur.insertProcInst("xml-foo","http://foo.org"); - * cur.insertElement("foobar1"); - *

        - * m_stream=cur.newXMLStreamReader(); - *

        - * assertEquals ( XMLStreamConstants.START_ELEMENT, m_stream.nextTag()); - * assertEquals("fooabar", m_stream.getLocalName()); - * assertEquals ( XMLStreamConstants.END_ELEMENT, m_stream.nextTag()); - * assertEquals("fooabar", m_stream.getLocalName()); - *

        - * assertEquals ( XMLStreamConstants.START_ELEMENT, m_stream.nextTag()); - * assertEquals("fooabar1", m_stream.getLocalName()); - * assertEquals ( XMLStreamConstants.END_ELEMENT, m_stream.nextTag()); - * assertEquals("fooabar1", m_stream.getLocalName()); - *

        - *

        - * } - */ - - - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - - cur.insertAttributeWithValue(new QName("foo.org", "at0", "pre"), - "val0"); - cur.insertAttributeWithValue(new QName("", "at1", "pre"), "val1"); - cur.insertNamespace("pre", "foons.bar.org"); - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertAttribute("localName"); - cur.insertChars("some text"); - cur.toNextToken(); - cur.toNextToken();//end elt - cur.insertProcInst("xml-stylesheet", "http://foobar"); - cur.insertChars("\t"); - cur.insertComment(" some comment "); - - cur.toStartDoc(); - - m_stream = getStream(cur); - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - private XMLStreamReader m_stream; - private XmlCursor cur; - - -} \ No newline at end of file diff --git a/test/src/xmlcursor/jsr173/common/NamespaceTest.java b/test/src/xmlcursor/jsr173/common/NamespaceTest.java deleted file mode 100755 index a64b6c3..0000000 --- a/test/src/xmlcursor/jsr173/common/NamespaceTest.java +++ /dev/null @@ -1,287 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.jsr173.common; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamConstants; - -import junit.framework.*; -import junit.framework.Assert.*; - - - -/** - * Methods tested - * getLocalName - * getName - * getNamespaceContext - * getNamespaceCount - * getNamespacePrefix - * getNamespaceURI x 3 - * getPrefix - * - * - */ -public abstract class NamespaceTest extends TestCase{ - - //only valid at TAGs and ER - //TODO: ER - - public abstract XMLStreamReader getStream(XmlCursor c)throws Exception; - public void testGetLocalName() throws Exception{ - try{ - m_stream.getLocalName(); - fail("no name at startdoc"); - }catch (IllegalStateException e){} - - m_stream.next(); m_stream.next(); - assertEquals( XMLStreamConstants.START_ELEMENT, m_stream.next() ); - assertEquals("foo",m_stream.getLocalName()); - m_stream.next(); - assertEquals( XMLStreamConstants.END_ELEMENT, m_stream.next() ); - assertEquals("foo",m_stream.getLocalName()); - } - public void testGetName(){ - //test in Element--only valid for Element events - } - - public void testGetPrefix()throws Exception{ - assertEquals(XMLStreamConstants.START_DOCUMENT, - m_stream.getEventType()); - - try{ - assertEquals( null, m_stream.getPrefix() ); - fail("no prefix here"); - }catch (IllegalStateException e){} - // assertFalse( m_stream.hasText() ); - assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.next()); - try{ - assertEquals( null, m_stream.getPrefix() ); - fail("no prefix here"); - }catch (IllegalStateException e){} - - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - try{ - assertEquals( null, m_stream.getPrefix() ); - fail("no prefix here"); - }catch (IllegalStateException e){} - - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals("",m_stream.getPrefix()); - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - try{ - assertEquals( null, m_stream.getPrefix() ); - fail("no prefix here"); - }catch (IllegalStateException e){} - - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertEquals("",m_stream.getPrefix()); - assertEquals(XMLStreamConstants.PROCESSING_INSTRUCTION, m_stream.next()); - try{ - assertEquals( null, m_stream.getPrefix() ); - fail("no prefix here"); - }catch (IllegalStateException e){} - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - - - assertEquals(XMLStreamConstants.COMMENT, m_stream.next()); - try{ - assertEquals( null, m_stream.getPrefix() ); - fail("no prefix here"); - }catch (IllegalStateException e){} - } - - /*@status inactive*/ - public void testGetNamespaceContext() throws Exception{ - - -// assertEquals(XMLStreamConstants.ATTRIBUTE, m_stream.next()); -// assertEquals("", m_stream.getNamespaceContext().getNamespaceURI("")) ; -// assertEquals("", m_stream.getNamespaceContext().getPrefix("foo.org")) ; -// java.util.Iterator it= m_stream.getNamespaceContext().getPrefixes("foo.bar") ; -// - m_stream.next(); - m_stream.next(); - m_stream.next(); - - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - // assertEquals("", m_stream.getNamespaceContext().getNamespaceURI("")) ; - //assertEquals("", m_stream.getNamespaceContext().getPrefix("foo.bar")) ; - assertEquals(null, m_stream.getNamespaceContext().getPrefix("foo.bar")) ; - java.util.Iterator it= m_stream.getNamespaceContext().getPrefixes("foo.bar") ; - } - - /** - * only valid at Tags and NS decl - * @throws Exception - */ - - public void testGetNamespaceCount()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - assertEquals( 1, m_stream.getNamespaceCount() ) ; - - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals( 2, m_stream.getNamespaceCount() ) ; - - //java.lang.IllegalStateException - // - if this is not a START_ELEMENT, END_ELEMENT or NAMESPACE - try{ - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - m_stream.getNamespaceCount(); - fail("can't do this on a txt node"); - } catch (IllegalStateException e){} - - - - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertEquals( 2, m_stream.getNamespaceCount() ) ; - - } - /** - * only valid at Tags and NS decl - * @throws Exception - */ - - public void testGetNamespacePrefix()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - assertEquals( "pre0", m_stream.getNamespacePrefix(0) ) ; - - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals( "pre", m_stream.getNamespacePrefix(0) ) ; - assertEquals( "pre1", m_stream.getNamespacePrefix(1) ) ; - //java.lang.IllegalStateException - // - if this is not a START_ELEMENT, END_ELEMENT or NAMESPACE - - try{ - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.getEventType()); - m_stream.getNamespacePrefix(0); - fail("can't do this on a txt node"); - } catch (IllegalStateException e){} - - - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertEquals( "pre", m_stream.getNamespacePrefix(0) ) ; - assertEquals( "pre1", m_stream.getNamespacePrefix(1) ) ; - } - - public void testGetNamespacePrefixNeg()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - try{ - assertEquals( "", m_stream.getNamespacePrefix(-1) ) ; - fail("negative index"); - }catch (java.lang.IndexOutOfBoundsException e){} - - } - - public void testGetNamespacePrefixLarge()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - try{ - assertEquals( "", m_stream.getNamespacePrefix(3) ) ; - fail("negative index"); - }catch (java.lang.IndexOutOfBoundsException e){} - - } - - //3 methods here - public void testGetNamespaceURI()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - assertEquals( "bea.com", m_stream.getNamespaceURI(0) ) ; - - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals( "foons.bar.org", m_stream.getNamespaceURI(0) ) ; - assertEquals( "foons1.bar1.org1", m_stream.getNamespaceURI(1) ) ; - try{ - assertEquals(XMLStreamConstants.CHARACTERS, m_stream.next()); - m_stream.getNamespaceURI(0); - fail("can't do this on a txt node"); - } catch (IllegalStateException e){} - - - assertEquals(XMLStreamConstants.END_ELEMENT, m_stream.next()); - assertEquals( "foons.bar.org", m_stream.getNamespaceURI(0) ) ; - assertEquals( "foons1.bar1.org1", m_stream.getNamespaceURI(1) ) ; - } - - public void testGetNamespaceURINeg()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - try{ - assertEquals( "", m_stream.getNamespaceURI(-1) ) ; - fail("negative index"); - }catch (java.lang.IndexOutOfBoundsException e){} - - } - - public void testGetNamespaceURILarge()throws Exception{ - m_stream.next(); - assertEquals(XMLStreamConstants.NAMESPACE, m_stream.next()); - try{ - assertEquals( "", m_stream.getNamespaceURI(3) ) ; - fail("negative index"); - }catch (java.lang.IndexOutOfBoundsException e){} - - } - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - - cur.insertAttributeWithValue(new QName("foo.org", "at0", "pre"), - "val0"); - cur.insertNamespace("pre0", "bea.com"); - - cur.beginElement(new QName("foo.org", "foo", "")); - cur.insertNamespace("pre", "foons.bar.org"); - cur.insertNamespace("pre1", "foons1.bar1.org1"); - cur.insertChars("some text"); - cur.toNextToken(); - cur.toNextToken();//end elt - cur.insertProcInst("xml-stylesheet", "http://foobar"); - cur.insertChars("\t"); - cur.insertComment(" some comment "); - - cur.toStartDoc(); - - m_stream=getStream( cur ); - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - private XMLStreamReader m_stream; - private XmlCursor cur; - -} - diff --git a/test/src/xmlcursor/jsr173/common/PITest.java b/test/src/xmlcursor/jsr173/common/PITest.java deleted file mode 100755 index b7061ef..0000000 --- a/test/src/xmlcursor/jsr173/common/PITest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.jsr173.common; - - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.namespace.QName; - -import javax.xml.stream.XMLStreamConstants; - -import junit.framework.*; -import junit.framework.Assert.*; - -/** - * Methods tested: - * getPIData - * getPITarget - * - * - * - */ -public abstract class PITest extends TestCase { - - public abstract XMLStreamReader getStream(XmlCursor c)throws Exception; - public void testGetPiData() throws XMLStreamException { - assertEquals(XMLStreamConstants.PROCESSING_INSTRUCTION, - m_stream.next()); - assertEquals("http://foobar", m_stream.getPIData()); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals(null, m_stream.getPIData()); - } - - public void testGetPiTarget() throws XMLStreamException { - assertEquals(XMLStreamConstants.PROCESSING_INSTRUCTION, - m_stream.next()); - assertEquals("xml-stylesheet", m_stream.getPITarget()); - assertEquals(XMLStreamConstants.START_ELEMENT, m_stream.next()); - assertEquals(null, m_stream.getPITarget()); - } - - public void setUp() throws Exception { - cur = XmlObject.Factory.newInstance().newCursor(); - cur.toNextToken(); - cur.insertProcInst("xml-stylesheet", "http://foobar"); - cur.insertElement("foobar"); - cur.toStartDoc(); - m_stream = getStream( cur ); - } - - public void tearDown() throws Exception - { - super.tearDown(); - if (m_stream != null) - m_stream.close(); - } - - private XMLStreamReader m_stream; - private XmlCursor cur; - -} - - diff --git a/test/src/xmlcursor/xpath/CustomerTest.java b/test/src/xmlcursor/xpath/CustomerTest.java deleted file mode 100755 index 31e61b9..0000000 --- a/test/src/xmlcursor/xpath/CustomerTest.java +++ /dev/null @@ -1,198 +0,0 @@ -package xmlcursor.xpath; - - -import java.io.*; -import java.util.HashMap; - -import org.apache.xmlbeans.*; - -/** - * - */ -public class CustomerTest -{ - - // public class XMLBeanXQueryTest { - - static String sXml = "\n" + - "\n" + - "\n" + - "\n" + - " Data on the Web\n" + - " Serge Abiteboul\n" + - " Peter Buneman\n" + - " Dan Suciu\n" + - "

        \n" + - " Introduction\n" + - "

        Text ...

        \n" + - "
        \n" + - " Audience\n" + - "

        Text ...

        \n" + - "
        \n" + - "
        \n" + - " Web Data and the Two Cultures\n" + - "

        Text ...

        \n" + - "
        \n" + - " Traditional client/server architecture\n" + - " \n" + - "
        \n" + - "

        Text ...

        \n" + - "
        \n" + - "
        \n" + - "
        \n" + - " A Syntax For Data\n" + - "

        Text ...

        \n" + - "
        \n" + - " Graph representations of structures\n" + - " \n" + - "
        \n" + - "

        Text ...

        \n" + - "
        \n" + - " Base Types\n" + - "

        Text ...

        \n" + - "
        \n" + - "
        \n" + - " Representing Relational Databases\n" + - "

        Text ...

        \n" + - "
        \n" + - " Examples of Relations\n" + - " \n" + - "
        \n" + - "
        \n" + - "
        \n" + - " Representing Object Databases\n" + - "

        Text ...

        \n" + - "
        \n" + - "
        \n" + - ""; - - - static String sXml1 = "\n" + - "
        \n" + - " Procedure\n" + - " \n" + - " The patient was taken to the operating room where she was placed\n" + - " in supine position and\n" + - "
        "; - - public static void test_xpath(int id, String xml, String xpath) - { - try - { - System.out.println("\n====== test" + id + ": " + xpath + " ======="); - XmlObject xmlObj = XmlObject.Factory.parse(xml); - XmlObject[] results = xmlObj.selectPath(xpath); - show_result(results); - } - catch (Throwable e) - { - e.printStackTrace(); - } - } - - public static void test_xquery(int id, String xmlFile, String xquery) - { - try - { - System.out.println("\n====== test" + id + ": " + xquery + " ======="); - XmlObject xmlObj = XmlObject.Factory.parse(sXml); - XmlObject[] results = xmlObj.execQuery(xquery); - show_result(results); - } - catch (Throwable e) - { - e.printStackTrace(); - } - } - - private static void show_result(Object[] results) - throws Throwable - { - for (int i = 0; i < results.length; i++) - { - Object node = results[i]; - System.out.println("=> class: " + node.getClass() + ", obj: " + node); - } - } - - public static void test_xpath() - { - System.out.println("\n====== xpath test ======="); - /* - test_xpath(1, "xml/data/book.xml", "./book/section[@difficulty = - \"easy\"]"); - test_xpath(2, "xml/data/book.xml", "./book/section"); - test_xpath(3, "xml/data/report1.xml", - "./report/section/section.title[text() = \"Procedure\"]"); - */ -// test_xpath(0, sXml, "./book/section"); -// test_xpath(1, sXml, "./book/section[@difficulty =\"easy\"]"); - test_xpath(2, sXml1, - "./report/section/section.title[text() = \"Procedure\"]"); -// test_xpath(3, sXml1, -// "./report/section[section.title = \"Procedure\"]"); - - // this is not allowed in XPath(but it is OK for XQuery). - // test_xpath(4, "xml/data/report1.xml", "./report/section/section.title =\"Procedure\""); - } - - public static void test_xquery() - { - System.out.println("\n====== xquery test ======="); - test_xquery(1, "xml/data/bib.xml", xquery1); - test_xquery(2, "xml/data/bib.xml", xquery2); - } - - /* - static final String xquery1 = "for $b in ./bib/book " - +" where $b/publisher[text() = \"Addison-Wesley\"] and $b[@year > 1992] " - +"return " - +" " - +"{ $b/title }" - +""; - static final String xquery2 = "for $b in ./bib/book " - +" where $b/publisher = \"Addison-Wesley\" and $b/@year > 1992 " - +"return " - +" " - +"{ $b/title }" - +""; - */ - static final String xquery1 = "for $b in $this/bib/book " - + - " where $b/publisher[text() = \"Addison-Wesley\"] and $b[@year > 1992] " - + "return " - + " " - + "{ $b/title }" - + ""; - static final String xquery2 = "for $b in $this/bib/book " - + " where $b/publisher = \"Addison-Wesley\" and $b/@year > 1992 " - + "return " - + " " - + "{ $b/title }" - + ""; - - public static void main(String[] args) - { - test_xpath(); - // test_xquery(); - try{ - testXMLBeans(); - }catch(Exception e){ - e.printStackTrace(); - } - } - - private static void testXMLBeans() throws Exception - { - XmlObject doc = XmlObject.Factory.parse(" "); - HashMap nsMap = new HashMap(); - nsMap.put("ns", "http://dearjohn/address-book"); - XmlObject[] xmlObjs = doc.execQuery("/ns:contact", new - XmlOptions().setLoadAdditionalNamespaces(nsMap)); - System.out.println(xmlObjs); - } - - -} - -//} diff --git a/test/src/xmlcursor/xpath/common/XPathCommon.java b/test/src/xmlcursor/xpath/common/XPathCommon.java deleted file mode 100755 index a235df8..0000000 --- a/test/src/xmlcursor/xpath/common/XPathCommon.java +++ /dev/null @@ -1,148 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.common; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import junit.framework.Assert; -import tools.xml.XmlComparator; - -/** - */ -public class XPathCommon { - - public static String display(XmlObject[] rObj) { - XmlOptions xm = new XmlOptions(); - xm.setSavePrettyPrint(); - xm.setLoadStripWhitespace(); - StringBuffer sb=new StringBuffer(); - for (int i = 0; i < rObj.length; i++) { - sb.append("[" + i + "] -- " + rObj[i].xmlText(xm)+"\n"); - } - return sb.toString(); - } - - - public static String getPrint(XmlObject[] rObj) { - XmlOptions xm = new XmlOptions(); - xm.setSavePrettyPrint(); - xm.setLoadStripWhitespace(); - - StringBuffer st = new StringBuffer(); - for (int i = 0; i < rObj.length; i++) { - st.append("[" + i + "] -- " + rObj[i].xmlText(xm)); - } - return st.toString(); - } - - public static String getPrint(XmlCursor rObj) { - XmlOptions xm = new XmlOptions(); - xm.setSavePrettyPrint(); - xm.setLoadStripWhitespace(); - - StringBuffer st = new StringBuffer(); - int i = 0; - while (rObj.toNextSelection()) { - st.append("[cursor-" + i + "] -- " + rObj.xmlText(xm)); - i++; - } - - return st.toString(); - } - - public static String display(XmlCursor rObj) { - XmlOptions xm = new XmlOptions(); - xm.setSavePrettyPrint(); - xm.setLoadStripWhitespace(); - StringBuffer sb=new StringBuffer(); - int i = 0; - while (rObj.toNextSelection()) { - sb.append("[cursor-" + i + "] -- " + rObj.xmlText(xm)+"\n"); - i++; - } - return sb.toString(); - } - - private static void check(XmlCursor actual, XmlCursor expected) { - try { - XmlComparator.Diagnostic diag = new XmlComparator.Diagnostic(); - boolean match = XmlComparator.lenientlyCompareTwoXmlStrings( - actual.xmlText(), - expected.xmlText(), diag); - - Assert.assertTrue("***********************\nFound difference: \nactual=\n'" + - actual.xmlText() + - "'\nexpected=\n'" + expected.xmlText() - + "'\ndiagnostic=" + diag, match); - } catch (XmlException e) { - throw new RuntimeException(e); - } - } - - public static void compare(XmlObject rObj, XmlObject rSet) throws Exception{ - check(rObj.newCursor(),rSet.newCursor()); - } - public static void compare(XmlObject[] rObj, XmlObject[] rSet) throws Exception { - - if (rObj.length != rSet.length) - throw new Exception("Comparison Failed\n " + - "Actual Count: "+rObj.length +" Expected Count: "+rSet.length+"\n" + - "Actual:"+getPrint(rObj)+"\nExpected:"+getPrint(rSet)); - - for (int i = 0; i < rObj.length; i++){ - check(rObj[i].newCursor(), rSet[i].newCursor()); - } - // This should be done in the test if no exception occurs...don't print here - // System.out.println("Test Passed"); - } - - public static void compare(XmlCursor rObj, XmlObject[] rSet) throws Exception { - if (rObj.getSelectionCount() != rSet.length) { - StringBuffer message = new StringBuffer(); - - message.append("EXPECTED ==\n"); - display(rSet); - message.append("ACTUAL ==\n"); - display(rObj); - - throw new Exception(message.toString()+ - "\nCompare failure == Result Count was not equal to actual count\n" + - "Actual Count: "+rObj.getSelectionCount() +" Expected Count: "+rSet.length+"\n" + - "Actual:" + getPrint(rObj) + "\nExpected:" + getPrint(rSet)); - } - int i = 0; - while (rObj.toNextSelection()) { - //System.out.println("[cursor-" + i + "] -- " + rObj.xmlText(xm)); - //System.out.println("[Expected-" + i + "] -- " + rSet[i].xmlText(xm)); - - check(rObj, rSet[i].newCursor()); - i++; - } - // This should be done in the test if no exception occurs...don't print here - // System.out.println("Test Passed"); - } - - public static void checkLength(XmlCursor rObj, int count) throws Exception{ - if(rObj.getSelectionCount() != count){ - throw new Exception("Length == Return Count was not equal\n"+ - "Cursor-Count: "+ rObj.getSelectionCount()+" Expected: "+count+"\n"+ - getPrint(rObj)); - } - } - -} diff --git a/test/src/xmlcursor/xpath/common/XPathFunctionAuxTest.java b/test/src/xmlcursor/xpath/common/XPathFunctionAuxTest.java deleted file mode 100644 index cdfb9b6..0000000 --- a/test/src/xmlcursor/xpath/common/XPathFunctionAuxTest.java +++ /dev/null @@ -1,294 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.common; - -import xmlcursor.common.BasicCursorTestCase; - -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; -import tools.util.JarUtil; - -import java.io.IOException; - -/** - * Verifies XPath using functions - * http://www.w3schools.com/xpath/xpath_functions.asp - */ - -public class XPathFunctionAuxTest - extends BasicCursorTestCase -{ - public XPathFunctionAuxTest(String sName) - { - super(sName); - } - - public static Test suite() - { - return new TestSuite(XPathFunctionAuxTest.class); - } - - static String fixPath(String path) - { - return path; - } - - public void testFunctionCount_caseB() - throws Exception - { - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/cdcatalog.xml")); - - String ex1Simple = "count(//cd)"; - String ex1R1 = Common.XMLFRAG_BEGINTAG + "26" + Common.XMLFRAG_ENDTAG; - XmlObject[] exXml1 = new XmlObject[]{XmlObject.Factory.parse(ex1R1)}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(ex1Simple); - XPathCommon.display(x1); - XPathCommon.compare(x1, exXml1); - x1.dispose(); - } - - public void testFunctionConcat_caseB() - throws Exception - { - String sXml = "3.00" + - "23.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "concat(name(/bar[position()=1]/*[position()=last()])," + - "//price[position()=1]/text())"; - String sExpected = Common.wrapInXmlFrag("price3.00"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionStringLength_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "string-length(name(//bar/*[last()]))"; - String sExpected = Common.wrapInXmlFrag("price".length() + ""); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionSubString_caseB() - throws Exception - { - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "substring(name(//bar[position()=1]/*[position()=1]),3,3)"; - String sExpected = Common.wrapInXmlFrag("ice"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(XmlCursor.TokenType.TEXT, - m_xc.currentTokenType()); - assertEquals(sExpected, m_xc.xmlText()); - - } - - public void testFunctionSubStringAfter_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "substring-after(name(//bar[position()=1]/*[position()=1]),'pr')"; - String sExpected = Common.wrapInXmlFrag("ice"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - - } - - public void testFunctionSubStringBefore_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "substring-before(" + - "name(//bar[position()=1]/*[position()=1]),'ice')"; - String sExpected = Common.wrapInXmlFrag("pr"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionTranslate_caseB() - throws Exception - { - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "translate(//bar[position()=1]/price[position()=1]/text()," + - "'200'," + - "'654')";//0 is now 5 &&4? - String sExpected = Common.wrapInXmlFrag("3.55"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionNumber_caseB() - throws Exception - { - String sXml = "3.003.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - String sXPath = "number(//price/text())+10"; - String sExpected = Common.wrapInXmlFrag("13.0"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - - } - - public void testFunctionRound_caseB() - throws Exception - { - String sXml = "3.152.873.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "round(//bar/price[position()=1]/text())"; - String sExpected = Common.wrapInXmlFrag("3.0"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionSum_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "sum(//bar/price)"; - String sExpected = Common.wrapInXmlFrag("5.0"); - m_xc.selectPath(sXPath); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } -// - - public void testFunctionBoolean_caseB_delete() - throws Exception - { - String sXml = "" + - "3.00" + - "2" + - "3.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "boolean(//foo/text())"; - m_xc.selectPath(sXPath); - System.out.println(m_xc.getSelectionCount()); - assertTrue(m_xc.toNextSelection()); - assertEquals(Common.wrapInXmlFrag("false"), - m_xc.xmlText()); - assertTrue(!m_xc.toNextSelection()); - System.out.println("DOC " + m_xc.xmlText()); - m_xc.clearSelections(); - m_xc.toStartDoc(); - m_xc.selectPath("boolean(//price/text())"); -// m_xc.selectPath("$this//bar"); - m_xc.toNextSelection(); - // System.out.println("HERE " + m_xc.xmlText()); - } - - public void testFunctionBoolean_caseB() - throws Exception - { - String sXml = "" + - "3.00" + - "2" + - "3.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - XmlCursor _startPos = m_xc.newCursor(); - - String sXPath = "boolean(//foo/text())";//"boolean(//foo/text())"; - m_xc.push(); - m_xc.selectPath(sXPath); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("false"), - m_xc.xmlText()); - m_xc.clearSelections(); - - //need to reset cursor since it's on a bool outside the doc - m_xc.pop(); - //number - m_xc.selectPath("boolean(//price/text())"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("true"), m_xc.xmlText()); - m_xc.clearSelections(); - - - //number - assertTrue(m_xc.toCursor(_startPos)); - //boolean of Nan is false - m_xc.selectPath("boolean(number(name(//price[position()=last()])))"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("false"), m_xc.xmlText()); - m_xc.clearSelections(); - - //node-set - m_xc.toCursor(_startPos); - m_xc.selectPath("boolean(//price)"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("true"), m_xc.xmlText()); - m_xc.clearSelections(); - - m_xc.toCursor(_startPos); - m_xc.selectPath("boolean(//barK)"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("false"), m_xc.xmlText()); - m_xc.clearSelections(); - - } - - public void testFunctionFalse_caseB() - throws Exception - { - m_xc = - XmlObject.Factory.parse( - "3.00") - .newCursor(); - m_xc.selectPath("name(//*[boolean(text())=false()])"); - String sExpected = Common.wrapInXmlFrag("foo"); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - - } -} diff --git a/test/src/xmlcursor/xpath/common/XPathLocationTest.java b/test/src/xmlcursor/xpath/common/XPathLocationTest.java deleted file mode 100755 index abfd8da..0000000 --- a/test/src/xmlcursor/xpath/common/XPathLocationTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.common; - -import xmlcursor.common.BasicCursorTestCase; -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * Verifies XPath with locations - * http://www.w3schools.com/xpath/xpath_location.asp - */ -public class XPathLocationTest extends BasicCursorTestCase { - - public XPathLocationTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(XPathLocationTest.class); - } - - //Axes and Node Tests - /** - * ancestor - * Contains all ancestors (parent, grandparent, etc.) of the current node - * Note: This axis will always include the root node, unless the current - * node is the root node - */ - public void testLocationAncestor() throws Exception { - //tested by zvon - } - - /** - * ancestor-or-self - * Contains the current node plus all its ancestors (parent, grandparent, etc.) - */ - public void testLocationAncestorOrSelf() throws Exception { - //tested by zvon??? - } - - /** - * attribute - * Contains all attributes of the current node - */ - public void testLocationAttribute() throws Exception { - - } - /** - * child - * Contains all children of the current node - */ - public void testLocationChild() throws Exception { - - } - /** - * descendant - * Contains all descendants (children, grandchildren, etc.) of the current node - * Note: This axis never contains attribute or namespace nodes - */ - public void testLocationDescendant() throws Exception { - - } - /** - * descendant-or-self - * Contains the current node plus all its descendants (children, grandchildren, etc.) - */ - public void testLocationDescendantOrSelf() throws Exception { - - } - /** - * following - * Contains everything in the document after the closing tag of the current node - */ - public void testLocationFollowing() throws Exception { - - } - /** - * following-sibling - * Contains all siblings after the current node - * Note: If the current node is an attribute node or namespace node, - * this axis will be empty - */ - public void testLocationFollowingSibling() throws Exception { - - } - /** - * namespace - * Contains all namespace nodes of the current node - */ - public void testLocationNamespace() throws Exception { - - } - /** - * parent - * Contains the parent of the current node - */ - public void testLocationParent() throws Exception { - - } - /** - * preceding - * Contains everything in the document that is before the starting tag - * of the current node - */ - public void testLocationPreceding() throws Exception { - - } - /** - * preceding-sibling - * Contains all siblings before the current node - * Note: If the current node is an attribute node or namespace node, - * this axis will be empty - */ - public void testLocationPrecedingSibling() throws Exception { - - } - /** - * self - * Contains the current node - */ - public void testLocationSelf() throws Exception { - - } - - - ////Predicates - ///** - // * - // */ - //public void testLocation() throws Exception { - // - //} - // - ////Location Path Abbreviated Syntax - ///** - // * - // */ - //public void testLocation() throws Exception { - // - //} - - - - - - - - - -} diff --git a/test/src/xmlcursor/xpath/common/XPathNodetestTest.java b/test/src/xmlcursor/xpath/common/XPathNodetestTest.java deleted file mode 100755 index e893c22..0000000 --- a/test/src/xmlcursor/xpath/common/XPathNodetestTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.common; - - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCursor.TokenType; - -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.*; - - -/** - * Verifies XPath nodetest functions - */ -public class XPathNodetestTest extends BasicCursorTestCase { - - - - public XPathNodetestTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(XPathNodetestTest.class); - } - - - static String fixPath(String path){ - return "."+path; - } - - - public void testAllNodes(){ - //e.g //A/B/*: tested by Zvon - } - - public void testComment()throws Exception { - String sXml=Common.XML_FOO_NS_PREFIX; - m_xc= XmlObject.Factory.parse(sXml).newCursor(); - String sExpected=Common.XMLFRAG_BEGINTAG+""+Common.XMLFRAG_ENDTAG;//the comment string - String sXPath="//comment()"; - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(m_xc.xmlText(),sExpected ); - } - - public void testNode()throws Exception{ - String sInput=" footxt"; - m_xc= XmlObject.Factory.parse(sInput).newCursor(); - String sXPath="//foo/node()"; - String[] sExpected=new String[]{Common.XMLFRAG_BEGINTAG+" "+Common.XMLFRAG_ENDTAG,"foo",Common.XMLFRAG_BEGINTAG+"txt"+Common.XMLFRAG_ENDTAG}; - m_xc.selectPath(fixPath(sXPath)); - int i=0; - if (m_xc.getSelectionCount()!=sExpected.length) - fail("node() failed"); - while(m_xc.hasNextSelection()){ - m_xc.toNextSelection(); - assertEquals(m_xc.xmlText(),sExpected[i++]); - } - - } - - public void testPI()throws Exception{ - String sInput=Common.XML_FOO_PROCINST; - m_xc= XmlObject.Factory.parse(sInput).newCursor(); - String sXPath1="//processing-instruction()"; - String sXPath2="//processing-instruction(\"xml-stylesheet\")"; - String sXPath3="//processing-instruction(\"xsl\")"; - String sExpected1=Common.XMLFRAG_BEGINTAG+""+Common.XMLFRAG_ENDTAG; - String sExpected2=""; - m_xc.selectPath(fixPath(sXPath1)); - assertEquals(m_xc.getSelectionCount(),1); - m_xc.toNextSelection(); - assertEquals(m_xc.xmlText(),sExpected1); - - - m_xc.clearSelections(); - m_xc.selectPath(fixPath(sXPath2)); - assertEquals(m_xc.xmlText(),sExpected1); - - m_xc.clearSelections(); - //shouldn't select any nodes - m_xc.selectPath(fixPath(sXPath3)); - assertEquals(m_xc.getSelectionCount(),0); - - } - - public void testText()throws Exception{ - String sInput="
        footext
        "; - m_xc= XmlObject.Factory.parse(sInput).newCursor(); - String sXPath="//text()"; - String sExpected1=Common.XMLFRAG_BEGINTAG+"foo"+Common.XMLFRAG_ENDTAG; - String sExpected2=Common.XMLFRAG_BEGINTAG+"text"+Common.XMLFRAG_ENDTAG; - m_xc.selectPath(sXPath); - assertEquals(m_xc.getSelectionCount(),2); - m_xc.toNextSelection(); - assertEquals(m_xc.xmlText(),sExpected1); - m_xc.toNextSelection(); - assertEquals(m_xc.xmlText(),sExpected2); - } - - public void testTextObject()throws Exception{ - String sInput="
        footext
        "; - m_xo= XmlObject.Factory.parse(sInput); - String sXPath="//text()"; - String sExpected1=Common.XMLFRAG_BEGINTAG+"foo"+Common.XMLFRAG_ENDTAG; - String sExpected2=Common.XMLFRAG_BEGINTAG+"text"+Common.XMLFRAG_ENDTAG; - XmlObject[] res=m_xo.selectPath(sXPath); - assertEquals(res.length,2); - assertEquals(res[0].xmlText(),sExpected1); - assertEquals(res[1].xmlText(),sExpected2); - } -} - - diff --git a/test/src/xmlcursor/xpath/complex/checkin/ContainerCommentTest.java b/test/src/xmlcursor/xpath/complex/checkin/ContainerCommentTest.java deleted file mode 100644 index 33abd2a..0000000 --- a/test/src/xmlcursor/xpath/complex/checkin/ContainerCommentTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xpath.complex.checkin; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import junit.framework.TestCase; - -/** - * Date: Apr 12, 2005 - * Time: 1:08:39 PM - * This class tests the execution of an XQuery where the - * starting point of the query is a comment - */ -public class ContainerCommentTest extends TestCase -{ - public static void testFunctionPathWithCursor() throws Exception - { - - - XmlObject employees = XmlObject.Factory.parse(sXml); - String m_namespaceDeclaration = - "declare namespace xq='http://xmlbeans.apache.org/samples/xquery/employees';"; - - boolean hasResults = false; - String[] names; - - XmlCursor cursor = employees.newCursor(); - cursor.toNextToken(); - - cursor.selectPath(m_namespaceDeclaration + "$this//xq:employee"); - if (cursor.getSelectionCount() > 0) - { - hasResults = true; - cursor.toNextSelection(); - - names = new String[cursor.getSelectionCount()]; - - for (int i = 0; i < cursor.getSelectionCount(); i++) - { - XmlCursor nameCursor = cursor.newCursor(); - nameCursor.selectPath(m_namespaceDeclaration + - "$this/xq:name/text()"); - nameCursor.toNextSelection(); - names[i] = nameCursor.getTextValue(); - cursor.toNextSelection(); - System.out.println(names[i]); - } - } - } - - static String prolog="" + - ""; - public static String sXml=prolog+ - "\n" + - " \n" + - " Fred Jones\n" + - "
        \n" + - " 900 Aurora Ave.\n" + - " Seattle\n" + - " WA\n" + - " 98115\n" + - "
        \n" + - " (425)555-5665\n" + - " (206)555-5555\n" + - " (206)555-4321\n" + - "
        \n" + - "
        "; - - -} diff --git a/test/src/xmlcursor/xpath/complex/checkin/JaxenXPathTests.java b/test/src/xmlcursor/xpath/complex/checkin/JaxenXPathTests.java deleted file mode 100755 index 8830eea..0000000 --- a/test/src/xmlcursor/xpath/complex/checkin/JaxenXPathTests.java +++ /dev/null @@ -1,356 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xpath.complex.checkin; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import xmlcursor.common.Common; -import xmlcursor.xpath.common.XPathCommon; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.PrintWriter; - -/** - * - */ -public class JaxenXPathTests - extends TestCase -{ - String sXml = - "" + - "" + - "" + - "" + - " " + - " " + - "" + - " "; - - - public JaxenXPathTests(String name) - { - super(name); - } - - public static Test suite() - { - return new TestSuite(JaxenXPathTests.class); - } - - public void testConformance() - throws Exception - { - XmlObject doc = XmlObject.Factory.parse(sXml); - runAll(doc, xpath); - } - - private void runAll(XmlObject doc, String[] xpathes) - throws Exception - { - StringBuffer errors = new StringBuffer(); - boolean bFail = false; - for (int i = 0; i < xpathes.length; i++) - { - try - { - runXpath2(doc, xpathes[i], i); - } - catch (Exception e) - { - bFail = true; - errors.append("**********************Failed at test " + i + - "\n path:" + xpathes[i] + "\n"); -// if (e.getMessage() == null) -// { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - errors.append(sw); -// } -// else - errors.append(e.getMessage()); - errors.append("\n\n"); - } - } - - if (bFail) - throw new RuntimeException(errors.toString()); - } - -// private static void runXpath(XmlObject doc, String xpathStr, int i) -// { -// try -// { -// XmlCursor xc = doc.newCursor(); -// XPath xpath = new XBeansXPath(xpathStr); -// List results = xpath.selectNodes( xc ); -// -// Iterator resultIter = results.iterator(); -// -// int j = 0; -// while ( resultIter.hasNext() ) -// { -// xc = (XmlCursor)resultIter.next(); //it's the same object as previous xc -// // generateExpected(i, j, xc.toString()); -// check(i, j, xc); -// j++; -// } -// -// xc.dispose(); -// } -// catch (XPathSyntaxException e) -// { -// System.err.println( e.getMultilineMessage() ); -// throw new RuntimeException(e); -// } -// catch (JaxenException e) -// { -// throw new RuntimeException(e); -// } -// } - - private void runXpath2(XmlObject doc, String xpathStr, int i) - throws Exception - { - XmlCursor xc = doc.newCursor(); - xc.selectPath(xpathStr); - check(i, xc); - xc.dispose(); - } - - private void check(int expresionNumber, - XmlCursor actual) - throws Exception - { - - if (actual.getSelectionCount() == 0) - { - assertEquals(null, expected[expresionNumber]); - return; - } - - int numCases = expected[expresionNumber].length; - XmlObject[] expected_val = new XmlObject[numCases]; - - - for (int i = 0; i < numCases; i++) - expected_val[i] = XmlObject.Factory.parse( - expected[expresionNumber][i]); - - try - { - XPathCommon.compare(actual, expected_val); - } - catch (Throwable e) - { - throw new Exception(e.getMessage()); - } - - } - - /** - * This is only used to regen the expected files. - */ - private void generateExpected(int expresionNumber, int resultNumber, - String content) - { - expected[expresionNumber][resultNumber] = content; - } - - public void setUp() - { - expected = new String[numExpressions][]; - - - xpath = new String[numExpressions]; - xpath[0] = "/doc/a/@test"; - xpath[1] = "//."; - xpath[2] = "/doc"; - xpath[3] = "/doc/a"; - xpath[4] = "//@*"; - xpath[5] = "."; - xpath[6] = "//ancestor-or-self::*"; - xpath[7] = "./child::*[1]"; - xpath[8] = "//descendant-or-self::*/@*[1]"; - xpath[9] = "//@* | * | node()"; - xpath[10] = "//*"; - xpath[11] = "/doc/n"; //"/doc/namespace::*"; - xpath[12] = "//descendant::comment()"; - xpath[13] = "//*[local-name()='a']"; - xpath[14] = "//*/@*"; - xpath[15] = "//*[last()]"; - xpath[16] = "doc/*[last()]"; - xpath[17] = "/doc/a/*/@*"; - xpath[18] = "doc/descendant::node()"; - xpath[19] = "doc/a/@*"; - xpath[20] = "doc/b/a/ancestor-or-self::*"; - xpath[21] = "doc/b/a/preceding::*"; - xpath[22] = "doc/a/following::*"; - xpath[23] = "/doc/b/preceding-sibling::*"; - xpath[24] = "/doc/a/following-sibling::*"; - - - String[] steps = new String[12]; - final String DEFAULT_NS = - ""; - steps[0] = - ""; - steps[1] = "" + - "" + - "" + - " "; - steps[2] = - ""; - steps[3] = - " "; - steps[4] = - ""; - steps[5] = - "" + - " "; - steps[6] = - ""; - steps[7] = - ""; - steps[8] = ""; - steps[9] = " "; - steps[10] = " "; - steps[11] = " "; - - expected[0] = new String[]{steps[2]}; - expected[1] = new String[]{sXml, - steps[1], - steps[2], - steps[5], - XMLFRAG_EMPTY, - steps[10], - XMLFRAG_EMPTY, - steps[8], - }; - - expected[2] = new String[]{steps[1]}; - expected[3] = new String[]{steps[2]}; - - expected[4] = new String[]{ - steps[3], - steps[6], - steps[7]}; - - expected[5] = new String[]{sXml}; - expected[6] = new String[]{sXml, - steps[2], - steps[5], - steps[10]}; - expected[7] = new String[]{steps[1]}; - expected[8] = - new String[]{ - steps[2], - steps[6]}; - - /** - * This is tricky: - * The expression "*" is true for the principal axis: since the axis is - * self, so we're looking for elements: doc elt - * node() also returns the doc elt, but also the comment - * nodes in the union set are returned in doc order - */ - expected[9] = new String[]{ - steps[1], - steps[3], - steps[6], - steps[7], - steps[8] - }; - - expected[10] = new String[]{ - steps[1], - steps[2], - steps[5], - steps[4] - }; - expected[11] = null; //new String[]{steps[0],DEFAULT_NS}; - expected[12] = new String[]{steps[8]}; - expected[13] = new String[]{steps[2], - steps[4] - }; - expected[14] = new String[]{steps[3], - steps[6], - steps[7]}; - - expected[15] = new String[]{steps[1], - steps[5], - steps[4]}; - expected[16] = new String[]{steps[5]}; - //TODO: BUGBUG: fix this - expected[17] = null; - - expected[18] = new String[]{ - steps[2], - steps[5], - steps[11], - steps[10], - steps[11] - }; - expected[19] = new String[]{steps[2]}; - expected[20] = new String[]{ - steps[1], - steps[5], - steps[4], - }; - expected[21] = new String[]{ - steps[2] - - }; - expected[22] = new String[]{ - steps[5], - steps[4]}; - - expected[23] = new String[]{ - steps[2]}; - - expected[24] = new String[]{ - steps[5]}; - - } - - private String[][] expected = null; - private String[] xpath = null; - private int numExpressions = 25; - private String XMLFRAG_EMPTY = ""; - - public void testDelete() throws Exception - { - String query="*"; - - XmlCursor xc = XmlObject.Factory.parse(sXml).newCursor(); - xc.selectPath(query); - while (xc.toNextSelection()) - System.out.println(xc.xmlText()); - } -} diff --git a/test/src/xmlcursor/xpath/complex/detailed/NodeCopyTest.java b/test/src/xmlcursor/xpath/complex/detailed/NodeCopyTest.java deleted file mode 100644 index 6f4c1b4..0000000 --- a/test/src/xmlcursor/xpath/complex/detailed/NodeCopyTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xpath.complex.detailed; - -import junit.framework.TestCase; -import org.apache.xmlbeans.*; -//import xbean.scomp.element.globalEltDefault.GlobalEltDefaultIntDocument; - -/** - * - */ -public class NodeCopyTest extends TestCase { - - public static void testNS() throws Exception{ - XmlObject s=XmlObject.Factory.parse("foobar"); - XmlObject[] res; - /* - res=s.selectPath("./a"); - assertTrue(s.selectChildren("","a")[0] == res[0] ); - assertEquals( res[0].xmlText(),"foobar"); - //"for $e in ./a return { $e } " - */ - XmlCursor s1=s.newCursor().execQuery("./a"); - assertEquals("foobar",s1.xmlText()); - - res=s.execQuery("./a"); - XmlCursor c1=s.newCursor(); - c1.toFirstContentToken(); - - XmlObject o = c1.getObject(); - assertTrue(o != res[0]); - assertEquals("foobar",res[0].xmlText()); - } - - public static void testText() throws Exception{ - XmlObject s=XmlObject.Factory.parse("barfoo"); - XmlObject[] res; - res=s.selectPath(".//text()"); - assertEquals(2, res.length); - assertEquals("bar",res[0].xmlText()); - assertEquals("foo",res[1].xmlText()); - } - - public static void testCount() throws Exception{ - XmlObject s=XmlObject.Factory.parse("barfoo"); - XmlObject[] res; - res=s.selectPath("count(.//b)"); - System.out.println(res[0].xmlText()); - XmlLong i=(XmlLong)res[0]; - assertEquals((long)1, i.getLongValue()); - // res= s.selectPath("//b"); - } - - /* - public void testInt()throws Exception{ - GlobalEltDefaultIntDocument d= - GlobalEltDefaultIntDocument.Factory - .parse("" + - "3"+ - ""); - d.getGlobalEltDefaultInt(); - } - */ - - public void testXmlObjectSelectPath(){ - - } - - public void testDeleteMe() throws Exception - { - XmlObject t= XmlObject.Factory.parse(""); - XmlCursor cursor = - t.newCursor(); - System.out.println(cursor.getObject()); - // use xpath to select elements - cursor.selectPath("*/*"); - - System.out.println("cnt "+cursor.getSelectionCount()); - // iterate over the selection - while (cursor.toNextSelection()) - { - // two views of the same data: - // move back and forth between XmlObject <-> XmlCursor - XmlObject trans =cursor.getObject(); - - System.out.println("Trans "+trans.xmlText()); - System.out.println("xmlText "+cursor.xmlText()); - - } - - } -} diff --git a/test/src/xmlcursor/xpath/complex/detailed/TypesTest.java b/test/src/xmlcursor/xpath/complex/detailed/TypesTest.java deleted file mode 100644 index 9bb2701..0000000 --- a/test/src/xmlcursor/xpath/complex/detailed/TypesTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xpath.complex.detailed; - -import org.apache.xmlbeans.GDurationSpecification; -import org.apache.xmlbeans.GDurationBuilder; -import org.apache.xmlbeans.XmlDate; -import org.apache.xmlbeans.XmlDecimal; -import org.apache.xmlbeans.XmlObject; -//import org.apache.xmlbeans.XmlInt; -import org.apache.xmlbeans.XmlLong; -import org.apache.xmlbeans.XmlTime; -//import org.apache.xmlbeans.XmlByte; -import org.apache.xmlbeans.XmlAnyURI; -//import org.apache.xmlbeans.XmlDateTime; - -import junit.framework.TestCase; - -/** - * - */ -public class TypesTest - extends TestCase -{ - XmlObject o; - XmlObject[] res; - - public void setUp() - throws Exception - { - o = XmlObject.Factory.parse(""); - } - - public void testDate() - { - res = o.selectPath("xs:date(\"2000-01-01\")"); - assertEquals(1, res.length); - XmlDate d = ((XmlDate) res[0]); - assertEquals( - "Fri Dec 31 16:00:00 PST 1999", - d.xmlText()); - } - - public void testDecimal() - { - res = - o.selectPath( - "seconds-from-dateTime(xs:dateTime('1997-07-16T19:20:30+01:00'))"); - assertEquals(1, res.length); - XmlDecimal dec = ((XmlDecimal) res[0]); - assertEquals("30", dec.xmlText()); - } - - //Saxon returns string here, though the string is a valid duration - //representation - public void testDuration() throws Exception - { - res = o.selectPath("xs:dayTimeDuration(\"PT12H\")*4"); - assertEquals(1, res.length); - System.out.println(res[0].schemaType()); - String s = res[0].xmlText(); - System.out.println(s); - int i = s.indexOf("(\""); - int j = s.indexOf("\")"); - assertTrue(0 < i); - assertTrue(i < j); - String duration = s.substring(i+2, j); - System.out.println(duration); - GDurationSpecification gDur = new GDurationBuilder(duration); - System.out.println(gDur.getDay()); - assertEquals(2, gDur.getDay()); - } - - public static void testTypes() - throws Exception - { - XmlObject o = XmlObject.Factory.parse( - "foobar"); - XmlObject[] res = null; - - //Long - res = o.selectPath("hours-from-dateTime(" + - "current-dateTime()) cast as xs:integer"); - assertEquals(1, res.length); - System.out.println(res[0].schemaType()); - XmlLong xl = ((XmlLong) res[0]); - System.out.println(xl.xmlText()); - - //Java type is string... - res = o.selectPath("current-time()"); - assertEquals(1, res.length); - System.out.println(res[0].schemaType()); - System.out.println(res[0].xmlText()); - XmlTime time = XmlTime.Factory.parse(res[0].xmlText()); - System.out.println(time.xmlText()); - - /* - res = o.selectPath("subtract-dateTimes-yielding-dayTimeDuration(" + - "current-dateTime()," + - "current-dateTime())"); - assertEquals(1, res.length); - XmlDuration dur = ((XmlDuration) res[0]); - System.out.println(dur.xmlText()); - */ - //Java type is long--is query right? - res = o.selectPath("xs:byte(3)"); - assertEquals(1, res.length); - System.out.println(res[0].schemaType()); //xs:long - //XmlByte b = ((XmlByte) res[0]); - //System.out.println(b.xmlText()); - - //Java type is string - res = o.selectPath("base-uri(/a)"); - assertEquals(1, res.length); - System.out.println(res[0].schemaType()); //xs:string - XmlAnyURI u = XmlAnyURI.Factory.parse(res[0].xmlText()); - System.out.println(u.xmlText()); - - //java type is Date - res = o.selectPath("current-dateTime()"); - assertEquals(1, res.length); - System.out.println(res[0].schemaType()); - XmlDate dt = ((XmlDate) res[0]); - System.out.println(dt.xmlText()); - } - -} diff --git a/test/src/xmlcursor/xpath/complex/detailed/XPathFunctionAuxTest.java b/test/src/xmlcursor/xpath/complex/detailed/XPathFunctionAuxTest.java deleted file mode 100755 index 5dd74ad..0000000 --- a/test/src/xmlcursor/xpath/complex/detailed/XPathFunctionAuxTest.java +++ /dev/null @@ -1,297 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.complex.detailed; - -import xmlcursor.common.BasicCursorTestCase; - -import xmlcursor.common.Common; -import xmlcursor.xpath.common.XPathCommon; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; -import tools.util.JarUtil; - -import java.io.IOException; - -/** - * Verifies XPath using functions - * http://www.w3schools.com/xpath/xpath_functions.asp - * - * @status inactive - */ - -public class XPathFunctionAuxTest - extends BasicCursorTestCase -{ - public XPathFunctionAuxTest(String sName) - { - super(sName); - } - - public static Test suite() - { - return new TestSuite(XPathFunctionAuxTest.class); - } - - static String fixPath(String path) - { - return path; - } - - public void testFunctionCount_caseB() - throws Exception - { - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/cdcatalog.xml")); - - String ex1Simple = "count(//cd)"; - String ex1R1 = Common.XMLFRAG_BEGINTAG + "26" + Common.XMLFRAG_ENDTAG; - XmlObject[] exXml1 = new XmlObject[]{XmlObject.Factory.parse(ex1R1)}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(ex1Simple); - XPathCommon.display(x1); - XPathCommon.compare(x1, exXml1); - x1.dispose(); - } - - public void testFunctionConcat_caseB() - throws Exception - { - String sXml = "3.00" + - "23.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "concat(name(//bar[position()=1]/*[position()=last()])," + - "//price[position()=1]/text())"; - String sExpected = Common.wrapInXmlFrag("price3.00"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionStringLength_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "string-length(name(//bar/*[last()]))"; - String sExpected = Common.wrapInXmlFrag("price".length() + ""); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionSubString_caseB() - throws Exception - { - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "substring(name(//bar[position()=1]/*[position()=1]),3,3)"; - String sExpected = Common.wrapInXmlFrag("ice"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(XmlCursor.TokenType.TEXT, - m_xc.currentTokenType()); - assertEquals(sExpected, m_xc.xmlText()); - - } - - public void testFunctionSubStringAfter_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "substring-after(name(//bar[position()=1]/*[position()=1]),'pr')"; - String sExpected = Common.wrapInXmlFrag("ice"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - - } - - public void testFunctionSubStringBefore_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "substring-before(" + - "name(//bar[position()=1]/*[position()=1]),'ice')"; - String sExpected = Common.wrapInXmlFrag("pr"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionTranslate_caseB() - throws Exception - { - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "translate(//bar[position()=1]/price[position()=1]/text()," + - "'200'," + - "'654')";//0 is now 5 &&4? - String sExpected = Common.wrapInXmlFrag("3.55"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionNumber_caseB() - throws Exception - { - String sXml = "3.003.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - String sXPath = "number(//price/text())+10"; - String sExpected = Common.wrapInXmlFrag("13.0"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - - } - - public void testFunctionRound_caseB() - throws Exception - { - String sXml = "3.152.873.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "round(//bar/price[position()=1]/text())"; - String sExpected = Common.wrapInXmlFrag("3.0"); - m_xc.selectPath(fixPath(sXPath)); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } - - public void testFunctionSum_caseB() - throws Exception - { - - String sXml = "3.0023.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "sum(//bar/price)"; - String sExpected = Common.wrapInXmlFrag("5.0"); - m_xc.selectPath(sXPath); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - } -// - - public void testFunctionBoolean_caseB_delete() - throws Exception - { - String sXml = "" + - "3.00" + - "2" + - "3.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - - String sXPath = "boolean(//foo/text())"; - m_xc.selectPath(sXPath); - System.out.println(m_xc.getSelectionCount()); - assertTrue(m_xc.toNextSelection()); - assertEquals(Common.wrapInXmlFrag("false"), - m_xc.xmlText()); - assertTrue(!m_xc.toNextSelection()); - System.out.println("DOC " + m_xc.xmlText()); - m_xc.clearSelections(); - m_xc.toStartDoc(); - m_xc.selectPath("boolean(//price/text())"); -// m_xc.selectPath("$this//bar"); - m_xc.toNextSelection(); - // System.out.println("HERE " + m_xc.xmlText()); - } - - public void testFunctionBoolean_caseB() - throws Exception - { - String sXml = "" + - "3.00" + - "2" + - "3.00"; - m_xc = XmlObject.Factory.parse(sXml).newCursor(); - XmlCursor _startPos = m_xc.newCursor(); - - String sXPath = "boolean(//foo/text())";//"boolean(//foo/text())"; - m_xc.push(); - m_xc.selectPath(sXPath); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("false"), - m_xc.xmlText()); - m_xc.clearSelections(); - - //need to reset cursor since it's on a bool outside the doc - m_xc.pop(); - //number - m_xc.selectPath("boolean(//price/text())"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("true"), m_xc.xmlText()); - m_xc.clearSelections(); - - - //number - assertTrue(m_xc.toCursor(_startPos)); - //boolean of Nan is false - m_xc.selectPath("boolean(number(name(//price[position()=last()])))"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("false"), m_xc.xmlText()); - m_xc.clearSelections(); - - //node-set - m_xc.toCursor(_startPos); - m_xc.selectPath("boolean(//price)"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("true"), m_xc.xmlText()); - m_xc.clearSelections(); - - m_xc.toCursor(_startPos); - m_xc.selectPath("boolean(//barK)"); - m_xc.toNextSelection(); - assertEquals(Common.wrapInXmlFrag("false"), m_xc.xmlText()); - m_xc.clearSelections(); - - } - - public void testFunctionFalse_caseB() - throws Exception - { - m_xc = - XmlObject.Factory.parse( - "3.00") - .newCursor(); - m_xc.selectPath("name(//*[boolean(text())=false()])"); - String sExpected = Common.wrapInXmlFrag("foo"); - m_xc.toNextSelection(); - assertEquals(sExpected, m_xc.xmlText()); - - } -} diff --git a/test/src/xmlcursor/xpath/complex/detailed/XPathTest.java b/test/src/xmlcursor/xpath/complex/detailed/XPathTest.java deleted file mode 100755 index 721fe6f..0000000 --- a/test/src/xmlcursor/xpath/complex/detailed/XPathTest.java +++ /dev/null @@ -1,1325 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.complex.detailed; - -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import xmlcursor.xpath.common.XPathCommon; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; -import tools.util.JarUtil; -import tools.xml.XmlComparator; - -import java.io.IOException; - -/** - * Verifies XPath impl using examples from - * http://www.zvon.org/xxl/XPathTutorial/Output/example1.html - * includes expanded notations as well - * - */ -public class XPathTest - extends BasicCursorTestCase -{ - public XPathTest(String sName) - { - super(sName); - } - - public static Test suite() - { - return new TestSuite(XPathTest.class); - } - - static String fixPath(String path) - { - // return "$this" + path; - return path; - } - - - /** - * @throws Exception - */ - public void testZvonExample1() - throws Exception - { - System.out.println("====== Example-1 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon1.xml")); - - String ex1Simple = "/AAA"; - String ex1Expanded = ""; - - String ex1R1 = ""; - XmlObject[] exXml1 = new XmlObject[]{XmlObject.Factory.parse(ex1R1)}; - - String ex2Simple = "/AAA/CCC"; - String ex2Expanded = ""; - - String ex2R1 = ""; - - XmlObject[] exXml2 = new XmlObject[]{XmlObject.Factory.parse(ex2R1), - XmlObject.Factory.parse(ex2R1)}; - - - String ex3Simple = "/AAA/DDD/BBB"; - String ex3Expanded = ""; - - // - String ex3R1 = ""; - XmlObject[] exXml3 = new XmlObject[]{XmlObject.Factory.parse(ex3R1)}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - XPathCommon.compare(x1, exXml1); - x1.dispose(); - - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - XPathCommon.compare(x2, exXml2); - x2.dispose(); - - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - XPathCommon.compare(x3, exXml3); - x3.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample2() - throws Exception - { - System.out.println("====== Example-2 =========="); - - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon2.xml")); - String ex1Simple = "//BBB"; - String ex1Expanded = ""; - - String ex1R1 = ""; // * 5 - XmlObject[] exXml1 = new XmlObject[]{XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1)}; - - String ex2Simple = "//DDD/BBB"; - String ex2Expanded = ""; - XmlObject[] exXml2 = new XmlObject[]{XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1)}; - - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - XPathCommon.compare(x1, exXml1); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - XPathCommon.compare(x2, exXml2); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample3() - throws Exception - { - System.out.println("====== Example-3 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon3.xml")); - String ex1Simple = "/AAA/CCC/DDD/*"; - String ex1R1 = ""; // * 5 - String ex1R2 = ""; - String ex1R3 = ""; - - XmlObject[] exXml1 = new XmlObject[]{XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R1), - XmlObject.Factory.parse(ex1R2), - XmlObject.Factory.parse(ex1R3)}; - String ex2Simple = "/*/*/*/BBB"; - String ex2R1 = ""; // * 5 - String ex2R2 = ""; - XmlObject[] exXml2 = new XmlObject[]{XmlObject.Factory.parse(ex2R1), - XmlObject.Factory.parse(ex2R1), - XmlObject.Factory.parse(ex2R1), - XmlObject.Factory.parse(ex2R1), - XmlObject.Factory.parse(ex2R2)}; - String ex3Simple = "//*"; - /* String ex3R0 = ""; - String ex3R1 = ""; - String ex3R2 = ""; - String ex3R3 = ""; - String ex3R4 = ""; - String ex3R5 = ""; - String ex3R6 = ""; - String ex3R7 = ""; - String ex3R8 = ""; - String ex3R9 = ""; - String ex3R10 = ""; - String ex3R11 = ""; - String ex3R12 = ""; - String ex3R13 = ""; - String ex3R14 = ""; - String ex3R15 = ""; - String ex3R16 = ""; - */ - //according to Galax the document order is : - String ex3R0 = ""; - String ex3R1 = ""; - - String ex3R2 = ""; - String ex3R3 = ""; - String ex3R4 = ""; - String ex3R5 = ""; - String ex3R6 = ""; - String ex3R7 = ""; - - String ex3R8 = ""; - - String ex3R9 = ""; - String ex3R10 = ""; - String ex3R11 = ""; - String ex3R12 = ""; - String ex3R13 = ""; - String ex3R14 = ""; - String ex3R15 = ""; - String ex3R16 = ""; - XmlObject[] exXml3 = new XmlObject[]{XmlObject.Factory.parse(ex3R0), - XmlObject.Factory.parse(ex3R1), - XmlObject.Factory.parse(ex3R2), - XmlObject.Factory.parse(ex3R3), - XmlObject.Factory.parse(ex3R4), - XmlObject.Factory.parse(ex3R5), - XmlObject.Factory.parse(ex3R6), - XmlObject.Factory.parse(ex3R7), - XmlObject.Factory.parse(ex3R8), - XmlObject.Factory.parse(ex3R9), - XmlObject.Factory.parse(ex3R10), - XmlObject.Factory.parse(ex3R11), - XmlObject.Factory.parse(ex3R12), - XmlObject.Factory.parse(ex3R13), - XmlObject.Factory.parse(ex3R14), - XmlObject.Factory.parse(ex3R15), - XmlObject.Factory.parse(ex3R16)}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, exXml1); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, exXml2); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - System.out.println(x3.xmlText()); - XPathCommon.compare(x3, exXml3); - x3.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample4() - throws Exception - { - System.out.println("====== Example-4 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon4.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/BBB[1]"; - String ex2Simple = "/AAA/BBB[last()]"; - String exR = ""; - XmlObject[] exXml = new XmlObject[]{XmlObject.Factory.parse(exR)}; - - - System.out.println("Test 1: " + fixPath(ex1Simple)); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, exXml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, exXml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample5() - throws Exception - { - System.out.println("====== Example-5 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon5.xml")); - XmlCursor xc = xDoc.newCursor(); - - String ex1Simple = "//@id"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex2Simple = "//BBB[@id]"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex3Simple = "//BBB[@name]"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - - String ex4Simple = "//BBB[@*]"; - XmlObject[] ex4Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex5Simple = "//BBB[not(@*)]"; - XmlObject[] ex5Xml = new XmlObject[]{ - XmlObject.Factory.parse("") - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - - System.out.println("Test 4: " + ex4Simple); - XmlCursor x4 = xDoc.newCursor(); - x4.selectPath(fixPath(ex4Simple)); - //XPathCommon.display(x4); - XPathCommon.compare(x4, ex4Xml); - x4.dispose(); - - System.out.println("Test 5: " + ex5Simple); - XmlCursor x5 = xDoc.newCursor(); - x5.selectPath(fixPath(ex5Simple)); - //XPathCommon.display(x5); - XPathCommon.compare(x5, ex5Xml); - - x5.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample6() - throws Exception - { - System.out.println("====== Example-16 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon6.xml")); - XmlCursor xc = xDoc.newCursor(); - - String ex1Simple = "//BBB[@id='b1']"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - - String ex2Simple = "//BBB[@name='bbb']"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - String ex3Simple = "//BBB[normalize-space(@name)='bbb']"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse("") - , - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample7() - throws Exception - { - System.out.println("====== Example-7 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon7.xml")); - XmlCursor xc = xDoc.newCursor(); - - String ex1Simple = "//*[count(BBB)=2]"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - String ex2Simple = "//*[count(*)=2]"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - String ex3Simple = "//*[count(*)=3]"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample8() - throws Exception - { - System.out.println("====== Example-8 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon8.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "//*[name()='BBB']"; - XmlObject[] ex1Xml = new XmlObject[]{XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - }; - String ex2Simple = "//*[starts-with(name(),'B')]"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - /**ykadiysk: Jaxen prints in BF left-to-right order - * but XPath wants doc order - XmlObject[] ex2Xml = new XmlObject[]{XmlObject.Factory.parse(""), - - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - */ - - String ex3Simple = "//*[contains(name(),'C')]"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - System.out.println("Zvon8 Test 2"); - XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample9() - throws Exception - { - System.out.println("====== Example-9 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon9.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "//*[string-length(name()) = 3]"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse("")}; - String ex2Simple = "//*[string-length(name()) < 3]"; - XmlObject[] ex2Xml = new XmlObject[]{XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - String ex3Simple = "//*[string-length(name()) > 3]"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample10() - throws Exception - { - System.out.println("====== Example-10 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon10.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "$this//CCC | $this//BBB"; - //document order - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - - }; - // Nodes are returned in document order - String ex2Simple = "$this/AAA/EEE | $this//BBB"; - - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - - }; - - String ex3Simple = "./AAA/EEE |.//DDD/CCC | ./AAA | .//BBB"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(ex1Simple); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(ex2Simple); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample11() - throws Exception - { - System.out.println("====== Example-11 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon11.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - - String ex2Simple = "/child::AAA"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - - String ex3Simple = "/AAA/BBB"; - XmlObject[] ex3Xml = new XmlObject[]{XmlObject.Factory.parse("")}; - - String ex4Simple = "/child::AAA/child::BBB"; - XmlObject[] ex4Xml = new XmlObject[]{XmlObject.Factory.parse("")}; - - String ex5Simple = "/child::AAA/BBB"; - XmlObject[] ex5Xml = new XmlObject[]{XmlObject.Factory.parse("")}; - - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - - System.out.println("Test 4: " + ex4Simple); - XmlCursor x4 = xDoc.newCursor(); - x4.selectPath(fixPath(ex4Simple)); - XPathCommon.display(x4); - XPathCommon.display(ex4Xml); - XPathCommon.compare(x4, ex4Xml); - x4.dispose(); - - System.out.println("Test 5: " + ex5Simple); - XmlCursor x5 = xDoc.newCursor(); - x5.selectPath(fixPath(ex5Simple)); - //XPathCommon.display(x5); - XPathCommon.compare(x5, ex5Xml); - x5.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample12() - throws Exception - { - System.out.println("====== Example-12 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon12.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/descendant::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - - XmlObject.Factory.parse(""), - - XmlObject.Factory.parse(""), - - - XmlObject.Factory.parse(""), - - - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex2Simple = "/AAA/BBB/descendant::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex3Simple = "//CCC/descendant::*"; - XmlObject[] ex3Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - - }; - String ex4Simple = "//CCC/descendant::DDD"; - XmlObject[] ex4Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - - System.out.println("Test 4: " + ex4Simple); - XmlCursor x4 = xDoc.newCursor(); - x4.selectPath(fixPath(ex4Simple)); - //XPathCommon.display(x4); - XPathCommon.compare(x4, ex4Xml); - x4.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample13() - throws Exception - { - System.out.println("====== Example-13 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon13.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "//DDD/parent::*"; - - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample14() - throws Exception - { - System.out.println("====== Example-14 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon14.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/BBB/DDD/CCC/EEE/ancestor::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - }; - - String ex2Simple = "//FFF/ancestor::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample15() - throws Exception - { - System.out.println("====== Example-15 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon15.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/BBB/following-sibling::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse("")}; - String ex2Simple = "//CCC/following-sibling::*"; - XmlObject[] ex2Xml = new XmlObject[]{XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - "")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample16() - throws Exception - { - System.out.println("====== Example-16 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon16.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/XXX/preceding-sibling::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - String ex2Simple = "//CCC/preceding-sibling::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample17() - throws Exception - { - System.out.println("====== Example-17 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon17.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/XXX/following::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - String ex2Simple = "//ZZZ/following::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - } - - /** - * the preceding axis contains all nodes that are descendants of the root - * of the tree in which the context node is found, are not ancestors of - * the context node, and occur before the context node in document order - * - * @throws Exception - */ - public void testZvonExample18() - throws Exception - { - System.out.println("====== Example-18 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon18.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/XXX/preceding::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - }; - - String ex2Simple = "//GGG/preceding::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("") - - /*XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - */ - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample19() - throws Exception - { - System.out.println("====== Example-19 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon19.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "/AAA/XXX/descendant-or-self::*"; - - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - String ex2Simple = "//CCC/descendant-or-self::*"; - - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample20() - throws Exception - { - System.out.println("====== Example-20 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon20.xml")); - XmlCursor xc = xDoc.newCursor(); - - String ex1Simple = "/AAA/XXX/DDD/EEE/ancestor-or-self::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - }; - String ex2Simple = "//GGG/ancestor-or-self::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - } - - /** - * @throws Exception - */ - public void testZvonExample21() - throws Exception - { - System.out.println("====== Example-21 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon21.xml")); - XmlCursor xc = xDoc.newCursor(); - String ex1Simple = "//GGG/ancestor::*"; - XmlObject[] ex1Xml = new XmlObject[]{ - - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - }; - String ex2Simple = "//GGG/descendant::*"; - XmlObject[] ex2Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - String ex3Simple = "//GGG/following::*"; - XmlObject[] ex3Xml = new XmlObject[]{XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse("")}; - String ex4Simple = "//GGG/preceding::*"; - XmlObject[] ex4Xml = new XmlObject[]{ - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - }; - String ex5Simple = "//GGG/self::*"; - XmlObject[] ex5Xml = new XmlObject[]{ - XmlObject.Factory.parse("")}; - - String ex6Simple = "//GGG/ancestor::* | //GGG/descendant::* | //GGG/following::* | //GGG/preceding::* | //GGG/self::*"; - XmlObject[] ex6Xml = new XmlObject[]{ - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse( - ""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - }; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - - System.out.println("Test 4: " + ex4Simple); - XmlCursor x4 = xDoc.newCursor(); - x4.selectPath(fixPath(ex4Simple)); - int i = 0; - /* System.out.println("****************HERE"); - - while (i < x4.getSelectionCount()) - { - x4.toSelection(i++); - System.out.println(x4.getName() + ((i - 1) + "")); - } - - System.out.println("****************SETS"); - XPathCommon.display(x4); - //XPathCommon.display(ex4Xml); - System.out.println("**************END SETS"); - */ - XPathCommon.compare(x4, ex4Xml); - x4.dispose(); - - - System.out.println("Test 5: " + ex5Simple); - XmlCursor x5 = xDoc.newCursor(); - x5.selectPath(fixPath(ex5Simple)); - //XPathCommon.display(x5); - XPathCommon.compare(x5, ex5Xml); - x5.dispose(); - - System.out.println("Test 6: " + ex6Simple); - XmlCursor x6 = xDoc.newCursor(); - x6.selectPath(fixPath(ex6Simple)); - //XPathCommon.display(x6); - XPathCommon.compare(x6, ex6Xml); - x6.dispose(); - } - - /** - * @throws Exception - */ - public void testZvonExample22() - throws Exception - { - System.out.println("====== Example-22 =========="); - XmlObject xDoc = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/xpath/zvon22.xml")); - XmlCursor xc = xDoc.newCursor(); - - String ex1Simple = "//BBB[position() mod 2 = 0 ]"; - XmlObject[] ex1Xml = new XmlObject[]{XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex2Simple = "//BBB[ position() = floor(last() div 2 + 0.5) or position() = ceiling(last() div 2 + 0.5) ]"; - XmlObject[] ex2Xml = new XmlObject[]{XmlObject.Factory.parse(""), - XmlObject.Factory.parse("")}; - - String ex3Simple = "//CCC[ position() = floor(last() div 2 + 0.5) or position() = ceiling(last() div 2 + 0.5) ]"; - XmlObject[] ex3Xml = new XmlObject[]{XmlObject.Factory.parse("")}; - - System.out.println("Test 1: " + ex1Simple); - XmlCursor x1 = xDoc.newCursor(); - x1.selectPath(fixPath(ex1Simple)); - //XPathCommon.display(x1); - XPathCommon.compare(x1, ex1Xml); - x1.dispose(); - System.out.println("Test 2: " + ex2Simple); - XmlCursor x2 = xDoc.newCursor(); - x2.selectPath(fixPath(ex2Simple)); - //XPathCommon.display(x2); - XPathCommon.compare(x2, ex2Xml); - x2.dispose(); - - System.out.println("Test 3: " + ex3Simple); - XmlCursor x3 = xDoc.newCursor(); - x3.selectPath(fixPath(ex3Simple)); - //XPathCommon.display(x3); - XPathCommon.compare(x3, ex3Xml); - x3.dispose(); - } - - - /* public static void main(String[] rgs) - { - try - { - new XPathTest("").testZvonExample21(); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - */ -// public void testZvonExample() throws Exception { -// XmlObject xDoc = XmlObject.Factory.parse(JarUtil.getResourceFromJar(Common.XMLCASES_JAR, -// "xbean/xmlcursor/xpath/zvon.xml")); -// XmlCursor xc = xDoc.newCursor(); -// } - - -} diff --git a/test/src/xmlcursor/xpath/xbean_xpath/detailed/AxesTest.java b/test/src/xmlcursor/xpath/xbean_xpath/detailed/AxesTest.java deleted file mode 100755 index 4889fd7..0000000 --- a/test/src/xmlcursor/xpath/xbean_xpath/detailed/AxesTest.java +++ /dev/null @@ -1,378 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.xbean_xpath.detailed; - -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlException; - -/** - * Axes Tested: - * child - * descendant - * attribute - * descendant-or-self - * self - * namespace - */ - -/** - * - */ -public class AxesTest extends TestCase { - String sXmlChild = " " + - "txt child", - - sXmlDesc = " " + - "txt child" - ; - - - public void testChildAxisAbbrev() throws XmlException { - - String sQuery1 = "./foo/bar"; - String sExpected = "" + - "txt child"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - sQuery1 = "$this/foo/child::bar"; - c.clearSelections(); - c.toStartDoc(); - c.selectPath(sQuery1,options); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - - } - - public void testChildAxis() throws XmlException { - String sQuery1 = "./foo/child::bar"; - String sExpected = "" + - "txt child"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); -// c.clearSelections(); -// c.toStartDoc(); - - c.selectPath(sQuery1, options); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - public void testChildAxisDot() throws XmlException { - - String sQuery1 = "$this/foo/./bar"; - String sExpected = "" + - "txt child"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - c.selectPath(sQuery1, options ); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - - } - - public void testChildAxisDNE() throws XmlException { - - String sQuery1 = "$this/foo/./baz"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - c.selectPath(sQuery1, options); - assertEquals(0, c.getSelectionCount()); - - } - -// public void testDescendantAxis() throws XmlException { -// -// String sQuery1 = "./descendant::foo"; -// String sExpected = "" + -// "txt child"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals("foo", c.getName().getLocalPart()); -// -// c.selectPath(sQuery1,options ); -// assertEquals(1, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected, c.xmlText()); -// -// -// } - - public void testDescendantAxisAbbrev() throws XmlException { - - String sQuery1 = ".//foo"; - String sExpected = "" + - "txt child"; - XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); - - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - - c.selectPath(sQuery1, options ); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - - } - -// public void testDescAxisDot() throws XmlException { -// -// String sQuery1 = "$this/descendant::foo/."; -// String sExpected = "" + -// "txt child"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// c.selectPath(sQuery1,options); -// assertEquals(1, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected, c.xmlText()); -// -// -// } - -// public void testDescAxisDNE() throws XmlException { -// -// String sQuery1 = "$this/descendant::baz"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// c.selectPath(sQuery1, options); -// assertEquals(0, c.getSelectionCount()); -// -// } - - - public void testChildAttribute() throws XmlException { - String sExpected = ""; - String sQuery1 = "$this/foo/bar/attribute::at0"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - c.selectPath(sQuery1, options ); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - } - - public void testChildAttributeAbbrev() throws XmlException { - String sExpected = ""; - ; - String sQuery1 = "$this/foo/bar/@at0"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - c.selectPath(sQuery1, options ); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - } - - public void testDescAttribute() throws XmlException { - String sExpected = ""; - String sQuery1 = "$this//attribute::at0"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - c.selectPath(sQuery1, options ); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - } - - -// public void testDescendantOrSelfAxis() throws XmlException { -// -// String sQuery1 = "./descendant-or-self::foo"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// String[] sExpected = new String[] -// { -// c.xmlText() -// , "" + -// "txt child" -// }; -// -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals("foo", c.getName().getLocalPart()); -// -// c.selectPath(sQuery1, options ); -// assertEquals(2, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected[0], c.xmlText()); -// c.toNextSelection(); -// assertEquals(sExpected[1], c.xmlText()); -// -// -// } - -// public void testDescendantOrSelfAxisDot() throws XmlException { -// -// String sQuery1 = "./descendant-or-self::foo"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// String[] sExpected = new String[] -// { -// c.xmlText() -// , "" + -// "txt child" -// }; -// -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// c.selectPath(sQuery1, options ); -// -// c.selectPath(sQuery1, options ); -// assertEquals(2, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected[0], c.xmlText()); -// c.toNextSelection(); -// assertEquals(sExpected[1], c.xmlText()); -// -// } - -// public void testDescendantOrSelfAxisDNE() throws XmlException { -// -// String sQuery1 = "$this/descendant-or-self::baz"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// c.selectPath(sQuery1, options ); -// assertEquals(0, c.getSelectionCount()); -// -// } - - -// public void testSelfAxis() throws XmlException { -// -// String sQuery1 = "$this/self::foo"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// String sExpected = -// c.xmlText(); -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals("foo", c.getName().getLocalPart()); -// -// c.selectPath(sQuery1, options ); -// assertEquals(1, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected, c.xmlText()); -// -// } - - public void testSelfAxisAbbrev() throws XmlException { - - String sQuery1 = "."; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - String sExpected = - c.xmlText(); - - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - assertEquals("foo", c.getName().getLocalPart()); - - c.selectPath(sQuery1, options ); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - -// public void testSelfAxisDot() throws XmlException { -// -// String sQuery1 = "./self::foo"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// String sExpected = -// c.xmlText(); -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals("foo", c.getName().getLocalPart()); -// -// c.selectPath(sQuery1, options ); -// assertEquals(1, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected, c.xmlText()); -// } -// -// public void testSelfAxisDNE() throws XmlException { -// -// String sQuery1 = "$this/self::baz"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// c.selectPath(sQuery1, options ); -// assertEquals(0, c.getSelectionCount()); -// -// } -// -// public void testNamespaceAxis() throws XmlException { -// -// String sQuery1 = "$this/namespace::http://uri.com"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// String sExpected = -// c.xmlText(); -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals(XmlCursor.TokenType.TEXT, c.toNextToken()); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals("foo", c.getName().getLocalPart()); -// -// c.selectPath(sQuery1, options ); -// assertEquals(1, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected, c.xmlText()); -// } -// -// public void testNamespaceAxisDot() throws XmlException { -// -// String sQuery1 = "./*/namespace::http://uri.com"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// String sExpected = -// c.xmlText(); -// -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals("foo", c.getName().getLocalPart()); -// -// c.selectPath(sQuery1, options ); -// assertEquals(1, c.getSelectionCount()); -// c.toNextSelection(); -// assertEquals(sExpected, c.xmlText()); -// } -// -// public void testNamespaceAxisDNE() throws XmlException { -// -// String sQuery1 = "$this/namespace::*"; -// XmlCursor c = XmlObject.Factory.parse( sXmlDesc ).newCursor(); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// assertEquals(XmlCursor.TokenType.TEXT, c.toNextToken()); -// assertEquals(XmlCursor.TokenType.START, c.toNextToken()); -// //to namespace -// assertEquals(XmlCursor.TokenType.NAMESPACE, c.toNextToken()); -// c.selectPath(sQuery1, options ); -// assertEquals(0, c.getSelectionCount()); -// -// } -// - public void setUp() { - options = new XmlOptions(); - options.put("use xbean for xpath"); - } - - private XmlOptions options; - -} - diff --git a/test/src/xmlcursor/xpath/xbean_xpath/detailed/NodeTest.java b/test/src/xmlcursor/xpath/xbean_xpath/detailed/NodeTest.java deleted file mode 100755 index 5fd280d..0000000 --- a/test/src/xmlcursor/xpath/xbean_xpath/detailed/NodeTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xpath.xbean_xpath.detailed; - -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; - -/** - * Nodes Tested: - * * - - * NameTest - * * "*" - * * NCName:* - * * QName - * NodeType - * * comment - * * node - * * pi - * * text - * PI(Literal) - */ - -/** - * - * - */ - -public class NodeTest extends TestCase { - - String sXmlChild = " " + - "txt child" + - ""; - String sXmlPI = ""; - - public void testNameTestStar() throws XmlException { - String sQuery1 = "./*"; - XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); - String sExpected = c.xmlText(); - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - public void testNameTestNCName() throws XmlException { - String sQuery1 = "$this//*"; - XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); - String sExpected = ""; - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - c.toNextToken(); - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - assertEquals("bar", c.getName().getLocalPart()); - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - public void testNameTestQName_1() throws XmlException { - String sQuery1 = "declare namespace pre=\"http://uri.com\"; $this//pre:*"; - XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); - String sExpected = - ""; - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - assertEquals("foo", c.getName().getLocalPart()); - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - //test a QName that DNE - public void testNameTestQName_2() throws XmlException { - String sQuery1 = "declare namespace pre=\"http://uri\"; $this//pre:baz"; - XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - c.selectPath(sQuery1); - assertEquals(0, c.getSelectionCount()); - - - } - - public void testNameTestQName_3() throws XmlException { - String sQuery1 = "$this//bar"; - XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); - String sExpected = "" + - "txt child"; - assertEquals(XmlCursor.TokenType.START, c.toNextToken()); - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - public void testNodeTypeComment() { - - } - - - public void testNodeTypeNodeAbbrev() throws XmlException { - String sQuery1 = "$this/foo/*"; - XmlCursor c = XmlObject.Factory.parse(sXmlChild).newCursor(); - String sExpected = "" + - "txt child"; - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - } - /** - * Will not support natively - * - public void testNodeTypeNode() throws XmlException { - String sQuery1 = "$this/foo/node()"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - String sExpected ="" + - "txt child"; - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - } - public void testNodeTypePI() throws XmlException { - - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - String sExpected =""; - String sQuery="./foo/processing-instruction()"; - c.selectPath(sQuery); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - public void testNodeTypeText() throws XmlException { - String sQuery1 = "$this//text()"; - XmlCursor c = XmlObject.Factory.parse( sXmlChild ).newCursor(); - String sExpected =" "; - assertEquals( XmlCursor.TokenType.START, c.toNextToken() ); - c.selectPath(sQuery1); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - } - - public void testPI() throws XmlException { - - XmlCursor c = XmlObject.Factory.parse( sXmlPI ).newCursor(); - String sExpected =""; - String sQuery="./foo/processing-instruction('xml-stylesheet')"; - c.selectPath(sQuery); - assertEquals(1, c.getSelectionCount()); - c.toNextSelection(); - assertEquals(sExpected, c.xmlText()); - - } - - public void testPIDNE() throws XmlException { - - XmlCursor c = XmlObject.Factory.parse( sXmlPI ).newCursor(); - String sQuery="./foo/processing-instruction('stylesheet')"; - c.selectPath(sQuery); - assertEquals(0, c.getSelectionCount()); - - } - */ -} diff --git a/test/src/xmlcursor/xquery/checkin/QueryEngineTests.java b/test/src/xmlcursor/xquery/checkin/QueryEngineTests.java deleted file mode 100644 index 56f4064..0000000 --- a/test/src/xmlcursor/xquery/checkin/QueryEngineTests.java +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.checkin; - -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlInteger; - -public class QueryEngineTests extends TestCase -{ - // Execute repeated queries to test picking up of the query engine from classpath - // This test is following rev 292446 - public void testQueryEngineSelection()throws Exception{ - XmlObject o = XmlObject.Factory.parse(""); - XmlObject[] res = o.execQuery("(//a/b)"); - res= o.execQuery("(//a/b)"); - String expectedRes = ""; - assertEquals(expectedRes,res[0].xmlText()); - - } - -} diff --git a/test/src/xmlcursor/xquery/common/AbstractRunner.java b/test/src/xmlcursor/xquery/common/AbstractRunner.java deleted file mode 100644 index 2230d66..0000000 --- a/test/src/xmlcursor/xquery/common/AbstractRunner.java +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.common; - -import junit.framework.TestSuite; -import tools.util.JarUtil; - -import java.io.FileNotFoundException; - -/** - * - */ -public class AbstractRunner - extends TestSuite -{ - - public void findZip() throws FileNotFoundException - { - pathToZip = JarUtil.getFilePath("xmlcases.jar"); - int i = pathToZip.lastIndexOf('/'); - i = (i == -1) ? pathToZip.lastIndexOf('\\') : i; - pathToZip=pathToZip.substring(0, i); - - } - - - public String pathToZip; -} diff --git a/test/src/xmlcursor/xquery/common/XQTestCase.java b/test/src/xmlcursor/xquery/common/XQTestCase.java deleted file mode 100644 index cca1fe5..0000000 --- a/test/src/xmlcursor/xquery/common/XQTestCase.java +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.common; - -import junit.framework.TestCase; - -/** - * - */ -public abstract class XQTestCase extends TestCase -{ - public XQTestCase(String s){ - super(s); - } - public abstract void testRun() throws Exception; - public void runTest() - throws Exception { - testRun(); - } -} diff --git a/test/src/xmlcursor/xquery/detailed/NISTSuiteRunner.java b/test/src/xmlcursor/xquery/detailed/NISTSuiteRunner.java deleted file mode 100644 index 3ceaa36..0000000 --- a/test/src/xmlcursor/xquery/detailed/NISTSuiteRunner.java +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.detailed; - -import junit.framework.TestSuite; -import junit.framework.Test; -import org.apache.xmlbeans.XmlException; -import tools.util.JarUtil; - -import java.io.InputStream; -import java.io.IOException; - -import noNamespace.TestSuiteDocument; -import noNamespace.TestCase; -import xmlcursor.xquery.common.AbstractRunner; - - -public class NISTSuiteRunner extends AbstractRunner - - -{ -/** - * - - public static Test suite() - throws java.lang.Exception - { - NISTSuiteRunner suite = new NISTSuiteRunner(); - suite.addAllTestInfos(); - return suite; - } - - public void addAllTestInfos() - { - NISTTest testCase; - firstCall = true; - - try - { - findZip(); - NISTTest.pathToZip=pathToZip; - while ((testCase = loadNIST()) != null) - { - addTest(testCase); - } - } - catch (Exception e) - { - e.printStackTrace(); - throw new RuntimeException(e); - } - - - } - - private NISTTest loadNIST() - throws XmlException, IOException - { - if (firstCall) - { - firstCall = false; - InputStream is = ZipUtil.getStreamFromZip(pathToZip,NISTTest.zipName, - pathToDescFile); - TestSuiteDocument doc = TestSuiteDocument.Factory.parse(is); - TestSuiteDocument.TestSuite suite = doc.getTestSuite(); - group = suite.getTestGroupArray(); - - } - while (groupInd < group.length) - { - TestCase[] tests = group[groupInd].getTestCaseArray(); - if (testInd++ < tests.length-1) - return new NISTTest(tests[testInd]); - else{ - testInd = -1; - groupInd++; - } - } - - return null; - } - - - private boolean firstCall; - private int testInd = -1; - private int groupInd = 0; - private final static String pathToDescFile = - "testSuite/NIST/files/catalog.xml"; - TestSuiteDocument.TestSuite.TestGroup[] group; - -*/ -} diff --git a/test/src/xmlcursor/xquery/detailed/NISTTest.java b/test/src/xmlcursor/xquery/detailed/NISTTest.java deleted file mode 100644 index 45faf73..0000000 --- a/test/src/xmlcursor/xquery/detailed/NISTTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.detailed; - -import junit.framework.TestCase; -import junit.framework.TestResult; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import tools.util.JarUtil; - -import java.io.IOException; -import java.io.InputStream; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.util.zip.ZipFile; -import java.util.zip.ZipEntry; - -import xmlcursor.xpath.common.XPathCommon; -import xmlcursor.xquery.common.XQTestCase; - -/** - * - */ -public class NISTTest extends XQTestCase -{ - - - public NISTTest(String s) - { - super(s); - } - public NISTTest(noNamespace.TestCase test) - { - this(test.getName()); - mTest=test; - } - - public void testRun() throws Exception - { - String query=null; - String outFile=null; - XmlObject obj=XmlObject.Factory.parse(""); - - - //NIST BUG: folder is called testSuite but appears - //as testsuite in desc. file - String temp = mTest.getFilePath(); - temp=temp.replaceAll("testsuite","testSuite"); - temp=temp.replace( (char)92,'/'); - query = ZipUtil.getStringFromZip( - pathToZip,zipName,temp + mTest.getName()+".xq") ; - //bad comment syntax in suite - query = query.replaceAll("\\{--","(:"); - query = query.replaceAll("--\\}",":)"); - noNamespace.TestCase.OutputFile[] outFiles - = mTest.getOutputFileArray(); - noNamespace.TestCase.InputFile[] inFiles - = mTest.getInputFileArray(); - - - for (int i=0; i < inFiles.length; i++) - { - if ( !inFiles[i].getStringValue().equals("emptyDoc")) - throw new RuntimeException ("Fix this code. Input file: "+ - inFiles[i]); - -// assertEquals(inFiles.length, outFiles.length); - - XmlObject[] queryRes = obj.execQuery(query); - String input = ZipUtil.getStringFromZip( - pathToZip,zipName,temp+outFiles[i].getStringValue()); - XmlObject expRes=XmlObject.Factory.parse( input ); - XPathCommon.compare(queryRes,new XmlObject[]{expRes}); - } - - } - - noNamespace.TestCase mTest; - static String pathToZip; - static final String zipName="xmlQuery.zip"; -} diff --git a/test/src/xmlcursor/xquery/detailed/StoreTestsXqrl.java b/test/src/xmlcursor/xquery/detailed/StoreTestsXqrl.java deleted file mode 100644 index c3c0ff8..0000000 --- a/test/src/xmlcursor/xquery/detailed/StoreTestsXqrl.java +++ /dev/null @@ -1,206 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlcursor.xquery.detailed; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - - - - -//Used to be a checkin -public class StoreTestsXqrl extends TestCase -{ - public StoreTestsXqrl(String name) { super(name); } - public static Test suite() { return new TestSuite(StoreTestsXqrl.class); } - - private void doTokenTest ( String xml ) - throws Exception - { - XmlCursor c = XmlObject.Factory.parse( xml ).newCursor(); - //String s = c.execQuery( "$this" ).xmlText(); - String s = c.execQuery( "." ).xmlText(); - Assert.assertTrue( s.equals( xml ) ); - } - - private void doSaveTest ( String xml ) - throws Exception - { - doTokenTest( xml ); - } - - public void testSaving ( ) - throws Exception - { - doSaveTest( "1" ); - doSaveTest( "" ); - doSaveTest( "abcde" ); - doSaveTest( "" ); - doSaveTest( "" ); - - String s = "aaabbb"; - s = s + s + s + s + s + s + s + s + s + s + s + s + s + s + s; - s = "xxxx" + s + ""; - - doSaveTest( s ); - - XmlObject x = - XmlObject.Factory.parse( "" ); - - XmlCursor c = x.newCursor(); - - c.toFirstChild(); - c.toFirstChild(); - - Assert.assertTrue( c.xmlText().equals( "" ) ); - - x = XmlObject.Factory.parse( "" ); - - c = x.newCursor(); - - c.toFirstChild(); - c.toFirstChild(); - - Assert.assertTrue( c.xmlText().equals( "" ) ); - } - - - private void testTextFrag ( String actual, String expected ) - { - String pre = ""; - - String post = ""; - - Assert.assertTrue( actual.startsWith( pre ) ); - Assert.assertTrue( actual.endsWith( post ) ); - - Assert.assertTrue( - expected.equals( - actual.substring( - pre.length(), actual.length() - post.length() ) ) ); - } - - // - // Make sure XQuery works (tests the saver too) - // - - public void testXQuery ( ) - throws Exception - { - XmlCursor c = - XmlObject.Factory.parse( - "12" ).newCursor(); - - String s = - c.execQuery( "for $b in //bar order by ($b) " + - "descending return $b").xmlText(); - - testTextFrag( s, "21" ); - - c = XmlObject.Factory.parse( "" ).newCursor(); - c.toNextToken(); - c.toNextToken(); - c.insertElement( "boo", "boo.com" ); - c.toStartDoc(); - - Assert.assertTrue( - //c.execQuery( "$this" ). - c.execQuery( "." ). - xmlText().equals( - "" ) ); - } - - - public void testPathing ( ) - throws Exception - { - XmlObject x = - XmlObject.Factory.parse( - "123" ); - - XmlCursor c = x.newCursor(); - - c.selectPath( "//bar" ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.xmlText().equals( "1" ) ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.xmlText().equals( "2" ) ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.xmlText().equals( "3" ) ); - - Assert.assertTrue( !c.toNextSelection() ); - - // - // - // - - x = - XmlObject.Factory.parse( - "" ); - - c = x.newCursor(); - - //c.selectPath( "$this//@x" ); - c.selectPath( ".//@x" ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.currentTokenType().isAttr() ); - Assert.assertTrue( c.getTextValue().equals( "1" ) ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.currentTokenType().isAttr() ); - Assert.assertTrue( c.getTextValue().equals( "2" ) ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.currentTokenType().isAttr() ); - Assert.assertTrue( c.getTextValue().equals( "3" ) ); - - Assert.assertTrue( !c.toNextSelection() ); - - // - // - // - - x = - XmlObject.Factory.parse( - "123" ); - - c = x.newCursor(); - - c.selectPath( "//text()" ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.currentTokenType().isText() ); - Assert.assertTrue( c.getChars().equals( "1" ) ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.currentTokenType().isText() ); - Assert.assertTrue( c.getChars().equals( "2" ) ); - - Assert.assertTrue( c.toNextSelection() ); - Assert.assertTrue( c.currentTokenType().isText() ); - Assert.assertTrue( c.getChars().equals( "3" ) ); - - Assert.assertTrue( !c.toNextSelection() ); - } -} diff --git a/test/src/xmlcursor/xquery/detailed/UseCaseTest.java b/test/src/xmlcursor/xquery/detailed/UseCaseTest.java deleted file mode 100644 index 3d2c9f2..0000000 --- a/test/src/xmlcursor/xquery/detailed/UseCaseTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.detailed; - -import junit.framework.TestCase; -import junit.framework.TestResult; - -import java.io.IOException; - -import xbeans.cases.xmlcursor.xquery.useCases.XmlQueryUseCasesDocument; -import xbeans.cases.xmlcursor.xquery.useCases.QueryT; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import xmlcursor.xpath.common.XPathCommon; -import xmlcursor.xquery.common.XQTestCase; - -/** - * - */ -public class UseCaseTest - extends XQTestCase -{ - - public UseCaseTest(String s) - { - super("testRun"); - } - - public UseCaseTest( - XmlQueryUseCasesDocument.XmlQueryUseCases.Group.Test test, - String groupName) - { - this(""); - super.setName(groupName+"."+test.getQuery().getFile()); - mTest = test; - this.groupName = groupName; - } - - - public void testRun() throws Exception - { - String query = null; - String outFile = null; - String inFile =null; - QueryT input = mTest.getInput(); - inFile = - input == null ? "input.xml" : input.getFile(); - - inFile = topDir+"/"+groupName + "/"+ inFile; - TestResult res=new TestResult(); - try - { - String sXml = ZipUtil.getStringFromZip(pathToZip,zipName,inFile); - XmlObject obj = XmlObject.Factory.parse(sXml); - query = ZipUtil.getStringFromZip(pathToZip, zipName, - topDir+"/"+groupName + "/"+ mTest.getQuery().getFile()); - - outFile - = mTest.getOutput().getFile(); - String expXml = ZipUtil.getStringFromZip(pathToZip,zipName, - topDir+"/"+groupName + "/"+ outFile); - XmlObject[] queryRes = obj.execQuery(query); - XmlObject expRes = XmlObject.Factory.parse(expXml); - XPathCommon.compare(queryRes, new XmlObject[]{expRes}); - - } - catch (IOException e) - { - res.addError(this, e); - } - catch (XmlException e) - { - res.addError(this, e); - } - catch (Exception e) - { - res.addError(this, e); - } - return; - - } - static void setPathToZip(String path) - { - pathToZip=path; - } - - XmlQueryUseCasesDocument.XmlQueryUseCases.Group.Test mTest; - private String groupName; - static String pathToZip; - static final String topDir="xmlUseCases"; - static final String zipName = "useCases.zip"; -} diff --git a/test/src/xmlcursor/xquery/detailed/XQUseCaseRunner.java b/test/src/xmlcursor/xquery/detailed/XQUseCaseRunner.java deleted file mode 100644 index a28dd76..0000000 --- a/test/src/xmlcursor/xquery/detailed/XQUseCaseRunner.java +++ /dev/null @@ -1,119 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.detailed; - -import junit.framework.TestSuite; -import junit.framework.Test; -import tools.util.JarUtil; -import org.apache.xmlbeans.XmlException; - -import java.io.IOException; -import java.io.InputStream; - -import xbeans.cases.xmlcursor.xquery.useCases.XmlQueryUseCasesDocument; -import xmlcursor.xquery.common.AbstractRunner; - -/** - * - */ -public class XQUseCaseRunner - extends AbstractRunner - -{ - - public static Test suite() - throws java.lang.Exception - { - XQUseCaseRunner suite = new XQUseCaseRunner(); - suite.addAllTestInfos(); - return suite; - } - - public void addAllTestInfos() - { - UseCaseTest testCase; - firstCall = true; - - try - { - findZip(); - UseCaseTest.pathToZip = pathToZip; - while ((testCase = loadUseCaseTest()) != null) - { - addTest(testCase); - } - } - catch (Exception e) - { - e.printStackTrace(); - throw new RuntimeException(e); - } - - - } - - private UseCaseTest loadUseCaseTest() - throws XmlException, IOException - { - if (firstCall) - { - firstCall = false; - InputStream is=null; - try - { - is = ZipUtil.getStreamFromZip(UseCaseTest.pathToZip, - UseCaseTest.zipName, pathToDescFile); - } - catch (java.util.zip.ZipException e) - { - if (is == null) - { - //the zip with cases was not found - return null; - } - } - XmlQueryUseCasesDocument doc = XmlQueryUseCasesDocument.Factory.parse( - is); - XmlQueryUseCasesDocument.XmlQueryUseCases suite = doc.getXmlQueryUseCases(); - group = suite.getGroupArray(); - - } - while (groupInd < group.length) - { - XmlQueryUseCasesDocument.XmlQueryUseCases.Group.Test[] - tests = group[groupInd].getTestArray(); - if (testInd++ < tests.length - 1) - return new UseCaseTest(tests[testInd], - group[groupInd].getName()); - else - { - testInd = -1; - groupInd++; - } - } - - return null; - } - - private boolean firstCall; - private int testInd = -1; - private int groupInd = 0; - private final static String pathToDescFile = - "xmlUseCases/catalog.xml"; - XmlQueryUseCasesDocument.XmlQueryUseCases.Group[] group; - -} - - diff --git a/test/src/xmlcursor/xquery/detailed/XQueryTest.java b/test/src/xmlcursor/xquery/detailed/XQueryTest.java deleted file mode 100644 index d1485f9..0000000 --- a/test/src/xmlcursor/xquery/detailed/XQueryTest.java +++ /dev/null @@ -1,311 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.detailed; - -import junit.framework.TestCase; -import tools.util.JarUtil; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlLong; - -import java.io.IOException; -import java.io.InputStream; - -import test.xbean.xmlcursor.xQueryInput.EmpT; -import xmlcursor.common.Common; - -/** - * - */ -public class XQueryTest extends TestCase { - - - public void testSimple() throws XmlException, - IOException { - String xq = "for $e in //employee where $e/name='Bob' return $e "; - String xq1 = "for $e in //employee return $e "; - InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); - - XmlObject o = XmlObject.Factory.parse(input); - XmlCursor c = o.newCursor(); - XmlCursor c1 = c.execQuery(xq); - c1.toFirstContentToken(); - assertEquals("\n" + - "\t\tBob\n" + - "\t\t1000\n" + - "\t", c1.xmlText()); - - XmlObject[] res = o.execQuery(xq); - EmpT employeeType = (EmpT) res[0]; - assertEquals("Bob", employeeType.getName()); - - } - - public void testObjConstruction() - throws XmlException, - IOException { - String query = JarUtil.getResourceFromJar("xbean/xmlcursor/xquery/Constructor.xq"); - InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); - XmlObject o = XmlObject.Factory.parse(input); - //via Object - XmlObject[] reslt = o.execQuery(query); - assertEquals(3, reslt.length); - assertEquals("Bob", - reslt[0].xmlText()); - assertEquals("Beth", - reslt[1].xmlText()); - assertEquals("NotBob", - reslt[2].xmlText()); - XmlCursor c = o.newCursor(); - - //via Cursor - /*XmlCursor c1=c.execQuery(query); - c1.toFirstContentToken(); - assertEquals("Bob", - c1.xmlText() ); - c1.toNextSibling(); - assertEquals("Beth", - c1.xmlText() ); - c1.dispose(); - c.dispose(); - */ - int i=0; - while ( i++ < 2){ - //via Cursor--new - XmlCursor c1 = c.execQuery(query); - //c.dispose(); - assertEquals(XmlCursor.TokenType.STARTDOC, c1.currentTokenType()); - assertEquals(XmlCursor.TokenType.START, c1.toNextToken() ); - assertEquals("Bob", - c1.xmlText()); - // assertTrue(c1.toNextSelection()); - assertTrue( c1.toNextSibling() ); - assertEquals("Beth", - c1.xmlText()); - //assertTrue(c1.toNextSelection()); - assertTrue( c1.toNextSibling() ); - assertEquals("NotBob", - c1.xmlText()); - c1.dispose(); - } - c.dispose(); - } - - - public void testJoin() - throws XmlException, - IOException { - String query = JarUtil.getResourceFromJar("xbean/xmlcursor/xquery/Join.xq"); - InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); - XmlObject o = XmlObject.Factory.parse(input); - XmlCursor c = o.newCursor(); - XmlCursor c1 = c.execQuery(query); - - // assertEquals(3, c1.getSelectionCount()); - c1.toFirstContentToken(); - assertEquals("" + - "1000,\n" + - "\t\tBob,\n" + - "\t\tNotBob" + - "", - c1.xmlText()); -/* assertEquals("" + - "" + - "1000,\n" + - "\t\tBob,\n" + - "\t\tNotBob" + - "" + - "1001,\n" + - "\t\tBeth,\n" + - "\t\t" + - "1000,\n" + - "\t\tNotBob,\n" + - "\t\tBob" + - "" + - "", - c1.xmlText() ); */ - c1.dispose(); - c.dispose(); - - XmlObject[] res = o.execQuery(query); - assertEquals(3, res.length); - } - - public void testTextSequenceRoot() - throws XmlException, - IOException { - //String query = "$this//text()"; - String query = ".//text()"; - InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); - XmlObject o = XmlObject.Factory.parse(input); - XmlObject[] res = o.execQuery(query); - assertEquals(19, res.length); - - XmlCursor c = o.newCursor(); - XmlCursor c1 = c.execQuery(query); - assertEquals(XmlCursor.TokenType.TEXT,c1.toNextToken()); - // assertEquals() - //assertEquals(19, c1.getSelectionCount()); - c.dispose();//make sure this doesn't screw things up - while (c1.toNextSibling()) - assertEquals(XmlCursor.TokenType.TEXT, c1.currentTokenType()); - c1.toStartDoc(); - assertEquals("Bob", - c1.xmlText()); - c1.dispose(); - c.dispose(); - } - - - public void testDocumentFunc() - throws XmlException, - IOException { - //String query = "{$this},{count(//employee)}"; - String query = "{.},{count(//employee)}"; - InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); - XmlCursor c = XmlObject.Factory.parse(input).newCursor(); - XmlCursor c1 = c.execQuery(query); - assertEquals("", - c1.xmlText()); - c1.dispose(); - c.dispose(); - } - - - public void testTextAtOddPlaces() throws Exception { - //String query = "{$this},{count(//employee)}"; - String query = "{.},{count(//employee)}"; - String input = "textmore text"; - XmlObject o = XmlObject.Factory.parse(input); - XmlCursor c = o.newCursor(); - - XmlObject[] res = o.execQuery("//a"); - assertEquals("textmore text", res[0].xmlText()); - - XmlCursor cur = c.execQuery("//a"); - // assertEquals(1, cur.getSelectionCount()); - cur.toFirstContentToken(); - assertEquals("textmore text", cur.xmlText()); - - - } - - - public void testMultiDocJoin() - throws XmlException, - IOException { - String query = JarUtil.getResourceFromJar("xbean/xmlcursor/xquery/2DocJoin.xq"); - InputStream input = JarUtil.getResourceFromJarasStream("xbean/xmlcursor/XQueryInput.xml"); - XmlCursor c = XmlObject.Factory.parse(input).newCursor(); - XmlCursor c1 = c.execQuery(query); - assertEquals("", - c1.xmlText()); - c1.dispose(); - c.dispose(); - } - - public void testFunction() throws Exception { - String query = " declare function local:summary($emps as element(employee)*) \n" + - " as element(dept)*\n" + - "{\n" + - " for $d in fn:distinct-values($emps/deptno)\n" + - " let $e := $emps[deptno = $d]\n" + - " return\n" + - " \n" + - " {$d}\n" + - " {fn:count($e)} \n" + - " {fn:sum($e/salary)} \n" + - " \n" + - "};\n" + - "\n" + - //"local:summary($this//employee[location = \"Denver\"])"; - "local:summary(.//employee[location = \"Denver\"])"; - - String xml = " " + - "" + - "Denver" + - "7" + - "20" + - "" + - "" + - "Seattle" + - "6" + - "30" + - "" + - "" + - "Denver" + - "5" + - "40" + - "" + - "" + - "Denver" + - "7" + - "10" + - "" + - ""; - - XmlObject o = XmlObject.Factory.parse(xml); - XmlObject[] res = o.execQuery(query); - assertEquals(2, res.length); - assertEquals("7230", - res[0].xmlText()); - assertEquals("5140", - res[1].xmlText()); - XmlCursor c = o.newCursor(); - XmlCursor c1 = c.execQuery(query); - c1.toFirstContentToken(); - assertEquals(res[0].xmlText(), - c1.xmlText()); - c1.dispose(); - c.dispose(); - } - - public void testType() throws Exception { - String xml = ""; - String query = "count(//b)"; - XmlObject o = XmlObject.Factory.parse(xml); - XmlObject[] res = o.execQuery(query); - XmlLong result = (XmlLong) res[0]; - assertEquals("2",result.getStringValue()); - assertEquals(2,result.getLongValue()); - - } - - - public void testQueryComment() throws Exception{ - String xml = ""; - String query = "(:comment:) count(//b)"; - XmlObject o = XmlObject.Factory.parse(xml); - XmlObject[] res = o.execQuery(query); - XmlLong result = (XmlLong) res[0]; - assertEquals("2",result.getStringValue()); - assertEquals(2,result.getLongValue()); - } - - - public void testStandaloneFunction() throws Exception{ - String query = "\n" + - " {fn:not(xs:unsignedShort(\"65535\"))}\n" + - " "; - XmlObject o = XmlObject.Factory.newInstance(); - XmlObject[] res = o.execQuery(query); - XmlLong result = (XmlLong) res[0]; - assertEquals("2",result.getStringValue()); - assertEquals(2,result.getLongValue()); - - } - -} diff --git a/test/src/xmlcursor/xquery/detailed/ZipUtil.java b/test/src/xmlcursor/xquery/detailed/ZipUtil.java deleted file mode 100644 index 99e6091..0000000 --- a/test/src/xmlcursor/xquery/detailed/ZipUtil.java +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlcursor.xquery.detailed; - -import java.io.IOException; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.InputStream; -import java.util.zip.ZipFile; -import java.util.zip.ZipEntry; -import java.util.HashMap; - -/** - * - */ -public class ZipUtil -{ - static String getStringFromZip(String pathToZip,String zipName,String file) - throws IOException - { - BufferedReader in = new BufferedReader( - new InputStreamReader(getStreamFromZip(pathToZip,zipName,file))); - - StringBuffer stb = new StringBuffer(); - String buffer; - - while (!((buffer = in.readLine()) == null)) { - stb.append(buffer + EOL); - } - return stb.toString(); - } - - static InputStream getStreamFromZip(String zipFileName,String fileName) throws IOException - { - Object file; - if ( (file = ZipFileMap.get(fileName)) == null ){ - file = new ZipFile(zipFileName); - ZipFileMap.put(fileName,file); - } - ZipEntry entry = ((ZipFile)file).getEntry(fileName); - return ((ZipFile)file).getInputStream(entry); - } - - static InputStream getStreamFromZip(String pathToZip,String zipName,String file) - throws IOException { - return getStreamFromZip(pathToZip+SLASH+zipName,file); - } - - private static HashMap ZipFileMap=new HashMap(); - static final String SLASH = System.getProperty("file.separator"); - static final String EOL=System.getProperty("line.separator"); -} diff --git a/test/src/xmlobject/checkin/AssortedTests.java b/test/src/xmlobject/checkin/AssortedTests.java deleted file mode 100755 index ce4b235..0000000 --- a/test/src/xmlobject/checkin/AssortedTests.java +++ /dev/null @@ -1,237 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlTime; -import com.easypo.XmlPurchaseOrderDocumentBean; -import com.easypo.XmlCustomerBean; -import com.easypo.XmlLineItemBean; - -import java.math.BigInteger; - -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; -import xint.test.PositionDocument; - -public class AssortedTests extends TestCase -{ - public AssortedTests(String name) { super(name); } - public static Test suite() { return new TestSuite(AssortedTests.class); } - - // bug 27489 - public static void testSaverCharEscaping() throws XmlException - { - XmlObject xdoc = XmlObject.Factory.parse("something"); - XmlCursor cur = xdoc.newCursor(); - cur.toFirstChild(); - // valid chars - cur.setTextValue(""); - Assert.assertEquals("<something or other:\u03C0\uD7FF>", xdoc.toString()); - - // invalid chars - control chars, FFFF/FFFE, etc - cur.setTextValue(""); - Assert.assertEquals("<something?or?other:\u0045?>", xdoc.toString()); - - String greekChars = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E\uD835\uDF4F\uD835\uDF50\uD835" - + "\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835\uDF55"; - cur.setTextValue(greekChars); - Assert.assertEquals("" + greekChars + "", xdoc.toString()); - } - - // bug 26140/26104 - public static void testNoTypeInvalid() throws XmlException - { - XmlObject xdoc = XmlObject.Factory.parse("something"); - Assert.assertTrue("Untyped document should be invalid", !xdoc.validate()); - - xdoc = XmlObject.Factory.parse(""); - Assert.assertTrue("Untyped document should be invalid", !xdoc.validate()); - } - - // bug 26790 - public static void testComplexSetter() throws XmlException - { - XmlPurchaseOrderDocumentBean xdoc = XmlPurchaseOrderDocumentBean.Factory.parse( - "" + - "" + - "David Bau" + - "
        100 Main Street
        " + - "
        " + - "2003-05-18T11:50:00" + - "" + - "Red Candy" + - "0.423" + - "4" + - "" + - "" + - "Blue Candy" + - "5.0" + - "1" + - "" + - "
        "); - // test copy-within doc - XmlLineItemBean newItem = xdoc.getPurchaseOrder().addNewLineItem(); - newItem.set(xdoc.getPurchaseOrder().getLineItemArray(0)); - Assert.assertEquals(BigInteger.valueOf(4), xdoc.getPurchaseOrder().getLineItemArray(2).getQuantity()); - xdoc.getPurchaseOrder().setLineItemArray(0, xdoc.getPurchaseOrder().getLineItemArray(1)); - Assert.assertEquals(BigInteger.valueOf(1), xdoc.getPurchaseOrder().getLineItemArray(0).getQuantity()); - - // test copy-between docs - XmlLineItemBean anotherItem = XmlLineItemBean.Factory.parse( - "" + - "Yellow Balloon" + - "0.001" + - "200" + - ""); - - Assert.assertEquals("Yellow Balloon", anotherItem.getDescription()); - xdoc.getPurchaseOrder().setLineItemArray(1, anotherItem); - - Assert.assertEquals("Yellow Balloon", xdoc.getPurchaseOrder().getLineItemArray(1).getDescription()); - Assert.assertEquals(BigInteger.valueOf(1), xdoc.getPurchaseOrder().getLineItemArray(0).getQuantity()); - Assert.assertEquals(BigInteger.valueOf(200), xdoc.getPurchaseOrder().getLineItemArray(1).getQuantity()); - Assert.assertEquals(BigInteger.valueOf(4), xdoc.getPurchaseOrder().getLineItemArray(2).getQuantity()); - - // test copy-to-self - xdoc.getPurchaseOrder().setLineItemArray(1, xdoc.getPurchaseOrder().getLineItemArray(1)); - Assert.assertEquals("Yellow Balloon", xdoc.getPurchaseOrder().getLineItemArray(1).getDescription()); - Assert.assertEquals(BigInteger.valueOf(1), xdoc.getPurchaseOrder().getLineItemArray(0).getQuantity()); - Assert.assertEquals(BigInteger.valueOf(200), xdoc.getPurchaseOrder().getLineItemArray(1).getQuantity()); - Assert.assertEquals(BigInteger.valueOf(4), xdoc.getPurchaseOrder().getLineItemArray(2).getQuantity()); - } - - // bug 45338 - public static void testComplexGetter() throws Exception - { - XmlPurchaseOrderDocumentBean xdoc = - XmlPurchaseOrderDocumentBean.Factory.parse( - "" + - "" + - "David Bau" + - "
        100 Main Street
        " + - "
        " + - "2003-05-18T11:50:00" + - "" + - "Blue Candy" + - "5.0" + - "1" + - "" + - "
        "); - - Assert.assertEquals(false, xdoc.validate()); - Assert.assertEquals(XmlPurchaseOrderDocumentBean.type, xdoc.schemaType()); - - // check type of element when xsi:type is bad - XmlObject cust = xdoc.getPurchaseOrder().getCustomer(); - Assert.assertEquals(XmlCustomerBean.type, cust.schemaType()); - - Assert.assertEquals("David Bau", ((XmlCustomerBean)cust).getName()); - } - - public static void donttestPrettyPrint() throws Exception - { - XmlObject xobj = XmlObject.Factory.parse("<SHOULDNOTBEATAG>simple<ALSOSHOULDNOTBEATAG>"); - // System.out.println(xobj); - System.out.println(xobj.xmlText()); - /* - XmlCursor xcur = xobj.newCursor(); - xcur.toFirstChild(); - xobj = xcur.getObject(); - String result = xobj.toString(); - System.out.println(result); - - xcur.toFirstChild(); - xcur.toFirstChild(); - xcur.toFirstContentToken(); - xcur.insertChars("this is a test"); - - System.out.println(xobj); - */ - } - - public static void dontTestQNameCopy() throws Exception - { - SchemaDocument xobj = SchemaDocument.Factory.parse( - "" + - ""); - SchemaDocument xobj2 = SchemaDocument.Factory.parse( - ""); - xobj2.getSchema().addNewElement().set(xobj.getSchema().getElementArray(0)); - System.out.println(xobj2); - } - - // don't run on normal drt because it's too slow: about 20-30 secs - public static void donttestCursorFinalize() - { - XmlObject obj = XmlObject.Factory.newInstance(); - int i = 0; - try - { - for (i = 0; i < 2000 * 1000; i++) - { - XmlCursor cur = obj.newCursor(); - // cur.dispose(); skipping this depends on finalization or else OOM - } - } - catch (OutOfMemoryError e) - { - System.err.println("Did " + i + " iterations before running out of memory"); - throw e; - } - } - - public static void testOutOfRange() throws Exception - { - PositionDocument doc = PositionDocument.Factory.parse("43037"); - Assert.assertEquals(43, doc.getPosition().getLat()); - Assert.assertEquals(37, doc.getPosition().getLon()); - Assert.assertTrue(doc.validate()); - - doc = PositionDocument.Factory.parse("443737"); - Assert.assertEquals(443, doc.getPosition().getLat()); - Assert.assertEquals(737, doc.getPosition().getLon()); - Assert.assertTrue(!doc.validate()); - - doc.getPosition().setLat((short)-300); - doc.getPosition().setLon((short)32767); - Assert.assertEquals(-300, doc.getPosition().getLat()); - Assert.assertEquals(32767, doc.getPosition().getLon()); - Assert.assertTrue(!doc.validate()); - - doc.getPosition().setLat((short)43); - doc.getPosition().setLon((short)127); - Assert.assertEquals(43, doc.getPosition().getLat()); - Assert.assertEquals(127, doc.getPosition().getLon()); - Assert.assertTrue(doc.validate()); - } - - public static void testParse() throws Exception - { - XmlTime xt = XmlTime.Factory.parse("12:00:00"); - Assert.assertEquals("12:00:00", xt.getCalendarValue().toString()); - } - - - -} diff --git a/test/src/xmlobject/checkin/CDataTest.java b/test/src/xmlobject/checkin/CDataTest.java deleted file mode 100644 index cb810db..0000000 --- a/test/src/xmlobject/checkin/CDataTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import java.io.File; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.XmlException; - -import dumbNS.RootDocument.Root; -import dumbNS.RootDocument; - -import tools.util.Util; -import tools.util.ResourceUtil; -import tools.util.JarUtil; -import xmlcursor.common.Common; - - -/** - * Test for finner CData control feature. - */ -public class CDataTest - extends TestCase -{ - static final String NL = SystemProperties.getProperty("line.separator")!=null ? - SystemProperties.getProperty("line.separator") : - (System.getProperty("line.separator") != null ? System.getProperty("line.separator") : "\n"); - - public CDataTest(String name) - { - super(name); - } - - public void testCData1() - throws Exception - { - String xmlText = ""; - String resultText = "cdata text"; - checkCData(xmlText, resultText, resultText); - } - - public void testCData2() - throws Exception - { - String xmlText = "" + NL + - " regular text" + NL + - ""; - String expected1 = "\n" + - "cdata text regular text\n" + - ""; - String expected2 = "" + NL + - " cdata text regular text" + NL + - ""; - - checkCData(xmlText, expected1, expected2); - } - - public void testCData3() - throws Exception - { - String xmlText = "\n" + - "text \n" + - ""; - String expected1 = "\n" + - "text cdata text\n" + - ""; - String expected2 = "" + NL + - " text cdata text" + NL + - ""; - - checkCData(xmlText, expected1, expected2); - } - - // https://issues.apache.org/jira/browse/XMLBEANS-404 - public void testXmlBeans404() - throws Exception - { - String xmlText = "\n" + - "text \n" + - ""; - String expected1 = "\n" + - "text cdata text]]\n" + - ""; - String expected2 = "" + NL + - " text cdata text]]" + NL + - ""; - - checkCData(xmlText, expected1, expected2); - } - - private void checkCData(String xmlText, String expected1, String expected2) - throws XmlException - { - System.out.println("\ninput:\n" + xmlText); - - XmlOptions opts = new XmlOptions(); - opts.setUseCDataBookmarks(); - - XmlObject xo = XmlObject.Factory.parse( xmlText , opts); - - String result1 = xo.xmlText(opts); - System.out.println("result xmlText:\n" + result1); - assertEquals("xmlText", expected1, result1); - - opts.setSavePrettyPrint(); - String result2 = xo.xmlText(opts); - System.out.println("result prettyPrint:\n" + result2); - assertEquals("prettyPrint", expected2, result2); - } -} diff --git a/test/src/xmlobject/checkin/CreationTests.java b/test/src/xmlobject/checkin/CreationTests.java deleted file mode 100755 index 5422b62..0000000 --- a/test/src/xmlobject/checkin/CreationTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Assert; -import com.easypo.XmlPurchaseOrderDocumentBean; -import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; -import com.easypo.XmlLineItemBean; -import com.easypo.XmlShipperBean; - -import java.math.BigDecimal; -import java.math.BigInteger; - -public class CreationTests extends TestCase -{ - public CreationTests(String name) { super(name); } - public static Test suite() { return new TestSuite(CreationTests.class); } - - public void testCreatePo() throws Exception - { - XmlPurchaseOrderDocumentBean doc = - XmlPurchaseOrderDocumentBean.Factory.newInstance(); - - PurchaseOrder order = doc.addNewPurchaseOrder(); - order.addNewCustomer().setName("David Bau"); - order.getCustomer().setAddress("Gladwyne, PA"); - XmlLineItemBean li; - li = order.addNewLineItem(); - li.setDescription("Burnham's Celestial Handbook, Vol 1"); - li.setPrice(new BigDecimal("21.79")); - li.setQuantity(BigInteger.valueOf(2)); - li.setPerUnitOunces(new BigDecimal("5")); - li = order.addNewLineItem(); - li.setDescription("Burnham's Celestial Handbook, Vol 2"); - li.setPrice(new BigDecimal("19.89")); - li.setQuantity(BigInteger.valueOf(2)); - li.setPerUnitOunces(new BigDecimal("5")); - li = order.addNewLineItem(); - li.setDescription("Burnham's Celestial Handbook, Vol 3"); - li.setPrice(new BigDecimal("19.89")); - li.setQuantity(BigInteger.valueOf(1)); - li.setPerUnitOunces(new BigDecimal("5")); - XmlShipperBean sh = order.addNewShipper(); - sh.setName("UPS"); - sh.setPerOunceRate(new BigDecimal("0.74")); - -// System.out.println(doc.xmlText()); - - Assert.assertEquals("David Bau", order.getCustomer().getName()); - Assert.assertEquals("Gladwyne, PA", order.getCustomer().getAddress()); - Assert.assertEquals(3, order.sizeOfLineItemArray()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 1", order.getLineItemArray(0).getDescription()); - Assert.assertEquals(new BigDecimal("21.79"), order.getLineItemArray(0).getPrice()); - Assert.assertEquals(new BigInteger("2"), order.getLineItemArray(0).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), order.getLineItemArray(0).getPerUnitOunces()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 2", order.getLineItemArray(1).getDescription()); - Assert.assertEquals(new BigDecimal("19.89"), order.getLineItemArray(1).getPrice()); - Assert.assertEquals(new BigInteger("2"), order.getLineItemArray(1).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), order.getLineItemArray(1).getPerUnitOunces()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 3", order.getLineItemArray(2).getDescription()); - Assert.assertEquals(new BigDecimal("19.89"), order.getLineItemArray(2).getPrice()); - Assert.assertEquals(new BigInteger("1"), order.getLineItemArray(2).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), order.getLineItemArray(2).getPerUnitOunces()); - - Assert.assertEquals(true, order.isSetShipper()); - Assert.assertEquals("UPS", order.getShipper().getName()); - Assert.assertEquals(new BigDecimal("0.74"), order.getShipper().getPerOunceRate()); - } -} diff --git a/test/src/xmlobject/checkin/DumbTest.java b/test/src/xmlobject/checkin/DumbTest.java deleted file mode 100755 index 0b6bac1..0000000 --- a/test/src/xmlobject/checkin/DumbTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import java.io.File; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.xmlbeans.XmlObject; - -import dumbNS.RootDocument.Root; -import dumbNS.RootDocument; - -import tools.util.Util; -import tools.util.ResourceUtil; -import tools.util.JarUtil; -import xmlcursor.common.Common; - - -/** - * - * - */ -public class DumbTest extends TestCase { - String instance; - - public DumbTest(String name) { - super(name); - } - - public void setUp() { - - try { - instance = JarUtil.getResourceFromJar("xbean/simple/dumb/dumb.xml"); - } catch (IOException e) { - System.err.println("Could not load xbean/simple/dumb/dumb.xml from " + Common.XMLCASES_JAR - + e.getMessage()); - e.printStackTrace(); - } - } - - public void testGetB2() - throws Exception { - RootDocument rootDoc = (RootDocument) XmlObject.Factory - .parse(instance); - Root root = rootDoc.getRoot(); - - System.out.println("root.xmlText() = " + root.xmlText()); - - assertTrue("bar:b attribute != 4", root.getB2().intValue() == 4); - } -} diff --git a/test/src/xmlobject/checkin/EasyPoTests.java b/test/src/xmlobject/checkin/EasyPoTests.java deleted file mode 100755 index 91c3ab7..0000000 --- a/test/src/xmlobject/checkin/EasyPoTests.java +++ /dev/null @@ -1,134 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import com.easypo.XmlPurchaseOrderDocumentBean; -import com.easypo.XmlPurchaseOrderDocumentBean.PurchaseOrder; - - - -import tools.util.*; - -public class EasyPoTests extends TestCase -{ - public EasyPoTests(String name) { super(name); } - public static Test suite() { return new TestSuite(EasyPoTests.class); } - - public void testEasyPo() throws Exception - { - XmlPurchaseOrderDocumentBean doc = (XmlPurchaseOrderDocumentBean) - XmlObject.Factory.parse(JarUtil.getResourceFromJarasFile( - "xbean/xmlobject/easypo1.xml")); - Assert.assertEquals(false, doc.isNil()); - PurchaseOrder order = doc.getPurchaseOrder(); - Assert.assertEquals("David Bau", order.getCustomer().getName()); - Assert.assertEquals("Gladwyne, PA", order.getCustomer().getAddress()); - Assert.assertEquals(3, order.sizeOfLineItemArray()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 1", order.getLineItemArray(0).getDescription()); - Assert.assertEquals(new BigDecimal("21.79"), order.getLineItemArray(0).getPrice()); - Assert.assertEquals(new BigInteger("2"), order.getLineItemArray(0).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), order.getLineItemArray(0).getPerUnitOunces()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 2", order.getLineItemArray(1).getDescription()); - Assert.assertEquals(new BigDecimal("19.89"), order.getLineItemArray(1).getPrice()); - Assert.assertEquals(new BigInteger("2"), order.getLineItemArray(1).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), order.getLineItemArray(1).getPerUnitOunces()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 3", order.getLineItemArray(2).getDescription()); - Assert.assertEquals(new BigDecimal("19.89"), order.getLineItemArray(2).getPrice()); - Assert.assertEquals(new BigInteger("1"), order.getLineItemArray(2).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), order.getLineItemArray(2).getPerUnitOunces()); - - Assert.assertEquals(true, order.isSetShipper()); - Assert.assertEquals("UPS", order.getShipper().getName()); - Assert.assertEquals(new BigDecimal("0.74"), order.getShipper().getPerOunceRate()); - - Assert.assertEquals(3, order.sizeOfLineItemArray()); - } - - - public void testSimpleAutoValidaiton() throws Exception - { - XmlPurchaseOrderDocumentBean.Factory.parse( - "" ); - - try - { - XmlPurchaseOrderDocumentBean.Factory.parse( - "" ); - - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - - try - { - XmlPurchaseOrderDocumentBean.Factory.parse( - "" ); - - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - - try - { - XmlPurchaseOrderDocumentBean.Factory.parse( - "" ); - - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - - try - { - XmlPurchaseOrderDocumentBean.Factory.parse( - "" ); - - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - - try - { - XmlPurchaseOrderDocumentBean.Factory.parse( - "" ); - - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - } -} diff --git a/test/src/xmlobject/checkin/InstanceValidationTests.java b/test/src/xmlobject/checkin/InstanceValidationTests.java deleted file mode 100755 index d67db23..0000000 --- a/test/src/xmlobject/checkin/InstanceValidationTests.java +++ /dev/null @@ -1,2033 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.*; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - -import javax.xml.namespace.QName; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import tools.util.*; - -public class InstanceValidationTests extends TestCase -{ - public InstanceValidationTests(String name) - { super(name); } - - public static Test suite() - { return new TestSuite(InstanceValidationTests.class); } - - static String[] _args; - static String _test; - - - public SchemaTypeLoader makeSchemaTypeLoader(String[] schemas) throws XmlException - { - XmlObject[] schemaDocs = new XmlObject[schemas.length]; - - for (int i = 0; i < schemas.length; i++) - { - schemaDocs[i] = XmlObject.Factory.parse(schemas[i]); - } - - return XmlBeans.loadXsd(schemaDocs); - } - - public SchemaTypeLoader makeSchemaTypeLoader(File[] schemas) throws XmlException, IOException - { - XmlObject[] schemaDocs = new XmlObject[schemas.length]; - - for (int i = 0; i < schemas.length; i++) - { - schemaDocs[i] = XmlObject.Factory.parse(schemas[i], new XmlOptions().setLoadLineNumbers().setLoadMessageDigest()); - } - - return XmlBeans.loadXsd(schemaDocs); - } - - - public List performValidation(String[] schemas, QName docType, String instances, - boolean startOnDocument) throws XmlException - { - SchemaTypeLoader stl = makeSchemaTypeLoader(schemas); - - XmlOptions options = new XmlOptions(); - - if (docType != null) - { - SchemaType docSchema = stl.findDocumentType(docType); - - Assert.assertTrue(docSchema != null); - - options.setDocumentType(docSchema); - } - - XmlObject x = stl.parse( instances, null, options); - - if (!startOnDocument) - { - XmlCursor c = x.newCursor(); - c.toFirstChild(); - x = c.getObject(); - c.dispose(); - } - - List xel = new ArrayList(); - options.setErrorListener(xel); - - x.validate(options); - - return xel; - } - - - public void testValidationElementError() throws XmlException - { - String bobSchema = "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "" + " \n" + " \n" + "" + " \n" + " \n" + "" + "
        \n"; - - String invalid = ""; - - String[] schemas = {bobSchema}; - - List errors = null; - - errors = performValidation(schemas, null, invalid, true); - Assert.assertTrue(errors != null); - Assert.assertTrue(errors.size()>0); - - for (Iterator it = errors.iterator(); it.hasNext();) - { - XmlValidationError xmlValError = (XmlValidationError) it.next(); - Assert.assertEquals(xmlValError.getErrorType(), XmlValidationError.INCORRECT_ELEMENT); - Assert.assertEquals(xmlValError.getBadSchemaType().getName().getLocalPart(), "biff"); - Assert.assertEquals(xmlValError.getOffendingQName().getLocalPart(), "q"); - Assert.assertEquals(xmlValError.getMessage(), "Expected element 'a@http://openuri.org/bobschema' instead of 'q@http://openuri.org/bobschema' here in element foo@http://openuri.org/bobschema"); - } - } - - - public void testValidationAttributeError() throws XmlException - { - StringBuffer empSchema = new StringBuffer(); - - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - - StringBuffer xmlInstance = new StringBuffer(); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("joe blow"); - xmlInstance.append("31"); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("test user"); - xmlInstance.append("29"); - xmlInstance.append(""); - xmlInstance.append(""); - - String[] schemas = {empSchema.toString()}; - - List errors = null; - - errors = performValidation(schemas, null, xmlInstance.toString(), true); - Assert.assertTrue(errors != null); - Assert.assertTrue(errors.size()>0); - - for (Iterator it = errors.iterator(); it.hasNext();) - { - XmlValidationError xmlValError = (XmlValidationError) it.next(); - Assert.assertEquals(xmlValError.getErrorType(), XmlValidationError.INCORRECT_ATTRIBUTE); - Assert.assertEquals(xmlValError.getBadSchemaType().getName().getLocalPart(), "personType"); - Assert.assertEquals(xmlValError.getOffendingQName().getLocalPart(), "employee"); - Assert.assertEquals(xmlValError.getMessage(), "Expected attribute: employee in element person"); - } - } - - public void testValidationIncorrectElementError() throws XmlException - { - StringBuffer empSchema = new StringBuffer(); - - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - - StringBuffer xmlInstance = new StringBuffer(); - xmlInstance.append(""); - xmlInstance.append(""); - //xmlInstance.append("joe blow"); - xmlInstance.append("31"); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("test user"); - xmlInstance.append("29"); - xmlInstance.append(""); - xmlInstance.append(""); - - String[] schemas = {empSchema.toString()}; - - List errors = null; - - errors = performValidation(schemas, null, xmlInstance.toString(), true); - Assert.assertTrue(errors != null); - Assert.assertTrue(errors.size()>0); - - Iterator it = errors.iterator(); - Assert.assertTrue(it.hasNext()); - - XmlValidationError xmlValError = (XmlValidationError) it.next(); - Assert.assertEquals(XmlValidationError.INCORRECT_ELEMENT, xmlValError.getErrorType()); - Assert.assertEquals("personType", xmlValError.getBadSchemaType().getName().getLocalPart()); - // todo debug this Assert.assertEquals(xmlValError.getOffendingQName().getLocalPart(), "age"); - Assert.assertEquals("Expected element 'name' instead of 'age' here in element person", xmlValError.getMessage()); - - Assert.assertTrue(it.hasNext()); - - xmlValError = (XmlValidationError) it.next(); - Assert.assertEquals(XmlValidationError.INCORRECT_ELEMENT, xmlValError.getErrorType()); - Assert.assertEquals("personType", xmlValError.getBadSchemaType().getName().getLocalPart()); - // todo debug this Assert.assertEquals(xmlValError.getOffendingQName().getLocalPart(), "age"); - Assert.assertEquals("Expected element 'name' before the end of the content in element person", xmlValError.getMessage()); - } - - public void testValidationElementNotAllowedError() throws XmlException - { - StringBuffer empSchema = new StringBuffer(); - - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - - StringBuffer xmlInstance = new StringBuffer(); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("joe blow"); - xmlInstance.append("31"); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("test user"); - xmlInstance.append("29"); - xmlInstance.append(""); - xmlInstance.append(""); - - String[] schemas = {empSchema.toString()}; - - List errors = null; - - errors = performValidation(schemas, null, xmlInstance.toString(), true); - Assert.assertTrue(errors != null); - // todo: enable this assert Assert.assertTrue(errors.size()>0); - - for (Iterator it = errors.iterator(); it.hasNext();) - { - XmlValidationError xmlValError = (XmlValidationError) it.next(); - - Assert.assertEquals(xmlValError.getErrorType(), XmlValidationError.ELEMENT_NOT_ALLOWED); - Assert.assertEquals(xmlValError.getBadSchemaType().getName().getLocalPart(), "personType"); - Assert.assertEquals(xmlValError.getMessage(), "Expected element(s)"); - } - } - - - public void testValidationAttributeTypeError() throws XmlException - { - StringBuffer empSchema = new StringBuffer(); - - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - - StringBuffer xmlInstance = new StringBuffer(); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("joe blow"); - xmlInstance.append("31"); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("test user"); - xmlInstance.append("junk"); - xmlInstance.append(""); - xmlInstance.append(""); - - String[] schemas = {empSchema.toString()}; - - List errors = null; - - errors = performValidation(schemas, null, xmlInstance.toString(), true); - Assert.assertTrue(errors != null); - Assert.assertTrue(errors.size()>0); - - for (Iterator it = errors.iterator(); it.hasNext();) - { - XmlValidationError xmlValError = (XmlValidationError) it.next(); - Assert.assertEquals(xmlValError.getErrorType(), XmlValidationError.ATTRIBUTE_TYPE_INVALID); - Assert.assertEquals(xmlValError.getMessage(), "Invalid decimal value: unexpected char '106'"); - } - } - - public void testElementError() throws XmlException - { - String bobSchema = "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + "" + - " \n" + - " \n" + "" + - " \n" + - " \n" + "" + - "
        \n"; - - String invalid = ""; - - String[] schemas = {bobSchema}; - - List errors = performValidation(schemas, null, invalid, true); - Assert.assertTrue(errors != null); - Assert.assertTrue(errors.size()>0); - - for (Iterator it = errors.iterator(); it.hasNext();) - { - XmlError xmlError = (XmlError) it.next(); - Assert.assertEquals(xmlError.getMessage(), "Expected element 'a@http://openuri.org/bobschema' instead of 'q@http://openuri.org/bobschema' here in element foo@http://openuri.org/bobschema"); - // todo check XmlValidationError - } - } - - public void testAttributeError() throws XmlException - { - StringBuffer empSchema = new StringBuffer(); - - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - empSchema.append("\n"); - - StringBuffer xmlInstance = new StringBuffer(); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("joe blow"); - xmlInstance.append("31"); - xmlInstance.append(""); - xmlInstance.append(""); - xmlInstance.append("test user"); - xmlInstance.append("29"); - xmlInstance.append(""); - xmlInstance.append(""); - - String[] schemas = {empSchema.toString()}; - - List errors = null; - - errors = performValidation(schemas, null, xmlInstance.toString(), true); - Assert.assertTrue(errors != null); - Assert.assertTrue(errors.size()>0); - - for (Iterator it = errors.iterator(); it.hasNext();) - { - XmlError xmlError = (XmlError) it.next(); - Assert.assertEquals(xmlError.getMessage(), "Expected attribute: employee in element person"); - // todo check XmlValidationError - } - } - - - - public void testValidate0 ( ) - throws Exception - { - // - // The most basic schema - // - - String schema = - "\n" + - "" + - ""; - - String[] schemas = { schema }; - - SchemaTypeLoader stl = makeSchemaTypeLoader( schemas ); - - // - // One which uses ##targetNamespace on a wildcard - // - - schema = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - ""; - - String[] schemas99 = { schema }; - - stl = makeSchemaTypeLoader( schemas99 ); - - // - // A big, nasty schema :-) - // - - File schemeFile = - JarUtil.getResourceFromJarasFile("xbean/xmlobject/store/XMLSchema.xsd" ); - File xmlFile = JarUtil.getResourceFromJarasFile("xbean/xmlobject/store/XML.xsd" ); - - File[] schemasF = { schemeFile, xmlFile }; - - stl = makeSchemaTypeLoader( schemasF ); - - SchemaType type = - stl.findDocumentType( - new QName( "http://www.w3.org/2001/XMLSchema", "schema" ) ); - - Assert.assertTrue( type != null ); - - - // - // A good piece from a J2EE schema - // - - schema = - "\n" + - "\n" + - "\n" + - "\n" + - "@(#)application-client_1_4.xsds 1.7 07/08/02\n" + - "\n" + - "\n" + - "\n"; - - String[] schemas5 = { schema }; - - stl = makeSchemaTypeLoader( schemas5 ); - - // - // A bad schema - // - - schema = ""; - - String[] schemas2 = { schema }; - - try - { - stl = makeSchemaTypeLoader( schemas2 ); - Assert.assertTrue( false ); - } - catch ( Exception e ) - { - } - - // - // A bad schema - // - schema = - "\n" + - " \n" + - "" + - ""; - - String[] schemas3 = { schema }; - - try - { - makeSchemaTypeLoader( schemas3 ); - - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - } - - public void testValidate1 ( ) - throws Exception - { - String ericSchema = - "\n" + - "\n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - "\n"; - - String eric2Schema = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n"; - - String eric = ""; - String eric2 = ""; - String xsi = "xmlns:eric2='http://openuri.org/ericschema2' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"; - - String[] valid = { - eric + "", - eric + "", - eric + "", - eric + "", - "" + - "" - }; - - String ericSansY = - ""; - - String[] invalid = { - "", - "", - eric + "text", - eric + "text", - eric + "text", - eric + "text", - eric + "text", - eric + "", - ericSansY + "", - "" + - "" - }; - - String[] schemas = { ericSchema, eric2Schema }; - - doTest( - schemas, - new QName( "http://openuri.org/ericschema", "eric" ), - valid, invalid ); - } - - public void testValidate2 ( ) - throws Exception - { - String bobSchema = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - "" + - "\n"; - - String xsiType = "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"; - - String[] valid = { - "" - }; - - String[] invalid = { - "", - "" - }; - - String[] schemas = { bobSchema }; - - doTest( schemas, null, valid, invalid ); - } - - String ns = - "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " + - "xmlns:xs='http://www.w3.org/2001/XMLSchema'"; - - public void testValidate3 ( ) - throws Exception - { - String schema = - "\n" + - "" + - " \n" + - " \n" + - " for maxOccurs\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - "" + - " \n" + - " \n" + - "" + - "\n"; - - String[] valid = { - ".1", - ".12", - ".123", - - "unbounded", - "0", - "1", - - "CAFEBABE", - "abcd", - - "abcdefgh", - "Eric", - - " Zero", - "Zero", - "0", - - "1", - " 1 ", - "Two", - " Three ", - - "", - "Brian", - "Kevin", - "Kevin Brian", - "Brian Kevin", - - " 1 22 333 4444 ", - "", - "5999", - - "P1Y", - - "abcde", - "xs:abc", - "foo", - "foo", - - "1965-06-11", - "1965-06-10", - "1999-05-31T13:20:00-05:00", - "00:00:00", - "13:20:00-05:00", - - "xs:abc", - "abcde", - "xs:ab", - "3", - "11", - "+45", - "1", - "0", - "-1", - "-1", - "489743579837589743434", - "1", - "", - "12", - "1", - "0", - "false", - "0", - "Monday", - "Sunday", - " Thursday ", - - "10.1", - "9.9", - "10", - "10.1", - "10", - "9.9", - - "10.1", - "9.9", - "10", - "10.1", - "10", - "9.9", - - "10.1", - "9.9", - "10", - "10.1", - "10", - "9.9", - - "eric", - "12345", - "1234", - "12345", - "1234", - "\n\n" - }; - - String[] invalid = { - "foo", - "P", - "CAFEBABP", - "abce", - - "abcde", - "Erik", - - "One", - "Twenty", - - "Seven", - "Bob", - "", - - "1", - "Bob", - "Ralph Frank", - - " 1 22 333 Eric ", - "Eric", - "-", - - "P2Y", - - "1965-06-10", - "1985-06-10", - "xx1999-05-31T13:20:00-05:00", - "eric", - "99:99:00", - "13:20:00-99:00", - - "moo", - "ab", - - "xs:abcdefghijk", - "xs:pqr", - "foo:bar", - "12", - "6", - "foo", - ".1", - "1", - "true", - "false", - "nibble", - "2", - "blurf", - "", - "", - "Monday Sucks", - - "10.1", - "10", - "10", - "9.9", - "9.9", - "10.1", - - "10.1", - "10", - "10", - "9.9", - "9.9", - "10.1", - - "10.1", - "10", - "10", - "9.9", - "9.9", - "10.1", - - " 1234 ", - "123456", - "vasilik", - "1", - "1234567", - ".1234", - " eric ", - - "", - "\n\n" - }; - - String[] schemas = { schema }; - - doTest( schemas, null, valid, invalid ); - } - - - public void testValidate5 ( ) - throws Exception - { - String schema = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - "\n" + - ""; - - String[] schemas = { schema }; - - SchemaTypeLoader stl = makeSchemaTypeLoader( schemas ); - - XmlObject x = - stl.parse( - "66", - null, null ); - - XmlCursor c = x.newCursor(); - - for ( ; ; ) - { - XmlObject obj = c.getObject(); - - if (obj != null) - obj.validate(); - - if (c.toNextToken().isNone()) - break; - } - - // invalid - - x = - stl.parse( - "66", - null, null ); - - Assert.assertTrue( ! x.validate() ); - - c = x.newCursor(); - c.toNextToken(); - c.toNextToken(); - - Assert.assertTrue( ! c.getObject().validate() ); - - // No schema - - x = XmlObject.Factory.parse( "asasasas" ); - - c = x.newCursor(); - - for ( ; ; ) - { - XmlObject obj = c.getObject(); - - if (obj != null) - obj.validate(); - - if (c.toNextToken().isNone()) - break; - } - } - - public void testValidate6 ( ) - throws Exception - { - String schema = - "\n" + - " \n" + - " \n" + - "\n" + - ""; - - String[] schemas = { schema, schema }; - - - // Should get a schema compile error - - try - { - makeSchemaTypeLoader( schemas ); - Assert.assertTrue( false ); - } - catch ( XmlException e ) - { - } - } - - public void testValidate7 ( ) - throws Exception - { - String schema = - "" + - "" + - " " + - "" + - " " + - " " + - " " + - " " + - " " + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "" + - "" + - ""; - - String[] schemas = { schema }; - - SchemaTypeLoader stl = makeSchemaTypeLoader( schemas ); - - XmlObject x = - stl.parse( - "", null, null ); - - Assert.assertTrue( x.validate() ); - - XmlCursor c = x.newCursor(); - - c.toFirstChild(); - - XmlObject base = c.getObject(); - - c.toEndToken(); - c.insertElement( "bar" ); - - Assert.assertTrue( !x.validate() ); - - c.toPrevSibling(); - - c.removeXml(); - - Assert.assertTrue( x.validate() ); - - base.changeType( stl.findType( new QName( "derived" ) ) ); - - c.insertElement( "bar" ); - - Assert.assertTrue( x.validate() ); - } - - // Tests abstract & block attributes on ComplexType - public void testValidate8() throws Exception - { - String[] schemas = { - "" + - "" + - " " + - " " + - "" + - " " + - "" + - " " + - " " + - " " + - " " + - " " + - "" + - " " + - "" + - " " + - " " + - " " + - " " + - " " + - "" + - " " + - " " + - " " + - " " + - " " + - "" + - "" + - "", - }; - - String xsiType = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "; - - String[] valid = { - "", - "", - "", - }; - String[] invalid = { - "", - "", - }; - - doTest(schemas, null, valid, invalid); - } - - public void testValidate9() throws Exception - { - - String[] schemas = { - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " ", - - "" + - - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - - " " + - " " + - " " + - " " + - " " + - " " + - - "", - - "" + - - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "", - - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "", - - }; - - String[] valid = { - "" + - " " + - " " + - " 1" + - " " + - " " + - " 1" + - " " + - " " + - " " + - " " + - " 124" + - " Shirt" + - " 29.99" + - " " + - " " + - " 563 " + - " Hat" + - " 69.99" + - " " + - " " + - " 443" + - " Umbrella" + - " 49.99" + - " " + - " " + - "", - - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "", - - "" + - " " + - " " + - "", - - "" + - " " + - " " + - " " + - "", - - "" + - " xyz" + - " abc def" + - " abc" + - " def" + - " xyz" + - " abc" + - " xyz abc" + - "", - }; - - String[] invalid = { - "" + - " " + - " " + - " 1" + - " " + - " " + - " 1" + - " " + - " " + - " " + - " " + - " 124" + - " Shirt" + - " 29.99" + - " " + - " " + - " 563" + - " Hat" + - " 69.99" + - " " + - " " + - " 443" + - " Umbrella" + - " 49.99" + - " " + - " " + - "", - - "" + - " " + - " " + - "", - - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "", - - "" + - " " + - " " + - " " + - "", - }; - - String[] invalidOnDocOnly = new String[] - { - - "" + - " foo" + - " abc" + - " def" + - " xyz" + - "", - - "" + - " abc foo" + - " abc" + - " def" + - " xyz" + - "", - }; - - - doTest(schemas, null, valid, invalid, true); - doTest(schemas, null, valid, invalid, false); - - // IDRefs are validated only if starting at the very root of the world - doTest(schemas, null, new String[0], invalidOnDocOnly, true); - doTest(schemas, null, invalidOnDocOnly, new String[0], false); - } - - // Test validation of setting with the ValidateOnSet option - public void testValidate10() throws Exception { - String schema = - "\n" + - " " + - " " + - " " + - " " + - " " + - "" + - ""; - - String[] schemas = { schema }; - - SchemaTypeLoader stl = makeSchemaTypeLoader( schemas ); - - XmlOptions validate = new XmlOptions().setValidateOnSet(); - XmlOptions noValidate = new XmlOptions(); - - SchemaType st = stl.findType(new QName("", "dec-restriction")); - - XmlDecimal dec = (XmlDecimal)stl.newInstance(st, validate); - - try { - dec.setStringValue("200"); - fail("Expected XmlValueOutOfRangeException"); - } - catch (XmlValueOutOfRangeException e) {} - - dec = (XmlDecimal)stl.newInstance(st, noValidate); - - try { - dec.setStringValue("200"); - } - catch (XmlValueOutOfRangeException e) { - fail("Should not throw exception"); - } - - } - - // tests numeral validation - public void testValidate11 ( ) - throws Exception - { - String schema = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "" + - "\n"; - - String[] valid = { - "" + - " \n -10" + - " " + - "", - "" + - " \n -9" + - " " + - "", - "" + - " +0008" + - " " + - "", - "" + - " +070" + - " " + - "" - }; - - String[] invalid = { - "" + - " " + - "", - "" + - " " + - "", - "" + - " + 4 " + - "" - }; - - String[] schemas = { schema }; - - doTest( - schemas, - new QName( "http://openuri.org/testNumerals", "doc" ), - valid, invalid ); - } - - // Bugzilla bug #26105: validate derived type from base type enumeration - public void testValidate12() throws Exception { - String schemas[] = { - "\n" + - - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - "\n" + - - "\n" + - " \n" + - " \n" + - " \n" + - "\n" + - "\n", - }; - - String[] valid = { - "enum1", - }; - - String[] invalid = { - "enum2/enumDef>", - }; - - doTest(schemas, null, valid, invalid); - } - - public void testValidateNestedGroups ( ) - throws Exception - { - // This is a weird Schema, inspired from JIRA bug XMLBEANS-35 - // Make sure we compile it and then validate correctly - String schemas[] = { - "\n" + - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - "\n" + - "\n" + - "\n"}; - - String valid[] = { - "\n" + - " \n" + - " \n" + - " " + - " \n" + - " \n" + - "\n"}; - - String invalid[] = { - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n"}; - - doTest(schemas, null, valid, invalid); - } - - public void doTest ( - String[] schemas, QName docType, - String[] validInstances, String[] invalidInstances) - throws Exception - { - doTest(schemas, docType, validInstances, invalidInstances, true); - } - - public void doTest ( - String[] schemas, QName docType, - String[] validInstances, String[] invalidInstances, boolean startOnDocument ) - throws Exception - { - SchemaTypeLoader stl = makeSchemaTypeLoader( schemas ); - - XmlOptions options = new XmlOptions(); - - if (docType != null) - { - SchemaType docSchema = stl.findDocumentType( docType ); - - Assert.assertTrue( docSchema != null ); - - options.put( XmlOptions.DOCUMENT_TYPE, docSchema ); - } - - for ( int i = 0 ; i < validInstances.length ; i++ ) - { - XmlObject x = - stl.parse( (String) validInstances[ i ], null, options ); - - if (!startOnDocument) - { - XmlCursor c = x.newCursor(); - c.toFirstChild(); - x = c.getObject(); - c.dispose(); - } - - List xel = new ArrayList(); - - options.put( XmlOptions.ERROR_LISTENER, xel ); - - boolean isValid = x.validate( options ); - - if (!isValid) - { - System.err.println( "Invalid doc, expected a valid doc: " ); - System.err.println( "Instance(" + i + "): " ); - System.err.println( x.xmlText() ); - System.err.println( "Errors: " ); - for ( int j = 0 ; j < xel.size() ; j++ ) - System.err.println( xel.get( j ) ); - System.err.println(); - } - - Assert.assertTrue( isValid ); - } - - for ( int i = 0 ; i < invalidInstances.length ; i++ ) - { - XmlObject x; - - try - { - x = stl.parse( (String) invalidInstances[ i ], null, options ); - - if (! startOnDocument) - { - XmlCursor c = x.newCursor(); - c.toFirstChild(); - x = c.getObject(); - c.dispose(); - } - - boolean isValid = x.validate(); - - if (isValid) - { - System.err.println( "Valid doc, expected a invalid doc: " ); - System.err.println( "Instance(" + i + "): " ); - System.err.println( x.xmlText() ); - System.err.println(); - } - - Assert.assertTrue( !isValid ); - } - catch ( XmlException e ) - { - } - } - } - - -} diff --git a/test/src/xmlobject/checkin/NameworldTest.java b/test/src/xmlobject/checkin/NameworldTest.java deleted file mode 100755 index b33a23a..0000000 --- a/test/src/xmlobject/checkin/NameworldTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import org.openuri.nameworld.NameworldDocument; -import org.openuri.nameworld.NameworldDocument.Nameworld; -import org.openuri.nameworld.Loc; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; - -import java.io.File; - -import javax.xml.namespace.QName; - -import junit.framework.Assert; -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; - - - -import tools.util.*; - - -public class NameworldTest extends TestCase -{ - public NameworldTest(String name) { super(name); } - public static Test suite() { return new TestSuite(NameworldTest.class); } - - public static void testWorld1() throws Exception - { - NameworldDocument doc = (NameworldDocument) - XmlObject.Factory.parse( - JarUtil.getResourceFromJarasFile( - "xbean/xmlobject/nameworld.xml")); - - Assert.assertEquals(new QName("http://openuri.org/nameworld", "nameworld"), doc.schemaType().getDocumentElementName()); - - QName[] contents = new QName[] - { - new QName("http://bar.com/", "barcity"), - new QName("http://foo.com/", "footown"), - new QName("http://bar.com/", "barvillage"), - new QName("http://bar.com/", "bartown"), - new QName("http://foo.com/", "foovillage"), - new QName("http://bar.com/", "barvillage"), - new QName("http://foo.com/", "foocity"), - new QName("http://bar.com/", "bartown"), - new QName("http://foo.com/", "foovillage"), - new QName("http://foo.com/", "footown"), - new QName("http://bar.com/", "barvillage"), - new QName("http://foo.com/", "foovillage"), - }; - int t = 0; - - Nameworld world = doc.getNameworld(); - Nameworld.Island[] islands = world.getIslandArray(); - for (int i = 0; i < islands.length; i++) - { - Loc[] locs = islands[i].getLocationArray(); - for (int j = 0; j < locs.length; j++) - { - Loc.Reference[] refs = locs[j].getReferenceArray(); - for (int k = 0; k < refs.length; k++) - { - Assert.assertEquals(contents[t++], refs[k].getTo()); - } - } - } - } - - /* - public static void testAccessByName() throws Exception - { - NameworldDocument doc = (NameworldDocument) - XmlLoader.Factory.parse(TestEnv.xbeanCase("xbean/xmlobject/nameworld.xml"), - NameworldDocument.type); - String[] contents = new String[] - { - "http://foo.com/", - "foocity", - "footown", - "foovillage", - "http://bar.com/", - "barcity", - "bartown", - "barvillage", - }; - int t = 0; - Nameworld world = (Nameworld)doc.elementByName(new Name("http://openuri.org/nameworld", "nameworld"), 0); - for (int i = 0; i < world.countOfElementByName(new Name("http://openuri.org/nameworld", "island")); i++) - { - Nameworld.Island island = (Nameworld.Island)world.elementByName(new Name("http://openuri.org/nameworld", "island"), i); - Assert.assertEquals(contents[t++], ((SimpleValue)island.attributeByName(new Name("targetNamespace"))).stringValue()); - for (int j = 0; j < island.countOfElementByName(new Name( "http://openuri.org/nameworld", "location")); j++) - { - Loc loc = (Loc)island.elementByName(new Name("http://openuri.org/nameworld", "location"), j); - Assert.assertEquals(contents[t++], ((SimpleValue)loc.attributeByName(new Name("name"))).stringValue()); - } - } - } - */ - -} diff --git a/test/src/xmlobject/checkin/RedefineTest.java b/test/src/xmlobject/checkin/RedefineTest.java deleted file mode 100755 index 56c13e0..0000000 --- a/test/src/xmlobject/checkin/RedefineTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.checkin; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlObject; - -import org.example.prod.NewSizeDocument; -import org.openuri.versionstest.ElementDocument; -import org.openuri.versionstest.Type; -import org.openuri.versionstest.TypeX; - -import java.util.List; -import java.util.ArrayList; -import java.io.PrintWriter; -import java.io.StringWriter; - -public class RedefineTest extends TestCase -{ - public RedefineTest(String name) { super(name); } - public static Test suite() { return new TestSuite(RedefineTest.class); } - - public void testRedefine() - { - try - { - String xml = "7"; - NewSizeDocument nsDoc = NewSizeDocument.Factory.parse(xml); - - boolean valid = nsDoc.validate(); - - if (!valid) - print(nsDoc); - - Assert.assertTrue(valid); - - Assert.assertTrue(nsDoc.getNewSize()==7); - - nsDoc.setNewSize(20); - - List errors = new ArrayList(); - XmlOptions options = new XmlOptions(); - options.setErrorListener(errors); - - valid = nsDoc.validate(options); - - if (valid || errors.size()!=1) - print(nsDoc); - - Assert.assertTrue(!valid); - - Assert.assertTrue(errors.size()==1); - } - catch (XmlException e) - { - StringWriter w = new StringWriter(); - e.printStackTrace(new PrintWriter(w)); - Assert.fail(w.toString()); - } - } - - public void testMultipleRedefine() - { - try - { - String xml = "" + - "AAABC" + ""; - ElementDocument doc = ElementDocument.Factory.parse(xml); - TypeX tx = doc.getElement(); - - Assert.assertTrue(tx.validate()); - Assert.assertEquals("A", tx.getA()); - Assert.assertEquals("B", tx.getB()); - Assert.assertEquals("C", tx.getC()); - Assert.assertEquals("AA", ((Type) tx).getAa()); - } - catch (XmlException e) - { - StringWriter w = new StringWriter(); - e.printStackTrace(new PrintWriter(w)); - Assert.fail(w.toString()); - } - } - - private static void print(XmlObject xo) - { - List errors = new ArrayList(); - XmlOptions options = new XmlOptions(); - options.setErrorListener(errors); - - System.out.println("Doc:\n" + xo + "\nValid: " + xo.validate(options)); - - for (int i = 0; i < errors.size(); i++) - { - XmlError xmlError = (XmlError) errors.get(i); - System.out.println(xmlError); - } - } -} diff --git a/test/src/xmlobject/checkin/SelectChldAttTests.java b/test/src/xmlobject/checkin/SelectChldAttTests.java deleted file mode 100755 index c5e2fdc..0000000 --- a/test/src/xmlobject/checkin/SelectChldAttTests.java +++ /dev/null @@ -1,265 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Assert; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.QNameSet; -import org.apache.xmlbeans.QNameSetBuilder; -import org.apache.xml.test.selectChldAtt.DocDocument; -import org.apache.xml.test.selectChldAtt.TypeExtendedC; - -import javax.xml.namespace.QName; -import java.util.Collection; -import java.util.ArrayList; -import java.util.Iterator; - -public class SelectChldAttTests extends TestCase -{ - public SelectChldAttTests(String name) { super(name); } - public static Test suite() { return new TestSuite(SelectChldAttTests.class); } - - private static final String XSI_URI="http://www.w3.org/2001/XMLSchema-instance"; - - public void testSelect() throws XmlException - { - String uri = "http://xml.apache.org/test/selectChldAtt"; - - String xml = "\n" + - " 7\n" + - " ... some text ... \n" + - - " \n" + - " this is wildcard bucket \n" + - " \n" + - - " \n" + - " 2\n" + - " element in #other namespace \n" + - " \n" + - - " \n" + - " element from typeC \n" + - " element in the 'any' bucket for typeExtendedC \n" + - " element from typeExtendedC \n" + - " \n" + - ""; - - DocDocument document = DocDocument.Factory.parse(xml); - DocDocument.Doc doc = document.getDoc(); - Collection errors = new ArrayList(); - Assert.assertTrue("Valid instance", doc.validate(new XmlOptions().setErrorListener(errors))); - printErrors(errors); - - XmlObject xo; - XmlObject[] xos; - - // select a known element - xos = doc.selectChildren(new QName(uri, "int")); - //print("1 selectChildren 'int' : ", xos); - Assert.assertTrue("1 selectChildren 'int' : ", verifyResult(xos, new String[]{"7"})); - - xos = doc.selectChildren(uri, "string"); - //print("2 selectChildren 'string' : ", xos); - Assert.assertTrue("2 selectChildren 'string' : ", verifyResult(xos, new String[]{"... some text ..."})); - - // elemA - xos = doc.selectChildren(new QName(uri, "elemA")); - //print("3 selectChildren 'elemA' : ", xos); - Assert.assertTrue("3 selectChildren 'elemA' : ", - verifyResult(xos, new String[]{"\n" + - " this is wildcard bucket\n" + - ""})); - - // select a known attribute - xo = xos[0].selectAttribute(new QName("", "price")); - //print("4 selectAttribute 'price' : ", xo); - Assert.assertTrue("4 selectAttribute 'price' : ", - verifyResult(xo, "4.321")); - - // select all attributes - QNameSet qns = QNameSet.forWildcardNamespaceString("##any", uri); - xos = xos[0].selectAttributes(qns); - //print("5 selectAttributes set'##any' :", xos); - Assert.assertTrue("5 selectAttributes set'##any' :", - verifyResult(xos, new String[]{"4.321"})); - - // elemB - xos = doc.selectChildren(new QName(uri, "elemB")); - //print("6 selectChildren 'elemB' : ", xos); - - //print("7 selectChildren set'##other' : " , xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##other", uri))); - Assert.assertTrue("7 selectChildren set'##other' : ", - verifyResult( xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##other", uri)) - , new String[]{"element in #other namespace"})); - //print("8 selectAttributes set'##other' : ", xos[0].selectAttributes(QNameSet.forWildcardNamespaceString("##other", uri))); - Assert.assertTrue("8 selectAttributes set'##other' : ", - verifyResult(xos[0].selectAttributes(QNameSet.forWildcardNamespaceString("##other", uri)), - new String[]{"attribute in #other namespace"})); - - // elemC - xos = doc.selectChildren(new QName(uri, "elemC")); - //print("9 selectChildren 'elemC' : ", xos); - //print("10 selectChildren set'##any' : " , xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##any", uri))); - Assert.assertTrue("10 selectChildren set'##any' : ", - verifyResult(xos[0].selectChildren(QNameSet.forWildcardNamespaceString("##any", uri)) - , new String[]{"element from typeC", - "element in the 'any' bucket for typeExtendedC", - "element from typeExtendedC"})); - - // select elements in the any bucket by excluding the the known elements - QNameSetBuilder qnsb = new QNameSetBuilder(); - qnsb.add(new QName(uri, "someElement")); - qnsb.add(new QName(uri, "aditionalElement")); - qnsb.invert(); - - //print("11a selectChildren in the any bucket for typeExtendedC: " , xos[0].selectChildren(qnsb.toQNameSet())); - Assert.assertTrue("11a selectChildren in the any bucket for typeExtendedC: ", - verifyResult(xos[0].selectChildren(qnsb.toQNameSet()), - new String[]{"element in the 'any' bucket for typeExtendedC"})); - - //print("11b selectChildren in the any bucket for typeExtendedC: " , xos[0].selectChildren(TypeExtendedC.type.qnameSetForWildcardElements())); - Assert.assertTrue("11b selectChildren in the any bucket for typeExtendedC: ", - verifyResult(xos[0].selectChildren(TypeExtendedC.type.qnameSetForWildcardElements()), - new String[]{"element in the 'any' bucket for typeExtendedC"})); - - // select attributes in the any bucket by excluding the the known attributes - qnsb = new QNameSetBuilder(); - qnsb.add(new QName("", "att1")); - qnsb.add(new QName("", "aditionalAtt")); - qnsb.add(new QName(XSI_URI, "type")); - qnsb.invert(); - - //print("12a selectChildren in the any bucket for typeExtendedC: " , xos[0].selectAttributes(qnsb.toQNameSet())); - Assert.assertTrue("12a selectChildren in the any bucket for typeExtendedC: ", - verifyResult(xos[0].selectAttributes(qnsb.toQNameSet()), - new String[]{"attribute in any bucket"})); - //print("12b selectChildren in the any bucket for typeExtendedC: " , xos[0].selectAttributes(TypeExtendedC.type.qnameSetForWildcardAttributes())); - Assert.assertTrue("12b selectChildren in the any bucket for typeExtendedC: ", - verifyResult(xos[0].selectAttributes(TypeExtendedC.type.qnameSetForWildcardAttributes()), - new String[]{"typeExtendedC", - "attribute in any bucket"})); - } - - private static void print(String msg, XmlObject[] xos) - { - System.out.println(msg + " " + xos.length); - for (int i=0; i43"; - XmlObject doc = XmlObject.Factory.parse(simpleDocument); - - // baseline test - Assert.assertEquals(simpleDocument, doc.xmlText()); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(out); - oos.writeObject(doc); - oos.close(); - - byte[] byteArray = out.toByteArray(); - ByteArrayInputStream in = new ByteArrayInputStream(byteArray); - ObjectInputStream ois = new ObjectInputStream(in); - XmlObject newdoc = (XmlObject)ois.readObject(); - ois.close(); - - Assert.assertEquals(simpleDocument, newdoc.xmlText()); - } - - public void testXBeanSerialization() throws Exception - { - XmlPurchaseOrderDocumentBean doc = XmlPurchaseOrderDocumentBean.Factory.newInstance(); - PurchaseOrder order = doc.addNewPurchaseOrder(); - order.addNewCustomer().setName("David Bau"); - order.getCustomer().setAddress("Gladwyne, PA"); - XmlLineItemBean li; - li = order.addNewLineItem(); - li.setDescription("Burnham's Celestial Handbook, Vol 1"); - li.setPrice(new BigDecimal("21.79")); - li.setQuantity(BigInteger.valueOf(2)); - li.setPerUnitOunces(new BigDecimal("5")); - li = order.addNewLineItem(); - li.setDescription("Burnham's Celestial Handbook, Vol 2"); - li.setPrice(new BigDecimal("19.89")); - li.setQuantity(BigInteger.valueOf(2)); - li.setPerUnitOunces(new BigDecimal("5")); - li = order.addNewLineItem(); - li.setDescription("Burnham's Celestial Handbook, Vol 3"); - li.setPrice(new BigDecimal("19.89")); - li.setQuantity(BigInteger.valueOf(1)); - li.setPerUnitOunces(new BigDecimal("5")); - XmlShipperBean sh = order.addNewShipper(); - sh.setName("UPS"); - sh.setPerOunceRate(new BigDecimal("0.74")); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(out); - oos.writeObject(doc.getPurchaseOrder().getLineItemArray(1)); - oos.writeObject(doc); - oos.writeObject(doc.getPurchaseOrder().getLineItemArray(2)); - oos.close(); - - byte[] byteArray = out.toByteArray(); - ByteArrayInputStream in = new ByteArrayInputStream(byteArray); - ObjectInputStream ois = new ObjectInputStream(in); - XmlLineItemBean newli1 = (XmlLineItemBean)ois.readObject(); - XmlPurchaseOrderDocumentBean newdoc = (XmlPurchaseOrderDocumentBean)ois.readObject(); - XmlLineItemBean newli2 = (XmlLineItemBean)ois.readObject(); - ois.close(); - - PurchaseOrder neworder = newdoc.getPurchaseOrder(); - - Assert.assertEquals(newli1, neworder.getLineItemArray(1)); - Assert.assertEquals(newli2, neworder.getLineItemArray(2)); - - Assert.assertEquals("David Bau", neworder.getCustomer().getName()); - Assert.assertEquals("Gladwyne, PA", neworder.getCustomer().getAddress()); - Assert.assertEquals(3, neworder.sizeOfLineItemArray()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 1", neworder.getLineItemArray(0).getDescription()); - Assert.assertEquals(new BigDecimal("21.79"), neworder.getLineItemArray(0).getPrice()); - Assert.assertEquals(new BigInteger("2"), neworder.getLineItemArray(0).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), neworder.getLineItemArray(0).getPerUnitOunces()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 2", neworder.getLineItemArray(1).getDescription()); - Assert.assertEquals(new BigDecimal("19.89"), neworder.getLineItemArray(1).getPrice()); - Assert.assertEquals(new BigInteger("2"), neworder.getLineItemArray(1).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), neworder.getLineItemArray(1).getPerUnitOunces()); - - Assert.assertEquals("Burnham's Celestial Handbook, Vol 3", neworder.getLineItemArray(2).getDescription()); - Assert.assertEquals(new BigDecimal("19.89"), neworder.getLineItemArray(2).getPrice()); - Assert.assertEquals(new BigInteger("1"), neworder.getLineItemArray(2).getQuantity()); - Assert.assertEquals(new BigDecimal("5"), neworder.getLineItemArray(2).getPerUnitOunces()); - - Assert.assertEquals(true, neworder.isSetShipper()); - Assert.assertEquals("UPS", neworder.getShipper().getName()); - Assert.assertEquals(new BigDecimal("0.74"), neworder.getShipper().getPerOunceRate()); - } - - public void testWsdlSerialization() - { - // test for TextSaver - try - { - File wsdlFile = JarUtil.getResourceFromJarasFile("xbean/xmlobject/wsdl.xml"); - - List loaders = new ArrayList(); - loaders.add(SchemaDocument.type.getTypeSystem()); - SchemaTypeLoader[] loadersArr = (SchemaTypeLoader[])loaders.toArray(new SchemaTypeLoader[1]); - SchemaTypeLoader loader = XmlBeans.typeLoaderUnion(loadersArr); - - XmlOptions options = new XmlOptions(); - options.setLoadLineNumbers(); - XmlObject wsdlObj = (XmlObject) loader.parse(wsdlFile, XmlObject.type, options); - - Reader reader = wsdlObj.newReader(); - InputSource source = new InputSource(reader); - source.setSystemId(""); - - - XmlObject wsdlDefinitions = XmlObject.Factory.parse(reader); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } -} diff --git a/test/src/xmlobject/checkin/SubstGroupTests.java b/test/src/xmlobject/checkin/SubstGroupTests.java deleted file mode 100755 index 6458c2e..0000000 --- a/test/src/xmlobject/checkin/SubstGroupTests.java +++ /dev/null @@ -1,248 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlNormalizedString; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlString; -import org.apache.xmlbeans.XmlToken; -import org.openuri.sgs.ADocument; -import org.openuri.sgs.BDocument; -import org.openuri.sgs.CDocument; -import org.openuri.sgs.RootDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -public class SubstGroupTests extends TestCase -{ - public SubstGroupTests(String name) { super(name); } - public static Test suite() { return new TestSuite(SubstGroupTests.class); } - - public void test1() throws Exception { - String xml1 = "" + - "\ta\ta\t" + - "\tb\tb\t" + - "\tc\tc\t" + - ""; - - - RootDocument doc1 = RootDocument.Factory.parse(xml1); - RootDocument.Root root = doc1.getRoot(); - assertTrue(doc1.validate()); - - XmlString a = root.xgetAArray(0); - assertTrue(a.schemaType().equals(XmlString.type)); - assertEquals("\ta\ta\t", a.getStringValue()); - - XmlString b = root.xgetAArray(1); - assertTrue(b.schemaType().equals(XmlNormalizedString.type)); - assertEquals(" b b ", b.getStringValue()); - - XmlString c = root.xgetAArray(2); - assertTrue(c.schemaType().equals(XmlToken.type)); - assertEquals("c c", c.getStringValue()); - - root.insertA(2, "d d"); - assertEquals("d d", root.getAArray(2)); - assertEquals(4, root.sizeOfAArray()); - root.removeA(2); - - root.removeA(1); - assertEquals("c c", root.getAArray(1)); - assertEquals(2, root.sizeOfAArray()); - - root.addA("f f"); - assertEquals(3, root.sizeOfAArray()); - assertEquals("f f", root.getAArray(2)); - - // Test array setters - - // test m < n case - String[] smaller = new String[]{ "x", "y" }; - root.setAArray(smaller); - assertEquals(2, root.sizeOfAArray()); - assertEquals("y", root.getAArray(1)); - - // test m > n case - String[] larger = new String[] { "p", "q", "r", "s" }; - root.setAArray(larger); - assertEquals(4, root.sizeOfAArray()); - assertEquals("r", root.getAArray(2)); - } - - public void test2() throws Exception { - String xml1 = "\ta\ta\t"; - String xml2 = "\tb\tb\t"; - String xml3 = "\tc\tc\t"; - - ADocument d1 = ADocument.Factory.parse(xml1); - XmlString a = d1.xgetA(); - assertTrue(a.schemaType().equals(XmlString.type)); - assertEquals("\ta\ta\t", a.getStringValue()); - - ADocument d2 = ADocument.Factory.parse(xml2); - XmlString b = d2.xgetA(); - assertTrue(d2.schemaType().equals(BDocument.type)); - assertTrue(b.schemaType().equals(XmlNormalizedString.type)); - assertEquals(" b b ", b.getStringValue()); - - ADocument d3 = ADocument.Factory.parse(xml3); - XmlString c = d3.xgetA(); - assertTrue(d3.schemaType().equals(CDocument.type)); - assertTrue(c.schemaType().equals(XmlToken.type)); - assertEquals("c c", c.getStringValue()); - } - - public static final String[] invalidSchemas = - { - " " + - " " + - " " + - "", - " " + - " " + - " " + - " " + - " " + - " " + - "", - " " + - " " + - " " + - "", - " " + - " " + - " " + - "", - " " + - " " + - " " + - " " + - " " + - " " + - "", - " " + - " " + - "", - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "", - }; - - public static final String[] validSchemas = - { - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - "", - }; - - public void test3() throws Exception { - SchemaDocument[] schemas = new SchemaDocument[invalidSchemas.length]; - - // Parse the invalid schema files - for (int i = 0 ; i < invalidSchemas.length ; i++) - schemas[i] = SchemaDocument.Factory.parse(invalidSchemas[i]); - - // Now compile the invalid schemas, test that they fail - for (int i = 0 ; i < schemas.length ; i++) - { - try { - XmlBeans.loadXsd(new XmlObject[] {schemas[i]}); - fail("Schema should have failed to compile:\n" + invalidSchemas[i]); - } - catch (XmlException success) { /* System.out.println(success); */ } - } - - - // Parse the valid schema files - schemas = new SchemaDocument[validSchemas.length]; - for (int i = 0 ; i < validSchemas.length ; i++) - schemas[i] = SchemaDocument.Factory.parse(validSchemas[i]); - - // Now compile the valid schemas, test that they succeed - for (int i = 0 ; i < schemas.length ; i++) - { - try { - XmlBeans.loadXsd(new XmlObject[] {schemas[i]}); - } - catch (XmlException fail) - { - fail("Failed to compile schema: " + schemas[i] + " with error: " + fail); - } - } - } - - public static String[] invalidDocs = - { - "" + - " content " + - " ", - }; - - public static String[] validDocs = - { - "" + - " content " + - " ", - }; - - public void test4() throws Exception - { - - for (int i = 0 ; i < invalidDocs.length ; i++) - { - XmlObject xo = XmlObject.Factory.parse(invalidDocs[i]); - assertTrue("Doc was valid. Should be invalid: " + invalidDocs[i], - ! xo.validate()); - } - - for (int i = 0 ; i < validDocs.length ; i++) - { - XmlObject xo = XmlObject.Factory.parse(validDocs[i]); - assertTrue("Doc was invalid. Should be valid: " + validDocs[i], - xo.validate()); - } - } - -} diff --git a/test/src/xmlobject/checkin/ValidateTest.java b/test/src/xmlobject/checkin/ValidateTest.java deleted file mode 100755 index 55f4f1c..0000000 --- a/test/src/xmlobject/checkin/ValidateTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.checkin; - -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; -import tools.util.JarUtil; - - -/** - * - * - */ -public class ValidateTest extends BasicCursorTestCase { - public ValidateTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ValidateTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } - - public void testValidateTrue() throws Exception { - //m_xo = XmlObject.Factory.parse(Common.XML_PURCHASEORDER); - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - assertEquals(true, m_xo.validate()); - } - - public void testValidateTrueWithOptionDiscardDocElement() throws Exception { - XmlOptions map = new XmlOptions(); - map.put(XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT, null); - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_XMLCURSOR_PO) - , map); - - assertEquals(false, m_xo.validate(map)); - } - - public void testValidateFalseFixedAttr() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - String ns="declare namespace po=\"http://xbean.test/xmlcursor/PurchaseOrder\";"; - String exp_ns="xmlns:po=\"http://xbean.test/xmlcursor/PurchaseOrder\""; - - m_xc = m_xo.newCursor(); - m_xc.selectPath(ns+" $this//po:shipTo"); - QName name = new QName("country"); - m_xc.setAttributeText(name, "UK"); - XmlObject xo = m_xc.getObject(); - assertEquals("UK", m_xc.getAttributeText(name)); - PurchaseOrderDocument pod = (PurchaseOrderDocument) m_xo; - - - - assertEquals(false, xo.validate()); - assertEquals(false, pod.validate()); - assertEquals(false, m_xo.validate()); - - assertTrue(true); - } -} - diff --git a/test/src/xmlobject/checkin/XPathTest.java b/test/src/xmlobject/checkin/XPathTest.java deleted file mode 100644 index a622927..0000000 --- a/test/src/xmlobject/checkin/XPathTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package xmlobject.checkin; - -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; - -/** - * Created by Cezar Andrei (cezar dot andrei at gmail dot com) - * Date: Apr 10, 2008 - */ -public class XPathTest - extends TestCase -{ - public XPathTest(String name) - { - super(name); - } - - public void testPath() - throws XmlException - { - final XmlObject obj = XmlObject.Factory.parse( - "" + - "" + - "val1" + - "val2" + - "" + - "val3" + - ""); - final XmlCursor c = obj.newCursor(); - - c.selectPath(".//b/c"); - - int selCount = c.getSelectionCount(); - assertEquals("SelectionCount", 1, selCount); - - while ( c.hasNextSelection() ) - { - c.toNextSelection(); - - assertEquals("OnStartElement", true, c.isStart()); - assertEquals("TextValue", "val1", c.getTextValue()); - System.out.println(" -> " + c.getObject() ); - } - c.dispose(); - } - - - public void testPath2() - throws XmlException - { - final XmlObject obj = XmlObject.Factory.parse( - "" + - "" + - "val1" + - "" + - "val2" + - "val3" + - "" + - "" + - "val4" + - ""); - final XmlCursor c = obj.newCursor(); - - c.selectPath(".//b/c"); - - int selCount = c.getSelectionCount(); - assertEquals("SelectionCount", 2, selCount); - - assertEquals("hasNextSelection", true, c.hasNextSelection() ); - c.toNextSelection(); - - System.out.println(" -> " + c.getObject() ); - assertEquals("OnStartElement", true, c.isStart()); - assertEquals("TextValue", "val1", c.getTextValue()); - - - assertEquals("hasNextSelection2", true, c.hasNextSelection() ); - c.toNextSelection(); - - System.out.println(" -> " + c.getObject() ); - assertEquals("OnStartElement2", true, c.isStart()); - assertEquals("TextValue2", "val3", c.getTextValue()); - - c.dispose(); - } - - public void testPath3() - throws XmlException - { - final XmlObject obj = XmlObject.Factory.parse( - "" + - "" + - "val1" + - "" + - "val2" + - "" + - "val3" + - "val5" + - "" + - "" + - "" + - "" + - "val4" + - ""); - final XmlCursor c = obj.newCursor(); - - c.selectPath(".//b/c//c"); - - int selCount = c.getSelectionCount(); - assertEquals("SelectionCount", 1, selCount); - - while ( c.hasNextSelection() ) - { - c.toNextSelection(); - - System.out.println(" -> " + c.getObject() ); - assertEquals("OnStartElement", true, c.isStart()); - assertEquals("TextValue", "val5", c.getTextValue()); - } - c.dispose(); - } -} diff --git a/test/src/xmlobject/common/SelectChildrenAttribCommon.java b/test/src/xmlobject/common/SelectChildrenAttribCommon.java deleted file mode 100755 index 1f77496..0000000 --- a/test/src/xmlobject/common/SelectChildrenAttribCommon.java +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.common; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; -import junit.framework.TestCase; -import tools.util.JarUtil; -import tools.xml.XmlComparator; - - -/** - * - * - */ -public class SelectChildrenAttribCommon - extends TestCase -{ - public SelectChildrenAttribCommon(String name) - { - super(name); - } - - public void setUp() - { - opts = new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2); - } - - - // Common - public XmlOptions opts; - - - ////////////////////////////////////////////////////////////////// - // Helper methods - public void validateTest(String testName, String[] exps, XmlObject[] act) - throws Exception - { - assertTrue(testName + ": Return array has more/less elements than expected: " - + act.length, act.length == exps.length); - boolean passed = true; - - for (int i = 0; i < act.length; i++) - { - boolean res; - res = XComp(convertFragToDoc(act[i].xmlText()), exps[i], true); - if (res == false) - { - System.out.println("Expected value differs from actual: Index=" + i); - System.out.println("Expected: " + exps[i]); - System.out.println("Actual: " + act[i].xmlText()); - passed = false; - } - } - assertTrue(testName + ": Failed!", passed); - } - - - public void validateTest(String testName, String exp, XmlObject xml) - throws Exception - { - if (xml == null) - fail(testName + ": XmlObject Recevied is null"); - - boolean res = XComp(convertFragToDoc(xml.xmlText()), exp, true); - assertTrue("Expected value differs from actual\n" + - "Expected: " + exp + "\n" + - "Actual: " + xml.xmlText(), - res); - } - - - public static String getXml(String file) - throws java.io.IOException - { - return JarUtil.getResourceFromJar(file); - } - - - /** - * Just a thin wrapper around XmlComparator - */ - public static boolean XComp(String actual, String expected, boolean verbose) - throws org.apache.xmlbeans.XmlException - { - boolean same; - XmlComparator.Diagnostic diag = new XmlComparator.Diagnostic(); - same = XmlComparator.lenientlyCompareTwoXmlStrings(actual, expected, diag); - if (!same && verbose) - System.out.println(diag.toString()); - - return same; - } - - /** - * This is a workaround for using XmlComparator to compare XML that are just - * a single value like '7' wrapped in tags. Inside - * XmlComparator creates XmlObjects and tags are ignored. So - * this method will replace that with something like so that they look - * like Xml Docs... - */ - public static String convertFragToDoc(String xmlFragment) - { - String startFragStr = "Runnable
        Interface - */ - public void run() { - // Read in the xml file - XmlObject x = null; - String tName = Thread.currentThread().getName(); - try { - x = XmlObject.Factory.parse(xmlFile); - } catch (XmlException xe) { - System.out.println("XmlException in thread " + tName); - xe.printStackTrace(); - status = false; - return; - } catch (IOException ioe) { - System.out.println("IOException in thread " + tName); - ioe.printStackTrace(); - status = false; - return; - } - - try { - // Walk through the XML - XmlCursor cur = x.newCursor(); - cur.toStartDoc(); - do { - // Sleep for 10 milliseconds - try { - Thread.sleep(10); - } catch (Exception e) { - // Continue ahead.. - } - // Print current token - //System.out.println("["+tName+"]: " + cur.currentTokenType().toString()); - cur.toNextToken(); - } while (cur.hasNextToken()); - cur.dispose(); - } catch (Exception e) { - System.out.println("Exception in thread " + tName); - e.printStackTrace(); - status = false; - } - } - - - public boolean getStatus() { - return status; - } - - public void doTest() throws Exception { - Thread t = new Thread(this, "test"); - t.start(); - t.join(); - } - - public static void main(String args[]) throws Exception { - File xmlFile = new File("po.xml"); - new XmlReader(xmlFile).doTest(); - } - -} \ No newline at end of file diff --git a/test/src/xmlobject/detailed/CompareToTest.java b/test/src/xmlobject/detailed/CompareToTest.java deleted file mode 100755 index a7e0643..0000000 --- a/test/src/xmlobject/detailed/CompareToTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.detailed; - -import junit.framework.*; - -import java.math.BigDecimal; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; - -//import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; - -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.EventStatusDocument.EventStatus; -import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; -import org.tranxml.tranXML.version40.CityNameDocument.CityName; -import org.tranxml.tranXML.version40.ETADocument.ETA; - -import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; -import tools.util.JarUtil; - - -/** - * - * - */ -public class CompareToTest extends TestCase { - public CompareToTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CompareToTest.class); - } - - /*public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } - */ - public void testCompareToEquals() throws Exception { - CarLocationMessageDocument clmDoc = (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - EventStatus[] aEventStatus = clmDoc.getCarLocationMessage() - .getEventStatusArray(); - if (aEventStatus.length < 1) { - fail( - "Unexpected: Missing EventStatus element. Test harness failure."); - } else { - GeographicLocation gl = aEventStatus[0].getGeographicLocation(); - CityName cname0 = gl.getCityName(); - ETA eta = aEventStatus[0].getETA(); - CityName cname1 = eta.getGeographicLocation().getCityName(); - assertTrue(cname0.valueEquals(cname1)); - try { - assertTrue(XmlObject.EQUAL == cname0.compareTo(cname1)); - fail("Expected ClassCastException."); - } - catch (ClassCastException e) { - assertTrue(true); - } - } - } - - public void testCompareToNull() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - try { - assertEquals(XmlObject.NOT_EQUAL, m_xo.compareTo(null)); - assertTrue(false); - } - catch (ClassCastException e) { - assertTrue(true); - } - } - - - public void testCompareToLessThan() throws Exception { -// PurchaseOrderDocument poDoc = (PurchaseOrderDocument) XmlObject.Factory.parse( - // Common.XML_PURCHASEORDER); - PurchaseOrderDocument poDoc = (PurchaseOrderDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - - try { - BigDecimal bdUSPrice0 = poDoc.getPurchaseOrder().getItems() - .getItemArray(0) - .getUSPrice(); - BigDecimal bdUSPrice1 = poDoc.getPurchaseOrder().getItems() - .getItemArray(1) - .getUSPrice(); - assertEquals(XmlObject.LESS_THAN, bdUSPrice1.compareTo(bdUSPrice0)); - } - catch (NullPointerException npe) { - fail("Unexpected instance document. Harness failure."); - } - } - - public void testCompareToGreaterThan() throws Exception { - PurchaseOrderDocument poDoc = (PurchaseOrderDocument) - XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - try { - BigDecimal bdUSPrice0 = poDoc.getPurchaseOrder().getItems() - .getItemArray(0) - .getUSPrice(); - BigDecimal bdUSPrice1 = poDoc.getPurchaseOrder().getItems() - .getItemArray(1) - .getUSPrice(); - assertEquals(XmlObject.GREATER_THAN, - bdUSPrice0.compareTo(bdUSPrice1)); - } - catch (NullPointerException npe) { - fail("Unexpected instance document. Harness failure."); - } - } - - - public void testCompareToString() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - try { - assertEquals(0, m_xo.compareTo("")); - fail("Expected ClassCastException"); - } - catch (ClassCastException cce) { - } - assertTrue(true); - } - - public void testCompareValue() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.toFirstChild(); - XmlObject xo = m_xc.getObject(); - assertEquals(XmlObject.NOT_EQUAL, m_xo.compareValue(xo)); - } - - private XmlObject m_xo; - private XmlCursor m_xc; - -} - diff --git a/test/src/xmlobject/detailed/CopyTest.java b/test/src/xmlobject/detailed/CopyTest.java deleted file mode 100644 index 9e76418..0000000 --- a/test/src/xmlobject/detailed/CopyTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.detailed; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlObject; - -public class CopyTest extends TestCase -{ - public CopyTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(CopyTest.class); - } - - // Test for a Document object being copied as DocFrag if the type of the - // source of the copy is not a document type (as is the case with NO_TYPE). - public void testXobjTypeOnDomNodeCopy() throws Exception - { - XmlObject o = XmlObject.Factory.parse(""); - String xobjOrgClassName = "org.apache.xmlbeans.impl.store.Xobj$DocumentXobj"; - assertEquals("Invalid Type!", o.getDomNode().getClass().getName(),xobjOrgClassName); - - XmlObject o2 = o.copy(); - String xobjCopyClassName = o2.getDomNode().getClass().getName(); - System.out.println ( "DocXobj:"+ xobjCopyClassName); - - // check for the expected type - assertEquals("Invalid Type!", "org.apache.xmlbeans.impl.store.Xobj$DocumentXobj",xobjOrgClassName); - assertEquals("Invalid Type!", "org.apache.xmlbeans.impl.store.Xobj$DocumentXobj",xobjCopyClassName); - } - - // Test the same for a simple untyped XmlObject copy - public void testXobjTypeOnCopy() throws Exception - { - String untypedXobjClass = "org.apache.xmlbeans.impl.values.XmlAnyTypeImpl"; - - XmlObject o = XmlObject.Factory.parse(""); - assertEquals("Invalid Type!",untypedXobjClass,o.getClass().getName()); - - XmlObject o2 = o.copy(); - String xobjClass = o2.getClass().getName(); - // type should be unchanged after the copy - assertEquals("Invalid Type!",untypedXobjClass,o2.getClass().getName()); - } - - -} diff --git a/test/src/xmlobject/detailed/IsImmutableTest.java b/test/src/xmlobject/detailed/IsImmutableTest.java deleted file mode 100755 index 99c1fa7..0000000 --- a/test/src/xmlobject/detailed/IsImmutableTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.detailed; - -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlOptions; - -import java.util.*; -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.XmlAnySimpleType; - -import java.util.Vector; - -import xmlcursor.common.*; - -import java.net.URL; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import tools.util.Util; -import tools.util.JarUtil; - - -/** - * - * - */ -public class IsImmutableTest extends BasicCursorTestCase { - public IsImmutableTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(IsImmutableTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } - - public void testIsImmutableFalse() throws Exception { - CarLocationMessageDocument clmDoc = - (CarLocationMessageDocument) XmlObject.Factory - .parse( JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - assertEquals(false, clmDoc.isImmutable()); - } - - public void testIsImmutableTrue() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//Initial"); - m_xc.toNextSelection(); - SchemaType st = m_xc.getObject().schemaType(); - XmlObject xoNew = st.newValue("ZZZZ"); - assertEquals(true, xoNew.isImmutable()); - // verify it's not in main store - assertEquals("GATX", m_xc.getTextValue()); - } - -} - diff --git a/test/src/xmlobject/detailed/SelectAttributeTests.java b/test/src/xmlobject/detailed/SelectAttributeTests.java deleted file mode 100755 index 1bf8b41..0000000 --- a/test/src/xmlobject/detailed/SelectAttributeTests.java +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - -import junit.framework.TestCase; -import junit.framework.Assert; - -import org.openuri.test.selectChildren.*; -import org.openuri.test.selectAttribute.*; - -import org.apache.xmlbeans.*; - -import javax.xml.namespace.QName; -import java.util.*; - -import xmlobject.common.SelectChildrenAttribCommon; - -/** - * - * - */ -public class SelectAttributeTests - extends SelectChildrenAttribCommon -{ - public SelectAttributeTests(String name) - { - super(name); - } - - static String saUri = "http://openuri.org/test/selectAttribute"; - static String saStartFrag = ""; - - static String abcUri = "http://abc"; - static String defUri = "http://def"; - static String xyzUri = "http://xyz"; - - static String anyStartFrag = ""; - - static String endFrag = ""; - // To speed up tests when running multiple test methods in the same run - DocDocument.Doc doc = null; - - /////////////////////////////////////////////////////////////////// - // Tests for non-wildcard attributes - public void testSelectWithQName() - throws Exception - { - if (doc == null) - doc = (DocDocument.Doc) getTestObject(); - QName qn = new QName("", "att1"); - XmlObject x = doc.getNormal().selectAttribute(qn); - String exp = saStartFrag + "Attribute 1" + endFrag; - - validateTest("testSelectWithQName", exp, x); - // Check Select with QName that is not present.. should get null back. - x = doc.getWithOther().selectAttribute(qn); - assertTrue(x == null); - } - - - public void testSelectWithURI() - throws Exception - { - if (doc == null) - doc = (DocDocument.Doc) getTestObject(); - - XmlObject x = doc.getNormal().selectAttribute("", "att2"); - String exp = saStartFrag + "Attribute 2" + endFrag; - - validateTest("testSelectWithURI", exp, x); - // Check Select with QName that is not present.. should get null back. - x = doc.getWithAny().selectAttribute("", "att2"); - assertTrue(x == null); - - } - - //////////////////////////////////////////////////////////////////// - // Test for wild-card attributes - public void testSelectWithQNameForAny() - throws Exception - { - if (doc == null) - doc = (DocDocument.Doc) getTestObject(); - - QName qn = new QName(abcUri, "att3"); - String exp = saStartFrag + "Attribute 3" + endFrag; - XmlObject x = doc.getWithOther().selectAttribute(qn); - - validateTest("testSelectWithQNameForAny", exp, x); - - - x = doc.getWithAny(); - System.out.println(x.xmlText()); - - } - - //////////////////////////////////////////////////////////////////// - // Helper - public XmlObject getTestObject() - throws Exception - { - String xml = getXml("xbean/xmlobject/SelectAttribute-Doc.xml"); - DocDocument xmlObj = DocDocument.Factory.parse(xml); - DocDocument.Doc doc = xmlObj.getDoc(); - - Collection errors = new ArrayList(); - opts.setErrorListener(errors); - boolean valid = doc.validate(opts); - tools.xml.Utils.printXMLErrors(errors); - - assertTrue("Test Xml is not valid!!", valid); - return doc; - } - - public void printXmlObj(XmlObject[] xobj) - throws Exception - { - for (int i = 0; i < xobj.length; i++) - System.out.println(convertFragToDoc(xobj[i].xmlText())); - } - - -} diff --git a/test/src/xmlobject/detailed/SelectChildrenTests.java b/test/src/xmlobject/detailed/SelectChildrenTests.java deleted file mode 100755 index 2eb7364..0000000 --- a/test/src/xmlobject/detailed/SelectChildrenTests.java +++ /dev/null @@ -1,216 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - - -import org.openuri.test.selectChildren.*; - -import org.apache.xmlbeans.*; - -import javax.xml.namespace.QName; -import java.util.*; - -import xmlobject.common.SelectChildrenAttribCommon; - -/** - * - * - */ -public class SelectChildrenTests - extends SelectChildrenAttribCommon -{ - public SelectChildrenTests(String name) - { - super(name); - } - - - static String scUri = "http://openuri.org/test/selectChildren"; - static String scStartFrag = ""; - - static String abcUri = "http://abc"; - static String defUri = "http://def"; - static String xyzUri = "http://xyz"; - - static String anyStartFrag = ""; - - static String endFrag = ""; - - ////////////////////////////////////////////////////////////////// - // Tests - public void testSelectWithQName() - throws Exception - { - String xml = getXml("xbean/xmlobject/SelectChildren-NormalDoc.xml"); - - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - - NormalDocument doc = NormalDocument.Factory.parse(xml); - assertTrue(doc.validate()); - NormalType norm = doc.getNormal(); - - exps = new String[]{scStartFrag + "first element" + endFrag}; - xos = norm.selectChildren(new QName(scUri, "first")); - - this.validateTest("testSelectWithQName", exps, xos); - } - - - public void testSelectWithURI() - throws Exception - { - String xml = getXml("xbean/xmlobject/SelectChildren-NormalDoc.xml"); - - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - - NormalDocument doc = NormalDocument.Factory.parse(xml); - assertTrue(doc.validate()); - NormalType norm = doc.getNormal(); - - exps = new String[]{scStartFrag + "second element" + endFrag}; - xos = norm.selectChildren(scUri, "second"); - - this.validateTest("testSelectWithURI", exps, xos); - } - - public void testSelectWithQNameSet() - throws Exception - { - String xml = getXml("xbean/xmlobject/SelectChildren-NormalDoc.xml"); - - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - - NormalDocument doc = NormalDocument.Factory.parse(xml); - assertTrue(doc.validate()); - NormalType norm = doc.getNormal(); - - QName[] qArr = new QName[] { new QName(scUri, "first"), - new QName(scUri, "numbers"), - new QName(scUri, "second")}; - - QNameSet qSet = QNameSet.forArray(qArr); - - exps = new String[]{scStartFrag + "first element" + endFrag, - scStartFrag + "second element" + endFrag, - scStartFrag + "10" + endFrag, - scStartFrag + "11" + endFrag, - scStartFrag + "12" + endFrag }; - - xos = norm.selectChildren(qSet); - - this.validateTest("testSelectWithQNameSet", exps, xos); - } - - ////////////////////////////////////////////////////////////////////// - // Tests with 'any' Element - public void testSelectWithQNameForAny() - throws Exception - { - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - - String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); - ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); - assertTrue(doc.validate()); - - WithAnyType any = doc.getElemWithAny(); - // Select children from a known namespace - xos = any.selectChildren(new QName(defUri, "someElem2")); - exps = new String[]{anyStartFrag + "DEF Namespace" + endFrag }; - - validateTest("testSelectWithQNameForAny", exps, xos); - } - - public void testSelectWithURIForAny() - throws Exception - { - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - - String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); - ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); - assertTrue(doc.validate()); - - WithAnyType any = doc.getElemWithAny(); - // Select children from a known namespace - xos = any.selectChildren(scUri, "simple"); - exps = new String[]{anyStartFrag + "Simple String" + endFrag }; - - validateTest("testSelectWithURIForAny", exps, xos); - } - - public void testSelectWithWildcard() - throws Exception - { - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); - ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); - assertTrue(doc.validate()); - - WithAnyType any = doc.getElemWithAny(); - - xos = any.selectChildren(QNameSet.forWildcardNamespaceString("##other", - scUri)); - exps = new String[]{anyStartFrag + "ABC Namespace" + endFrag, - anyStartFrag + "DEF Namespace" + endFrag, - anyStartFrag + "XYX Namespace" + endFrag, - anyStartFrag + "ABC-SameElem" + endFrag, - anyStartFrag + "DEF-SameElem" + endFrag, - anyStartFrag + "XYZ-SameElem" + endFrag}; - - validateTest("testSelectWithWildcard", exps, xos); - } - - public void testSelectWithQNameBuilder() - throws Exception - { - XmlObject[] xos; // For the return from selectChildren - String[] exps; // For the expected xml strings - String xml = getXml("xbean/xmlobject/SelectChildren-AnyTypeDoc.xml"); - ElemWithAnyDocument doc = ElemWithAnyDocument.Factory.parse(xml); - assertTrue(doc.validate()); - - WithAnyType any = doc.getElemWithAny(); - - Set excFromIncSet = new HashSet(); - excFromIncSet.add(new QName(scUri, "simple")); - - Set excSet = new HashSet(); - excSet.add(xyzUri); - - Set incFromExcSet = new HashSet(); - incFromExcSet.add(new QName(xyzUri, "sameElem")); - - QNameSet qset = new QNameSetBuilder(excSet, - null, - excFromIncSet, - incFromExcSet).toQNameSet(); - xos = any.selectChildren(qset); - - for (int i =0; i < xos.length; i++) - System.out.println(xos[i].xmlText()); - - } - - -} diff --git a/test/src/xmlobject/detailed/SerializationDetailedTests.java b/test/src/xmlobject/detailed/SerializationDetailedTests.java deleted file mode 100644 index 4319253..0000000 --- a/test/src/xmlobject/detailed/SerializationDetailedTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.detailed; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlInteger; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Node; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.math.BigInteger; - -public class SerializationDetailedTests extends TestCase -{ - public SerializationDetailedTests (String name) { super(name); } - public static Test suite() { return new TestSuite(SerializationDetailedTests.class); } - - public void testDocFragmentSerialization() throws Exception - { - XmlInteger xmlInt = XmlInteger.Factory.newInstance(); - xmlInt.setBigIntegerValue(new BigInteger("10")); - - Node node = xmlInt.getDomNode(); - assertTrue("DOM node from XmlObject not instance of DocumentFragment (it is a "+node+")", node instanceof DocumentFragment); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(out); - oos.writeObject(xmlInt); - - - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - ObjectInputStream ois = new ObjectInputStream(in); - XmlInteger deserialized = (XmlInteger) ois.readObject(); - - node = deserialized.getDomNode(); - assertTrue("DOM node from deserialized XmlObject not instance of DocumentFragment (it is a "+node+")", node instanceof DocumentFragment); } - - } diff --git a/test/src/xmlobject/detailed/SetIdentityTest.java b/test/src/xmlobject/detailed/SetIdentityTest.java deleted file mode 100755 index 9eb59ba..0000000 --- a/test/src/xmlobject/detailed/SetIdentityTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.detailed; - -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlDocumentProperties; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; -import org.apache.xmlbeans.SchemaType; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import java.net.URL; - -import tools.util.Util; -import tools.util.JarUtil; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.GeographicLocationDocument.GeographicLocation; -import org.tranxml.tranXML.version40.CodeList309; -import org.tranxml.tranXML.version40.LocationIdentifierDocument.LocationIdentifier; - - -/** - * - * - */ -public class SetIdentityTest extends TestCase { - public SetIdentityTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(SetIdentityTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } - - public void testSetIdentity() throws Exception { - CarLocationMessageDocument clm = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - XmlCursor xc = clm.newCursor(); - - xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//GeographicLocation"); - xc.toNextSelection(); - GeographicLocation gl = (GeographicLocation) xc.getObject(); - xc.dispose(); - LocationIdentifier li = gl.addNewLocationIdentifier(); - li.setQualifier(CodeList309.FR); - CodeList309 cl309 = li.xgetQualifier(); - // setQualifier to itself, i.e. x == x - li.xsetQualifier(cl309); - gl.setLocationIdentifier(li); - assertEquals(CodeList309.FR, gl.getLocationIdentifier().getQualifier()); - - } - -} - diff --git a/test/src/xmlobject/detailed/SoapFaultTest.java b/test/src/xmlobject/detailed/SoapFaultTest.java deleted file mode 100755 index 88a7ff5..0000000 --- a/test/src/xmlobject/detailed/SoapFaultTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - -import junit.framework.TestCase; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlError; - -import javax.xml.namespace.QName; - -import org.xmlsoap.schemas.soap.envelope.Fault; -//import org.xmlsoap.schemas.soap.envelope.FaultDocument; -import org.xmlsoap.schemas.soap.envelope.Detail; - -import xmlobjecttest.soapfaults.FirstFaultType; -import xmlobjecttest.soapfaults.FirstFaultDocument; -import xmlobjecttest.soapfaults.SecondFaultType; -import xmlobjecttest.soapfaults.SecondFaultDocument; - -import java.util.ArrayList; - - -/** - * - */ -public class SoapFaultTest extends TestCase { - public static final String soapenc = "http://schemas.xmlsoap.org/soap/encoding/"; - public static final String soapenv = "http://schemas.xmlsoap.org/soap/envelope/"; - - public SoapFaultTest(String name) { - super(name); - } - - /** Regression test for Radar bug #25114 */ - - /** - * - - public void testSetDetail() throws Exception { - Fault fault = Fault.Factory.newInstance(); - fault.setDetail(Detail.Factory.parse(XmlObject.Factory.parse("").newXMLInputStream())); - - assertEquals("", fault.xmlText()); - assertEquals("", fault.getDetail().xmlText()); - } - */ - - /** Regression test for Radar bug #25119 */ - - /** - * - */ - public void testAddNewDetail() throws Exception { - Fault fault = Fault.Factory.newInstance(); - - fault.setFaultcode(new QName(soapenv, "foo")); - fault.setFaultstring("Undefined"); - fault.addNewDetail().set( - XmlObject.Factory.parse("").changeType(Detail.type)); - - String expect = "" + - "soapenv:foo" + - "Undefined" + - "" + - ""; - assertEquals(expect, fault.xmlText()); - assertEquals(new QName(soapenv, "foo"), fault.getFaultcode()); - assertEquals("Undefined", fault.getFaultstring()); - assertEquals("", fault.getDetail().xmlText()); - } - - /** Regression test for Radar bug #25409 */ - - /** - * - * @status inactive - - public void testSetFaultDetail() throws Exception { - String soapFault = - "" + - "soapenv:Server" + - "Undefined" + - "" + - " " + - " The First Fault" + - " " + - " " + - " 1" + - " " + - " " + - " 2003-03-28" + - " " + - "" + - ""; - - Fault faultDoc = Fault.Factory.parse(soapFault); - XmlOptions opt=new XmlOptions(); - ArrayList errors=new ArrayList(); - opt.setErrorListener(errors); - try{ - assertTrue(faultDoc.validate(opt)); - }catch (Throwable t){ - for (int i = 0; i < errors.size(); i++) { - XmlError error = (XmlError) errors.get(i); - System.out.println("\n"); - System.out.println("Message: " + error.getMessage() + "\n"); - if (error.getCursorLocation() != null) - System.out.println("Location of invalid XML: " + - error.getCursorLocation().xmlText() + "\n"); - } - } - assertEquals(new QName(soapenv, "Server"), faultDoc.getFaultcode()); - assertEquals("Undefined", faultDoc.getFaultstring()); - - - FirstFaultType firstFault = FirstFaultType.Factory.newInstance(); - System.out.println("firstFault = " + firstFault.xmlText()); - firstFault.set(faultDoc.getDetail()); - - assertEquals("The First Fault", firstFault.getAString().trim()); - assertEquals(1, firstFault.getAInt()); - assertEquals(new org.apache.xmlbeans.XmlCalendar("2003-03-28"), - firstFault.getADate()); - } - */ -} diff --git a/test/src/xmlobject/detailed/SubstGroupTests.java b/test/src/xmlobject/detailed/SubstGroupTests.java deleted file mode 100644 index cf5df00..0000000 --- a/test/src/xmlobject/detailed/SubstGroupTests.java +++ /dev/null @@ -1,592 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - -import junit.framework.Assert; -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlError; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.impl.values.XmlValueDisconnectedException; -import tools.xml.XmlComparator; -import xmlobject.substgroup.*; - -import javax.xml.namespace.QName; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Iterator; - -public class SubstGroupTests extends TestCase -{ - - private String URI = "http://xmlobject/substgroup"; - - public SubstGroupTests(String name) - { - super(name); - } - - /** - * Convenience Method to return: - * - * - * - * - * - * - * - * @return - */ - public ItemType getItemType() - { - xmlobject.substgroup.ItemType item = ItemType.Factory.newInstance(); - item.setName("ItemType"); - item.setSku(new BigInteger("12")); - return item; - } - - /** - * Convenience Method to return: - * - * - * @return - */ - public ItemDocument getItemDoc() - { - xmlobject.substgroup.ItemDocument item = ItemDocument.Factory.newInstance(); - ItemType it = item.addNewItem(); - it.setName("ItemDocument"); - it.setSku(new BigInteger("12")); - item.setItem(it); - return item; - } - - - /** - * Convenience Method to return: - * - * - * @return - */ - public ChairDocument getChairDoc() - { - xmlobject.substgroup.ChairDocument chair = ChairDocument.Factory.newInstance(); - ItemType item = chair.addNewChair(); - item.setName("Chair"); - item.setSku(new BigInteger("12")); - chair.setChair(item); - return chair; - } - - /** - * Convenience Method to return: - * - * - * @return - */ - public NotachairDocument getNotaChairDoc() - { - xmlobject.substgroup.NotachairDocument nochair = NotachairDocument.Factory.newInstance(); - ItemType item = nochair.addNewNotachair(); - item.setName("NotAChair"); - item.setSku(new BigInteger("12")); - nochair.setNotachair(item); - return nochair; - } - - /** - * Convenience Method to return: - * - * - * - * - * - * - * - * - * - * - * @return - */ - public BeanBagType getBeanBagType() - { - xmlobject.substgroup.BeanBagType bag = BeanBagType.Factory.newInstance(); - BeanBagSizeType size = bag.addNewSize(); - size.setColor("Blue"); - bag.setSize(size); - bag.setName("BeanBagType"); - bag.setSku(new BigInteger("17")); - return bag; - } - - /** - * Convenience Method to return: - * - * - * @return - */ - public BeanBagDocument getBeanBagDoc() - { - xmlobject.substgroup.BeanBagDocument bean = BeanBagDocument.Factory.newInstance(); - BeanBagType item = bean.addNewBeanBag(); - item.setName("BeanBagDoc"); - item.setSku(new BigInteger("13")); - BeanBagSizeType size = item.addNewSize(); - size.setColor("Blue"); - item.setSize(size); - bean.setBeanBag(item); - return bean; - } - - /** - * Convenience Method to return: - * - * - * @return - */ - public BeanBagDocument getBeanBagDocItem() - { - xmlobject.substgroup.BeanBagDocument bean = BeanBagDocument.Factory.newInstance(); - ItemType item = bean.addNewItem(); - item.setName("BeanBagDocItem"); - item.setSku(new BigInteger("14")); - bean.setItem(item); - return bean; - } - - /** - * Convenience Method to return: - * - * - * @return - */ - public BeanBagDocument getBeanBagDocBagType() - { - xmlobject.substgroup.BeanBagDocument bean = BeanBagDocument.Factory.newInstance(); - ItemType item = bean.addNewBeanBag(); - item.setName("BeanBagDocBeanBag"); - item.setSku(new BigInteger("14")); - bean.setItem(item); - return bean; - } - - /** - * Convenience Method to return: - * * - * - * @return - */ - public FootstoolDocument getFootStoolDoc() - { - xmlobject.substgroup.FootstoolDocument foot = FootstoolDocument.Factory.newInstance(); - foot.setFootstool("FootStool"); - return foot; - } - - /** - * TODO: Determine what the proper Return value is - * - * @throws Exception - */ - public void test_invalidSubstitute() throws Exception - { - OrderItem order = OrderItem.Factory.newInstance(); - ItemType item = order.addNewItem(); - item.setName("ItemType"); - item.setSku(new BigInteger("42")); - - //FootstoolDocument fsd; - boolean cClassException = false; - try { - - //on invalid substitute orignal value is returned. - FootstoolDocument fsd = (FootstoolDocument) item.substitute( - FootstoolDocument.type.getDocumentElementName(), - FootstoolDocument.type); - fail("Class Cast Exception was thrown on invalid substitute "); - - - } catch (ClassCastException ccEx) { - cClassException = true; - } - - if (!cClassException) - throw new Exception("An Invalid Substitution did not throw " + - "a Class Cast Exception"); - - try { - XmlObject xm = item.substitute( - FootstoolDocument.type.getDocumentElementName(), - FootstoolDocument.type); - - System.out.println("XM: " + xm.xmlText()); - ArrayList err = new ArrayList(); - XmlOptions xOpts = new XmlOptions().setErrorListener(err); - //no way this should happen - if (xm.validate(xOpts)) { - System.err.println("Invalid substitute validated"); - - for (Iterator iterator = err.iterator(); iterator.hasNext();) { - System.err.println("Error: " + iterator.next()); - } - } - - //invalid substitute should leave good state - System.out.println("Item: " + item.xmlText()); - - String exp = "42ItemType"; - - Assert.assertTrue("text values should be the same", - exp.compareTo(xm.xmlText()) == 0); - - } catch (Exception e) { - throw e; - } - } - - public void test_validSubstitute() throws Exception - { - QName name = new QName(URI, "beanBag"); - // get an item - xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); - ItemType item = order.addNewItem(); - item.setName("ItemForTest"); - item.setSku(new BigInteger("12")); - - // types and content before substitution - System.out.println("Before Substitution :\nQNAme Item doc :" + ItemDocument.type.getName()); - System.out.println("QNAme beanBag elem:" + name); - System.out.println("item type:" + item.getClass().getName()); - System.out.println("item XMLText : " + item.xmlText()); - - try{ - XmlObject xObj = item.substitute(name, BeanBagType.type); - System.out.println("After Substitution :\nSubstituted XObj text: "+xObj.xmlText()); - System.out.println("Substituted XObj type: " + xObj.getClass().getName()); - Assert.assertNotSame("Invalid Substitution. Xobj Types after substitution are the same.",xObj.getClass().getName(),item.getClass().getName() ); - - }catch(NullPointerException npe){ - System.out.println("NPE Thrown: "+npe.getMessage()); - npe.printStackTrace(); - } - - boolean xvdThrown = false; - try{ - // invoke some operation on the original XmlObject, it should thrown an XmlValueDisconnectedException - item.xmlText(); - }catch(XmlValueDisconnectedException xvdEx){ - xvdThrown = true; - } - - if( !xvdThrown ){ - Assert.fail("Referencing Item after " + - "substitute did not throw the expected XmlValueDisconnectedException"); - } - - } - - /* public void test_item_downcasts_valid() throws Exception - { - BigInteger bInt = new BigInteger("12"); - - xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); - ItemType item = order.addNewItem(); - - BeanBagType b2Type = (BeanBagType) item.substitute( - BeanBagDocument.type.getDocumentElementName(), - BeanBagType.type); - - BeanBagSizeType bbSize = b2Type.addNewSize(); - bbSize.setColor("Blue"); - bbSize.setStringValue("Blue"); - b2Type.setSku(bInt); - b2Type.setSize(bbSize); - b2Type.setName("BeanBagType"); - - ItemType nItem = order.getItem(); - item = - (ItemType) nItem.substitute( - ItemDocument.type.getDocumentElementName(), - ItemType.type); - System.out.println( - "Item: " + item.xmlText(new XmlOptions().setSavePrettyPrint())); - ArrayList err = new ArrayList(); - XmlOptions opts = new XmlOptions( - new XmlOptions().setErrorListener(err)); - - if (!item.validate(opts)) - throw new Exception("Downcasting Failed Validation:\n" + err); - - item.setName("ItemType"); - - if (!order.validate(opts)) - throw new Exception("Downcasting Failed Validation:\n" + err); - - }*/ - - /** - * Tests substition upcase, from item to Document, then ensure validation - * - * @throws Exception - */ - public void test_valid_sub() throws Exception - { - String expectedXML = "" + - " 12" + - " BeanBagType" + - " Blue" + - ""; - XmlObject xm = XmlObject.Factory.parse(expectedXML); - String itemName = "item"; - BigInteger bInt = new BigInteger("12"); - - xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); - ItemType item = order.addNewItem(); - item.setName(itemName); - item.setSku(bInt); - - System.out.println("Order: " + - order.xmlText(new XmlOptions().setSavePrettyPrint())); - System.out.println("valid: " + order.validate()); - - BeanBagType b2Type = (BeanBagType) item.substitute( - BeanBagDocument.type.getDocumentElementName(), - BeanBagType.type); - - Assert.assertTrue("Name Value was not as expected\nactual: " + - b2Type.getName() + - " exp: " + - itemName, - b2Type.getName().compareTo(itemName) == 0); - Assert.assertTrue("Integer Value was not as Excepted", - b2Type.getSku().compareTo(bInt) == 0); - - BeanBagSizeType bbSize = b2Type.addNewSize(); - bbSize.setColor("Blue"); - bbSize.setStringValue("Blue"); - b2Type.setSize(bbSize); - b2Type.setName("BeanBagType"); - - System.out.println("b2Type: " + - b2Type.xmlText(new XmlOptions().setSavePrettyPrint())); - System.out.println("b2Type: " + b2Type.validate()); - - System.out.println("Order: " + - order.xmlText(new XmlOptions().setSavePrettyPrint())); - System.out.println("ovalid: " + order.validate()); - - tools.xml.XmlComparator.Diagnostic diag = new tools.xml.XmlComparator.Diagnostic(); - - if (!XmlComparator.lenientlyCompareTwoXmlStrings(order.xmlText(), - xm.xmlText(), diag)) - throw new Exception("Compare Values Fails\n" + diag.toString()); - } - - - public void test_item_disconnect() throws Exception - { - String itemName = "item"; - BigInteger bInt = new BigInteger("12"); - boolean exThrown = false; - - xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); - ItemType item = order.addNewItem(); - item.setName(itemName); - item.setSku(bInt); - - System.out.println("Order: " + - order.xmlText(new XmlOptions().setSavePrettyPrint())); - System.out.println("valid: " + order.validate()); - - BeanBagType b2Type = (BeanBagType) item.substitute( - BeanBagDocument.type.getDocumentElementName(), - BeanBagType.type); - - try { - System.out.println("This should Fail: " + item.xmlText()); - System.out.println("This should Fail: " + item.validate()); - } catch (XmlValueDisconnectedException xmvEx) { - exThrown = true; - System.err.println( - "Failed as Expected - message: " + xmvEx.getMessage()); - } catch (Exception e) { - throw e; - } - - if (!exThrown) - throw new Exception( - "Value Disconnect Exception was not thrown as Expected"); - } - - - public void test_item_downcasts_valid() throws Exception - { - BigInteger bInt = new BigInteger("12"); - ArrayList err = new ArrayList(); - XmlOptions opts = new XmlOptions( - new XmlOptions().setErrorListener(err)); - - xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); - ItemType item = order.addNewItem(); - - BeanBagType b2Type = (BeanBagType) item.substitute( - BeanBagDocument.type.getDocumentElementName(), - BeanBagType.type); - - BeanBagSizeType bbSize = b2Type.addNewSize(); - bbSize.setColor("Blue"); - bbSize.setStringValue("Blue"); - b2Type.setSku(bInt); - b2Type.setSize(bbSize); - b2Type.setName("BeanBagType"); - - ItemType nItem = order.getItem(); - - //nItem.validate(opts); - if (!nItem.validate(opts)) - System.out.println( - "nItem - Downcasting Failed Validation:\n" + err); - err.clear(); - - item = (ItemType) nItem.substitute( - ItemDocument.type.getDocumentElementName(), - ItemType.type); - - //System.out.println("Item1: " + item.xmlText()); - - if (!item.validate(opts)) - System.out.println("Item - Downcasting Failed Validation:\n" + err); - - XmlError[] xErr = getXmlErrors(err); - Assert.assertTrue("Length of xm_errors was greater than expected", - xErr.length == 1); - Assert.assertTrue("Error Code was not as Expected", - xErr[0].getErrorCode().compareTo("cvc-complex-type.2.4b") == 0); - err.clear(); - - String nName = "ItemType"; - item.setName(nName); - System.out.println("Item2: " + item.xmlText()); - - if (!order.validate(opts)) - System.out.println( - "Order - Downcasting Failed Validation:\n" + err); - - //Check value was set - if (!(nName.compareTo(order.getItem().getName()) == 0)) - throw new Exception("Name Value was not changed"); - - //Check Error message - String expText = "Element not allowed: size in element item@http://xmlobject/substgroup"; - XmlError[] xErr2 = getXmlErrors(err); - Assert.assertTrue("Length of xm_errors was greater than expected", - xErr2.length == 1); - Assert.assertTrue("Error Code was not as Expected", - xErr2[0].getErrorCode().compareTo("cvc-complex-type.2.4b") == - 0); - Assert.assertTrue("Error Message was not as expected", - xErr2[0].getMessage().compareTo(expText) == 0); - - err.clear(); - } - - private XmlError[] getXmlErrors(ArrayList c) - { - XmlError[] errs = new XmlError[c.size()]; - for (int i = 0; i < errs.length; i++) { - errs[i] = (XmlError) c.get(i); - } - return errs; - } - - public void test_null_newName() throws Exception - { - boolean exThrown = false; - try { - xmlobject.substgroup.OrderItem order = OrderItem.Factory.newInstance(); - order.substitute(null, OrderItem.type); - } catch (IllegalArgumentException iaEx) { - exThrown = true; - } - if (exThrown != true) - throw new Exception("Exception was not thrown"); - } - - public void test_null_newType() throws Exception - { - boolean exThrown = false; - try { - OrderItem order = OrderItem.Factory.newInstance(); - order.substitute(OrderItem.type.getDocumentElementName(), null); - - } catch (IllegalArgumentException iaEx) { - exThrown = true; - } catch (Exception e) { - throw e; - } - - if (exThrown != true) - throw new Exception("Exception was not thrown"); - } - - public void test_unknownQName() throws Exception - { - boolean exThrown = false; - QName exp = new QName("http://www.w3.org/2001/XMLSchema", "anyType"); - try { - OrderItem order = OrderItem.Factory.newInstance(); - XmlObject xm = order.substitute(new QName("http://baz", "baz"), - OrderItem.type); - - //Verify that the invalid substitution results in an anyType - Assert.assertTrue("Namespace URIs were not the same", - exp.getNamespaceURI().compareTo( - xm.type.getName().getNamespaceURI()) == 0); - Assert.assertTrue("Local Part was not as Expected", - xm.type.getName().getLocalPart().compareTo( - exp.getLocalPart()) == 0); - - } catch (IllegalArgumentException iaEx) { - exThrown = true; - } catch (Exception e) { - throw e; - } - - if (exThrown == true) - throw new Exception("Exception was not thrown"); - } - - public void test_null_Params() throws Exception - { - boolean exThrown = false; - try { - XmlObject xml = XmlObject.Factory.newInstance(); - xml.substitute(null, null); - } catch (IllegalArgumentException iaEx) { - exThrown = true; - } catch (Exception e) { - throw e; - } - - if (exThrown != true) - throw new Exception("Exception was not thrown"); - } - - -} diff --git a/test/src/xmlobject/detailed/TestXmlReader.java b/test/src/xmlobject/detailed/TestXmlReader.java deleted file mode 100755 index 7933a8d..0000000 --- a/test/src/xmlobject/detailed/TestXmlReader.java +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - -import junit.framework.TestCase; - -import java.io.File; -import java.io.IOException; -import java.io.FileReader; -import java.io.PrintWriter; - -import tools.util.ResourceUtil; -import tools.util.JarUtil; - -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlCursor.TokenType; -import xmlcursor.common.Common; -import xmlobject.common.StringXmlReader; - - -/** - * - * - */ -public class TestXmlReader extends TestCase { - - public TestXmlReader(String name) { - super(name); - } - - /** - * Tests read-only concurrency support in XML Beans - * See Radar Bug: 33254 - */ - public void testConcurrency() throws Exception { - // Get the file contents - String xmlFile = JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml"); - - StringXmlReader rdr1 = new StringXmlReader(xmlFile); - StringXmlReader rdr2 = new StringXmlReader(xmlFile); - StringXmlReader rdr3 = new StringXmlReader(xmlFile); - - Thread t1 = new Thread(rdr1, "Reader1"); - Thread t2 = new Thread(rdr2, "Reader2"); - Thread t3 = new Thread(rdr3, "Reader3"); - t1.start(); - t2.start(); - t3.start(); - - // Wait for threads to finish - t1.join(); - t2.join(); - t3.join(); - - // Check the status of the XmlReaders - boolean status = rdr1.getStatus() & rdr2.getStatus() & rdr3.getStatus(); - - assertTrue("Concurrency Test Failed.", status); - } - - - public static void main(String args[]) throws Exception { - new TestXmlReader("Test").testConcurrency(); - } - -} \ No newline at end of file diff --git a/test/src/xmlobject/detailed/TestsFromBugs.java b/test/src/xmlobject/detailed/TestsFromBugs.java deleted file mode 100755 index de69d09..0000000 --- a/test/src/xmlobject/detailed/TestsFromBugs.java +++ /dev/null @@ -1,180 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - -import org.apache.xmlbeans.*; -import com.mytest.Bar; -import com.mytest.Foo; -import com.mytest.Info; -import com.mytest.TestDocument; -import test.xmlobject.test36510.Test36510AppDocument; -import junit.framework.TestCase; - -import java.io.File; - -/** - * Test file that implements test cases that come from closing bugs. - */ -public class TestsFromBugs extends TestCase -{ - File instance; - - public TestsFromBugs(String name) - { - super(name); - } - - /** - * Radar Bug: 36156 - * Problem with Namespace leaking into siblings - */ - public void test36156() - throws Exception - { - String str = ""; - XmlObject x = XmlObject.Factory.parse(str); - - assertTrue("Test 36156 failed: ", x.xmlText().equals(str)); - } - - /* - * Radar Bug: 36510 - */ - public void test36510() - throws Exception - { - String str = "" + - "" + - "" + - "These portlets don't" + - " require any guarantee" + - "BEST" + - "" + - ""; - - Test36510AppDocument doc = Test36510AppDocument.Factory.parse(str); - str = doc.getTest36510App().getTestConstraintArray()[0]. - getCustomConstraint().getOptions().toString(); - assertTrue("Test 36510 failed: ", str.equals("BEST")); - } - - - /* - * Radar Bug: 40907 - */ - public void test40907() - throws Exception - { - String str = "" + - "" + - "this is foo member" + - "" + - ""; - TestDocument doc = TestDocument.Factory.parse(str); - - assertTrue("XML Instance did not validate.", doc.validate()); - - Bar bar = Bar.Factory.newInstance(); - bar.setFooMember("new foo member"); - bar.setBarMember("new bar member"); - - Info info = doc.getTest(); - - Foo foo = info.addNewFoo(); - foo.set(bar); - - assertTrue("Modified XML instance did not validate.", doc.validate()); - str = "" + - "" + - "this is foo member" + - "" + - "" + - "new foo member" + - "new bar member" + - "" + - ""; - assertEquals("XML instance is not as expected", doc.xmlText(), str); - - } - - /** - * Simple Compilation Tests - If the methods are not present, - * - this class won't compile - * Ensures method getSourceName is on SchemaComponent and - * can be called from SchemaGlobalElement and SchemaGlobalAttribute - * @throws Exception - */ - public void test199585() throws Exception - { - String str = "\n" + - "\n" + - " "+ - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - ""; - - XmlObject[] schemas = new XmlObject[]{ - XmlObject.Factory.parse(str)}; - XmlOptions xOpt = new XmlOptions().setValidateTreatLaxAsSkip(); - - SchemaTypeSystem sts = XmlBeans.compileXmlBeans(null, null, schemas, - null, XmlBeans.getBuiltinTypeSystem(), null, xOpt); - - //ensure SchemaGlobalElement has getSourceName Method - SchemaGlobalElement[] sge = sts.globalElements(); - for (int i = 0; i < sge.length; i++) { - System.out.println("SGE SourceName: "+sge[i].getSourceName()); - - } - //ensure SchemaGlobalAttribute has getSourceName Method - SchemaGlobalAttribute[] sga = sts.globalAttributes(); - for (int i = 0; i < sga.length; i++) { - System.out.println("SGE SourceName: " + sga[i].getSourceName()); - } - - //ensure SchemaGlobalElement is a subType of SchemaComponent - SchemaComponent[] sce = sts.globalElements(); - for (int i = 0; i < sce.length; i++) { - System.out.println("SCE SourceName: " + sce[i].getSourceName()); - - } - - //ensure SchemaGlobalAttribute is a subType of SchemaComponent - SchemaComponent[] sca = sts.globalElements(); - for (int i = 0; i < sca.length; i++) { - System.out.println("SCA SourceName: " + sca[i].getSourceName()); - } - - - - } - -} diff --git a/test/src/xmlobject/detailed/TypedObjectCursor.java b/test/src/xmlobject/detailed/TypedObjectCursor.java deleted file mode 100644 index ec5eefd..0000000 --- a/test/src/xmlobject/detailed/TypedObjectCursor.java +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package xmlobject.detailed; - -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.detailed.*; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; -import com.easypo.XmlPurchaseOrderDocumentBean; -import com.easypo.XmlCustomerBean; -import org.apache.xmlbeans.XmlCursor; - -public class TypedObjectCursor extends TestCase{ - public TypedObjectCursor(String name){ - super(name); - } - public static Test suite() { - return new TestSuite(TypedObjectCursor.class); - } - - public void testObjectCursor(){ - XmlPurchaseOrderDocumentBean.PurchaseOrder po= XmlPurchaseOrderDocumentBean.PurchaseOrder.Factory.newInstance(); - XmlCursor cur=po.newCursor(); - XmlCustomerBean cust=po.addNewCustomer(); - cust.setAddress("123 Fake Street"); - cust.setAge(23); - cust.setName("Lisa Simpson"); - cur.toFirstContentToken(); - assertEquals(XmlCursor.TokenType.START, cur.currentTokenType()); - assertEquals(XmlCursor.TokenType.ATTR,cur.toNextToken()); - assertEquals("", cur.xmlText()); - assertEquals(XmlCursor.TokenType.START,cur.toNextToken()); - assertEquals(XmlCursor.TokenType.TEXT,cur.toNextToken()); - assertEquals("Lisa Simpson", cur.xmlText()); - assertEquals(XmlCursor.TokenType.END,cur.toNextToken()); - assertEquals(XmlCursor.TokenType.START,cur.toNextToken()); - assertEquals(XmlCursor.TokenType.TEXT,cur.toNextToken()); - assertEquals("123 Fake Street", cur.xmlText()); - cur.toPrevToken(); - cur.setTextValue("456".toCharArray(),0,3); -} -} diff --git a/test/src/xmlobject/detailed/TypedSettersTests.java b/test/src/xmlobject/detailed/TypedSettersTests.java deleted file mode 100755 index 2397aa5..0000000 --- a/test/src/xmlobject/detailed/TypedSettersTests.java +++ /dev/null @@ -1,164 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.detailed; - -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlCursor.XmlBookmark; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlSaxHandler; -import org.apache.xmlbeans.XmlLineNumber; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlInt; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.StringReader; -import java.lang.Comparable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.Iterator; -import java.util.TreeSet; -import javax.xml.namespace.QName; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - - -public class TypedSettersTests extends TestCase -{ - public TypedSettersTests(String name) { super(name); } - public static Test suite() { return new TestSuite(TypedSettersTests.class); } - - private static final String schemaNs ="xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; - private static final String instanceNs = "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""; - - private static final String fmt ( String s ) - { - StringBuffer sb = new StringBuffer(); - - for ( int i = 0 ; i < s.length() ; i++ ) - { - char ch = s.charAt( i ); - - if (ch != '$') - { - sb.append( ch ); - continue; - } - - ch = s.charAt( ++i ); - - String id = ""; - - while ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) - { - id = id + ch; - ch = s.charAt( ++i ); - } - - String arg = ""; - - if (ch == '(') - { - ch = s.charAt( ++i ); - - while ( ch != ')' ) - { - arg += ch; - ch = s.charAt( ++i ); - } - } - else - i--; - - if (id.equals( "schema" )) - sb.append( schemaNs ); - else if (id.equals( "xsi" )) - sb.append( instanceNs ); - else if (id.equals( "type" )) - { - Assert.assertTrue( arg.length() > 0 ); - sb.append( "xsi:type=\"" + arg + "\"" ); - } - else - Assert.assertTrue( false ); - } - - return sb.toString(); - } - - private static final String nses = schemaNs + " " + instanceNs; - - public void testJavaNoTypeSingletonElement ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "" ); - XmlObject x2 = XmlObject.Factory.parse( "moo" ); - XmlCursor c = x.newCursor(); - XmlCursor c2 = x2.newCursor(); - - c.toNextToken(); - c2.toNextToken(); - - c.getObject().set( c2.getObject() ); - - Assert.assertTrue( x.xmlText().equals( "moo" ) ); - } - - public void testJavaNoTypeSingletonAttribute ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "" ); - XmlObject x2 = XmlObject.Factory.parse( "" ); - XmlCursor c = x.newCursor(); - XmlCursor c2 = x2.newCursor(); - - c.toNextToken(); - c.toNextToken(); - c2.toNextToken(); - c2.toNextToken(); - - c.getObject().set( c2.getObject() ); - - Assert.assertTrue( x.xmlText().equals( "" ) ); - } - - public void testJavaNoTypeSingletonElementWithXsiType ( ) - throws Exception - { - XmlObject x = XmlObject.Factory.parse( "", new XmlOptions() - .setDocumentType( XmlObject.type ) ); - String input= fmt( "" + - "69" ); - //String input= - XmlObject x2 = XmlObject.Factory - .parse( input ); - - - - Assert.assertTrue(x2.schemaType() == XmlInt.type ); - - } - -} diff --git a/test/src/xmlobject/detailed/TypesTest.java b/test/src/xmlobject/detailed/TypesTest.java deleted file mode 100755 index ccff5d9..0000000 --- a/test/src/xmlobject/detailed/TypesTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.detailed; - -import junit.framework.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SimpleValue; - -import javax.xml.namespace.QName; - -import xmlcursor.common.*; - -import test.xbean.xmlcursor.purchaseOrder.PurchaseOrderDocument; -import tools.util.JarUtil; - - -/** - * - * - */ -public class TypesTest extends BasicCursorTestCase { - public TypesTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(TypesTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - i = sClassPath.indexOf(Common.XMLCURSOR_JAR); - assertTrue(i >= 0); - } - - public void testSchemaTypeFromStronglyTypedBuiltIn() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//EventStatus/Date"); - m_xc.toNextSelection(); - XmlObject xo = m_xc.getObject(); - SchemaType st = xo.schemaType(); - assertEquals(true, st.isBuiltinType()); - QName q = st.getName(); - assertEquals("{" + Common.XML_SCHEMA_TYPE_SUFFIX + "}date", - q.toString()); - } - - public void testSchemaTypeFromStronglyTyped() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//EventStatus"); - m_xc.toNextSelection(); - XmlObject xo = m_xc.getObject(); - SchemaType st = xo.schemaType(); - assertEquals(false, st.isBuiltinType()); - assertEquals( - "E=EventStatus|D=EventStatus@" + - Common.TRANXML_SCHEMA_TYPE_SUFFIX, - st.toString()); - - } - - public void testSchemaTypeFromNonTyped() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_TEXT); - m_xc = m_xo.newCursor(); - m_xc.selectPath("$this//bar"); - m_xc.toNextSelection(); - XmlObject xo = m_xc.getObject(); - SchemaType st = xo.schemaType(); - assertEquals(true, st.isNoType()); - //assertEquals("TanyType@" + Common.XML_SCHEMA_TYPE_SUFFIX, st.toString()); - } - - - public void testInstanceTypeNotNillable() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + - "$this//EventStatus"); - XmlObject xo = m_xc.getObject(); - assertEquals(xo.schemaType(), ((SimpleValue) xo).instanceType()); - } - - public void testInstanceTypeNil() throws Exception { - PurchaseOrderDocument pod = (PurchaseOrderDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml")); - m_xo = pod.getPurchaseOrder().getShipTo().xgetName(); - m_xo.setNil(); - assertEquals(true, m_xo.isNil()); - if (m_xo.schemaType() == ((SimpleValue) m_xo).instanceType()) { - fail("Nil object's instanceType should not be equal to schemaType"); - } - assertTrue(true); - } - - /* - public void testInstanceTypeUnion() throws Exception - { - // tbd - } - */ - - -} - diff --git a/test/src/xmlobject/detailed/ValueEqualsTest.java b/test/src/xmlobject/detailed/ValueEqualsTest.java deleted file mode 100755 index 3870400..0000000 --- a/test/src/xmlobject/detailed/ValueEqualsTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.detailed; - -import junit.framework.*; -import junit.framework.Assert.*; - -import java.io.*; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.SchemaTypeSystem; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlOptions; - -import java.util.*; -import javax.xml.namespace.QName; - - -import java.util.Vector; - -import xmlcursor.common.*; - -import java.net.URL; - -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import org.tranxml.tranXML.version40.FleetIDDocument; -import tools.util.Util; -import tools.util.JarUtil; - - -/** - * - * - */ -public class ValueEqualsTest extends BasicCursorTestCase { - public ValueEqualsTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ValueEqualsTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } - - public void testValueEqualsTrue() throws Exception { - CarLocationMessageDocument clmDoc = (CarLocationMessageDocument) - XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - assertEquals(true, clmDoc.valueEquals(m_xo)); - } - -} - diff --git a/test/src/xmlobject/detailed/XmlObjectAbstractClassTest.java b/test/src/xmlobject/detailed/XmlObjectAbstractClassTest.java deleted file mode 100755 index 5e90799..0000000 --- a/test/src/xmlobject/detailed/XmlObjectAbstractClassTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.detailed; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; -import org.apache.xmlbeans.impl.tool.CodeGenUtil; -import tools.util.JarUtil; -import xmlcursor.common.Common; - -/** - * JUnit Test file to test XmlObject Abstract base class - * - * @author: Raju Subramanian. - * - * - */ - -public class XmlObjectAbstractClassTest - extends TestCase { - - public XmlObjectAbstractClassTest(String name) { - super(name); - } - - /** - * The test entry point. - */ - public void testAbstractBaseClass() throws Exception { - // create the source file - //String src = JarUtil.getResourceFromJarasStream(Common.XMLCASES_JAR, "xbean/xmlobject/SimpleXmlObject.java.txt"); - File to = new File("SimpleXmlObject.java"); - InputStreamReader r=new InputStreamReader( - JarUtil.getResourceFromJarasStream( - "xbean/xmlobject/SimpleXmlObject.java.txt")); - assertTrue("Could not create source file", - copyTo(r , to)); - assertTrue("Could not compile SimpleXmlObject.java", - compileFile(to)); - to.deleteOnExit(); - } - - - /** - * Compiles the source file. - * The destination for the compiled file is the current directory - */ - private boolean compileFile(File source) { - // the location for the compiled file - File dir = new File(System.getProperty("user.dir")); - File[] classpath = CodeGenUtil.systemClasspath(); - List srcFiles = new ArrayList(); - srcFiles.add(source); - - if (!CodeGenUtil.externalCompile(srcFiles, dir, classpath, false, - CodeGenUtil.DEFAULT_COMPILER, null, CodeGenUtil.DEFAULT_MEM_START, - CodeGenUtil.DEFAULT_MEM_MAX, false, false)){ - return false; - } - return true; - } - - /** - * Copies a file. If destination file exists it will be overwritten - */ - private boolean copyTo(InputStreamReader src, File to) { - try { - // inputstream to read in the file - BufferedReader in = new BufferedReader(src); - - // delete the existing file - to.delete(); - to.createNewFile(); - // outputstream to write out the java file - FileOutputStream fos = new FileOutputStream(to); - int b; - - while ((b = in.read()) != -1) { - fos.write(b); - } - - in.close(); - fos.close(); - } - catch (Exception ioe) { - System.out.println("Could not create source file: " + ioe); - ioe.printStackTrace(); - return false; - } - - return true; - } - - /** - * Copies a file. If destination file exists it will be overwritten - */ - private boolean copyTo(File src, File to) { - try { - // inputstream to read in the file - FileInputStream fis = new FileInputStream(src); - - // delete the existing file - to.delete(); - to.createNewFile(); - // outputstream to write out the java file - FileOutputStream fos = new FileOutputStream(to); - int b; - - while ((b = fis.read()) != -1) { - fos.write(b); - } - fis.close(); - fos.close(); - } - catch (Exception ioe) { - System.out.println("Could not create source file: " + ioe); - return false; - } - - return true; - } - - /** - * - */ - public static void main(String args[]) throws Exception { - new XmlObjectAbstractClassTest("test").testAbstractBaseClass(); - } -} diff --git a/test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/checkin/NameCollisionTest.java b/test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/checkin/NameCollisionTest.java deleted file mode 100755 index 4c63aa4..0000000 --- a/test/src/xmlobject/extensions/interfaceFeature/methodNameCollision/checkin/NameCollisionTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.extensions.interfaceFeature.methodNameCollision.checkin; - -import junit.framework.TestCase; -import interfaceFeature.xbean.methodNameCollision.company.CompanyDocument; -import interfaceFeature.xbean.methodNameCollision.company.CompanyType; -import interfaceFeature.xbean.methodNameCollision.company.DepartmentType; -import interfaceFeature.xbean.methodNameCollision.company.ConsultantType; -import xmlobject.extensions.interfaceFeature.methodNameCollision.existing.IFoo; - -import org.apache.xmlbeans.XmlString; - -public class NameCollisionTest extends TestCase{ - - public NameCollisionTest(String s){ - super(s); - } - - public void test(){ - CompanyDocument poDoc ; - - poDoc= CompanyDocument.Factory.newInstance(); - CompanyType po=poDoc.addNewCompany(); - - - int LEN=20; - - StringBuffer sExpected=new StringBuffer(); - sExpected.append("" + - ""); - DepartmentType dept=po.addNewDepartments(); - ConsultantType[] it= new ConsultantType[LEN]; - for (int i=0; i < LEN; i++){ - it[i]=dept.addNewConsultant(); - XmlString s= XmlString.Factory.newInstance(); - it[i].setAge(50); - it[i].setName4("BEAN Name"+i); - sExpected.append(""); - } - - sExpected.append(""); - - int[][] ints = new int[2][3]; - for (int i = 0; i < ints.length; i++) - for (int j = 0; j < ints[i].length; j++) - ints[i][j] = (i+1) * (j+1); - - IFoo.Inner inner = new IFoo.Inner() { - public String getValue() { return "inner value"; } - }; - - assertEquals( sExpected.toString(), poDoc.xmlText()); - assertTrue( poDoc.validate() ); - assertEquals("Name0", it[0].getName()); - assertEquals("Name2: [1, 2, 3, ], [2, 4, 6, ], ",it[0].getName2(ints)); - assertEquals("Name3: inner value",it[0].getName3(inner)); - assertEquals("BEAN Name0",it[0].getName4()); - - - - } - -} diff --git a/test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/checkin/ReadOnlyTest.java b/test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/checkin/ReadOnlyTest.java deleted file mode 100755 index 01410c8..0000000 --- a/test/src/xmlobject/extensions/interfaceFeature/readOnlyBean/checkin/ReadOnlyTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.extensions.interfaceFeature.readOnlyBean.checkin; - - -import interfaceFeature.xbean.readOnlyBean.purchaseOrder.PurchaseOrderDocument ; -import interfaceFeature.xbean.readOnlyBean.purchaseOrder.PurchaseOrderType; -import interfaceFeature.xbean.readOnlyBean.purchaseOrder.Items; - - -import java.math.BigDecimal; -import junit.framework.*; - -public class ReadOnlyTest extends TestCase{ - - - public ReadOnlyTest(String s){ - super(s); - } - public void test(){ - - PurchaseOrderDocument poDoc ; - - poDoc= PurchaseOrderDocument.Factory.newInstance(); - PurchaseOrderType po=poDoc.addNewPurchaseOrder(); - int LEN=20; - - Items.Item[] it= new Items.Item[LEN]; - for (int i=0; i< LEN; i++){ - it[i]=Items.Item.Factory.newInstance(); - it[i].setUSPrice(new BigDecimal(""+ 4 )); - } - Items items= Items.Factory.newInstance(); - items.setItemArray(it); - po.setItems(items); - - StringBuffer sb = new StringBuffer(); - sb.append( - ""); - - sb.append(""); - - StringBuffer sbContent = new StringBuffer(); - for (int i = 0; i < LEN; i++) - sbContent.append("4"); - - int pos = sb.length(); - sb.append(""); - - String sExpected = sb.subSequence(0, pos) + - sbContent.toString() + - sb.subSequence(pos, sb.length()); - - assertEquals( sExpected, poDoc.xmlText()); - - try{ - poDoc.setPrice(10); - - }catch (Exception t){ - t.printStackTrace(System.err); - System.exit(-1); - } - - - assertTrue ( !poDoc.validate() ); - } - -} diff --git a/test/src/xmlobject/extensions/prePostFeature/ValueRestriction/checkin/ValueRestrictionTest.java b/test/src/xmlobject/extensions/prePostFeature/ValueRestriction/checkin/ValueRestrictionTest.java deleted file mode 100755 index c4ab0fe..0000000 --- a/test/src/xmlobject/extensions/prePostFeature/ValueRestriction/checkin/ValueRestrictionTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.extensions.prePostFeature.ValueRestriction.checkin; - -import junit.framework.TestCase; -import prePostFeature.xbean.valueRestriction.company.*; -import org.apache.xmlbeans.XmlString; - - -public class ValueRestrictionTest extends TestCase{ - - public ValueRestrictionTest(String s){ - super(s); - } - public void test() throws Exception{ - - CompanyDocument poDoc ; - - poDoc= CompanyDocument.Factory.newInstance(); - CompanyType po=poDoc.addNewCompany(); - - - int LEN=20; - - StringBuffer sExpected=new StringBuffer(); - sExpected.append(""); - DepartmentType dept=po.addNewDepartments(); - ConsultantType[] it= new ConsultantType[LEN]; - for (int i=0; i < LEN; i++){ - it[i]=dept.addNewConsultant(); - XmlString s= XmlString.Factory.newInstance(); - it[i].setAge(50); - sExpected.append(""); - } - - sExpected.append(""); - - assertEquals( sExpected.toString(), poDoc.xmlText()); - assertTrue( poDoc.validate() ); - - - xmlobject.extensions.prePostFeature.ValueRestriction.existing.SetterHandler.bReady=true; - - - for (int i=0; i< LEN; i++){ - it[i].setAge(150); - } - - assertEquals( sExpected.toString(), poDoc.xmlText()); - assertTrue( poDoc.validate() ); - - for (int i=0; i< LEN; i++){ - it[i].setEmployeeAge(150); - } - assertTrue( sExpected.toString().equals(poDoc.xmlText()) ); - assertTrue ( poDoc.validate() ); - } - -} - diff --git a/test/src/xmlobject/schematypes/checkin/EnumTests.java b/test/src/xmlobject/schematypes/checkin/EnumTests.java deleted file mode 100755 index e91008a..0000000 --- a/test/src/xmlobject/schematypes/checkin/EnumTests.java +++ /dev/null @@ -1,180 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.schematypes.checkin; - -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import com.enumtest.StatusreportDocument; -import com.enumtest.SalesreportDocument; -import com.enumtest.SalesreportDocument.Salesreport.Unit; -import com.enumtest.Quantity; -import com.enumtest.Data; - -import tools.util.*; - - -public class EnumTests extends TestCase -{ - public EnumTests(String name) { super(name); } - public static Test suite() { return new TestSuite(EnumTests.class); } - - public static void testReport1() throws Exception - { - StatusreportDocument doc = (StatusreportDocument) - XmlObject.Factory.parse( - JarUtil.getResourceFromJarasFile( - "xbean/xmlobject/enumtest.xml")); - - Quantity.Enum[] contents = new Quantity.Enum[] - { - Quantity.ALL, - Quantity.ALL, - Quantity.FEW, - Quantity.ALL, - Quantity.MOST, - Quantity.NONE, - Quantity.NONE, - Quantity.NONE, - }; - Data[] data = doc.getStatusreport().getStatusArray(); - int t = 0; - for (int i = 0; i < data.length; i++) - { - Assert.assertEquals(contents[t++], data[i].enumValue()); - // System.out.println("Target: " + data[i].getTarget() + ", value: " + data[i].enumValue()); - Assert.assertEquals(contents[t++], data[i].getTarget()); - } - } - - public static void testReport2() throws Exception - { - StatusreportDocument doc = StatusreportDocument.Factory.newInstance(); - StatusreportDocument.Statusreport report = doc.addNewStatusreport(); - - Data d = report.addNewStatus(); - d.set(Quantity.ALL); - d.setTarget(Quantity.ALL); - - d = report.addNewStatus(); - d.set(Quantity.FEW); - d.setTarget(Quantity.ALL); - - d = report.addNewStatus(); - d.set(Quantity.MOST); - d.setTarget(Quantity.NONE); - - d = report.addNewStatus(); - d.set(Quantity.NONE); - d.setTarget(Quantity.NONE); - - Quantity.Enum[] contents = new Quantity.Enum[] - { - Quantity.ALL, - Quantity.ALL, - Quantity.FEW, - Quantity.ALL, - Quantity.MOST, - Quantity.NONE, - Quantity.NONE, - Quantity.NONE, - }; - Data[] data = doc.getStatusreport().getStatusArray(); - int t = 0; - for (int i = 0; i < data.length; i++) - { - Assert.assertEquals(contents[t++], data[i].enumValue()); - // System.out.println("Target: " + data[i].getTarget() + ", value: " + data[i].enumValue()); - Assert.assertEquals(contents[t++], data[i].getTarget()); - } - } - - public static void testReport3() throws Exception - { - SalesreportDocument doc = SalesreportDocument.Factory.newInstance(); - SalesreportDocument.Salesreport report = doc.addNewSalesreport(); - - report.addUnit(Unit.ONE); - report.addUnit(Unit.TWO); - report.addUnit(Unit.NINETY_NINE); - report.addUnit(Unit.ONE_HUNDRED); - - Unit.Enum[] contents = new Unit.Enum[] - { - Unit.ONE, - Unit.TWO, - Unit.NINETY_NINE, - Unit.ONE_HUNDRED, - }; - - Unit[] xunits = report.xgetUnitArray(); - for (int i = 0; i < xunits.length; i++) - { - Assert.assertEquals(contents[i], xunits[i].enumValue()); - } - - Unit.Enum[] units = report.getUnitArray(); - for (int i = 0; i < units.length; i++) - { - Assert.assertEquals(contents[i], units[i]); - } - } - - public static void testEnumRestriction() throws Exception - { - String schema = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - // 'xyz' is an invalid enumeration value - " \n" + - " \n" + - " \n" + - "\n" + - "\n"; - - XmlObject xobj = XmlObject.Factory.parse(schema); - //ArrayList errors = new ArrayList(); - //XmlOptions opts = new XmlOptions().setErrorListener(errors); - - try - { - XmlBeans.loadXsd(new XmlObject[]{xobj}); - fail("Expected loadXsd() to throw an exception."); - } - catch (XmlException xe) - { - // - System.out.println("caught: " + xe); - } - } - -} diff --git a/test/src/xmlobject/schematypes/checkin/GDateTests.java b/test/src/xmlobject/schematypes/checkin/GDateTests.java deleted file mode 100755 index a67e347..0000000 --- a/test/src/xmlobject/schematypes/checkin/GDateTests.java +++ /dev/null @@ -1,755 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.schematypes.checkin; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.GDateBuilder; -import org.apache.xmlbeans.GDuration; -import org.apache.xmlbeans.GDurationBuilder; -import org.apache.xmlbeans.XmlCalendar; - -import java.util.GregorianCalendar; -import java.util.Date; -import java.util.Calendar; -import java.math.BigDecimal; - -public class GDateTests extends TestCase -{ - public GDateTests(String name) { super(name); } - public static Test suite() { return new TestSuite(GDateTests.class); } - - static String[] validDurations = - { - "PT0S", - "P1Y", - "P1M", - "P1D", - "P2Y", - "P2M", - "P2D", - "PT1H", - "PT1M", - "PT1S", - "PT3600S", - "P1Y1M1DT1H1M1S", - "P1Y1M1DT1H1M1.1S", - "P1Y365D", - "P1Y366D", - "PT0.1S", - "P1M29D", - - "PT0.1415926S", - "PT5233132S", - "PT142332M", - "PT98023H", - - "-PT0S", - "-P1Y", - "-P1M", - "-P1D", - "-PT1H", - "-PT1M", - "-PT1S", - "-P1Y1M1DT1H1M1S", - "-P1Y1M1DT1H1M1.1S", - "-P27D", - "-P28D", - "-P29D", - "-P30D", - "-P31D", - "-P364D", - "-P365D", - "-P366D", - "-PT0.1S", - "-PT0.1415926S", - "-PT5233132S", - "-PT142332M", - "-PT98023H", - - }; - - static String[] invalidDurations = - { - "P1Y-364D", - "P1Y-365D", - "P1Y-366D", - "P1Y-367D", - "P1Y-12M", - "P1M-27D", - "P1M-28D", - "P1M-29D", - "P1M-31D", - "P1M-32D", - "P1MT-660H", - "P1MT-670H", - "P1MT-680H", - "P1MT-690H", - "P1MT-700H", - "P1MT-710H", - "P1MT-720H", - "P1MT-730H", - "P1MT-740H", - - "-PT-0S", - "-P-1Y", - "-P-1M", - "-P-1D", - "-PT-1H", - "-PT-1M", - "-PT-1S", - "-P1Y1M-1DT1H1M1S", - "-P1Y1M1DT1H-1M1.1S", - "-PT-0.1S", - "-PT-0.1415926S", - }; - - static String[] invalidDates = - { - "+14:01", // tz - "-14:01", // tz - "+15:00", // tz - "-15:00", // tz - "X", - ",", - "T", - "+", - "-", - ":", - "0", - "March 2", - "T00:00:00Z", // T not allowed - "-00:00:00Z", // - not allowed - "96-02-28T00:00:00Z", // year width - "100-02-28T00:00:00Z", // year width - "1900-2-28T00:00:00Z", // month width - "1900-02-8T00:00:00Z", // day width - "1900-02-08T0:00:00Z", // hour width - "1900-02-08T00:0:00Z", // hour width - "1900-02-08T00:00:0Z", // hour width - "1900-02-08T00:00Z", // time incomplete - "1900-02-08 T00:00:00Z", // space - "1900-02-08T 00:00:00Z", // space - "1900-02-08T00:00:00 Z", // space - "1900-02-29T00Z", // time incomplete - "00:00", // time incomplete - "00", // incomplete - "2100-02-29", // not leap - "-999999999-02-28T00:00:00Z", // too long ago - "999999999-02-28T00:00:00Z", // too long from now - "9999999999999999999999999999999-02-28T00:00:00Z", // overflow? - "0000-01-01", // year zero - "0000-12-31T04:35:22.456", // year zero - "1996-00-28T00:00:00Z", // month - "1996-13-28T00:00:00Z", // month - "1996-02-00T00:00:00Z", // day - "2000-02-30T00:00:00Z", // day - "1996-02-29T25:00:00Z", // hr - "1996-02-29T24:00:01Z", // hr - "1996-02-29T00:60:00Z", // min - "1996-02-29T00:00:60Z", // sec - "1996-02-29T00:00:00+14:01", // tz - "1996-02-29T00:00:00-14:01", // tz - "1996-02-29T00:00:00+15:00", // tz - "1996-02-29T00:00:00-15:00", // tz - "1996-00-29", // month - "1996-13-29", // month - "1996-02-00", // day - "2000-02-30", // day - "--00", // month - "--13", // month - "--00-01", // month - "--13-01", // month - "--02-00", // day - "--02-30", // day - "--01-32", // day - "--11-31", // day - "---00", // day - "---32", // day - "25:00:00Z", // hr - "24:01:00Z", // hr - "00:60:00Z", // min - "00:00:60Z", // sec - "00:00:00+14:01", // tz - "00:00:00-14:01", // tz - "00:00:00+15:00", // tz - "00:00:00-15:00", // tz - }; - - static String[] validDates = - { - "", - "Z", // timezone only - "-14:00", // timezone only - "999999-12-31T23:59:59.999Z", - "1970-12-31T23:59:59.990+14:00", - "1996-02-29T00:00:00Z", // leap - "2000-02-29T00:00:00Z", // leap - "2004-02-29T00:00:00Z", // leap - "2008-02-29T00:00:00Z", // leap - "2012-02-29T00:00:00Z", // leap - "1900-02-28T00:00:00Z", // not leap - "2100-02-28T00:00:00Z", // not leap - "1900-03-28T00:00:00Z", // not leap - "-4712-01-01T00:00:00Z", - "1999-01-01T00:00:00+01:00", - "2001-12-31T23:59:59.010", - "2001-12-31T23:59:59.999901000", - "1999-12-31T23:59:59.1234567890-14:00", - "1992-12-31T23:59:59.01-14:00", - "1965-12-31T23:59:59.000Z", - //"0000-12-31T04:35:22.456", - "1696-09-01T00:00:00Z", - "1697-02-01T00:00:00Z", - "1903-03-01T00:00:00Z", - "1903-07-01T00:00:00Z", - "1696-09-01T00:00:00+00:00", - "1697-02-01T00:00:00-00:00", - "2002", - "-0001", - "--12", - "-0001-11", - "2002-01", - "---31", - "1554--31", - "-0004--31", - "--02-29", - "--12-31", - "2002-04-18", - "-0423-12-31", - "23:59:59", - "00:00:00", - "2010T23:59:59", - "-0001T00:00:00", - "--12T23:59:59", - "-0001-11T00:00:00", - "2011-01T23:59:59", - "---31T00:00:00", - "2002--31T23:59:59", - "-0004--31T00:00:00", - "2002-02-18T23:59:59", - "-0423-12-31T00:00:00", - "2002Z", - "-0001+01:30", - "--12-14:00", - "-0001-11Z", - "1970-12-01:00", - "---31+01:30", - "2002--31Z", - "--03-31-03:00", - "--04-30+05:00", - "-0004--31-01:00", - "2002-04-18-14:00", - "-0423-12-31Z", - "23:59:59-01:00", - "00:00:00Z", - "00:00:00+01:30", - "1776T23:59:59-14:00", - "-0001T00:00:00Z", - "--12T23:59:59+01:30", - "-0001-11T00:00:00-01:00", - "2002-02T23:59:59Z", - "---31T00:00:00-14:00", - "2002--31T23:59:59-01:00", - "-0004--31T00:00:00+01:30", - "2002-04-18T23:59:59Z", - "-0423-12-31T00:00:00-05:00", - "1996-02-29T24:00:00Z", // 24:00:00 is valid - "24:00:00Z", // 24:00:00 is valid - - }; - - private boolean hasTime(GDuration gd) - { - return gd.getHour() != 0 || gd.getMinute() != 0 || gd.getSecond() != 0 || gd.getFraction().signum() != 0; - } - - public void testGregorianCalendar() - { - // this is a check of DST offsets - Date date = new GDate("2002-04-18T23:59:59Z").getDate(); - GregorianCalendar gcal = new XmlCalendar(date); - Assert.assertEquals(date, gcal.getTime()); - - // now check out some things - GDate gd = new GDate("2001-12-31T07:00:59.010"); - GregorianCalendar gc = gd.getCalendar(); - Date gdd = gd.getDate(); - Date gcd = gc.getTime(); - Assert.assertEquals(gdd, gcd); - - // set up 2/29, and read out Feb 29 in the year 1 BC. - Calendar gregcal = new GDate("--02-29").getCalendar(); - Assert.assertEquals(29, gregcal.get(Calendar.DAY_OF_MONTH)); - Assert.assertEquals(2 - 1, gregcal.get(Calendar.MONTH)); - Assert.assertEquals(1, gregcal.get(Calendar.YEAR)); - Assert.assertEquals(0, gregcal.get(Calendar.ERA)); - // repeat some tests to make sure it's stable. - Assert.assertEquals(29, gregcal.get(Calendar.DAY_OF_MONTH)); - Assert.assertEquals(2 - 1, gregcal.get(Calendar.MONTH)); - - // now try some setters - gregcal = new GDate("--02-29").getCalendar(); - gregcal.set(Calendar.MONTH, 10); - Assert.assertEquals("--11-29", gregcal.toString()); - // repeat to ensure it's stable. - Assert.assertEquals("--11-29", gregcal.toString()); - } - - private void _testEmptyDuration(GDuration gd) - { - assertTrue(gd.isValid()); - assertEquals("PT0S", gd.toString()); - assertEquals(0, gd.getYear()); - assertEquals(0, gd.getMonth()); - assertEquals(0, gd.getDay()); - assertEquals(0, gd.getHour()); - assertEquals(0, gd.getMinute()); - assertEquals(0, gd.getSecond()); - assertEquals(new java.math.BigDecimal(0.0), gd.getFraction()); - } - - public void testEmptyDuration() - { - GDuration gd = new GDuration(); - _testEmptyDuration(gd); - GDuration gdCopy = new GDuration(gd); - _testEmptyDuration(gdCopy); - } - - public void testValidDuration() - { - for (int i = 0; i < validDurations.length; i++) - { - GDuration gd = null; - String str = validDurations[i]; - try - { - gd = new GDuration(str); - } - catch (IllegalArgumentException e) - { - Assert.fail("Problem with " + str + ": " + e.getMessage()); - } - - Assert.assertEquals(str, gd.toString()); - - for (int j = 0; j < validDurations.length; j++) - { - GDuration gd2 = null; - String str2 = validDurations[j]; - try - { - gd2 = new GDuration(str2); - } - catch (IllegalArgumentException e) - { - Assert.fail("Problem with " + str2 + ": " + e.getMessage()); - } - - // subtracting two ways works - GDuration diff = gd.subtract(gd2); - GDurationBuilder gdb = new GDurationBuilder(gd2); - gdb.setSign(-gdb.getSign()); - gdb.addGDuration(gd); - GDuration sum2 = gdb.toGDuration(); - Assert.assertEquals(0, diff.compareToGDuration(sum2)); - gdb.normalize(); - GDurationBuilder gdb1 = new GDurationBuilder(diff); - gdb1.normalize(); - Assert.assertEquals("Problem: " + gd + " and " + gd2, gdb.toString(), gdb1.toString()); - - // comparing is reversible - int comp1 = gd.compareToGDuration(gd2); - int comp2 = gd2.compareToGDuration(gd); - if (comp1 == 2) - Assert.assertEquals(2, comp2); - else - Assert.assertEquals(-comp1, comp2); - - // comparing translates to addition to dates - boolean[] seen = new boolean[3]; - - for (int k = 0; k < validDates.length; k++) - { - GDate date = new GDate(validDates[k]); - if (!date.hasDate() || date.getYear() > 99999 || date.getYear() < -4000) - continue; - if ((hasTime(gd) || hasTime(gd2)) && !date.hasTime()) - continue; - // System.out.println("Adding " + gd + " and " + gd2 + " to " + date + ", expecting " + comp1); - GDate date1 = date.add(gd); - GDate date2 = date.add(gd2); - - comp2 = date1.compareToGDate(date2); - if (comp1 != 2) - { - Assert.assertEquals("Adding " + date + " + " + gd + " -> " + date1 + ", " + gd2 + " -> " + date2 + ", expecting " + comp1, comp1, comp2); - } - else - { - Assert.assertTrue(comp2 != 2); - seen[comp2 + 1] = true; - } - - // subtraction should yield the same result - if (comp1 != 2) - { - GDate date3 = date.add(diff); - Assert.assertEquals(comp1, date3.compareToGDate(date)); - } - } - - if (comp1 == 2) - { - int seencount = 0; - for (int k = 0; k < seen.length; k++) - if (seen[k]) - seencount += 1; - Assert.assertTrue("Not ambiguous as advertised" /* + gd + ", " + gd2 + " d: " + diff */, seencount > 1); - } - } - } - } - - private void _testAddAndSubtract(String date1, String date2, - String duration) - { - GDate gd1 = new GDate(date1); - GDate gd2 = new GDate(date2); - GDuration gdur = new GDuration(duration); - GDate gd = gd1.add(gdur); - System.out.println(date1 + " + " + duration + " = " + gd.toString()); - assertEquals(gd2, gd); - gd = gd2.subtract(gdur); - System.out.println(date2 + " - " + duration + " = " + gd.toString()); - assertEquals(gd1, gd); - } - - private void _testAdd(String date1, String date2, String duration) - { - GDate gd1 = new GDate(date1); - GDate gd2 = new GDate(date2); - GDuration gdur = new GDuration(duration); - GDate gd = gd1.add(gdur); - System.out.println(date1 + " + " + duration + " = " + gd.toString()); - assertEquals(gd2, gd); - } - - private void _testSubtract(String date1, String date2, String duration) - { - GDate gd1 = new GDate(date1); - GDate gd2 = new GDate(date2); - GDuration gdur = new GDuration(duration); - GDate gd = gd2.subtract(gdur); - System.out.println(date2 + " - " + duration + " = " + gd.toString()); - assertEquals(gd1, gd); - } - - public void testAddAndSubtractDuration() - { - _testAddAndSubtract("1970-01-01", "1973-01-01", "P3Y"); - _testAddAndSubtract("0001-01-01", "0004-01-01", "P3Y"); - // there is no year 0, so 1 BCE + 3Y = 3 CE - _testAddAndSubtract("-0001-01-01", "0003-01-01", "P3Y"); - _testAddAndSubtract("-0002-01-01", "0003-01-01", "P4Y"); - _testAddAndSubtract("-0001-01-01", "0001-01-01", "P1Y"); - _testSubtract("-0001-02-29", "0004-02-29", "P4Y"); - _testSubtract("-0001-12-31", "0001-01-01", "P1D"); - _testSubtract("-0002-12-31", "0001-12-31", "P731D"); - _testAddAndSubtract("1970-01-01T00:00:00", "1973-02-01T01:30:45", "P3Y31DT1H30M45S"); - _testAddAndSubtract("-0001-01-01T00:00:00", "0003-02-01T01:30:45", "P3Y31DT1H30M45S"); - // addition and subtraction of duration is not necessarily symmetric - // if duration is not constant, i.e., contains a component that varies - // in length, such as month (or year) - _testAdd("2000-02-29", "2001-02-28", "P1Y"); - _testSubtract("2000-02-28", "2001-02-28", "P1Y"); - _testAddAndSubtract("1970-01-01T23:00:00", "1970-01-02T00:00:00", "PT1H"); - _testAddAndSubtract("1970-01-01T00:00:00", "1969-12-31T23:00:00", "-PT1H"); - _testAddAndSubtract("1970-01-01T00:00:00", "1969-12-31T22:59:59", "-PT1H1S"); - _testAddAndSubtract("1971-02-02T01:01:01.1", "1970-01-01T00:00:00", "-P1Y1M1DT1H1M1.1S"); - _testAdd("1970-01-01T00:00:00", "1968-11-29T22:58:58.9", "-P1Y1M1DT1H1M1.1S"); - _testSubtract("1969-12-31T00:00:00", "1968-11-29T22:58:58.9", "-P1Y1M1DT1H1M1.1S"); - _testAdd("0001-01-01T00:00:00", "-0002-11-29T22:58:58.9", "-P1Y1M1DT1H1M1.1S"); - _testSubtract("0001-01-01T00:00:00", "-0002-11-29T22:58:58.9", "-P1Y1M2DT1H1M1.1S"); - } - - public void testOrder() - { - Assert.assertEquals(-1, new GDate("1998-08-26").compareToGDate(new GDate("2001-08-06"))); - Assert.assertEquals(-1, new GDate("1970-12-20T04:14:22Z").compareToGDate(new GDate("1971-04-18T12:51:41Z"))); - Assert.assertEquals(2, new GDate("2001-08-06").compareToGDate(new GDate("2001-08-06Z"))); - Assert.assertEquals(2, new GDate("2001-08-06").compareToGDate(new GDate("2001-08-07+10:00"))); - Assert.assertEquals(2, new GDate("2001-08-06").compareToGDate(new GDate("2001-08-05-10:00"))); - Assert.assertEquals(2, new GDate("2001-02-28").compareToGDate(new GDate("2001-03-01+10:00"))); - Assert.assertEquals(2, new GDate("2001-03-01").compareToGDate(new GDate("2001-02-28-10:00"))); - Assert.assertEquals(-1, new GDate("2000-02-28").compareToGDate(new GDate("2000-03-01+10:00"))); - Assert.assertEquals(1, new GDate("2000-03-01").compareToGDate(new GDate("2000-02-28-10:00"))); - Assert.assertEquals(-1, new GDate("2001-08-06Z").compareToGDate(new GDate("2001-08-06-00:01"))); - Assert.assertEquals(0, new GDate("00:00:00Z").compareToGDate(new GDate("00:01:00+00:01"))); - Assert.assertEquals(0, new GDate("12:00:00-05:00").compareToGDate(new GDate("09:00:00-08:00"))); - Assert.assertEquals(-1, new GDate("09:00:00-05:00").compareToGDate(new GDate("09:00:00-08:00"))); // the east coast rises before the west - Assert.assertEquals(-1, new GDate("2003-05-05T09:00:00-05:00").compareToGDate(new GDate("2003-05-05T09:00:00-08:00"))); // the east coast rises before the west - Assert.assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---31"))); - Assert.assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---31+14:00"))); - Assert.assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---31-14:00"))); - Assert.assertEquals(1, new GDate("---31").compareToGDate(new GDate("---01"))); - Assert.assertEquals(1, new GDate("---31").compareToGDate(new GDate("---01+14:00"))); - Assert.assertEquals(1, new GDate("---31").compareToGDate(new GDate("---01-14:00"))); - Assert.assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---02"))); - Assert.assertEquals(1, new GDate("---02").compareToGDate(new GDate("---01"))); - Assert.assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---02Z"))); - Assert.assertEquals(1, new GDate("---02").compareToGDate(new GDate("---01Z"))); - Assert.assertEquals(2, new GDate("---02").compareToGDate(new GDate("---01-10:00"))); - Assert.assertEquals(2, new GDate("---01").compareToGDate(new GDate("---02+10:00"))); - Assert.assertEquals(1, new GDate("---02").compareToGDate(new GDate("---01-09:00"))); - Assert.assertEquals(-1, new GDate("---01").compareToGDate(new GDate("---02+09:00"))); - Assert.assertEquals(0, new GDate("---01").compareToGDate(new GDate("---01"))); - Assert.assertEquals(-1, new GDate("2003").compareToGDate(new GDate("2004"))); - Assert.assertEquals(-1, new GDate("--11").compareToGDate(new GDate("--12"))); - Assert.assertEquals(-1, new GDate("2003-12").compareToGDate(new GDate("2004-01"))); - Assert.assertEquals(-1, new GDate("--11-30").compareToGDate(new GDate("--12-01"))); - Assert.assertEquals(-1, new GDate("--02-28").compareToGDate(new GDate("--02-29"))); - Assert.assertEquals(-1, new GDate("--02-29").compareToGDate(new GDate("--03-01"))); - Assert.assertEquals(2, new GDate("--02-29").compareToGDate(new GDate("--03-01+10:00"))); - Assert.assertEquals(2, new GDate("--02-28").compareToGDate(new GDate("--03-01+10:00"))); - Assert.assertEquals(2, new GDate("--03-01").compareToGDate(new GDate("--02-28-10:00"))); - Assert.assertEquals(2, new GDate("--03-01").compareToGDate(new GDate("--02-29-10:00"))); - Assert.assertEquals(-1, new GDate("--02-29").compareToGDate(new GDate("--03-01+09:00"))); - Assert.assertEquals(-1, new GDate("--02-28").compareToGDate(new GDate("--03-01+09:00"))); - Assert.assertEquals(1, new GDate("--03-01").compareToGDate(new GDate("--02-28-09:00"))); - Assert.assertEquals(1, new GDate("--03-01").compareToGDate(new GDate("--02-29-09:00"))); - Assert.assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:59"))); - Assert.assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:59+09:59"))); - Assert.assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:01+09:59"))); - Assert.assertEquals(2, new GDate("00:00:00").compareToGDate(new GDate("23:59:00+09:59"))); - Assert.assertEquals(2, new GDate("00:00:00").compareToGDate(new GDate("23:59:59+10:00"))); - Assert.assertEquals(-1, new GDate("00:00:00").compareToGDate(new GDate("23:59:59-14:00"))); - Assert.assertEquals(1, new GDate("23:59:59").compareToGDate(new GDate("00:00:00-09:59"))); - Assert.assertEquals(1, new GDate("23:59:59").compareToGDate(new GDate("00:00:58-09:59"))); - Assert.assertEquals(2, new GDate("23:59:59").compareToGDate(new GDate("00:00:59-09:59"))); - Assert.assertEquals(2, new GDate("23:59:59").compareToGDate(new GDate("00:00:00-10:00"))); - Assert.assertEquals(1, new GDate("23:59:59").compareToGDate(new GDate("00:00:00+14:00"))); - } - - public void testAPI() throws Exception - { - GDateBuilder builder = new GDateBuilder("1970-12-20T04:14:22Z"); - builder.normalizeToTimeZone(1, 0, 0); - Assert.assertEquals("1970-12-20T04:14:22+00:00", builder.toString()); - builder.setTimeZone(615); - Assert.assertEquals("1970-12-20T04:14:22+10:15", builder.toString()); - builder.setTimeZone(-345); - Assert.assertEquals("1970-12-20T04:14:22-05:45", builder.toString()); - builder.normalizeToTimeZone(-300); - Assert.assertEquals("1970-12-20T04:59:22-05:00", builder.toString()); - } - - public void testFailure() throws Exception - { - for (int i = 0; i < invalidDurations.length; i++) - { - String str = invalidDurations[i]; - try - { - new GDuration(str); - } - catch (IllegalArgumentException e) - { - continue; - } - Assert.fail("Missing exception for GDuration: " + str); - } - - for (int i = 0; i < invalidDates.length; i++) - { - String str = invalidDates[i]; - try - { - new GDate(str); - } - catch (IllegalArgumentException e) - { - continue; - } - Assert.fail("Missing exception for GDate " + str); - } - } - - public void testSuccess() throws Exception - { - for (int i = 0; i < validDates.length; i++) - { - String str = validDates[i]; - GDate gdate = null; - try - { - gdate = new GDate(str); - } - catch (IllegalArgumentException e) - { - Assert.fail("Problem with " + str + ": " + e.getMessage()); - } - - if ( str.indexOf("24:00:00") >= 0 && gdate.hasDay() ) // for 24h if hasDay must be normalized, else has the same representation - { - Assert.assertTrue(str + " " + gdate.toString(), gdate.hasDay() && gdate.toString().indexOf("00:00:00") >= 0); - } - else - // must round-trip to string - Assert.assertEquals(str, gdate.toString()); - - // must round-trip to GregorianCalendar if fractions-of-seconds <=3 digits - if (gdate.getFraction() == null || gdate.getFraction().scale() <= 3) - if (!gdate.toString().equals("--02-29")) // bug in gcal -> 03-01 - { - GregorianCalendar gcal = gdate.getCalendar(); - GDate gdate2 = new GDate(gcal); - Assert.assertEquals(gdate, gdate2); - - // and if fractions-of-seconds is 3 digits, stringrep must round-trip - if (gdate.getFraction() == null || gdate.getFraction().scale() == 3 || gdate.getFraction().scale() == 0) - Assert.assertEquals(gdate.toString(), gdate2.toString()); - } - - // must round-trip to Date if absolute time+timezone + fractions-of-seconds <= 3 - if (gdate.hasTimeZone() && gdate.getYear() > -4000 && gdate.getYear() < 99999 && gdate.getBuiltinTypeCode() == SchemaType.BTC_DATE_TIME && gdate.getFraction().scale() <= 3) - { - Date date = gdate.getDate(); - GDate gdate2 = new GDate(date); - Assert.assertEquals(gdate, gdate2); - - // normalize to UTC fractions-of-seconds is 0 or 3 digits [not 000], stringrep must round-trip - if (gdate.getTimeZoneSign() == 0 && ((gdate.getFraction().scale() == 3 && gdate.getFraction().signum() != 0) || gdate.getFraction().scale() == 0)) - { - GDateBuilder gdb = new GDateBuilder(gdate2); - gdb.normalizeToTimeZone(0, 0, 0); - Assert.assertEquals(gdate.toString(), gdb.toString()); - } - - // verify that going through gcal gives us the same thing - GregorianCalendar gcal = gdate.getCalendar(); - Assert.assertEquals(date, gcal.getTime()); - - // double-check XmlCalendar constructor - gcal = new XmlCalendar(date); - Assert.assertEquals("Doing " + gdate, date, gcal.getTime()); - } - else if (gdate.hasDate() && (gdate.getFraction() == null || gdate.getFraction().scale() <= 3)) - { - // must be able to get a date if time+timezone is unset (midnight, ltz are assumed) - Date date = gdate.getDate(); - GDateBuilder gdate1 = new GDateBuilder(gdate); - if (!gdate1.hasTime()) - gdate1.setTime(0, 0, 0, null); - Assert.assertEquals(gdate1.getDate(), date); - - // verify that going through gcal gives us the same thing - GregorianCalendar gcal = gdate.getCalendar(); - Assert.assertEquals("Comparing " + gdate + " and " + gcal, date, gcal.getTime()); - } - } - } - - public void test24hDates() - { - GDate d1 = new GDate("2004-03-31T24:00:00"); - Assert.assertEquals("2004-04-01T00:00:00", d1.toString()); - - - GDateBuilder b = new GDateBuilder(); - b.setTime(24, 0, 0, new BigDecimal("0.00")); - System.out.println("hour 24: " + b.getCalendar()); - Assert.assertEquals("24:00:00.000", b.getCalendar().toString()); - - b.setDay(10); - b.setMonth(1); - System.out.println("hour 24: " + b.getCalendar()); - Assert.assertEquals("--01-10T24:00:00.000", b.getCalendar().toString()); - - b.setYear(2010); - System.out.println("hour 24: " + b.getCalendar()); - Assert.assertEquals("2010-01-10T24:00:00.000", b.getCalendar().toString()); - - b.setDay(31); - b.setMonth(03); - b.setYear(2004); - - System.out.println("hour 24: canonical str: " + b.canonicalString()); - Assert.assertEquals("2004-04-01T00:00:00", b.canonicalString()); - System.out.println("hour 24: toString: " + b.toString()); - Assert.assertEquals("2004-03-31T24:00:00.00", b.toString()); - System.out.println("hour 24: toGDate: " + b.toGDate()); - Assert.assertEquals("2004-03-31T24:00:00.00", b.toGDate().toString()); - System.out.println("hour 24: toGDate().canonicalStr: " + b.toGDate().canonicalString()); - Assert.assertEquals("2004-04-01T00:00:00", b.toGDate().canonicalString()); - System.out.println("hour 24: toGDate().getCal: " + b.toGDate().getCalendar()); - Assert.assertEquals("2004-03-31T24:00:00.000", b.toGDate().getCalendar().toString()); - - - GDateBuilder gdb = new GDateBuilder("24:00:00+01:00"); - System.out.println("gdb: " + gdb); - Assert.assertEquals("24:00:00+01:00", gdb.toString()); - - gdb.normalize(); - System.out.println("gdb.normalize(): " + gdb); - Assert.assertEquals("23:00:00Z", gdb.toString()); - } - - public void testYearStartingWith0() - { - GDate gdate = new GDate("0004-08-01"); // 00004-08-01 must fail - System.out.println("year starting with 0: " + gdate.getCalendar()); - Assert.assertEquals("0004-08-01", gdate.toString()); - - String txt = "-9999-06"; - GDate d = new GDate(txt); - System.out.println(" gdate(" + txt + ") = " + d); - Assert.assertEquals("-9999-06", d.toString()); - - txt = "-12345-06"; - d = new GDate(txt); - System.out.println(" gdate(" + txt + ") = " + d); - Assert.assertEquals(txt, d.toString()); - - - try - { - txt = "00004-08-01"; - d = new GDate(txt); // 00004-08-01 must fail - Assert.assertTrue("Year starting with 0 of five digits: " + txt, false); - } - catch(IllegalArgumentException e) - { - Assert.assertTrue("Year starting with 0 of five digits: " + txt, true); - } - - try - { - txt = "-012340-08-01"; - d = new GDate(txt); - Assert.assertTrue("Year starting with 0 of six digits: " + txt, false); - } - catch(IllegalArgumentException e) - { - Assert.assertTrue("Year starting with 0 of six digits: " + txt, true); - } - } -} diff --git a/test/src/xmlobject/schematypes/checkin/IntTests.java b/test/src/xmlobject/schematypes/checkin/IntTests.java deleted file mode 100755 index f060f0c..0000000 --- a/test/src/xmlobject/schematypes/checkin/IntTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.schematypes.checkin; - -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.TestCase; -import junit.framework.Assert; - -import xint.test.PositionDocument; - -public class IntTests extends TestCase -{ - public IntTests(String name) { super(name); } - public static Test suite() { return new TestSuite(IntTests.class); } - - public static void testLatLong() throws Exception - { - PositionDocument doc = PositionDocument.Factory.parse( - "43020"); - Assert.assertEquals(43, doc.getPosition().getLat()); - Assert.assertEquals(20, doc.getPosition().getLon()); - doc.getPosition().xgetLat().setStringValue("07"); - doc.getPosition().xgetLon().setStringValue("040"); - Assert.assertEquals(7, doc.getPosition().getLat()); - Assert.assertEquals(40, doc.getPosition().getLon()); - doc.getPosition().setLat((short)22); - } -} diff --git a/test/src/xmlobject/schematypes/checkin/NumeralsTests.java b/test/src/xmlobject/schematypes/checkin/NumeralsTests.java deleted file mode 100755 index 431dae0..0000000 --- a/test/src/xmlobject/schematypes/checkin/NumeralsTests.java +++ /dev/null @@ -1,274 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.schematypes.checkin; - - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.openuri.testNumerals.DocDocument; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - -import java.math.BigDecimal; -import java.math.BigInteger; - -/** - * Author: Cezar Andrei (cezar.andrei at bea.com) - * Date: Nov 23, 2003 - */ -public class NumeralsTests extends TestCase -{ - public NumeralsTests(String name) { super(name); } - public static Test suite() { return new TestSuite(NumeralsTests.class); } - - private static DocDocument.Doc doc; - static - { - String inst = - "\n" + - " this is a long string \n" + - " ... \n" + - " \n" + - " +5\n" + - " \n" + - " \n" + - " -6\n" + - " \n" + - " \n" + - " +00000000015\n" + - " \n" + - " 77\n" + - " \n" + - " true\n" + - " \n" + - " \n" + - " false\n" + - " \n" + - " \n" + - " 0\n" + - " \n" + - " \n" + - " 1\n" + - " \n" + - " \n" + - " true is not\n" + - " \n" + - " \n" + - " +03\n" + - " \n" + - " \n" + - " +001\n" + - " \n" + - " -0500000\n" + - " \n" + - " 001\n" + - " \n" + - " \n" + - " +002\n" + - " \n" + - " \n" + - " +001\n" + - " \n" + - " \n" + - " -002.007000\n" + - " \n" + - " \n" + - " INF\n" + - " \n" + - " \n" + - " -INF\n" + - " \n" + - " \n" + - " NaN\n" + - " \n" + - " \n" + - " +12.325\n" + - " \n" + - " \n" + - " NaN\n" + - " \n" + - " \n" + - " INF\n" + - " \n" + - " \n" + - " -INF\n" + - " \n" + - " \n" + - " +001.001\n" + - " \n" + - " \n" + - " +001000000000\n" + - " \n" + - ""; - - try - { - doc = DocDocument.Factory.parse(inst).getDoc(); - } - catch (XmlException e) - { - throw new IllegalStateException(e.getMessage()); - } - } - - public void test1() throws XmlException - { - String s = " this is a long string \n" + " ... "; - Assert.assertTrue("String expected:\n'" + s + "' actual:\n'" + - doc.getStringArray()[0] + "'", s.equals(doc.getStringArray()[0])); - } - - public void test2() throws XmlException - { - Assert.assertTrue("int expected:" + 5 + " actual:" + doc.getIntArray()[0], doc.getIntArray()[0]==5); - } - - public void test3() throws XmlException - { - Assert.assertTrue("int expected:" + (-6) + " actual:" + doc.getIntArray()[1], doc.getIntArray()[1]==-6); - } - - public void test4() throws XmlException - { - Assert.assertTrue("int expected:" + 15 + " actual:" + doc.getIntArray()[2], doc.getIntArray()[2]==15); - } - - public void test5() throws XmlException - { - Assert.assertTrue("int expected:" + 77 + " actual:" + doc.getIntArray()[3], doc.getIntArray()[3]==77); - } - - public void test6() throws XmlException - { - Assert.assertTrue(doc.getBooleanArray(0)==true); - } - - public void test7() throws XmlException - { - Assert.assertTrue(doc.getBooleanArray(1)==false); - } - - public void test8() throws XmlException - { - Assert.assertTrue(doc.getBooleanArray(2)==false); - } - - public void test9() throws XmlException - { - Assert.assertTrue(doc.getBooleanArray(3)==true); - } - - public void test10() throws XmlException - { - try { boolean b = doc.getBooleanArray()[4]; Assert.assertTrue(false); } - catch(XmlValueOutOfRangeException e) - { Assert.assertTrue(true); } - } - - public void test11() throws XmlException - { - Assert.assertTrue(doc.getShortArray()[0]==3); - } - - public void test12() throws XmlException - { - Assert.assertTrue(doc.getByteArray()[0]==1); - } - - public void test13() throws XmlException - { - Assert.assertTrue("long expected:" + (-50000) + " actual:" + doc.getLongArray()[0], - doc.getLongArray()[0]==-500000); - } - - public void test14() throws XmlException - { - Assert.assertTrue("long expected:" + 1 + " actual:" + doc.getLongArray()[1], - doc.getLongArray()[1]==1); - } - - public void test15() throws XmlException - { - Assert.assertTrue("long expected:" + 2 + " actual:" + doc.getLongArray()[2], - doc.getLongArray()[2]==2); - } - - public void test16() throws XmlException - { - Assert.assertTrue(doc.getDoubleArray()[0]==1); - } - - public void test17() throws XmlException - { - Assert.assertTrue("double expected:" + -2.007d + " actual:" + doc.getDoubleArray()[1], - doc.getDoubleArray()[1]==-2.007d); - } - - public void test18() throws XmlException - { - Assert.assertTrue(new Double(Double.POSITIVE_INFINITY). - equals(new Double(doc.getDoubleArray()[2]))); - } - - public void test19() throws XmlException - { - Assert.assertTrue(new Double(Double.NEGATIVE_INFINITY). - equals(new Double(doc.getDoubleArray()[3]))); - } - - public void test20() throws XmlException - { - Assert.assertTrue(new Double(Double.NaN). - equals(new Double(doc.getDoubleArray()[4]))); - } - - public void test21() throws XmlException - { - Assert.assertTrue("fload expected:" + 12.325f + " actual:" + doc.getFloatArray()[0], - doc.getFloatArray()[0]==12.325f); - } - - public void test22() throws XmlException - { - Assert.assertTrue(new Float(Float.NaN). - equals(new Float(doc.getFloatArray()[1]))); - } - - public void test23() throws XmlException - { - Assert.assertTrue("fload expected:" + Float.POSITIVE_INFINITY + " actual:" + doc.getFloatArray()[2], - new Float(Float.POSITIVE_INFINITY).equals(new Float(doc.getFloatArray()[2]))); - } - - public void test24() throws XmlException - { - Assert.assertTrue(new Float(Float.NEGATIVE_INFINITY). - equals(new Float(doc.getFloatArray()[3]))); - } - - public void test25() throws XmlException - { - Assert.assertTrue(new BigDecimal("1.001").equals(doc.getDecimalArray()[0])); - } - - public void test26() throws XmlException - { - Assert.assertTrue(new BigInteger("1000000000").equals(doc.getIntegerArray(0))); - } -} diff --git a/test/src/xmlobject/schematypes/checkin/QNameTests.java b/test/src/xmlobject/schematypes/checkin/QNameTests.java deleted file mode 100755 index 2c266d2..0000000 --- a/test/src/xmlobject/schematypes/checkin/QNameTests.java +++ /dev/null @@ -1,120 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.schematypes.checkin; - -import org.apache.xmlbeans.XmlQName; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlAnySimpleType; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class QNameTests extends TestCase -{ - public QNameTests(String name) { super(name); } - public static Test suite() { return new TestSuite(QNameTests.class); } - - static String[] _args; - static String _test; - - public void testQName ( ) - throws Exception - { - String schema = - "\n" + - "" + - " \n" + - " \n" + - "" + - "\n" + - ""; - - SchemaTypeLoader stl = - XmlBeans.loadXsd( new XmlObject[] { - XmlObject.Factory.parse(schema) } ); - - - // - // Test the set_XMLName function on XmlQNameImpl - // - - String ns = - "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " + - "xmlns:xs='http://www.w3.org/2001/XMLSchema'"; - - XmlObject sourceDocument = - stl.parse( - "" + - "xxx:abc", null, null ); - - XmlCursor sourceCursor = sourceDocument.newCursor(); - - sourceCursor.toFirstChild(); - - XmlQName sourceQName = (XmlQName) sourceCursor.getObject(); - - XmlObject targetDocument = - stl.parse( - "" + - "", null, null ); - - XmlCursor targetCursor = targetDocument.newCursor(); - - targetCursor.toFirstChild(); - - XmlQName targetQName = (XmlQName) targetCursor.getObject(); - - targetQName.set( sourceQName ); - - Assert.assertTrue( - targetQName.getQNameValue().getNamespaceURI().equals( "xxx.com" ) ); - - // - // Test the set_text function on XmlQNameImpl - // - - targetDocument = - stl.parse( - "" + - "", null, null ); - - targetCursor = targetDocument.newCursor(); - - targetCursor.toFirstChild(); - - targetQName = (XmlQName) targetCursor.getObject(); - - try - { - targetQName.setStringValue( "zzz:abc" ); - - Assert.assertTrue( false ); // Must fail - } - catch ( Throwable t ) - { - } - - targetQName.setStringValue( "xxx:abc" ); - - Assert.assertTrue( - targetQName.getQNameValue().getNamespaceURI().equals( "xxx.com" ) ); - } -} diff --git a/test/src/xmlobject/schematypes/checkin/SchemaTypesTests.java b/test/src/xmlobject/schematypes/checkin/SchemaTypesTests.java deleted file mode 100755 index 8caa3c3..0000000 --- a/test/src/xmlobject/schematypes/checkin/SchemaTypesTests.java +++ /dev/null @@ -1,213 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmlobject.schematypes.checkin; - -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlCalendar; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import junit.framework.TestCase; - -import java.util.Date; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.io.InputStream; - -import org.openuri.xstypes.test.*; -import org.openuri.def.DefaultsDocument; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -import javax.xml.namespace.QName; - - -import tools.util.*; - -public class SchemaTypesTests extends TestCase -{ - public SchemaTypesTests(String name) { super(name); } - public static Test suite() { return new TestSuite(SchemaTypesTests.class); } - - private CustomerDocument doc; - - private void ensureDoc() - throws Exception - { - if( doc==null ) - { - doc = (CustomerDocument) - XmlObject.Factory.parse( - JarUtil.getResourceFromJarasFile("xbean/xmlobject/person.xml")); - } - } - - public void testDefaults() throws Throwable - { - DefaultsDocument doc = DefaultsDocument.Factory.newInstance(); - DefaultsDocument.Defaults defs = doc.addNewDefaults(); - Assert.assertEquals(783, defs.getCool()); // this is the default value - } - - public void testSourceName() throws Throwable - { - String name = DefaultsDocument.type.getSourceName(); - Assert.assertEquals("defaults.xsd", name); - InputStream str = XmlBeans.getContextTypeLoader().getSourceAsStream("defaults.xsd"); - SchemaDocument doc = SchemaDocument.Factory.parse(str); - Assert.assertTrue(doc.validate()); - } - - public void testRead() throws Throwable - { - ensureDoc(); - - // Move from the root to the root customer element - Person person = doc.getCustomer(); - Assert.assertEquals("Howdy", person.getFirstname()); - Assert.assertEquals(4, person.sizeOfNumberArray()); - Assert.assertEquals(436, person.getNumberArray(0)); - Assert.assertEquals(123, person.getNumberArray(1)); - Assert.assertEquals(44, person.getNumberArray(2)); - Assert.assertEquals(933, person.getNumberArray(3)); - Assert.assertEquals(2, person.sizeOfBirthdayArray()); - Assert.assertEquals(new XmlCalendar("1998-08-26Z"), - person.getBirthdayArray(0)); - Assert.assertEquals(new XmlCalendar("2000-08-06-08:00"), - person.getBirthdayArray(1)); - - Person.Gender.Enum g = person.getGender(); - Assert.assertEquals(Person.Gender.MALE, g); - - Assert.assertEquals("EGIQTWYZJ", new String(person.getHex())); - Assert.assertEquals("This string is base64Binary encoded!", - new String(person.getBase64())); - - Assert.assertEquals("GGIQTWYGG", new String(person.getHexAtt())); - Assert.assertEquals("This string is base64Binary encoded!", - new String(person.getBase64Att())); - - Assert.assertEquals("{some_uri}localname", person.getQnameAtt().toString()); - Assert.assertEquals("{http://openuri.org/xstypes/test}openuri_org_localname", person.getQname().toString()); - - //Assert.assertEquals("http://dmoz.org/World/Fran\u00e7ais/", person.getAnyuriAtt().toString()); - Assert.assertEquals("http://3space.org/space%20space/", person.getAnyuri().toString()); - - //RuntimeException: src/xmlstore/org/apache/xmlbeans/impl/store/Splay.java(1537): ns != null && ns.length() > 0 failed - //Assert.assertEquals("JPEG", person.getNotationAtt().toString()); - //Assert.assertEquals("GIF", person.getNotation().toString()); - } - - public void testWriteRead() throws Throwable - { - ensureDoc(); - // Move from the root to the root customer element - Person person = doc.getCustomer(); - - person.setFirstname("George"); - Assert.assertEquals("George", person.getFirstname()); - - person.setHex("hex encoding".getBytes()); - Assert.assertEquals("hex encoding", new String(person.getHex())); - - person.setBase64("base64 encoded".getBytes()); - Assert.assertEquals("base64 encoded", - new String(person.getBase64())); - - person.setHexAtt("hex encoding in attributes".getBytes()); - Assert.assertEquals("hex encoding in attributes", - new String(person.getHexAtt())); - - person.setBase64Att("This string is base64Binary encoded!".getBytes()); - Assert.assertEquals("This string is base64Binary encoded!", - new String(person.getBase64Att())); - - person.setAnyuri("a.c:7001"); - Assert.assertEquals("a.c:7001", person.getAnyuri()); - - person.setAnyuriAtt("b.d:7002"); - Assert.assertEquals("b.d:7002", person.getAnyuriAtt()); - - person.setQnameAtt(new QName("aaa","bbb")); - Assert.assertEquals("{aaa}bbb", person.getQnameAtt().toString()); - - person.setQname(new QName("ddd","eee")); - Assert.assertEquals("{ddd}eee", person.getQname().toString()); - - //Exception: src/xmlstore/org/apache/xmlbeans/impl/store/Type.java(189): user == _user failed -// person.setAnyuriAtt(URI.create("b.d:7002")); -// Assert.assertEquals("b.d:7002", person.getAnyuriAtt().toString()); - - //XmlNOTATION notation = (XmlNOTATION)Person.Notation.type.createNode(); - //notation.setValue("JPEG"); - //person.setNotation( notation ); - //Assert.assertEquals("JPEG", person.getNotation().toString()); - - //XmlNOTATION notationAtt = (XmlNOTATION)Person.NotationAtt.type.createNode(); - //notationAtt.setValue("GIF"); - //person.setNotationAtt( notationAtt ); - //person.setNotationAtt(notation); - //Assert.assertEquals("GIF", person.getNotationAtt().toString()); - } - - public void testStoreWrite() throws Throwable - { - ensureDoc(); - // Move from the root to the root customer element - Person person = doc.getCustomer(); - - XmlObject xmlobj; - XmlCursor xmlcurs; - - person.setFirstname("George"); - xmlobj = person.xgetFirstname(); - xmlcurs = xmlobj.newCursor(); - Assert.assertEquals("George", xmlcurs.getTextValue() ); - - person.setQnameAtt( new QName("http://ggg.com","hhh") ); - xmlobj = person.xgetQnameAtt(); - xmlcurs = xmlobj.newCursor(); - Assert.assertEquals("ggg:hhh", xmlcurs.getTextValue() ); - - person.setQname( new QName("http://ggg.com/gggAgain","kkk") ); - xmlobj = person.xgetQname(); - xmlcurs = xmlobj.newCursor(); - Assert.assertEquals("ggg1:kkk", xmlcurs.getTextValue() ); - - person.setAnyuri( "crossgain.com" ); - xmlobj = person.xgetAnyuri(); - xmlcurs = xmlobj.newCursor(); - Assert.assertEquals("crossgain.com", xmlcurs.getTextValue() ); - - person.setAnyuriAtt( "www.crossgain.com" ); - xmlobj = person.xgetAnyuriAtt(); - xmlcurs = xmlobj.newCursor(); - Assert.assertEquals("www.crossgain.com", xmlcurs.getTextValue() ); - - //person.setNotation("GIF"); - //xmlobj = person.getNotation(); - //xmlcurs = xmlobj.newXmlCursor(); - //Assert.assertEquals("GIF", xmlcurs.getText() ); - - //person.setNotationAtt("JPEGu"); - //xmlobj = person.xgetNotationAtt(); - //xmlcurs = xmlobj.newXmlCursor(); - //Assert.assertEquals("JPEG", xmlcurs.getText() ); - } -} diff --git a/test/src/xmlobject/schematypes/detailed/ListAndUnionTests.java b/test/src/xmlobject/schematypes/detailed/ListAndUnionTests.java deleted file mode 100755 index c050745..0000000 --- a/test/src/xmlobject/schematypes/detailed/ListAndUnionTests.java +++ /dev/null @@ -1,184 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.schematypes.detailed; - -import junit.framework.TestCase; -import junit.framework.Test; -import junit.framework.TestSuite; -import junit.framework.Assert; -import org.openuri.lut.ListsDocument; -import org.openuri.lut.UnionsDocument; -import org.openuri.lut.IncidentReportsDocument; -import org.openuri.lut.DateOrDateTime; - -import java.util.List; -import java.util.Arrays; -import java.util.Calendar; -import java.math.BigInteger; - -import org.apache.xmlbeans.GDate; -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.XmlDate; -import org.apache.xmlbeans.XmlDateTime; -import org.apache.xmlbeans.XmlCalendar; - -public class ListAndUnionTests extends TestCase -{ - public ListAndUnionTests(String name) { super(name); } - public static Test suite() { return new TestSuite(ListAndUnionTests.class); } - - public void testListGetters() throws Exception - { - ListsDocument lists = ListsDocument.Factory.parse( - "2 4 8 16 32unbounded 3 unbounded 6"); - List intList = lists.getLists().getIntList(); - Assert.assertEquals(new Integer(2), intList.get(0)); - Assert.assertEquals(new Integer(4), intList.get(1)); - Assert.assertEquals(new Integer(8), intList.get(2)); - Assert.assertEquals(new Integer(16), intList.get(3)); - Assert.assertEquals(new Integer(32), intList.get(4)); - Assert.assertEquals(5, intList.size()); - - List nniList = lists.getLists().getNniList(); - Assert.assertEquals("unbounded", nniList.get(0)); - Assert.assertEquals(BigInteger.valueOf(3), nniList.get(1)); - Assert.assertEquals("unbounded", nniList.get(2)); - Assert.assertEquals(BigInteger.valueOf(6), nniList.get(3)); - Assert.assertEquals(4, nniList.size()); - } - - public void testListSetters() throws Exception - { - ListsDocument doc = ListsDocument.Factory.newInstance(); - ListsDocument.Lists lists = doc.addNewLists(); - lists.setIntList(Arrays.asList(new Object[] { new Integer(4), new Integer(18) })); - lists.setNniList(Arrays.asList(new Object[] { BigInteger.valueOf(1), BigInteger.valueOf(2), "unbounded" })); - String xtext = doc.xmlText(); - - ListsDocument docrt = ListsDocument.Factory.parse(xtext); - List intList = docrt.getLists().getIntList(); - Assert.assertEquals(new Integer(4), intList.get(0)); - Assert.assertEquals(new Integer(18), intList.get(1)); - Assert.assertEquals(2, intList.size()); - - List nniList = docrt.getLists().getNniList(); - Assert.assertEquals(BigInteger.valueOf(1), nniList.get(0)); - Assert.assertEquals(BigInteger.valueOf(2), nniList.get(1)); - Assert.assertEquals("unbounded", nniList.get(2)); - Assert.assertEquals(3, nniList.size()); - } - - public void testUnionGetters() throws Exception - { - UnionsDocument unions = UnionsDocument.Factory.parse( - "unbounded2 3 5 7 11"); - - Assert.assertEquals("unbounded", unions.getUnions().getNni()); - - Assert.assertTrue(unions.getUnions().getSizes() instanceof List); - List sizes = (List)unions.getUnions().getSizes(); - Assert.assertEquals(new Integer(2), sizes.get(0)); - Assert.assertEquals(new Integer(3), sizes.get(1)); - Assert.assertEquals(new Integer(5), sizes.get(2)); - Assert.assertEquals(new Integer(7), sizes.get(3)); - Assert.assertEquals(new Integer(11), sizes.get(4)); - Assert.assertEquals(5, sizes.size()); - - UnionsDocument unions2 = UnionsDocument.Factory.parse( - "37all"); - - Assert.assertEquals(BigInteger.valueOf(37), unions2.getUnions().getNni()); - Assert.assertEquals("all", unions2.getUnions().getSizes()); - } - - public void testUnionSetters() throws Exception - { - - // create a document - UnionsDocument doc = UnionsDocument.Factory.newInstance(); - UnionsDocument.Unions unions = doc.addNewUnions(); - unions.setNni("unbounded"); - unions.setSizes(Arrays.asList(new Object[] { new Integer(5), new Integer(22) })); - - // round trip to s text - String xtext = doc.xmlText(); - UnionsDocument docrt = UnionsDocument.Factory.parse(xtext); - - // verify contents - Assert.assertEquals("unbounded", docrt.getUnions().getNni()); - List sizes = (List)docrt.getUnions().getSizes(); - Assert.assertEquals(new Integer(5), sizes.get(0)); - Assert.assertEquals(new Integer(22), sizes.get(1)); - Assert.assertEquals(2, sizes.size()); - - // change the original document - unions.setNni(new Integer(11)); - unions.setSizes("unknown"); - - // round trip it again - xtext = doc.xmlText(); - docrt = UnionsDocument.Factory.parse(xtext); - - // verify contents again - Assert.assertEquals(BigInteger.valueOf(11), docrt.getUnions().getNni()); - Assert.assertEquals("unknown", docrt.getUnions().getSizes()); - } - - public void testUnionArray() throws Exception - { - IncidentReportsDocument doc = IncidentReportsDocument.Factory.parse( - "" + - "2001-08-06T03:34:00" + - "2002-01-04" + - "2002-08-26T23:10:00" + - ""); - IncidentReportsDocument.IncidentReports reports = doc.getIncidentReports(); - DateOrDateTime[] dt = reports.xgetWhenArray(); - Calendar[] gd = reports.getWhenArray(); - Assert.assertEquals(3, dt.length); - Assert.assertEquals(3, gd.length); - for (int i = 0; i < 3; i++) - { - Assert.assertEquals(((SimpleValue)dt[i]).getGDateValue(), new GDate(gd[i])); - Assert.assertEquals(gd[i], dt[i].getObjectValue()); - } - - Assert.assertEquals(new XmlCalendar("2001-08-06T03:34:00"), gd[0]); - Assert.assertEquals(new XmlCalendar("2002-01-04"), gd[1]); - Assert.assertEquals(new XmlCalendar("2002-08-26T23:10:00"), gd[2]); - - Assert.assertEquals(XmlDateTime.type, dt[0].instanceType()); - Assert.assertEquals(XmlDate.type, dt[1].instanceType()); - Assert.assertEquals(XmlDateTime.type, dt[2].instanceType()); - - reports.setWhenArray(0, new XmlCalendar("1980-04-18")); - reports.setWhenArray(1, new XmlCalendar("1970-12-20T04:33:00")); - - dt = reports.xgetWhenArray(); - gd = reports.getWhenArray(); - - Assert.assertEquals(new XmlCalendar("1980-04-18"), gd[0]); - Assert.assertEquals(new XmlCalendar("1970-12-20T04:33:00"), gd[1]); - Assert.assertEquals(new XmlCalendar("2002-08-26T23:10:00"), gd[2]); - - Assert.assertEquals(XmlDate.type, dt[0].instanceType()); - Assert.assertEquals(XmlDateTime.type, dt[1].instanceType()); - Assert.assertEquals(XmlDateTime.type, dt[2].instanceType()); - - } - -} diff --git a/test/src/xmlobject/schematypes/detailed/QNameSetTest.java b/test/src/xmlobject/schematypes/detailed/QNameSetTest.java deleted file mode 100755 index 59a56c3..0000000 --- a/test/src/xmlobject/schematypes/detailed/QNameSetTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.schematypes.detailed; - -import javax.xml.namespace.QName; - -import java.text.DecimalFormat; -import java.util.Random; -import java.util.Stack; - -import org.apache.xmlbeans.QNameSetBuilder; -import org.apache.xmlbeans.QNameSetSpecification; -import junit.framework.TestCase; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; - -public class QNameSetTest extends TestCase -{ - public QNameSetTest(String name) { super(name); } - public static Test suite() { return new TestSuite(QNameSetTest.class); } - - public static String format(int indent, int iter, String p, QNameSetBuilder set) - { - /* - System.err.print(new DecimalFormat("00000 ").format(iter)); - while (indent-- > 0) - System.err.print(' '); - System.err.print(p); - System.err.print(" = "); - System.err.println(set.dump()); - */ - - return "case# " + iter + " " + p + " " + set.toString(); - - } - - - public void testQNameSets() - { - int iterations = 10000; - int seed = 0; - int stopat = -1; - - Random rnd = new Random(seed); - String[] localname = {"a", "b", "c", "d", "e"}; - String[] namespace = {"n1", "n2", "n3", "n4", "n5"}; - int width = localname.length; - - QName[] name = new QName[width * namespace.length]; - for (int i = 0; i < width; i++) - { - for (int j = 0; j < namespace.length; j++) - { - name[i + width * j] = new QName(namespace[j], localname[i]); - } - } - - Stack teststack = new Stack(); // stack of sets - Stack trackstack = new Stack(); // stack of boolean arrays - - QNameSetBuilder current = new QNameSetBuilder(); - boolean[] contents = new boolean[width * namespace.length]; - boolean[] temp; - int i = 0; - int j = 0; - - for (int l = 0; l < iterations; l++) - { - // for debugging - - if (l == stopat) - System.err.println("We're here"); - - // apply a random operation - - if (rnd.nextInt(3) != 0) - { - i = rnd.nextInt(width - 1); // don't do the last one for isAll test - j = rnd.nextInt(namespace.length - 1); // don't do the last one for isAll test - } - - String label; - - switch (teststack.size() < 1 ? 24 : rnd.nextInt(iterations - l > teststack.size() ? 24 : 5)) - { - default: - teststack.push(current); - trackstack.push(contents); - current = new QNameSetBuilder(); - contents = new boolean[width * namespace.length]; - label = "new"; - break; - - case 19: - case 20: - case 22: - teststack.push(current); - trackstack.push(contents); - current = new QNameSetBuilder(); - contents = new boolean[width * namespace.length]; - - if (rnd.nextInt(2) == 0) - { - current.invert(); - for (int k = 0; k < width; k++) - { - contents[k + width * (namespace.length - 1)] = true; - } - } - - for (int h = 0; h < namespace.length - 1; h++) - { - if (rnd.nextInt(2) == 0) - current.removeNamespace(namespace[h]); - else - { - current.addNamespace(namespace[h]); - contents[width - 1 + width * h] = true; - } - for (int k = 0; k < width - 1; k++) - { - if (rnd.nextInt(2) == 0) - current.remove(name[k + width * h]); - else - { - current.add(name[k + width * h]); - contents[k + width * h] = true; - } - } - } - label = "random"; - break; - - case 0: - current.addAll((QNameSetSpecification)teststack.pop()); - temp = (boolean[])trackstack.pop(); - for (int k = 0; k < width * namespace.length; k++) - if (temp[k]) - contents[k] = true; - label = "add set"; - break; - - case 1: - current.removeAll((QNameSetSpecification)teststack.pop()); - temp = (boolean[])trackstack.pop(); - for (int k = 0; k < width * namespace.length; k++) - if (temp[k]) - contents[k] = false; - label = "remove set"; - break; - - case 2: - current.restrict((QNameSetSpecification)teststack.pop()); - temp = (boolean[])trackstack.pop(); - for (int k = 0; k < width * namespace.length; k++) - if (!temp[k]) - contents[k] = false; - label = "restrict set"; - break; - - case 3: - label = "union"; - current = new QNameSetBuilder(current.union((QNameSetSpecification)teststack.pop())); - temp = (boolean[])trackstack.pop(); - for (int k = 0; k < width * namespace.length; k++) - if (temp[k]) - contents[k] = true; - label = "union"; - break; - - case 4: - label = "intersect"; - current = new QNameSetBuilder(current.intersect((QNameSetSpecification)teststack.pop())); - temp = (boolean[])trackstack.pop(); - for (int k = 0; k < width * namespace.length; k++) - if (!temp[k]) - contents[k] = false; - label = "intersect"; - break; - - case 5: - current = new QNameSetBuilder(current); - label = "copy"; - break; - - case 6: - case 7: - case 8: - current.add(name[i + width * j]); - contents[i + width * j] = true; - label = "add one " + name[i + width * j]; - break; - - case 9: - case 10: - case 11: - current.remove(name[i + width * j]); - contents[i + width * j] = false; - label = "remove one " + name[i + width * j]; - break; - - case 12: - case 13: - current.addNamespace(namespace[j]); - for (int k = 0; k < width; k++) - contents[k + width * j] = true; - label = "add namespace " + namespace[j]; - break; - - case 14: - case 15: - current.removeNamespace(namespace[j]); - for (int k = 0; k < width; k++) - contents[k + width * j] = false; - label = "remove namespace " + namespace[j]; - break; - - case 16: - case 17: - current.invert(); - for (int k = 0; k < width * namespace.length; k++) - contents[k] = !contents[k]; - label = "invert"; - break; - - case 18: - current = new QNameSetBuilder(current.inverse()); - for (int k = 0; k < width * namespace.length; k++) - contents[k] = !contents[k]; - label = "inverse"; - break; - - } - - // System.out.println(format(teststack.size(), l, label, current)); - - // then, verify current matches contents - int count = 0; - for (int k = 0; k < width * namespace.length; k++) - { - Assert.assertTrue(format(0, l, "Content mismatch " + name[k], current), (current.contains(name[k]) == contents[k])); - { - // testprint(0, l, "ERROR ON " + name[k], current); - // testprint(0, l, "expected " + contents[k] + ", got " + !contents[k], current); - // System.exit(1); - } - if (contents[k]) - count++; - } - - Assert.assertTrue(format(0, l, "ERROR: isEmpty is wrong", current), ((count == 0) == current.isEmpty())); - { - // testprint(0, l, "ERROR: isEmpty is wrong", current); - // testprint(0, l, "expected " + (count == 0) + ", got " + !(count == 0), current); - // System.exit(1); - } - - Assert.assertTrue(format(0, l, "ERROR: isAll is wrong", current), (count == width * namespace.length) == current.isAll()); - { - // testprint(0, l, "ERROR: isAll is wrong", current); - // testprint(0, l, "expected " + (count == width * namespace.length) + ", got " + !(count == width * namespace.length), current); - // System.exit(1); - } - - // test isDisjoint and containsAll - if (teststack.size() >= 1) - { - boolean disjoint = true; - temp = (boolean[])trackstack.peek(); - for (int k = 0; k < width * namespace.length; k++) - { - if (temp[k] && contents[k]) - { - disjoint = false; - break; - } - } - Assert.assertTrue(format(0, l, "ERROR: disjoint is wrong", current), disjoint == current.isDisjoint((QNameSetSpecification)teststack.peek())); - { - // testprint(0, l, "ERROR: disjoint is wrong", current); - // testprint(0, l, "expected " + disjoint + ", got " + !disjoint, (QNameSetBuilder)teststack.peek()); - // System.exit(1); - } - - - boolean containsAll = true; - for (int k = 0; k < width * namespace.length; k++) - { - if (temp[k] && !contents[k]) - { - containsAll = false; - break; - } - } - Assert.assertTrue(format(0, l, "ERROR: containsAll is wrong", current), containsAll == current.containsAll((QNameSetSpecification)teststack.peek())); - } - - } - } -} diff --git a/test/src/xmlobject/usertype/averageCase/checkin/AverageTest.java b/test/src/xmlobject/usertype/averageCase/checkin/AverageTest.java deleted file mode 100644 index fe49eca..0000000 --- a/test/src/xmlobject/usertype/averageCase/checkin/AverageTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.usertype.averageCase.checkin; - -import java.math.BigDecimal; - -import javax.xml.stream.XMLOutputFactory; - -import junit.framework.TestCase; - -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - -import usertype.xbean.averageCase.purchaseOrder.Items; -import usertype.xbean.averageCase.purchaseOrder.PurchaseOrderDocument; -import usertype.xbean.averageCase.purchaseOrder.PurchaseOrderType; -import xmlobject.usertype.averageCase.existing.SKU; - - -public class AverageTest extends TestCase -{ - - public AverageTest(String s){ - super(s); - } - - public void test(){ - - PurchaseOrderDocument poDoc ; - - poDoc= PurchaseOrderDocument.Factory.newInstance(); - PurchaseOrderType po=poDoc.addNewPurchaseOrder(); - int LEN=20; - - Items.Item[] it= new Items.Item[LEN]; - for (int i=0; i< LEN; i++){ - it[i]=Items.Item.Factory.newInstance(); - it[i].setUSPrice(new BigDecimal(""+ 2 )); - it[i].setPartNum(new SKU(i, "AB")); - } - Items items= Items.Factory.newInstance(); - items.setItemArray(it); - po.setItems(items); - // System.out.println("poDoc: " + poDoc); - - for (int i=0; i< LEN; i++){ - assertEquals(i, it[i].getPartNum().getDigits()); - assertEquals("AB", it[i].getPartNum().getLetters()); - } - - - } - - public void testBadInput() throws XmlException{ - - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append("2"); - sb.append("2"); - sb.append(""); - - PurchaseOrderDocument poDocument = PurchaseOrderDocument.Factory.parse(sb.toString()); - - PurchaseOrderType po = poDocument.getPurchaseOrder(); - - Items.Item[] it = po.getItems().getItemArray(); - assertEquals(2, it.length); - - - SKU sku = it[0].getPartNum(); - - assertEquals(0, sku.getDigits()); - assertEquals("AB", sku.getLetters()); - - try { - - sku = it[1].getPartNum(); - fail("Invalid SKU format should have failed"); - - } catch (XmlValueOutOfRangeException e) { - - // test passed - } - - - } -} diff --git a/test/src/xmlobject/usertype/averageCase/existing/SKU.java b/test/src/xmlobject/usertype/averageCase/existing/SKU.java deleted file mode 100644 index 63f7a27..0000000 --- a/test/src/xmlobject/usertype/averageCase/existing/SKU.java +++ /dev/null @@ -1,42 +0,0 @@ -package xmlobject.usertype.averageCase.existing; - -public class SKU -{ - private int digits; - private String letters; - - - public SKU() - { - } - - public SKU(int digits, String letters) - { - setDigits(digits); - setLetters(letters); - } - - public int getDigits() - { - return digits; - } - - public void setDigits(int digits) - { - if (digits > 999 || digits < 0) - throw new IllegalArgumentException("bad digits"); - this.digits = digits; - } - - public String getLetters() - { - return letters; - } - - public void setLetters(String letters) - { - if (letters == null || letters.length() != 2) - throw new IllegalArgumentException("bad letters"); - this.letters = letters; - } -} diff --git a/test/src/xmlobject/usertype/averageCase/existing/SKUHandler.java b/test/src/xmlobject/usertype/averageCase/existing/SKUHandler.java deleted file mode 100644 index 310bad6..0000000 --- a/test/src/xmlobject/usertype/averageCase/existing/SKUHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -package xmlobject.usertype.averageCase.existing; - -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - -public class SKUHandler -{ - - public static void encodeSKU(SKU obj, SimpleValue target) - { - String digits; - if (obj.getDigits() < 10) - digits = "00" + Integer.toString(obj.getDigits()); - else if (obj.getDigits() < 100) - digits = "0" + Integer.toString(obj.getDigits()); - else - digits = Integer.toString(obj.getDigits()); - target.setStringValue(digits + "-" + obj.getLetters()); - } - - public static SKU decodeSKU(SimpleValue obj) throws XmlValueOutOfRangeException - { - String encoded = obj.getStringValue(); - if (encoded.length() != 6) - throw new XmlValueOutOfRangeException("Invalid SKU format: " + encoded); - - SKU sku = new SKU(); - try - { - sku.setDigits(Integer.parseInt(encoded.substring(0,3))); - } catch (NumberFormatException e) { - throw new XmlValueOutOfRangeException("Invalid SKU format: " + encoded); - } catch (IllegalArgumentException e) { - throw new XmlValueOutOfRangeException("Invalid SKU format: " + encoded); - } - - sku.setLetters(encoded.substring(4,6)); - return sku; - } -} diff --git a/test/src/xmlobject/usertype/multipleItems/checkin/AverageTest.java b/test/src/xmlobject/usertype/multipleItems/checkin/AverageTest.java deleted file mode 100644 index ec33d7b..0000000 --- a/test/src/xmlobject/usertype/multipleItems/checkin/AverageTest.java +++ /dev/null @@ -1,222 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.usertype.multipleItems.checkin; - - -import java.math.BigInteger; - -import junit.framework.TestCase; - -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - -import usertype.xbean.multipleItems.company.CompanyDocument; -import usertype.xbean.multipleItems.company.CompanyType; -import usertype.xbean.multipleItems.company.ConsultantType; -import usertype.xbean.multipleItems.company.DepartmentType; -import xmlobject.usertype.multipleItems.existing.Room; - - -public class AverageTest extends TestCase{ - - public AverageTest(String s){ - super(s); - } - - public void test() { - - CompanyDocument doc; - - doc = CompanyDocument.Factory.newInstance(); - - CompanyType company = doc.addNewCompany(); - - DepartmentType dept = company.addNewDepartments(); - - - ConsultantType cons = dept.addNewConsultant(); - - cons.setName("Joe Smith"); - cons.setAge(BigInteger.valueOf(100)); - - int LEN=20; - - for (int i=0; i < LEN; i++) { - cons.addRoom(new Room(i, "AB")); - } - - System.out.println(doc.xmlText()); - - Room[] rooms = cons.getRoomArray(); - - for (int i=0; i < LEN; i++) { - assertEquals(i, rooms[i].getDigits()); - assertEquals("AB", rooms[i].getLetters()); - } - } - - - public void testArrayGetSet() { - - CompanyDocument doc; - - doc = CompanyDocument.Factory.newInstance(); - - CompanyType company = doc.addNewCompany(); - - DepartmentType dept = company.addNewDepartments(); - - - ConsultantType cons = dept.addNewConsultant(); - - cons.setName("Joe Smith"); - cons.setAge(BigInteger.valueOf(100)); - - int LEN=20; - - Room[] rooms = new Room[LEN]; - - for (int i=0; i < LEN; i++) { - rooms[i] = new Room(i, "AB"); - } - - cons.setRoomArray(rooms); - - rooms = cons.getRoomArray(); - for (int i=0; i < LEN; i++) { - assertEquals(i, rooms[i].getDigits()); - assertEquals("AB", rooms[i].getLetters()); - } - - - } - - public void testIthGetSet() { - - CompanyDocument doc; - - doc = CompanyDocument.Factory.newInstance(); - - CompanyType company = doc.addNewCompany(); - - DepartmentType dept = company.addNewDepartments(); - - - ConsultantType cons = dept.addNewConsultant(); - - cons.setName("Joe Smith"); - cons.setAge(BigInteger.valueOf(100)); - - - int LEN=20; - - for (int i=0; i < LEN; i++) { - cons.addNewRoom(); - } - - - for (int i=0; i < LEN; i++) { - cons.setRoomArray(i, new Room(i, "AB")); - } - - for (int i=0; i < LEN; i++) { - assertEquals(i, cons.getRoomArray(i).getDigits()); - assertEquals("AB", cons.getRoomArray(i).getLetters()); - } - - - } - - - public void testBadInput() throws XmlException{ - - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(""); - sb.append("000-AB0001-AB002-AB"); - sb.append(""); - - CompanyDocument doc = CompanyDocument.Factory.parse(sb.toString()); - - CompanyType company = doc.getCompany(); - - ConsultantType cons = company.getDepartmentsArray(0).getConsultantArray(0); - assertEquals(3, cons.xgetRoomArray().length); - - try - { - cons.getRoomArray(); - fail("Invalid Room format should have failed"); - - } catch (XmlValueOutOfRangeException e) { - - // test passed - } - - } - - - - public void testBadInputGetIthBad() throws XmlException{ - - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(""); - sb.append("000-AB0001-AB002-AB"); - sb.append(""); - - CompanyDocument doc = CompanyDocument.Factory.parse(sb.toString()); - - CompanyType company = doc.getCompany(); - - ConsultantType cons = company.getDepartmentsArray(0).getConsultantArray(0); - assertEquals(3, cons.xgetRoomArray().length); - - try - { - cons.getRoomArray(1); - fail("Invalid Room format should have failed"); - } catch (XmlValueOutOfRangeException e) { - - // test passed - } - - } - - - public void testBadInputGetIthGood() throws XmlException{ - - StringBuffer sb = new StringBuffer(); - sb.append(""); - sb.append(""); - sb.append("000-AB0001-AB002-AB"); - sb.append(""); - - CompanyDocument doc = CompanyDocument.Factory.parse(sb.toString()); - - CompanyType company = doc.getCompany(); - - ConsultantType cons = company.getDepartmentsArray(0).getConsultantArray(0); - assertEquals(3, cons.xgetRoomArray().length); - - assertEquals(0, cons.getRoomArray(0).getDigits()); - assertEquals("AB", cons.getRoomArray(0).getLetters()); - assertEquals(2, cons.getRoomArray(2).getDigits()); - assertEquals("AB", cons.getRoomArray(2).getLetters()); - - } - -} diff --git a/test/src/xmlobject/usertype/multipleItems/existing/Room.java b/test/src/xmlobject/usertype/multipleItems/existing/Room.java deleted file mode 100644 index 94ead9b..0000000 --- a/test/src/xmlobject/usertype/multipleItems/existing/Room.java +++ /dev/null @@ -1,42 +0,0 @@ -package xmlobject.usertype.multipleItems.existing; - -public class Room -{ - private int digits; - private String letters; - - - public Room() - { - } - - public Room(int digits, String letters) - { - setDigits(digits); - setLetters(letters); - } - - public int getDigits() - { - return digits; - } - - public void setDigits(int digits) - { - if (digits > 999 || digits < 0) - throw new IllegalArgumentException("bad digits"); - this.digits = digits; - } - - public String getLetters() - { - return letters; - } - - public void setLetters(String letters) - { - if (letters == null || letters.length() != 2) - throw new IllegalArgumentException("bad letters"); - this.letters = letters; - } -} diff --git a/test/src/xmlobject/usertype/multipleItems/existing/RoomHandler.java b/test/src/xmlobject/usertype/multipleItems/existing/RoomHandler.java deleted file mode 100644 index f7c70c6..0000000 --- a/test/src/xmlobject/usertype/multipleItems/existing/RoomHandler.java +++ /dev/null @@ -1,41 +0,0 @@ -package xmlobject.usertype.multipleItems.existing; - -import org.apache.xmlbeans.SimpleValue; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; - -public class RoomHandler -{ - - public static void encodeRoom(Room obj, SimpleValue target) - { - String digits; - if (obj.getDigits() < 10) - digits = "00" + Integer.toString(obj.getDigits()); - else if (obj.getDigits() < 100) - digits = "0" + Integer.toString(obj.getDigits()); - else - digits = Integer.toString(obj.getDigits()); - target.setStringValue(digits + "-" + obj.getLetters()); - } - - - public static Room decodeRoom(SimpleValue obj) throws XmlValueOutOfRangeException - { - String encoded = obj.getStringValue(); - if (encoded.length() != 6) - throw new XmlValueOutOfRangeException("Invalid Room format: " + encoded); - - Room sku = new Room(); - try - { - sku.setDigits(Integer.parseInt(encoded.substring(0,3))); - } catch (NumberFormatException e) { - throw new XmlValueOutOfRangeException("Invalid Room format: " + encoded); - } catch (IllegalArgumentException e) { - throw new XmlValueOutOfRangeException("Invalid Room format: " + encoded); - } - - sku.setLetters(encoded.substring(4,6)); - return sku; - } -} diff --git a/test/src/xmlobject/xmlloader/detailed/JapaneseTextTest.java b/test/src/xmlobject/xmlloader/detailed/JapaneseTextTest.java deleted file mode 100644 index 0e5ddda..0000000 --- a/test/src/xmlobject/xmlloader/detailed/JapaneseTextTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package xmlobject.xmlloader.detailed; - -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlObject; -import tools.util.JarUtil; - -public class JapaneseTextTest extends TestCase { - - public void testEucJp() throws Exception{ - loadFile("pr-xml-euc-jp.xml"); - } - public void testIso2022Jp()throws Exception{ - loadFile("pr-xml-iso-2022-jp.xml"); - } - public void testLittleEndian()throws Exception{ - loadFile("pr-xml-little-endian.xml"); - } - public void testShift_jis()throws Exception{ - loadFile("pr-xml-shift_jis.xml"); - } - public void testUtf8()throws Exception{ - loadFile("pr-xml-utf-8.xml"); - } - public void testUtf16()throws Exception{ - loadFile("pr-xml-utf-16.xml"); - } - - public void testWeeklyEucJp()throws Exception{ - loadFile("weekly-euc-jp.xml"); - } - public void testWeeklyIso2022Jp()throws Exception{ - loadFile("weekly-iso-2022-jp.xml"); - } - public void testWeeklyLittleEndian()throws Exception{ - loadFile("weekly-little-endian.xml"); - } - public void testWeeklyShift_jis()throws Exception{ - loadFile("weekly-shift_jis.xml"); - } - public void testWeeklyUtf8()throws Exception{ - loadFile("weekly-utf-8.xml"); - } - public void testWeeklyUtf16()throws Exception{ - loadFile("weekly-utf-16.xml"); - } - - public void testPrefixLocalName()throws Exception{ - loadFile("prefix_test.xml"); - } - - - public void loadFile(String file) throws Exception{ - - XmlObject.Factory.parse(JarUtil. - getResourceFromJarasStream("xbean/xmlobject/japanese/"+file)); - - } - - - -} diff --git a/test/src/xmlobject/xmlloader/detailed/ParseTest.java b/test/src/xmlobject/xmlloader/detailed/ParseTest.java deleted file mode 100755 index 2b87c91..0000000 --- a/test/src/xmlobject/xmlloader/detailed/ParseTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.xmlloader.detailed; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import xmlcursor.common.BasicCursorTestCase; - -import javax.xml.namespace.QName; -import java.util.Vector; - -public class ParseTest extends BasicCursorTestCase { - private XmlOptions m_map = new XmlOptions(); - - public ParseTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(ParseTest.class); - } - - public void testLoadStripWhitespace() throws Exception { - m_map.put(XmlOptions.LOAD_STRIP_WHITESPACE, ""); - m_xo = XmlObject.Factory.parse("01234 text chars \r\n ", - m_map); - m_xc = m_xo.newCursor(); - assertEquals("01234textchars", m_xc.xmlText()); - } - - public void testLoadDiscardDocumentElement() throws Exception { - QName name = new QName(""); - - m_map.put(XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT, name); - System.out.println("here"); - - try { - m_xo = XmlObject.Factory.parse("01234 text chars ", - m_map); - } catch (IllegalArgumentException e) { - } - - } - - public void testPrefixNotDefined() throws Exception { - String sXml = "steve"; - try { - XmlObject.Factory.parse(sXml); - fail("Expected XmlException"); - } catch (org.apache.xmlbeans.XmlException e) { - } - } - - public void testErrorListener() throws Exception { - Vector vErrors = new Vector(); - m_map.setErrorListener(vErrors); - try { - m_xo = XmlObject.Factory.parse("text", m_map); // improper end tag - fail("Expected parsing exception!"); - } catch (org.apache.xmlbeans.XmlException xe) { - - } - } - - -} - diff --git a/test/src/xmlobject/xmlloader/detailed/XmlLoaderBvtTest.java b/test/src/xmlobject/xmlloader/detailed/XmlLoaderBvtTest.java deleted file mode 100755 index e27590b..0000000 --- a/test/src/xmlobject/xmlloader/detailed/XmlLoaderBvtTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package xmlobject.xmlloader.detailed; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.apache.xmlbeans.XmlObject; -import org.tranxml.tranXML.version40.CarLocationMessageDocument; -import tools.util.JarUtil; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; - - - -public class XmlLoaderBvtTest extends BasicCursorTestCase { - public XmlLoaderBvtTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(XmlLoaderBvtTest.class); - } - - public void testClassPath() throws Exception { - String sClassPath = System.getProperty("java.class.path"); - int i = sClassPath.indexOf(Common.CARLOCATIONMESSAGE_JAR); - assertTrue(i >= 0); - } - - public void testCastDocument() throws Exception { - - CarLocationMessageDocument clm = - (CarLocationMessageDocument) XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - - assertNotNull(clm); - } - -} - diff --git a/test/src/xmlobject/xmlloader/detailed/XmlStreamBeanReader.java b/test/src/xmlobject/xmlloader/detailed/XmlStreamBeanReader.java deleted file mode 100644 index 583fdf7..0000000 --- a/test/src/xmlobject/xmlloader/detailed/XmlStreamBeanReader.java +++ /dev/null @@ -1,101 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package xmlobject.xmlloader.detailed; - -import junit.framework.TestCase; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlCursor; -import org.openuri.bea.samples.workshop.CreditCardDataDocument; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamException; -import java.io.ByteArrayInputStream; - -/** - * Date: Oct 29, 2004 - * Time: 11:43:06 AM - * - * @owner ykadiysk - */ -public class XmlStreamBeanReader extends TestCase{ - - String creditCardXmlwPrefix = - " \n" + - " \n" + - " \n" + - " 0\n" + - " 0\n" + - " \n" + - " \n" + - " 0\n" + - " 0\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 0\n" + - " 0\n" + - " \n" + - " \n" + - " 0\n" + - " 0\n" + - " \n" + - " \n" + - " "; - - - public void testXMLStreamReaderLoader () throws XMLStreamException, XmlException { - XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(creditCardXmlwPrefix.getBytes())); - CreditCardDataDocument ccdoc = (CreditCardDataDocument) XmlObject.Factory.parse(reader, new XmlOptions().setDocumentType(CreditCardDataDocument.type)); - assertEquals(1,ccdoc.getCreditCardData().getCustomerArray(0).getId()); - - - } - - // test for IllegalStateException thrown on using XmlStreamReader - public void testXmlStreamReaderException() { - - XmlObject xo = XmlObject.Factory.newInstance(); - XmlCursor xc = xo.newCursor(); - xc.toNextToken(); - - xc.insertElementWithText("int", "http://openuri.org/testNumerals", "5"); - xc.insertElementWithText("float", "http://openuri.org/testNumerals", "7.654321"); - - try { - - XMLStreamReader xsr = xo.newXMLStreamReader(); - - while(xsr.hasNext()) - { - xsr.next(); - } - } - catch (XMLStreamException xse) - { - xse.printStackTrace(); - fail("XMLStreamException thrown with XMLStreamReader usage"); - } - catch (IllegalStateException ise) - { - ise.printStackTrace(); - fail("IllegalStateException thrown with XMLStreamReader usage"); - } - } - -} diff --git a/test/src/xmltokensource/detailed/RoundTripLoaderTest.java b/test/src/xmltokensource/detailed/RoundTripLoaderTest.java deleted file mode 100755 index 2cc4d7b..0000000 --- a/test/src/xmltokensource/detailed/RoundTripLoaderTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmltokensource.detailed; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.w3c.dom.Node; -import org.apache.xmlbeans.xml.stream.XMLInputStream; - -import java.io.InputStream; -import java.io.Reader; - - -public class RoundTripLoaderTest extends BasicCursorTestCase { - public static final String DOC_FRAGMENT = "#document-fragment"; - private XmlOptions m_map = new XmlOptions(); - - public RoundTripLoaderTest(String sName) { - super(sName); - m_map.put(XmlOptions.CHARACTER_ENCODING, "Big5"); - m_map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); - } - - public static Test suite() { - return new TestSuite(RoundTripLoaderTest.class); - } - - private void _newDomNodeRoundTrip(XmlOptions map) throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); - Node doc = m_xo.newDomNode(map); - assertNotNull(doc); - XmlObject xo = XmlObject.Factory.parse(doc, map); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = xo.newCursor(); - try { - compareDocTokens(m_xc, xc1); - } finally { - xc1.dispose(); - } - } - - public void testNewDomNodeRoundTrip() throws Exception { - _newDomNodeRoundTrip(null); - } - - public void testNewDomNodeWithOptionsRoundTrip() throws Exception { - _newDomNodeRoundTrip(m_map); - } - - private void _newInputStreamRoundTrip(XmlOptions map) throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); - InputStream is = m_xo.newInputStream(map); - assertNotNull(is); - XmlOptions options = new XmlOptions(map); - XmlObject xo = XmlObject.Factory.parse(is, options); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = xo.newCursor(); - try { - compareDocTokens(m_xc, xc1); - } finally { - xc1.dispose(); - } - } - - public void testNewInputStreamRoundTrip() throws Exception { - _newInputStreamRoundTrip(null); - } - - public void testNewInputStreamWithOptionsRoundTrip() throws Exception { - _newInputStreamRoundTrip(m_map); - } - - private void _newReaderRoundTrip(XmlOptions map) throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); - Reader reader = m_xo.newReader(map); - assertNotNull(reader); - XmlOptions options = new XmlOptions(map); - XmlObject xo = XmlObject.Factory.parse(reader, options); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = xo.newCursor(); - try { - compareDocTokens(m_xc, xc1); - } finally { - xc1.dispose(); - } - } - /** - * yana_kadiyska (3:25:15 PM): Eric, is this going to be impl - * on this release? Bug? store.Cursor._newXMLInputStream - * ericvasilik (3:26:01 PM): This is not a v2 feature. ... - * but otherwise, we should disable XMLInputStream tests - * - public void testNewReaderRoundTrip() throws Exception { - _newReaderRoundTrip(null); - } - - public void testNewReaderWithOptionsRoundTrip() throws Exception { - _newReaderRoundTrip(m_map); - } - - */ - private void _newXMLInputStreamRoundTrip(XmlOptions map) throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); - XMLInputStream xmlIs = m_xo.newXMLInputStream(map); - assertNotNull(xmlIs); - XmlObject xo = XmlObject.Factory.parse(xmlIs, map); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = xo.newCursor(); - try { - compareDocTokens(m_xc, xc1); - } finally { - xc1.dispose(); - } - } - - /** - * - * @throws Exception - */ - public void testNewXMLInputStreamRoundTrip() throws Exception { - _newXMLInputStreamRoundTrip(null); - } - - public void testNewXMLInputStreamWithOptionsRoundTrip() throws Exception { - _newXMLInputStreamRoundTrip(m_map); - } - - private void _xmlTextRoundTrip(XmlOptions map) throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_BAR_NESTED_SIBLINGS); - String sXml = m_xo.xmlText(map); - assertNotNull(sXml); - XmlOptions options = new XmlOptions(map); - XmlObject xo = XmlObject.Factory.parse(sXml, options); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = xo.newCursor(); - try { - compareDocTokens(m_xc, xc1); - } finally { - xc1.dispose(); - } - } - - public void testXmlTextRoundTrip() throws Exception { - _xmlTextRoundTrip(null); - } - - public void testXmlTextWithOptionsRoundTrip() throws Exception { - _xmlTextRoundTrip(m_map); - } - - -} - diff --git a/test/src/xmltokensource/detailed/XmlTextTest.java b/test/src/xmltokensource/detailed/XmlTextTest.java deleted file mode 100755 index b703cfa..0000000 --- a/test/src/xmltokensource/detailed/XmlTextTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -package xmltokensource.detailed; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import xmlcursor.common.BasicCursorTestCase; -import xmlcursor.common.Common; -import tools.util.JarUtil; -import junit.framework.Test; -import junit.framework.TestSuite; - -import javax.xml.namespace.QName; - - - -public class XmlTextTest extends BasicCursorTestCase { - private XmlOptions m_map = new XmlOptions(); - - public XmlTextTest(String sName) { - super(sName); - } - - public static Test suite() { - return new TestSuite(XmlTextTest.class); - } - - public void testSAVENAMESPACESFIRST() throws Exception { - m_xo = XmlObject.Factory.parse("01234"); - m_xc = m_xo.newCursor(); - m_map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); - assertEquals("01234", - m_xc.xmlText(m_map)); - } - - public void testSAVENAMESPACESlast() throws Exception { - m_xo = XmlObject.Factory.parse("01234"); - m_xc = m_xo.newCursor(); - assertEquals("01234", - m_xc.xmlText(m_map)); - } - - public void testSaveSyntheticDocumentElement() throws Exception { - m_xo = XmlObject.Factory.parse("text"); - m_xc = m_xo.newCursor(); - m_map.put(XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT, - new QName("foo")); - assertEquals("text", m_xc.xmlText(m_map)); - } - - public void testSavePrettyPrint() throws Exception { - m_xo = XmlObject.Factory.parse(" text "); - m_xc = m_xo.newCursor(); - m_map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); - String lnSep = System.getProperty("line.separator"); - assertEquals("" + lnSep + " " + lnSep + " text" + lnSep + " " + lnSep + "", m_xc.xmlText(m_map)); - } - - public void testSavePrettyPrintIndent3() throws Exception { - m_xo = XmlObject.Factory.parse(" text "); - m_xc = m_xo.newCursor(); - m_map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); - m_map.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(3)); - String lnSep = System.getProperty("line.separator"); - assertEquals("" + lnSep + " " + lnSep + " text" + lnSep + " " + lnSep + "", m_xc.xmlText(m_map)); - } - - public void testSavePrettyPrintIndentNeg1() throws Exception { - m_xc = XmlObject.Factory.parse(" \n \n text \n \n ").newCursor(); - m_map.put(XmlOptions.SAVE_PRETTY_PRINT, ""); - m_map.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, new Integer(-1)); - assertEquals("text", m_xc.xmlText(m_map)); - } - - public void testDefaultNamespace() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - m_xc.selectPath(Common.CLM_NS_XQUERY_DEFAULT + "$this//FleetID"); - m_xc.toNextSelection(); - m_map.put(XmlOptions.SAVE_NAMESPACES_FIRST, ""); - assertEquals("FLEETNAME", - m_xc.xmlText(m_map)); - } - - public void testSTARTDOCvsFirstChild() throws Exception { - m_xo = XmlObject.Factory.parse( - JarUtil.getResourceFromJar(Common.TRANXML_FILE_CLM)); - m_xc = m_xo.newCursor(); - XmlCursor xc1 = m_xo.newCursor(); - xc1.toFirstChild(); - try { - assertEquals(m_xc.xmlText(), xc1.xmlText()); - } finally { - xc1.dispose(); - } - } - - public void testXmlTextFromTEXT() throws Exception { - m_xo = XmlObject.Factory.parse(Common.XML_FOO_1ATTR_TEXT); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals("text", m_xc.getChars()); - } - - public void testXmlTextFromTEXTafterEND() throws Exception { - m_xo = XmlObject.Factory.parse(" text ws \\r\\n "); - m_xc = m_xo.newCursor(); - toNextTokenOfType(m_xc, TokenType.TEXT); - toNextTokenOfType(m_xc, TokenType.TEXT); - assertEquals(" ws \\r\\n ", m_xc.getChars()); - } -} - diff --git a/test/tools/src/tools/JUnit/JUnitXResultFormatter.java b/test/tools/src/tools/JUnit/JUnitXResultFormatter.java deleted file mode 100755 index 716f6c4..0000000 --- a/test/tools/src/tools/JUnit/JUnitXResultFormatter.java +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.JUnit; - -import junit.framework.TestListener; - -import java.io.OutputStream; - -public interface JUnitXResultFormatter extends TestListener -{ - /** Signals start of run */ - public void startRun(); - - /** Signals end of run */ - public void endRun(); - - /** Sets an outputstream to output logs to */ - public void setOutput(OutputStream out); - - /** Tells an ResultFormatter to show stdout/stderr if its capturing - * the streams - */ - public void showTestOutput(boolean show); - /* Any class implementing this will automatically have to - * implement TestListener - */ -} diff --git a/test/tools/src/tools/JUnit/JUnitXRunner.java b/test/tools/src/tools/JUnit/JUnitXRunner.java deleted file mode 100755 index 12a22f0..0000000 --- a/test/tools/src/tools/JUnit/JUnitXRunner.java +++ /dev/null @@ -1,234 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.JUnit; - -import junit.runner.BaseTestRunner; -import junit.runner.TestRunListener; -import junit.framework.*; - -import java.io.*; -import java.util.*; - -import org.apache.xmlbeans.impl.tool.CommandLine; - -public class JUnitXRunner extends BaseTestRunner - implements JUnitXResultFormatter { - public static void main(String args[]) - throws Exception { - - File file = new File(args[0]); - String resListener = null; - String outFile = null; - boolean showOutput = false; - - Collection flags = new TreeSet(); - flags.add("showoutput"); - - Collection options=new TreeSet(); - options.add(JUnitXTask.resultListener); - options.add(JUnitXTask.outFile); - - CommandLine cmdl = new CommandLine(args, flags, options); - showOutput = cmdl.getOpt("showoutput") != null; - resListener = cmdl.getOpt(JUnitXTask.resultListener); - if (resListener != null) { - outFile = cmdl.getOpt(JUnitXTask.outFile); - if (outFile == null) - throw new RuntimeException("No output file specified"); - } - ArrayList files = new ArrayList(); - try { - BufferedReader in = new BufferedReader(new FileReader(file)); - String line; - while ((line = in.readLine()) != null) - files.add(line); - in.close(); - - } - catch (Exception e) { - e.printStackTrace(); - } - - JUnitXRunner runner; - if (resListener != null) { - // Try to instantiate a class of resListener - Object obj; - try { - Class c = Class.forName(resListener); - obj = c.newInstance(); - } - catch (Exception e) { - throw new RuntimeException(e); - } - JUnitXResultFormatter fmt = (JUnitXResultFormatter) obj; - runner = new JUnitXRunner(files, fmt, outFile, showOutput); - } else - runner = new JUnitXRunner(files, showOutput); - - - int nFailureCount = runner.runTests(); - - System.exit(nFailureCount); - } - - ///////////////////////////////////////////////////////////////////////// - // Runner implementation - - ArrayList classes; - ArrayList tests; - int testCount = 0; - JUnitXResultFormatter _listener = null; - String outFile = null; - boolean showOutput = false; - - public JUnitXRunner(ArrayList classes, boolean showOutput) { - this.classes = classes; - tests = new ArrayList(); - _listener = this; - this.showOutput = showOutput; - } - - public JUnitXRunner(ArrayList classes, - JUnitXResultFormatter listener, - String outFile, - boolean showOutput) { - this.classes = classes; - tests = new ArrayList(); - _listener = listener; - this.outFile = outFile; - this.showOutput = showOutput; - - } - - - public int runTests() { - collectTests(); - Iterator itr = tests.iterator(); - - TestResult res = new TestResult(); - res.addListener(_listener); - - try { - if (outFile != null) { - FileOutputStream fos = new FileOutputStream(new File(outFile)); - _listener.setOutput(fos); - } - } - catch (FileNotFoundException fnfe) { - throw new RuntimeException("Unable to initialize output to file " - + outFile + "\n" + fnfe.getMessage()); - } - - _listener.showTestOutput(showOutput); - _listener.startRun(); - while (itr.hasNext()) { - Test test = (Test) itr.next(); - test.run(res); - } - _listener.endRun(); - return res.failureCount(); - } - - private void collectTests() { - Iterator itr = classes.iterator(); - - while (itr.hasNext()) { - Test suite = null; - String className = (String) itr.next(); - suite = getTest(className); - - if (suite != null && suite.countTestCases() > 0) { - tests.addAll(getSubTests(suite)); - } else { - //System.out.println("No tests found in " + testClassName); - // Ignore files which are not Junit tests. - } - } - } - - private Collection getSubTests(Test test) { - Collection ret = new ArrayList(); - - if (TestSuite.class.isAssignableFrom(test.getClass())) { - Enumeration e = ((TestSuite) test).tests(); - while (e.hasMoreElements()) { - ret.addAll(getSubTests((Test) e.nextElement())); - } - } else if (TestCase.class.isAssignableFrom(test.getClass())) { - ret.add(((TestCase) test)); - } else { - System.out.println( - "Could not find any tests in " + test.toString()); - } - - return ret; - } - - // JUnitXResultFormatter Implementation - public void startRun() { - - } - - public void endRun() { - - } - - public void setOutput(OutputStream out) { - // Ignored. Custom ResultFormatters will use - } - - public void showTestOutput(boolean show) { - // Ignore. We don't capture stdout or stderr. - } - - // TestRunListener implementation - public void testStarted(String testName) { - System.out.println("\nStarted: " + testName); - } - - public void testEnded(String testName) { - System.out.println("Ended: " + testName); - } - - public void testFailed(int status, Test test, Throwable t) { - if (status == TestRunListener.STATUS_FAILURE) - System.out.println("Failure: "); - else - System.out.println("Error: "); - - System.out.println(getFilteredTrace(t)); - } - - protected void runFailed(String message) { - //System.out.println("RUN had failures"); - } - - /* This is important - not setting this to false expilcitly - * will cause Junit to create a new classloader instance for - * every class it loads, causing a OOM sooner or later. - * - * @see junit.runner.BaseTestRunner#useReloadingTestSuiteLoader() - */ - protected boolean useReloadingTestSuiteLoader() { - return false; - } - - private String getStackTraceAsString(Throwable t) { - StringWriter sw = new StringWriter(); - t.printStackTrace(new PrintWriter(sw, true)); - - return sw.toString(); - } -} diff --git a/test/tools/src/tools/JUnit/JUnitXTask.java b/test/tools/src/tools/JUnit/JUnitXTask.java deleted file mode 100755 index c1ad88b..0000000 --- a/test/tools/src/tools/JUnit/JUnitXTask.java +++ /dev/null @@ -1,264 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.JUnit; - -import org.apache.tools.ant.DirectoryScanner; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.types.FileSet; - -import java.util.Vector; -import java.io.File; -import java.io.FileWriter; -import java.io.BufferedWriter; - -/** - *

        This task runs tests from the JUnit testing framework. The latest version - * of JUnit can be found at http://www.junit.org. - *

        - *

        Note: This task depends on external libraries not included - * in the Ant distribution. See - *

        - * Library Dependencies for more information. - *

        - *

        - * Note: - * You must have junit.jar and the class files for the - * <junit> task in the same classpath. - * You can do one of: - *

          - *
        1. - * Put both junit.jar and the optional tasks jar file in - *

          - * ANT_HOME/lib. - *

        2. - *
        3. - * Do not put either in ANT_HOME/lib, and instead - * include their locations in your CLASSPATH environment variable. - *
        4. - *
        5. - * Do neither of the above, and instead, specify their locations using - * a <classpath> element in the build file. - *

          - * See the - * FAQ for details.

          - *

          - *

          - *

          - * Usage:
          - * This task is derived from the Java task and supports all attributes and nested
          - * elements of the Java task. Additionally it supports the following attributes
          - * 

          - * formatter = Optional class that implements tools.JUnit.JUnitXResultFormatter - * to be passed to the JUnit runner for formatting the results - * reportFile = File for the formatter to write too. - * (Required if formatter is specified. The formatter may choose - * to ignore this) - * showOutput = Tells the formatter to show the output of the tests. - * The default formatter ignores this flag, since it anyway - * displays everything to stdout/stderr. - * classes = Ignored unless the fileset is not valid. If the user has specified - * valid classnames, this variable is used to run the classes. Hacky but - * allows the user to use the same command line parameter as when specifying filesets. - *

          - * The tests to run are specified using nested Filesets elements - * The task picks up any .class or .java files from the filesets and tries to run - * them as JUnit tests. - *

          - */ -public class JUnitXTask extends org.apache.tools.ant.taskdefs.Java { - // Task attributes vars - private String reportFile; - private boolean showOutput = false; - private String formatterClass; - private String[] classFiles = null; - - public final static String resultListener="listener"; - public final static String outFile="file"; - - /** - * the list of filesets containing the testcase filename rules - */ - private Vector filesets = new Vector(); - - /** - * Add a new fileset instance to this batchtest. Whatever the fileset is, - * only filename that are .java or .class will be - * considered as 'candidates'. - * - * @param fs the new fileset containing the rules to get the testcases. - */ - public void addFileSet(FileSet fs) { - filesets.addElement(fs); - } - - // Additional Attributes - /** - * - */ - public void setClasses(String classes) { - this.classFiles = classes.split(","); - } - - /** - * Set the file to write the test run report to - * - * @param reportFile - */ - public void setReportFile(String reportFile) { - this.reportFile = reportFile; - } - - /** - * Sets the class to be used as the Result formatter for the test results - * This class should implement tools.JUnit.JUnitXResultFormatter - * - * @param fmtClass - */ - public void setFormatter(String fmtClass) { - this.formatterClass = fmtClass; - } - - /** - * Controls whether the output from the tests is sent to stdout/stderr. - * - * @param show - */ - public void setShowOutput(boolean show) { - this.showOutput = show; - } - - public void execute() throws BuildException { - validate(); - String[] files = getFilenames(); - File temp = null; - String fName = Long.toString(System.currentTimeMillis()); - - - //issue w/ JDK 1.4 IOException - // temp = File.createTempFile(,null); - temp = new File(fName); - - try { - temp.deleteOnExit(); - // System.out.println(temp.toString()); - BufferedWriter out = new BufferedWriter(new FileWriter(temp)); - System.out.println(temp.toString()); - for (int i = 0; i < files.length; i++) - out.write(javaToClass(files[i]) + "\n"); - out.close(); - } - catch (java.io.IOException ioe) { - throw new BuildException("Could not write out temporary file for " + - "passing arguments to the JUnit runner: " + - ioe.getMessage()); - } - - super.setClassname("tools.JUnit.JUnitXRunner"); - // Args: tempFile reportFormatter outFile - super.createArg().setFile(temp); - if (formatterClass != null) { - super.createArg().setValue("-"+resultListener); - super.createArg().setValue(this.formatterClass); - super.createArg().setValue("-"+outFile); - super.createArg().setValue(this.reportFile); - } - if (showOutput){ - super.createArg().setValue("-showoutput"); - super.createArg().setValue(new Boolean(this.showOutput).toString()); - } - super.execute(); - } - - /** - * Validates the attributes - */ - private void validate() { - // Check if any filesets have been specified - if (filesets.size() == 0) - throw new BuildException("You have to specify atleast one Fileset"); - - // If Custom ResultFormatter is specified, then an outfile should be - // specified. The default ResultFormatter write only to Stdout - if ((formatterClass != null) && (reportFile == null)) - throw new BuildException( - "Using custom ReportFormatter: " + - "reportFile attribute should be specified"); - - } - - /** - * Iterate over all filesets and return the filename of all files - * that end with .java or .class. This is to avoid - * wrapping a JUnitTest over an xml file for example. A Testcase - * is obviously a java file (compiled or not). - * - * @return an array of filenames without their extension. As they should - * normally be taken from their root, filenames should match their fully - * qualified class name (If it is not the case it will fail when running the test). - * For the class org/apache/Whatever.class it will return org/apache/Whatever. - */ - private String[] getFilenames() { - Vector v = new Vector(); - final int size = this.filesets.size(); - for (int j = 0; j < size; j++) { - FileSet fs = (FileSet) filesets.elementAt(j); - // DirectoryScanner ds = fs.getDirectoryScanner(project); - DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject()); - ds.scan(); - String[] f = ds.getIncludedFiles(); - //check for an actual class here - if (f.length == 0 && size == 1) - f = classFiles; - for (int k = 0; k < f.length; k++) { - String pathname = f[k]; - if (pathname.endsWith(".java")) { - v.addElement( - pathname.substring(0, - pathname.length() - ".java".length())); - } else if (pathname.endsWith(".class")) { - // DOn't try to run inner classes - if (pathname.indexOf("$") == -1) - v.addElement( - pathname.substring(0, - pathname.length() - ".class".length())); - } else - try { - Class.forName(pathname); - v.addElement(pathname); - } - catch (ClassNotFoundException e) { - ;//filename is not a class - } - } - } - String[] files = new String[v.size()]; - v.copyInto(files); - return files; - } - - /** - * Convenient method to convert a pathname without extension to a - * fully qualified classname. For example org/apache/Whatever will - * be converted to org.apache.Whatever - * - * @param filename the filename to "convert" to a classname. - * @return the classname matching the filename. - */ - public static final String javaToClass(String filename) { - return filename.replace(File.separatorChar, '.'); - } - - -} diff --git a/test/tools/src/tools/JUnit/SimpleResultFormatter.java b/test/tools/src/tools/JUnit/SimpleResultFormatter.java deleted file mode 100755 index be0be96..0000000 --- a/test/tools/src/tools/JUnit/SimpleResultFormatter.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package tools.JUnit; - -import java.io.*; -import java.text.NumberFormat; -import java.util.*; - -import junit.framework.AssertionFailedError; -import junit.framework.Test; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.optional.junit.*; - - -/** - * Prints plain text output of the test to a specified Writer. - * - * @author Stefan Bodewig - */ -public class SimpleResultFormatter implements JUnitResultFormatter { - - public static int TEST_SUCCESS = 0; - public static int TEST_FAILURE = 1; - public static int TEST_ERROR = 2; - public static int TEST_UNKNOWN = 3; - - // Lets capture STDOUT and STDERR - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ByteArrayOutputStream bErr = new ByteArrayOutputStream(); - - PrintStream _out; - PrintStream _err; - private TestRecord testRecord; - Collection records; - - /** - * Formatter for timings. - */ - private NumberFormat nf = NumberFormat.getInstance(); - /** - * Timing helper. - */ - private Hashtable testStarts = new Hashtable(); - /** - * Where to write the log to. - */ - private OutputStream out; - /** - * Helper to store intermediate output. - */ - private StringWriter inner; - /** - * Convenience layer on top of {@link #inner inner}. - */ - private PrintWriter wri; - /** - * Suppress endTest if testcase failed. - */ - private Hashtable failed = new Hashtable(); - - private String systemOutput = null; - private String systemError = null; - - public SimpleResultFormatter() { - inner = new StringWriter(); - wri = new PrintWriter(inner); - } - - public void setOutput(OutputStream out) { - this.out = out; - } - - public void setSystemOutput(String out) { - // We will be capturing Stdout and Stderr internally so this is - // redundant - //systemOutput = out; - } - - public void setSystemError(String err) { - // We will be capturing Stdout and Stderr internally so this is - // redundant - //systemError = err; - } - - /** - * Signals starting of a Suite of tests - */ - public void startTestSuite(JUnitTest suite) { - records = new ArrayList(); - } - - /** - * The whole testsuite ended. - */ - public void endTestSuite(JUnitTest suite) throws BuildException { - String newLine = System.getProperty("line.separator"); - StringBuffer sb = new StringBuffer("Testsuite: "); - sb.append(suite.getName()); - sb.append(newLine); - sb.append("Tests run: "); - sb.append(suite.runCount()); - sb.append(", Failures: "); - sb.append(suite.failureCount()); - sb.append(", Errors: "); - sb.append(suite.errorCount()); - sb.append(", Time elapsed: "); - sb.append(nf.format(suite.getRunTime() / 1000.0)); - sb.append(" sec"); - sb.append(newLine); - //sb.append("DEBUG: " + records.size()); - sb.append("======================================================"); - Iterator it = records.iterator(); - - while (it.hasNext()) - { - TestRecord rec = (TestRecord) it.next(); - sb.append(newLine); - sb.append("Test: " + rec.getTestname()).append(newLine); - sb.append("Result: " + rec.getStatusString()).append(newLine); - float diff = rec.getEndTime() - rec.getStartTime(); - sb.append("Start time: " + rec.getStartTime()).append(newLine); - sb.append("End time : " + rec.getEndTime()).append(newLine); - sb.append("Execution time: " + diff/1000).append(newLine); - sb.append("[STDOUT]").append(newLine); - sb.append(rec.getSysout()).append(newLine); - sb.append("[STDERR]").append(newLine); - sb.append(rec.getSyserr()).append(newLine); - - if (rec.isFailure()) - { - sb.append("[EXCEPTION]").append(newLine); - sb.append(JUnitTestRunner.getFilteredTrace(rec.getThrowable())); - sb.append(newLine); - } - sb.append("======================================================"); - } - - - - /* - // append the err and output streams to the log - if (systemOutput != null && systemOutput.length() > 0) { - sb.append("------------- Standard Output ---------------") - .append(newLine) - .append(systemOutput) - .append("------------- ---------------- ---------------") - .append(newLine); - } - - if (systemError != null && systemError.length() > 0) { - sb.append("------------- Standard Error -----------------") - .append(newLine) - .append(systemError) - .append("------------- ---------------- ---------------") - .append(newLine); - } - - sb.append(newLine); - */ - if (out != null) { - try { - out.write(sb.toString().getBytes()); - wri.close(); - //out.write(inner.toString().getBytes()); - out.flush(); - } catch (IOException ioex) { - throw new BuildException("Unable to write output", ioex); - } finally { - if (out != System.out && out != System.err) { - try { - out.close(); - } catch (IOException e) { - // ignore - } - } - } - } - - } - - /** - * Interface TestListener. - * - *

          A new Test is started. - */ - public void startTest(Test t) { - // Lets start the capture - System.out.flush(); - System.err.flush(); - - _out = System.out; - _err = System.err; - bOut.reset(); - bErr.reset(); - System.setOut(new PrintStream(bOut)); - System.setErr(new PrintStream(bErr)); - - // Store the previous record - - testRecord = new TestRecord(t.toString()); - testRecord.setStartTime(System.currentTimeMillis()); - testStarts.put(t, new Long(System.currentTimeMillis())); - failed.put(t, Boolean.FALSE); - - } - - /** - * Interface TestListener. - * - *

          A Test is finished. - */ - public void endTest(Test test) { - long endTime = System.currentTimeMillis(); - - System.out.flush(); - System.err.flush(); - // Update the test record - testRecord.setSysout(bOut.toString()); - testRecord.setSyserr(bErr.toString()); - testRecord.setEndTime(endTime); - // If the test did not fail, record it as a success - if (!testRecord.isFailure()) - testRecord.setStatus(TEST_SUCCESS); - - // Add it to the set - records.add(testRecord); - - System.setOut(_out); - System.setErr(_err); - } - - /** - * Interface TestListener for JUnit > 3.4. - * - *

          A Test failed. - */ - public void addFailure(Test test, AssertionFailedError t) { - //addFailure(test, (Throwable) t); - testRecord.setStatus(TEST_FAILURE); - testRecord.setThrowable(t); - // Record end time now.. - } - - /** - * Interface TestListener. - * - *

          An error occured while running the test. - */ - public void addError(Test test, Throwable t) { - testRecord.setStatus(TEST_ERROR); - testRecord.setThrowable(t); - } - - /** - * Utility class to record per test data like test name, status, start - * and end time, STDOUT, STDERR from text execution etc. - */ - private class TestRecord - { - public TestRecord(String name) - { - setTestname(name); - } - - private String testname; - private String sysout; - private String syserr; - private Throwable t; - private long startTime; - private long endTime; - private int status; - boolean failed = false; - - private String testUnitName; - private String testLogicalName; - - public void setTestname(String name) - { - this.testname = name; - } - - public String getTestname() - { - return testname; - } - - public void setStatus(int status) - { - this.status = status; - if (status == TEST_ERROR || status == TEST_FAILURE) - failed = true; - } - - public int getStatus() - { - return status; - } - - public String getStatusString() - { - return (status == TEST_SUCCESS)?"SUCCESS": - (status == TEST_ERROR)?"ERROR":"FAILURE"; - } - - public boolean isFailure() - { - return failed; - } - - public String getSysout() - { - return sysout; - } - - public void setSysout(String sysout) - { - this.sysout = sysout; - } - - public String getSyserr() - { - return syserr; - } - - public void setSyserr(String syserr) - { - this.syserr = syserr; - } - - public Throwable getThrowable() - { - return t; - } - - public void setThrowable(Throwable t) - { - this.t = t; - } - - public long getStartTime() - { - return startTime; - } - - public void setStartTime(long startTime) - { - this.startTime = startTime; - } - - public long getEndTime() - { - return endTime; - } - - public void setEndTime(long endTime) - { - this.endTime = endTime; - } - - } - - - -} // PlainJUnitResultFormatter diff --git a/test/tools/src/tools/JUnit/TestReportMergeUtility.java b/test/tools/src/tools/JUnit/TestReportMergeUtility.java deleted file mode 100755 index dd0cdfb..0000000 --- a/test/tools/src/tools/JUnit/TestReportMergeUtility.java +++ /dev/null @@ -1,297 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.JUnit; - -import junit.framework.TestCase; -import junit.framework.Assert; - -import noNamespace.TestLogDocument.TestLog; -import noNamespace.TestLogDocument.TestLog.HeaderInfo; -import noNamespace.*; -import noNamespace.TestResultContainerDocument.TestResultContainer; - -import java.util.*; -import java.io.File; -import java.io.IOException; -import java.io.FileOutputStream; -import java.text.SimpleDateFormat; - -import org.apache.xmlbeans.XmlOptions; - -/** - * Utility to merge JUnit Xml log files generated by the custom Xml - * ResultFormatter plugin for Ant's JUnit task. - */ -public class TestReportMergeUtility -{ - public static int INFO_VERBOSE = 3; - public static int INFO_NORMAL = 2; - public static int INFO_SILENT = 1; - - private int _infoLevel = INFO_NORMAL; - private File dir, outFile; - - - public TestReportMergeUtility(File baseDir, File outFile, int infoLevel) - { - this.dir = baseDir; - this.outFile = outFile; - this._infoLevel = infoLevel; - } - - public void info(String message, int infoLevel) - { - if (infoLevel <= this._infoLevel) - System.out.println(message); - } - - public void doMerge() - throws IOException - { - TestLogDocument logDoc = TestLogDocument.Factory.newInstance(); - TestLog log = logDoc.addNewTestLog(); - File[] files = getXmlFiles(dir); - int testCount = 0; - ArrayList results = new ArrayList(); - for (int i = 0; i < files.length; i++) - { - try - { - TestResultContainerDocument doc = - TestResultContainerDocument.Factory.parse(files[i]); - TestResultType[] resArr = - doc.getTestResultContainer().getTestResultArray(); - for (int j = 0; j < resArr.length; j++) - { - log.addNewTestResult(); - log.setTestResultArray(testCount++, resArr[j]); - } - info("Processed: " + files[i].getAbsolutePath(), INFO_VERBOSE); - } - catch (org.apache.xmlbeans.XmlException xe) - { - // Possible parse error - info("Could not process " + files[i].getAbsolutePath(), INFO_NORMAL); - info(xe.getMessage(), INFO_NORMAL); - } - } - // Populate the attributes for test-log - - // testtype - String testtype = System.getProperty("TESTTYPE", "AUTO"); - if (testtype.equalsIgnoreCase("AUTO")) - log.setTesttype(TestLog.Testtype.AUTOMATED); - else - log.setTesttype(TestLog.Testtype.MANUAL); - - // runid - String dateFormatStr = "_yy_MMM_dd_HH_mm_ss_SS"; - String dateStr = new SimpleDateFormat(dateFormatStr).format(new java.util.Date()); - String defRunId = System.getProperty("user.name").toUpperCase() + dateStr; - String runId = System.getProperty("RUNID", defRunId); - log.setRunid(runId); - - // hostname - String hostname; - try - { - hostname = java.net.InetAddress.getLocalHost().getHostName(); - } catch (Exception e) - { - // Ignore.. not critical - hostname = "UNKNOWN_HOST"; - info("Could not get Hostname. Using UNKNOWN_HOST", INFO_VERBOSE); - } - log.setHostname(hostname); - - // TODO: set Defaults/check sysprop for other attributes - - // Add element - EnvironmentType env = log.addNewEnvironment(); - Map envMap = new HashMap(); - envMap.put("JVM_NAME", System.getProperty("java.vm.name")); - envMap.put("JVM_VENDOR", System.getProperty("java.vm.vendor")); - envMap.put("JVM_VERSION", System.getProperty("java.vm.version")); - envMap.put("OS", System.getProperty("os.name")); - String defFreq = "checkin"; - envMap.put("Frequency", System.getProperty("test.run.frequency", defFreq)); - - Iterator itr = envMap.keySet().iterator(); - int envCount = 0; - while (itr.hasNext()) - { - EnvironmentType.EnvAttribute envAttr = env.addNewEnvAttribute(); - String name = (String) itr.next(); - String value = (String) envMap.get(name); - envAttr.setValue(value); - envAttr.setName(name); - } - - // Add element - HeaderInfo hdrInfo = log.addNewHeaderInfo(); - hdrInfo.setResultcount(Integer.toString(testCount)); - hdrInfo.setChecksum(Integer.toString(testCount)); - hdrInfo.setExecdate(log.getTestResultArray(0).getExectime()); - hdrInfo.setExecaccount(System.getProperty("user.name")); - - XmlOptions opts = new XmlOptions().setSavePrettyPrint(); - - // Write it out the outfile - FileOutputStream fos = null; - try - { - outFile.delete(); - fos = new FileOutputStream(outFile); - fos.write(logDoc.xmlText(opts).getBytes()); - info("Log files merged to " + outFile.getAbsolutePath(), INFO_NORMAL); - } - catch(IOException ioe) - { - info("Could not write to outfile file: " + outFile.getAbsolutePath(), - INFO_NORMAL); - info(ioe.getMessage(), INFO_NORMAL); - } - finally - { - if (fos != null) - fos.close(); - } - - } - - public File[] getXmlFiles(File dir) - throws IOException - { - if (dir.isFile() || !dir.exists()) - throw new IOException("Not a directory: " + dir.getAbsolutePath()); - - return dir.listFiles(new XmlFileFilter()); - } - - - public class XmlFileFilter implements java.io.FileFilter - { - public boolean accept(File pathname) - { - if (pathname == null) - return false; - String filename = pathname.getAbsolutePath(); - int index = filename.lastIndexOf("."); - if (filename.substring(index+1).equalsIgnoreCase("xml")) - return true; - return false; - } - } - - ////////////////////////////////////////////////////////////////// - // Main - public static void main(String args[]) - throws Exception - { - int level = INFO_NORMAL; // Default: Normal - File baseDir = null; - File outFile = null; - // Process the arguments - for (int i = 0; i < args.length; i++) - { - String arg = args[i]; - if (arg.charAt(0) == '-') - { - if (arg.equals("-silent")) - level = INFO_SILENT; // level: Silent - else if (arg.equals("-normal")) - level = INFO_NORMAL; // level: Normal - else if (arg.equals("-verbose")) - level = INFO_VERBOSE; // level: Verbose - continue; - } - - int index = arg.indexOf('='); - if (index == -1) - continue; // Not a valid argument.. ignore. - if (arg.substring(0, index).equals("dir")) - { - baseDir = new File(arg.substring(index+1)); - continue; - } - if (arg.substring(0, index).equals("outfile")) - { - outFile = new File(arg.substring(index+1)); - continue; - } - } - - // Verify baseDir and outfile - if (baseDir == null) - usage("Specify the directory containing the log files", true); - if (outFile == null) - usage("Specify the file to write the merged log", true); - - // Check validity of basedir and outfile - if (!baseDir.isDirectory()) - usage("The 'dir' specified is not a directory: " - + baseDir.toString(), - true); - if (outFile.exists() && !outFile.isFile()) - usage("The output file specified is not a valid file: " - + outFile.toString(), - true); - - // Everything looks good. - new TestReportMergeUtility(baseDir, outFile, level).doMerge(); - } - - static void println(Object O) - { - System.out.println(O.toString()); - } - - public static void usage() - { - usage(null, false); - } - - public static void usage(String extraMessage) - { - usage(extraMessage, false); - } - - public static void usage(String extraMessage, boolean exit) - { - if ((extraMessage != null) && (extraMessage.trim().length() > 0)) - println(extraMessage); - - println("*** JUnit Xml Log Merge tool ***"); - println("Usage:"); - println("TestReportMergeUtility dir= outfile= -"); - println(""); - println("Where"); - println(" dir - Directory containing report files to merge"); - println(" All .xml files in this folder will be processed"); - println(" outfile - The file to write out the merged Xml file"); - println(" - - Optional verbosity level"); - println(" silent - No messages will be printed during processing"); - println(" normal - A message will be printed for every time that"); - println(" an error occurs when processing a file"); - println(" verbose - A message will be printed for every file processed"); - - if (exit) - System.exit(1); - } - - - - -} \ No newline at end of file diff --git a/test/tools/src/tools/JUnit/XmlResultFormatter.java b/test/tools/src/tools/JUnit/XmlResultFormatter.java deleted file mode 100755 index 3c97e8f..0000000 --- a/test/tools/src/tools/JUnit/XmlResultFormatter.java +++ /dev/null @@ -1,477 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package tools.JUnit; - -import java.io.*; -import java.text.NumberFormat; -import java.util.*; - -import junit.framework.AssertionFailedError; -import junit.framework.Test; -import junit.framework.TestCase; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.optional.junit.*; -import noNamespace.TestResultContainerDocument; -import noNamespace.TestResultContainerDocument.TestResultContainer; -import noNamespace.TestResultType; -import noNamespace.TestResultType.ExecutionOutput; -import org.apache.xmlbeans.XmlOptions; - - -/** - * Prints plain text output of the test to a specified Writer. - * - * @author Stefan Bodewig - */ - -public class XmlResultFormatter implements JUnitResultFormatter { - - public static int TEST_SUCCESS = 0; - public static int TEST_FAILURE = 1; - public static int TEST_ERROR = 2; - public static int TEST_UNKNOWN = 3; - - // Lets capture STDOUT and STDERR - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ByteArrayOutputStream bErr = new ByteArrayOutputStream(); - - PrintStream _out; - PrintStream _err; - private TestRecord testRecord; - Collection records; - - JUnitTest currentSuite; - /** - * Formatter for timings. - */ - private NumberFormat nf = NumberFormat.getInstance(); - /** - * Timing helper. - */ - private Hashtable testStarts = new Hashtable(); - /** - * Where to write the log to. - */ - private OutputStream out; - /** - * Helper to store intermediate output. - */ - private StringWriter inner; - /** - * Convenience layer on top of {@link #inner inner}. - */ - private PrintWriter wri; - /** - * Suppress endTest if testcase failed. - */ - private Hashtable failed = new Hashtable(); - - private String systemOutput = null; - private String systemError = null; - - public XmlResultFormatter() { - inner = new StringWriter(); - wri = new PrintWriter(inner); - } - - public void setOutput(OutputStream out) { - this.out = out; - } - - public void setSystemOutput(String out) { - // We will be capturing Stdout and Stderr internally so this is - // redundant - //systemOutput = out; - } - - public void setSystemError(String err) { - // We will be capturing Stdout and Stderr internally so this is - // redundant - //systemError = err; - } - - /** - * Signals starting of a Suite of tests - */ - public void startTestSuite(JUnitTest suite) { - currentSuite = suite; - records = new ArrayList(); - } - - /** - * The whole testsuite ended. - */ - public void endTestSuite(JUnitTest suite) throws BuildException - { - // Write out the XmlReport for this suite - writeOutXmlResult(); - } - - /** - * Interface TestListener. - * - *

          A new Test is started. - */ - public void startTest(Test test) { - // Lets start the capture - System.out.flush(); - System.err.flush(); - - _out = System.out; - _err = System.err; - bOut.reset(); - bErr.reset(); - System.setOut(new PrintStream(bOut)); - System.setErr(new PrintStream(bErr)); - - // Discard the previous record - String fullTestName = test.toString(); - testRecord = new TestRecord(fullTestName); - testRecord.setStartTime(System.currentTimeMillis()); - testStarts.put(test, new Long(System.currentTimeMillis())); - failed.put(test, Boolean.FALSE); - - } - - /** - * Interface TestListener. - * - *

          A Test is finished. - */ - public void endTest(Test test) { - long endTime = System.currentTimeMillis(); - - System.out.flush(); - System.err.flush(); - // Update the test record - testRecord.setSysout(bOut.toString()); - testRecord.setSyserr(bErr.toString()); - testRecord.setEndTime(endTime); - - // this is a little hack for our reporting.. - // We could be on shaky ground if the behaviour of the JUnit task - // ever changes.. OH Well... - String fullTestName = test.toString(); - // Test-unit is between '(' and ')' - int startindex = fullTestName.indexOf("("); - int lastindex = fullTestName.indexOf(")"); - String testUnit; - if (startindex >= 0 && lastindex > startindex) - testUnit = fullTestName.substring(startindex+1, lastindex); - else - testUnit = fullTestName; - String testMethod = ((TestCase) test).getName(); - // Get the last token from testUnit for the logical name - startindex = testUnit.lastIndexOf("."); - String baseClass = testUnit.substring(startindex+1); - - // update the extra fields of TestRecord - testRecord.setTestUnitName(testUnit); - testRecord.setTestLogicalName(baseClass + "." + testMethod); - - // If the test did not fail, record it as a success - if (!testRecord.isFailure()) - testRecord.setStatus(TEST_SUCCESS); - - // Add it to the set - records.add(testRecord); - // set testRecord to null.. - testRecord = null; - - System.setOut(_out); - System.setErr(_err); - } - - /** - * Interface TestListener for JUnit > 3.4. - * - *

          A Test failed. - */ - public void addFailure(Test test, AssertionFailedError t) { - //addFailure(test, (Throwable) t); - if (testRecord == null) - testRecord = getMissingTestRecord(); - testRecord.setStatus(TEST_FAILURE); - testRecord.setThrowable(t); - // Record end time now.. - } - - /** - * Interface TestListener. - * - *

          An error occured while running the test. - */ - public void addError(Test test, Throwable t) { - if (testRecord == null) - testRecord = getMissingTestRecord(); - testRecord.setStatus(TEST_ERROR); - testRecord.setThrowable(t); - // Special case when test class is missing... - if (t.toString().indexOf("ClassNotFoundException") > -1) - { - records.add(testRecord); - testRecord = null; - } - } - - /** - * Write out the current TestRecord as an Xml - * Ant's JUnit Task gives us a OutputStream to write out too. - */ - private void writeOutXmlResult() - { - // First build the XmlBean - XmlOptions opts = new XmlOptions(); - opts.setSavePrettyPrint(); - - TestResultContainerDocument doc = - TestResultContainerDocument.Factory.newInstance(); - TestResultContainer container = doc.addNewTestResultContainer(); - - Iterator itr = records.iterator(); - int count = 0; - while (itr.hasNext()) - { - TestRecord rec = (TestRecord) itr.next(); - container.addNewTestResult(); - container.setTestResultArray(count++, getTestResultType(rec)); - } - - if (out != null) - { - try { - out.write(doc.xmlText(opts).getBytes()); - out.flush(); - } catch (IOException ioex) { - throw new BuildException("Unable to write output", ioex); - } finally { - if (out != System.out && out != System.err) { - try { - out.close(); - } catch (IOException e) { - // ignore - } - } - } - } - - - } - - /** - * Creates the TestResultDocument and returns the Xml as a string - */ - private TestResultType getTestResultType(TestRecord rec) - { - TestResultType tr = TestResultType.Factory.newInstance(); - // Children of TestResult - TestResultType.TestCase tc = tr.addNewTestCase(); - TestResultType.ExecutionOutput exo = tr.addNewExecutionOutput(); - - // Set the logical test name... 'Class.Methodname' - tr.setLogicalname(rec.getTestLogicalName()); - // Set the test Start time as a String - tr.setExectime(new java.util.Date(rec.getStartTime()).toString()); - String status = rec.getStatusString(); - // Set the test result - if (status.equals("SUCCESS")) - tr.setResult(TestResultType.Result.SUCCESS); - else - tr.setResult(TestResultType.Result.FAILURE); - // Set the test execution time.. in milliseconds - String dur = Long.toString(rec.getEndTime() - rec.getStartTime()); - tr.setDuration(dur); - // Set the completion status.. - tr.setIsdone(TestResultType.Isdone.TRUE); - - // Setup the children elements - // test-case - tc.setTestcasename(rec.getTestLogicalName()); - tc.setTestunit(rec.getTestUnitName()); - // This should ideally be the whole path to the class... - tc.setTestpath(rec.getTestname()); - - // execution-output - // if FAILURE.. set erroname attribute - if (rec.isFailure()) - { - String exp = rec.getThrowable().toString(); - int index = exp.indexOf(":"); - // the above line is very flaky.. - if (index < 0) index = exp.length(); - exo.setErrorname(exp.substring(0, index)); - } - StringBuffer output = new StringBuffer(); - String eol = System.getProperty("line.separator"); - output.append("[STDOUT]").append(eol); - output.append(rec.getSysout()).append(eol); - output.append("[STDERR]").append(eol); - output.append(rec.getSyserr()).append(eol); - if (rec.isFailure()) - { - output.append("[EXCEPTION]").append(eol); - output.append(JUnitTestRunner.getFilteredTrace(rec.getThrowable())); - } - - exo.setOutputDetails(output.toString()); - - return tr; - } - - - /** - * Utility class to record per test data like test name, status, start - * and end time, STDOUT, STDERR from text execution etc. - */ - private class TestRecord - { - public TestRecord(String name) - { - setTestname(name); - } - - private String testname; - private String sysout; - private String syserr; - private Throwable t; - private long startTime; - private long endTime; - private int status; - boolean failed = false; - - private String testUnitName; - private String testLogicalName; - - public void setTestname(String name) - { - this.testname = name; - } - - public String getTestname() - { - return testname; - } - - public void setStatus(int status) - { - this.status = status; - if (status == TEST_ERROR || status == TEST_FAILURE) - failed = true; - } - - public int getStatus() - { - return status; - } - - public String getStatusString() - { - return (status == TEST_SUCCESS)?"SUCCESS": - (status == TEST_ERROR)?"ERROR":"FAILURE"; - } - - public boolean isFailure() - { - return failed; - } - - public String getSysout() - { - return sysout; - } - - public void setSysout(String sysout) - { - this.sysout = sysout; - } - - public String getSyserr() - { - return syserr; - } - - public void setSyserr(String syserr) - { - this.syserr = syserr; - } - - public Throwable getThrowable() - { - return t; - } - - public void setThrowable(Throwable t) - { - this.t = t; - } - - public long getStartTime() - { - return startTime; - } - - public void setStartTime(long startTime) - { - this.startTime = startTime; - } - - public long getEndTime() - { - return endTime; - } - - public void setEndTime(long endTime) - { - this.endTime = endTime; - } - - public String getTestUnitName() - { - return testUnitName; - } - - public void setTestUnitName(String testUnitName) - { - this.testUnitName = testUnitName; - } - - public String getTestLogicalName() - { - return testLogicalName; - } - - public void setTestLogicalName(String testLogicalName) - { - this.testLogicalName = testLogicalName; - } - - } - - private TestRecord getMissingTestRecord() - { - TestRecord tr = new TestRecord("Missing"); - tr.setStartTime(System.currentTimeMillis()); - tr.setEndTime(System.currentTimeMillis()); - tr.setStatus(TEST_ERROR); - tr.setTestLogicalName("Missing"); - tr.setTestUnitName(currentSuite.getName()); - return tr; - } - - -} // PlainJUnitResultFormatter diff --git a/test/tools/src/tools/JUnit/XmlResultFormatterImpl.java b/test/tools/src/tools/JUnit/XmlResultFormatterImpl.java deleted file mode 100755 index 88c2185..0000000 --- a/test/tools/src/tools/JUnit/XmlResultFormatterImpl.java +++ /dev/null @@ -1,551 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.JUnit; - -import java.util.*; - -import java.io.*; - -import java.text.SimpleDateFormat; - - - -import junit.framework.Test; - -import junit.framework.AssertionFailedError; - -import junit.framework.TestCase; - - - -import noNamespace.TestResultContainerDocument.TestResultContainer; - -import noNamespace.*; - -import noNamespace.TestResultType.ExecutionOutput; - -import org.apache.xmlbeans.XmlOptions; - -import tools.io.TeeOutputStream; - -import org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner; - -/** - * Implementation of JUnitXResultFormatter that records JUnit results - * and publishes the result as a XML Document - */ -public class XmlResultFormatterImpl implements JUnitXResultFormatter -{ - public static int TEST_SUCCESS = 0; - public static int TEST_FAILURE = 1; - public static int TEST_ERROR = 2; - public static int TEST_UNKNOWN = 3; - - // Lets capture STDOUT and STDERR - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ByteArrayOutputStream bErr = new ByteArrayOutputStream(); - - TeeOutputStream tOut; - TeeOutputStream tErr; - - PrintStream _out; - PrintStream _err; - - private TestRecord testRecord; - Collection records; - - // By default write to StdOut - OutputStream logOut = System.out; - - // Record Stats - int testCount = 0; - int passCount = 0; - int failCount = 0; - long startTime = 0; - - boolean showOutput = false; - - public void startRun() - { - records = new ArrayList(); - - // Reset stats - testCount = 0; - passCount = 0; - failCount = 0; - startTime = System.currentTimeMillis(); - } - - public void endRun() - { - System.out.println("================================================="); - System.out.println("Tests Ran: " + testCount); - System.out.println("Success: " + passCount); - System.out.println("Failures: " + failCount); - - // Generate log: - System.out.println("Starting Publish: " + System.currentTimeMillis()); - publishResults(); - System.out.println("Finished Publish: " + System.currentTimeMillis()); - } - - public void setOutput(OutputStream out) - { - if (out != null) - logOut = out; - } - - public void showTestOutput(boolean show) - { - showOutput = show; - } - - public void info(Object msg) - { - if (showOutput) - System.out.println(msg); - } - - /* - * Implementation of TestListener - */ - public synchronized void startTest(Test test) - { - String fullTestName = test.toString(); - info("Starting Test: " + fullTestName); - - // Lets start the capture - System.out.flush(); - System.err.flush(); - - _out = System.out; - _err = System.err; - - bOut.reset(); - bErr.reset(); - - // Redirect Stdout & Stderr to both console and our capture stream - if (showOutput) - { - tOut = new TeeOutputStream(_out, bOut); - tErr = new TeeOutputStream(_err, bErr); - System.setOut(new PrintStream(tOut)); - System.setErr(new PrintStream(tErr)); - } - else - { - System.setOut(new PrintStream(bOut)); - System.setErr(new PrintStream(bErr)); - } - - // Discard the previous record - testRecord = new TestRecord(fullTestName); - testRecord.setStartTime(System.currentTimeMillis()); - } - - public synchronized void endTest(Test test) - { - long endTime = System.currentTimeMillis(); - - System.out.flush(); - System.err.flush(); - - // Update the test record - testRecord.setSysout(bOut.toString()); - testRecord.setSyserr(bErr.toString()); - testRecord.setEndTime(endTime); - - // this is a little hack for our reporting.. - // We could be on shaky ground if the behaviour of the JUnit task - // ever changes.. OH Well... - String fullTestName = test.toString(); - - // Test-unit is between '(' and ')' - int startindex = fullTestName.indexOf("("); - int lastindex = fullTestName.indexOf(")"); - - String testUnit; - if (startindex >= 0 && lastindex > startindex) - testUnit = fullTestName.substring(startindex+1, lastindex); - else - testUnit = fullTestName; - - String testMethod = ((TestCase) test).getName(); - - // Get the last token from testUnit for the logical name - startindex = testUnit.lastIndexOf("."); - String baseClass = testUnit.substring(startindex+1); - - // update the extra fields of TestRecord - testRecord.setTestUnitName(testUnit); - testRecord.setTestLogicalName(baseClass + "." + testMethod); - - // If the test did not fail, record it as a success - if (!testRecord.isFailure()) - { - testRecord.setStatus(TEST_SUCCESS); - passCount++; - } - else - failCount++; - - testCount++; - - // Add it to the set - records.add(testRecord); - - // set testRecord to null.. - // Restore STDOUT and STDERR - System.setOut(_out); - System.setErr(_err); - - info("Finished Test: " + fullTestName + " " - + testRecord.getStatusString() + "\n"); - - // Reset TestRecord - testRecord = null; - } - - public synchronized void addError(final Test test, final Throwable t) - { - if (testRecord == null) - testRecord = getMissingTestRecord(); - - testRecord.setStatus(TEST_ERROR); - testRecord.setThrowable(t); - - // Special case when test class is missing... - if (t.toString().indexOf("ClassNotFoundException") > -1) - { - records.add(testRecord); - testRecord = null; - } - } - - public synchronized void addFailure(final Test test, final AssertionFailedError t) - { - if (testRecord == null) - testRecord = getMissingTestRecord(); - - testRecord.setStatus(TEST_FAILURE); - testRecord.setThrowable(t); - } - - /** - * Utility class to record per test data like test name, status, start - * and end time, STDOUT, STDERR from text execution etc. - */ - private class TestRecord - { - public TestRecord(String name) - { - setTestname(name); - } - - private String testname; - private String sysout; - private String syserr; - - private Throwable t; - - private long startTime; - private long endTime; - - private int status; - boolean failed = false; - - private String testUnitName; - private String testLogicalName; - - public void setTestname(String name) - { - this.testname = name; - } - - public String getTestname() - { - return testname; - } - - public void setStatus(int status) - { - this.status = status; - - if (status == TEST_ERROR || status == TEST_FAILURE) - failed = true; - } - - public int getStatus() - { - return status; - } - - public String getStatusString() - { - return (status == TEST_SUCCESS)?"SUCCESS": - (status == TEST_ERROR)?"ERROR":"FAILURE"; - } - - public boolean isFailure() - { - return failed; - } - - public String getSysout() - { - return sysout; - } - - public void setSysout(String sysout) - { - this.sysout = sysout; - } - - public String getSyserr() - { - return syserr; - } - - public void setSyserr(String syserr) - { - this.syserr = syserr; - } - - public Throwable getThrowable() - { - return t; - } - - public void setThrowable(Throwable t) - { - this.t = t; - } - - public long getStartTime() - { - return startTime; - } - - public void setStartTime(long startTime) - { - this.startTime = startTime; - } - - public long getEndTime() - { - return endTime; - } - - public void setEndTime(long endTime) - { - this.endTime = endTime; - } - - public String getTestUnitName() - { - return testUnitName; - } - - public void setTestUnitName(String testUnitName) - { - this.testUnitName = testUnitName; - } - - public String getTestLogicalName() - { - return testLogicalName; - } - - public void setTestLogicalName(String testLogicalName) - { - this.testLogicalName = testLogicalName; - } - - } - - private TestRecord getMissingTestRecord() - { - TestRecord tr = new TestRecord("Missing"); - tr.setStartTime(System.currentTimeMillis()); - tr.setEndTime(System.currentTimeMillis()); - tr.setStatus(TEST_ERROR); - tr.setTestLogicalName("Missing"); - tr.setTestUnitName("Missing"); - return tr; - } - - public void publishResults() - { - TestLogDocument logDoc = TestLogDocument.Factory.newInstance(); - TestLogDocument.TestLog log = logDoc.addNewTestLog(); - - // Populate the attributes for test-log - // testtype - String testtype = System.getProperty("TESTTYPE", "AUTO"); - - if (testtype.equalsIgnoreCase("AUTO")) - log.setTesttype(TestLogDocument.TestLog.Testtype.AUTOMATED); - else - log.setTesttype(TestLogDocument.TestLog.Testtype.MANUAL); - - // runid - String dateFormatStr = "_yy_MMM_dd_HH_mm_ss_SS"; - String dateStr = new SimpleDateFormat(dateFormatStr).format(new java.util.Date(startTime)); - String defRunId = System.getProperty("user.name").toUpperCase() + dateStr; - String runId = System.getProperty("RUNID", defRunId); - log.setRunid(runId); - - // hostname - String hostname; - - try - { - hostname = java.net.InetAddress.getLocalHost().getHostName(); - } catch (Exception e) - { - // Ignore.. not critical - hostname = "UNKNOWN_HOST"; - } - - log.setHostname(hostname); - - // TODO: set Defaults/check sysprop for other attributes - - // Add element - EnvironmentType env = log.addNewEnvironment(); - Map envMap = new HashMap(); - envMap.put("JVM_NAME", System.getProperty("java.vm.name")); - envMap.put("JVM_VENDOR", System.getProperty("java.vm.vendor")); - envMap.put("JVM_VERSION", System.getProperty("java.vm.version")); - envMap.put("OS", System.getProperty("os.name")); - String defFreq = "checkin"; - envMap.put("Frequency", System.getProperty("test.run.frequency", defFreq)); - - Iterator itr = envMap.keySet().iterator(); - - int envCount = 0; - while (itr.hasNext()) - { - EnvironmentType.EnvAttribute envAttr = env.addNewEnvAttribute(); - String name = (String) itr.next(); - String value = (String) envMap.get(name); - envAttr.setValue(value); - envAttr.setName(name); - } - - // Add element - TestLogDocument.TestLog.HeaderInfo hdrInfo = log.addNewHeaderInfo(); - hdrInfo.setResultcount(Integer.toString(testCount)); - hdrInfo.setChecksum(Integer.toString(testCount)); - hdrInfo.setExecdate(new java.util.Date(startTime).toString()); - hdrInfo.setExecaccount(System.getProperty("user.name")); - - // Add test-results - Iterator rItr = records.iterator(); - - while (rItr.hasNext()) - { - TestResultType tr = log.addNewTestResult(); - tr.set(getTestResultType((TestRecord) rItr.next())); - } - - // Publish it to the outputStream - XmlOptions opts = new XmlOptions().setSavePrettyPrint(); - try - { - logOut.write(logDoc.xmlText(opts).getBytes()); - } catch (IOException ioe) - { - System.out.println("XmlResultFormatter: Unable to publish results"); - System.out.println(ioe.toString()); - } - - } - - /** - * Creates the TestResultDocument and returns the Xml - */ - private TestResultType getTestResultType(TestRecord rec) - { - TestResultType tr = TestResultType.Factory.newInstance(); - - // Children of TestResult - TestResultType.TestCase tc = tr.addNewTestCase(); - TestResultType.ExecutionOutput exo = tr.addNewExecutionOutput(); - - // Set the logical test name... 'Class.Methodname' - tr.setLogicalname(rec.getTestLogicalName()); - - // Set the test Start time as a String - tr.setExectime(new java.util.Date(rec.getStartTime()).toString()); - - String status = rec.getStatusString(); - - // Set the test result - if (status.equals("SUCCESS")) - tr.setResult(TestResultType.Result.SUCCESS); - else if (status.equals("FAILURE")) - tr.setResult(TestResultType.Result.FAILURE); - else - tr.setResult(TestResultType.Result.ABORT); - - // Set the test execution time.. in milliseconds - String dur = java.lang.Long.toString(rec.getEndTime() - rec.getStartTime()); - tr.setDuration(dur); - - // Set the completion status.. - tr.setIsdone(TestResultType.Isdone.TRUE); - - // Setup the children elements - // test-case - tc.setTestcasename(rec.getTestLogicalName()); - tc.setTestunit(rec.getTestUnitName()); - - // This should ideally be the whole path to the class... - tc.setTestpath(rec.getTestname()); - - // execution-output - // if FAILURE.. set erroname attribute - if (rec.isFailure()) - { - String exp = rec.getThrowable().toString(); - int index = exp.indexOf(":"); - - // the above line is very flaky.. - if (index < 0) index = exp.length(); - - exo.setErrorname(exp.substring(0, index)); - } - - StringBuffer output = new StringBuffer(); - String eol = System.getProperty("line.separator"); - output.append("[STDOUT]").append(eol); - output.append(rec.getSysout()).append(eol); - output.append("[STDERR]").append(eol); - output.append(rec.getSyserr()).append(eol); - - if (rec.isFailure()) - { - output.append("[EXCEPTION]").append(eol); - output.append(JUnitTestRunner.getFilteredTrace(rec.getThrowable())); - } - - exo.setOutputDetails(output.toString()); - - return tr; - } - -} - diff --git a/test/tools/src/tools/ant/BuildFileTest.java b/test/tools/src/tools/ant/BuildFileTest.java deleted file mode 100755 index c7ad15f..0000000 --- a/test/tools/src/tools/ant/BuildFileTest.java +++ /dev/null @@ -1,486 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2001-2002 The Apache Software Foundation. All rights - * reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowlegement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "Ant" and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package tools.ant; - -import junit.framework.*; -import org.apache.tools.ant.*; -import java.io.*; -import java.net.URL; - -/** - * A BuildFileTest is a TestCase which executes targets from an Ant buildfile - * for testing. - * - * This class provides a number of utility methods for particular build file - * tests which extend this class. - * - * @author Nico Seessle - * @author Conor MacNeill - */ -public abstract class BuildFileTest extends TestCase { - - protected Project project; - - private StringBuffer logBuffer; - private StringBuffer fullLogBuffer; - private StringBuffer outBuffer; - private StringBuffer errBuffer; - private BuildException buildException; - - /** - * Constructor for the BuildFileTest object - * - *@param name string to pass up to TestCase constructor - */ - public BuildFileTest(String name) { - super(name); - } - - /** - * run a target, expect for any build exception - * - *@param target target to run - *@param cause information string to reader of report - */ - protected void expectBuildException(String target, String cause) { - expectSpecificBuildException(target, cause, null); - } - - /** - * Assert that only the given message has been logged with a - * priority >= INFO when running the given target. - */ - protected void expectLog(String target, String log) { - executeTarget(target); - String realLog = getLog(); - assertEquals(log, realLog); - } - - /** - * Assert that the given message has been logged with a priority - * >= INFO when running the given target. - */ - protected void expectLogContaining(String target, String log) { - executeTarget(target); - String realLog = getLog(); - assertTrue("expecting log to contain \""+log+"\" log was \"" - + realLog + "\"", - realLog.indexOf(log) >= 0); - } - - /** - * Gets the log the BuildFileTest object. - * only valid if configureProject() has - * been called. - * @pre logBuffer!=null - * @return The log value - */ - protected String getLog() { - return logBuffer.toString(); - } - - /** - * Assert that the given message has been logged with a priority - * >= DEBUG when running the given target. - */ - protected void expectDebuglog(String target, String log) { - executeTarget(target); - String realLog = getFullLog(); - assertEquals(log, realLog); - } - - /** - * Gets the log the BuildFileTest object. - * only valid if configureProject() has - * been called. - * @pre fullLogBuffer!=null - * @return The log value - */ - protected String getFullLog() { - return fullLogBuffer.toString(); - } - - /** - * execute the target, verify output matches expectations - * - *@param target target to execute - *@param output output to look for - */ - - protected void expectOutput(String target, String output) { - executeTarget(target); - String realOutput = getOutput(); - assertEquals(output, realOutput); - } - - /** - * execute the target, verify output matches expectations - * and that we got the named error at the end - *@param target target to execute - *@param output output to look for - *@param error Description of Parameter - */ - - protected void expectOutputAndError(String target, String output, String error) { - executeTarget(target); - String realOutput = getOutput(); - assertEquals(output, realOutput); - String realError = getError(); - assertEquals(error, realError); - } - - protected String getOutput() { - return cleanBuffer(outBuffer); - } - - protected String getError() { - return cleanBuffer(errBuffer); - } - - protected BuildException getBuildException() { - return buildException; - } - - private String cleanBuffer(StringBuffer buffer) { - StringBuffer cleanedBuffer = new StringBuffer(); - boolean cr = false; - for (int i = 0; i < buffer.length(); i++) { - char ch = buffer.charAt(i); - if (ch == '\r') { - cr = true; - continue; - } - - if (!cr) { - cleanedBuffer.append(ch); - } else { - if (ch == '\n') { - cleanedBuffer.append(ch); - } else { - cleanedBuffer.append('\r').append(ch); - } - } - } - return cleanedBuffer.toString(); - } - - /** - * set up to run the named project - * - * @param filename name of project file to run - */ - protected void configureProject(String filename) throws BuildException { - logBuffer = new StringBuffer(); - fullLogBuffer = new StringBuffer(); - project = new Project(); - project.init(); - project.setUserProperty( "ant.file" , new File(filename).getAbsolutePath() ); - project.addBuildListener(new AntTestListener()); - //ProjectHelper.configureProject(project, new File(filename)); - ProjectHelper.getProjectHelper().parse(project, new File(filename)); - } - - /** - * execute a target we have set up - * @pre configureProject has been called - * @param targetName target to run - */ - protected void executeTarget(String targetName) { - PrintStream sysOut = System.out; - PrintStream sysErr = System.err; - try { - sysOut.flush(); - sysErr.flush(); - outBuffer = new StringBuffer(); - PrintStream out = new PrintStream(new AntOutputStream()); - System.setOut(out); - errBuffer = new StringBuffer(); - PrintStream err = new PrintStream(new AntOutputStream()); - System.setErr(err); - logBuffer = new StringBuffer(); - fullLogBuffer = new StringBuffer(); - buildException = null; - project.executeTarget(targetName); - } finally { - System.setOut(sysOut); - System.setErr(sysErr); - // rajus: 2004/04/07 - System.out.println("STDOUT+STDERR:\n" + getOutput() + getError()); - System.out.println("END STDOUT+STDERR:"); - } - - } - - /** - * Get the project which has been configured for a test. - * - * @return the Project instance for this test. - */ - protected Project getProject() { - return project; - } - - /** - * get the directory of the project - * @return the base dir of the project - */ - protected File getProjectDir() { - return project.getBaseDir(); - } - - /** - * run a target, wait for a build exception - * - *@param target target to run - *@param cause information string to reader of report - *@param msg the message value of the build exception we are waiting for - set to null for any build exception to be valid - */ - protected void expectSpecificBuildException(String target, String cause, String msg) { - try { - executeTarget(target); - } catch (org.apache.tools.ant.BuildException ex) { - buildException = ex; - if ((null != msg) && (!ex.getMessage().equals(msg))) { - fail("Should throw BuildException because '" + cause - + "' with message '" + msg - + "' (actual message '" + ex.getMessage() + "' instead)"); - } - return; - } - fail("Should throw BuildException because: " + cause); - } - - /** - * run a target, expect an exception string - * containing the substring we look for (case sensitive match) - * - *@param target target to run - *@param cause information string to reader of report - *@param msg the message value of the build exception we are waiting for - *@param contains substring of the build exception to look for - */ - protected void expectBuildExceptionContaining(String target, String cause, String contains) { - try { - executeTarget(target); - } catch (org.apache.tools.ant.BuildException ex) { - buildException = ex; - if ((null != contains) && (ex.getMessage().indexOf(contains) == -1)) { - fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)"); - } - return; - } - fail("Should throw BuildException because: " + cause); - } - - - /** - * call a target, verify property is as expected - * - * @param target build file target - * @param property property name - * @param value expected value - */ - - protected void expectPropertySet(String target, String property, String value) { - executeTarget(target); - assertPropertyEquals(property, value); - } - - /** - * assert that a property equals a value; comparison is case sensitive. - * @param property property name - * @param value expected value - */ - protected void assertPropertyEquals(String property, String value) { - String result = project.getProperty(property); - assertEquals("property " + property,value,result); - } - - /** - * assert that a property equals "true" - * @param property property name - */ - protected void assertPropertySet(String property) { - assertPropertyEquals(property, "true"); - } - - /** - * assert that a property is null - * @param property property name - */ - protected void assertPropertyUnset(String property) { - assertPropertyEquals(property, null); - } - - - /** - * call a target, verify named property is "true". - * - * @param target build file target - * @param property property name - */ - protected void expectPropertySet(String target, String property) { - expectPropertySet(target, property, "true"); - } - - - /** - * call a target, verify property is null - * @param target build file target - * @param property property name - */ - protected void expectPropertyUnset(String target, String property) { - expectPropertySet(target, property, null); - } - - /** - * Retrieve a resource from the caller classloader to avoid - * assuming a vm working directory. The resource path must be - * relative to the package name or absolute from the root path. - * @param resource the resource to retrieve its url. - * @throws AssertionFailureException if resource is not found. - */ - protected URL getResource(String resource){ - URL url = getClass().getResource(resource); - assertNotNull("Could not find resource :" + resource, url); - return url; - } - - /** - * an output stream which saves stuff to our buffer. - */ - private class AntOutputStream extends java.io.OutputStream { - public void write(int b) { - outBuffer.append((char)b); - } - } - - /** - * our own personal build listener - */ - private class AntTestListener implements BuildListener { - /** - * Fired before any targets are started. - */ - public void buildStarted(BuildEvent event) { - } - - /** - * Fired after the last target has finished. This event - * will still be thrown if an error occured during the build. - * - * @see BuildEvent#getException() - */ - public void buildFinished(BuildEvent event) { - } - - /** - * Fired when a target is started. - * - * @see BuildEvent#getTarget() - */ - public void targetStarted(BuildEvent event) { - //System.out.println("targetStarted " + event.getTarget().getName()); - } - - /** - * Fired when a target has finished. This event will - * still be thrown if an error occured during the build. - * - * @see BuildEvent#getException() - */ - public void targetFinished(BuildEvent event) { - //System.out.println("targetFinished " + event.getTarget().getName()); - } - - /** - * Fired when a task is started. - * - * @see BuildEvent#getTask() - */ - public void taskStarted(BuildEvent event) { - //System.out.println("taskStarted " + event.getTask().getTaskName()); - } - - /** - * Fired when a task has finished. This event will still - * be throw if an error occured during the build. - * - * @see BuildEvent#getException() - */ - public void taskFinished(BuildEvent event) { - //System.out.println("taskFinished " + event.getTask().getTaskName()); - } - - /** - * Fired whenever a message is logged. - * - * @see BuildEvent#getMessage() - * @see BuildEvent#getPriority() - */ - public void messageLogged(BuildEvent event) { - if (event.getPriority() == Project.MSG_INFO || - event.getPriority() == Project.MSG_WARN || - event.getPriority() == Project.MSG_ERR) { - logBuffer.append(event.getMessage()); - } - fullLogBuffer.append(event.getMessage()); - - } - } - - -} diff --git a/test/tools/src/tools/io/TeeOutputStream.java b/test/tools/src/tools/io/TeeOutputStream.java deleted file mode 100755 index 5c2c6f3..0000000 --- a/test/tools/src/tools/io/TeeOutputStream.java +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.io; - -import java.io.OutputStream; - -public class TeeOutputStream extends OutputStream -{ - OutputStream out1; - OutputStream out2; - - public TeeOutputStream(OutputStream out1, OutputStream out2) - { - this.out1 = out1; - this.out2 = out2; - } - - // Override methods of OutputStream - public void close() - throws java.io.IOException - { - out1.close(); - out2.close(); - } - - public void flush() - throws java.io.IOException - { - out1.flush(); - out2.flush(); - } - - // Implementation of Outputstream's abstract method - public void write(int b) - throws java.io.IOException - { - out1.write(b); - out2.write(b); - } - -} diff --git a/test/tools/src/tools/util/ClassCompare.java b/test/tools/src/tools/util/ClassCompare.java deleted file mode 100755 index 0e2015c..0000000 --- a/test/tools/src/tools/util/ClassCompare.java +++ /dev/null @@ -1,57 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.lang.reflect.Method; -import java.lang.reflect.Field; - -/** - * Compare two classes based on methods and fields - */ -public class ClassCompare { - - public String compareClass(Class actual, Class expected) throws Exception { - Method[] actualMethods = actual.getMethods(); - Method[] expectedMethods = expected.getMethods(); - Field[] actualField = actual.getFields(); - Field[] bField = expected.getFields(); - - if (actual.getName() != expected.getName()) - throw new Exception("Class Names were not equal:\n" + - "Actual: " + actual.getName() + "\n" + - "Expected: " + expected.getName()); - - - return null; - } - - public String compareMethods(Method[] actual, Method[] expected) throws Exception { - if (actual.length != expected.length) - throw new Exception("Method Count was not equal"); - - //for (int i=0; i < actual.length) - - - return null; - } - - public String compareFields(Field[] actual, Field[] expected) throws Exception { - - - return null; - } - - -} diff --git a/test/tools/src/tools/util/ComparisonError.java b/test/tools/src/tools/util/ComparisonError.java deleted file mode 100755 index 4daa67f..0000000 --- a/test/tools/src/tools/util/ComparisonError.java +++ /dev/null @@ -1,26 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -public class ComparisonError extends junit.framework.AssertionFailedError -{ - public ComparisonError() { - super(); - } - - public ComparisonError(String msg) { - super(msg); - } -} diff --git a/test/tools/src/tools/util/Diff.java b/test/tools/src/tools/util/Diff.java deleted file mode 100755 index 84cf978..0000000 --- a/test/tools/src/tools/util/Diff.java +++ /dev/null @@ -1,853 +0,0 @@ -package tools.util; - -// Diff -- text file difference utility. -// See full docu-comment at beginning of Diff class. - -// $Id$ - -import java.io.*; -import java.util.Vector; - -/** - * This is the info kept per-file. - */ -class fileInfo -{ - - static final int MAXLINECOUNT = 20000; - - //DataInputStream file; /* File handle that is open for read. */ - File file; - public int maxLine; /* After input done, # lines in file. */ - node symbol[]; /* The symtab handle of each line. */ - int other[]; /* Map of line# to line# in other file */ - /* ( -1 means don't-know ). */ - /* Allocated AFTER the lines are read. */ - - /** - * Normal constructor with one filename - * Tests whether file actually exists - */ - fileInfo(String filename) - { - symbol = new node[MAXLINECOUNT + 2]; - other = null; // allocated later! - file = new File(filename); - } - - // This is done late, to be same size as # lines in input file. - void alloc() - { - other = new int[symbol.length + 2]; - } -} - -; - -/** - * diff Text file difference utility. - * ---- Copyright 1987, 1989 by Donald C. Lindsay, - * School of Computer Science, Carnegie Mellon University. - * Copyright 1982 by Symbionics. - * Use without fee is permitted when not for direct commercial - * advantage, and when credit to the source is given. Other uses - * require specific permission. - * - * Converted from C to Java by Ian F. Darwin, ian@darwinsys.com, January, 1997. - * Copyright 1997, Ian F. Darwin. - * - * Conversion is NOT FULLY TESTED. - * - * USAGE: diff oldfile newfile - * - * This program assumes that "oldfile" and "newfile" are text files. - * The program writes to stdout a description of the changes which would - * transform "oldfile" into "newfile". - * - * The printout is in the form of commands, each followed by a block of - * text. The text is delimited by the commands, which are: - * - * DELETE AT n - * ..deleted lines - * - * INSERT BEFORE n - * ..inserted lines - * - * n MOVED TO BEFORE n - * ..moved lines - * - * n CHANGED FROM - * ..old lines - * CHANGED TO - * ..newer lines - * - * The line numbers all refer to the lines of the oldfile, as they are - * numbered before any commands are applied. - * The text lines are printed as-is, without indentation or prefixing. The - * commands are printed in upper case, with a prefix of ">>>>", so that - * they will stand out. Other schemes may be preferred. - * Files which contain more than MAXLINECOUNT lines cannot be processed. - * This can be fixed by changing "symbol" to a Vector. - * The algorithm is taken from Communications of the ACM, Apr78 (21, 4, 264-), - * "A Technique for Isolating Differences Between Files." - * Ignoring I/O, and ignoring the symbol table, it should take O(N) time. - * This implementation takes fixed space, plus O(U) space for the symbol - * table (where U is the number of unique lines). Methods exist to change - * the fixed space to O(N) space. - * Note that this is not the only interesting file-difference algorithm. In - * general, different algorithms draw different conclusions about the - * changes that have been made to the oldfile. This algorithm is sometimes - * "more right", particularly since it does not consider a block move to be - * an insertion and a (separate) deletion. However, on some files it will be - * "less right". This is a consequence of the fact that files may contain - * many identical lines (particularly if they are program source). Each - * algorithm resolves the ambiguity in its own way, and the resolution - * is never guaranteed to be "right". However, it is often excellent. - * This program is intended to be pedagogic. Specifically, this program was - * the basis of the Literate Programming column which appeared in the - * Communications of the ACM (CACM), in the June 1989 issue (32, 6, - * 740-755). - * By "pedagogic", I do not mean that the program is gracefully worded, or - * that it showcases language features or its algorithm. I also do not mean - * that it is highly accessible to beginners, or that it is intended to be - * read in full, or in a particular order. Rather, this program is an - * example of one professional's style of keeping things organized and - * maintainable. - * The program would be better if the "print" variables were wrapped into - * a struct. In general, grouping related variables in this way improves - * documentation, and adds the ability to pass the group in argument lists. - * This program is a de-engineered version of a program which uses less - * memory and less time. The article points out that the "symbol" arrays - * can be implemented as arrays of pointers to arrays, with dynamic - * allocation of the subarrays. (In C, macros are very useful for hiding - * the two-level accesses.) In Java, a Vector would be used. This allows an - * extremely large value for MAXLINECOUNT, without dedicating fixed arrays. - * (The "other" array can be allocated after the input phase, when the exact - * sizes are known.) The only slow piece of code is the "strcmp" in the tree - * descent: it can be speeded up by keeping a hash in the tree node, and - * only using "strcmp" when two hashes happen to be equal. - * - * Change Log - * ---------- - * 1Jan97 Ian F. Darwin: first working rewrite in Java, based entirely on - * D.C.Lindsay's reasonable C version. - * Changed comments from /***************** to /**, shortened, added - * whitespace, used tabs more, etc. - * 6jul89 D.C.Lindsay, CMU: fixed portability bug. Thanks, Gregg Wonderly. - * Just changed "char ch" to "int ch". - * Also added comment about way to improve code. - * 10jun89 D.C.Lindsay, CMU: posted version created. - * Copyright notice changed to ACM style, and Dept. is now School. - * ACM article referenced in docn. - * 26sep87 D.C.Lindsay, CMU: publication version created. - * Condensed all 1982/83 change log entries. - * Removed all command line options, and supporting code. This - * simplified the input code (no case reduction etc). It also - * simplified the symbol table, which was capable of remembering - * offsets into files (instead of strings), and trusting (!) hash - * values to be unique. - * Removed dynamic allocation of arrays: now fixed static arrays. - * Removed speed optimizations in symtab package. - * Removed string compression/decompression code. - * Recoded to Unix standards from old Lattice/MSDOS standards. - * (This affected only the #include's and the IO.) - * Some renaming of variables, and rewording of comments. - * 1982/83 D.C.Lindsay, Symbionics: created. - * - * @author Ian F. Darwin, Java version - * @version Java version 0.9, 1997 - * @author D. C. Lindsay, C version (1982-1987) - */ -public class Diff -{ - - /** - * block len > any possible real block len - */ - final int UNREAL = Integer.MAX_VALUE; - - /** - * Keeps track of information about file1 and file2 - */ - fileInfo oldinfo, newinfo; - - /** - * blocklen is the info about found blocks. It will be set to 0, except - * at the line#s where blocks start in the old file. At these places it - * will be set to the # of lines in the block. During printout , - * this # will be reset to -1 if the block is printed as a MOVE block - * (because the printout phase will encounter the block twice, but - * must only print it once.) - * The array declarations are to MAXLINECOUNT+2 so that we can have two - * extra lines (pseudolines) at line# 0 and line# MAXLINECOUNT+1 - * (or less). - */ - int blocklen[]; - - /** - * Controls how trailing whitespace lines is handled - */ - boolean trimLines; - - /** - * main - entry point when used standalone. - * NOTE: no routines return error codes or throw any local - * exceptions. Instead, any routine may complain - * to stderr and then exit with error to the system. - */ - public static void main(String argstrings[]) - { - if (argstrings.length != 2) - { - System.err.println("Usage: diff oldfile newfile"); - System.exit(1); - } - Diff d = new Diff(false); - d.doDiff(argstrings[0], argstrings[1]); - return; - } - - /** - * Construct a Diff object. - */ - public Diff(boolean trimLines) - { - this.trimLines = trimLines; - } - - /** - * Construct a Diff object. - */ - public Diff() - { - this.trimLines = false; - } - - /** - * Do one file comparison. Called with both filenames. - */ - public void doDiff(String oldFile, String newFile) - { - println(">>>> Difference of file \"" + oldFile + - "\" and file \"" + newFile + "\".\n"); - oldinfo = new fileInfo(oldFile); - newinfo = new fileInfo(newFile); - /* we don't process until we know both files really do exist. */ - try - { - inputscan(oldinfo); - inputscan(newinfo); - } - catch (IOException e) - { - System.err.println("Read error: " + e); - } - - /* Now that we've read all the lines, allocate some arrays. - */ - blocklen = new int[(oldinfo.maxLine > newinfo.maxLine ? - oldinfo.maxLine : newinfo.maxLine) + 2]; - oldinfo.alloc(); - newinfo.alloc(); - - /* Now do the work, and print the results. */ - transform(); - printout(); - } - - public String compareFiles(String oldFile, String newFile) - throws IOException - { - //println("Diff of \"" + oldFile + "\" and \"" + newFile); - oldinfo = new fileInfo(oldFile); - newinfo = new fileInfo(newFile); - /* we don't process until we know both files really do exist. */ - inputscan(oldinfo); - inputscan(newinfo); - - /* Now that we've read all the lines, allocate some arrays. - */ - blocklen = new int[(oldinfo.maxLine > newinfo.maxLine ? - oldinfo.maxLine : newinfo.maxLine) + 2]; - oldinfo.alloc(); - newinfo.alloc(); - - /* Now do the work, and print the results. */ - transform(); - return printout(); - } - - - /** - * inputscan Reads the file specified by pinfo.file. - * --------- Places the lines of that file in the symbol table. - * Sets pinfo.maxLine to the number of lines found. - */ - void inputscan(fileInfo pinfo) - throws IOException - { - pinfo.maxLine = 0; - - BufferedReader reader = new BufferedReader(new FileReader(pinfo.file)); - Vector v = new Vector(); - - while (true) - { - String s = reader.readLine(); - if (s == null) break; - v.addElement(s); - } - reader.close(); - // Discard all trailing lines that are only whitespaces.. - if (trimLines) - { - int i = v.size(); - while (--i >= 0) - if (Util.isWhiteSpace((String) v.get(i))) - v.removeElementAt(i); - } - - int i = 0; - while (i < v.size()) - storeline((String) v.get(i++), pinfo); - - } - - /** - * storeline Places line into symbol table. - * --------- Expects pinfo.maxLine initted: increments. - * Places symbol table handle in pinfo.ymbol. - * Expects pinfo is either oldinfo or newinfo. - */ - void storeline(String linebuffer, fileInfo pinfo) - { - int linenum = ++pinfo.maxLine; /* note, no line zero */ - if (linenum > fileInfo.MAXLINECOUNT) - { - System.err.println("MAXLINECOUNT exceeded, must stop."); - System.exit(1); - } - pinfo.symbol[linenum] = - node.addSymbol(linebuffer, pinfo == oldinfo, linenum); - } - - /* - * transform - * Analyzes the file differences and leaves its findings in - * the global arrays oldinfo.other, newinfo.other, and blocklen. - * Expects both files in symtab. - * Expects valid "maxLine" and "symbol" in oldinfo and newinfo. - */ - void transform() - { - int oldline, newline; - int oldmax = oldinfo.maxLine + 2; /* Count pseudolines at */ - int newmax = newinfo.maxLine + 2; /* ..front and rear of file */ - - for (oldline = 0; oldline < oldmax; oldline++) - oldinfo.other[oldline] = -1; - for (newline = 0; newline < newmax; newline++) - newinfo.other[newline] = -1; - - scanunique(); /* scan for lines used once in both files */ - scanafter(); /* scan past sure-matches for non-unique blocks */ - scanbefore(); /* scan backwards from sure-matches */ - scanblocks(); /* find the fronts and lengths of blocks */ - } - - /* - * scanunique - * Scans for lines which are used exactly once in each file. - * Expects both files in symtab, and oldinfo and newinfo valid. - * The appropriate "other" array entries are set to the line# in - * the other file. - * Claims pseudo-lines at 0 and XXXinfo.maxLine+1 are unique. - */ - void scanunique() - { - int oldline, newline; - node psymbol; - - for (newline = 1; newline <= newinfo.maxLine; newline++) - { - psymbol = newinfo.symbol[newline]; - if (psymbol.symbolIsUnique()) - { // 1 use in each file - oldline = psymbol.linenum; - newinfo.other[newline] = oldline; // record 1-1 map - oldinfo.other[oldline] = newline; - } - } - newinfo.other[0] = 0; - oldinfo.other[0] = 0; - newinfo.other[newinfo.maxLine + 1] = oldinfo.maxLine + 1; - oldinfo.other[oldinfo.maxLine + 1] = newinfo.maxLine + 1; - } - - /* - * scanafter - * Expects both files in symtab, and oldinfo and newinfo valid. - * Expects the "other" arrays contain positive #s to indicate - * lines that are unique in both files. - * For each such pair of places, scans past in each file. - * Contiguous groups of lines that match non-uniquely are - * taken to be good-enough matches, and so marked in "other". - * Assumes each other[0] is 0. - */ - void scanafter() - { - int oldline, newline; - - for (newline = 0; newline <= newinfo.maxLine; newline++) - { - oldline = newinfo.other[newline]; - if (oldline >= 0) - { /* is unique in old & new */ - for (; ;) - { /* scan after there in both files */ - if (++oldline > oldinfo.maxLine) break; - if (oldinfo.other[oldline] >= 0) break; - if (++newline > newinfo.maxLine) break; - if (newinfo.other[newline] >= 0) break; - - /* oldline & newline exist, and - aren't already matched */ - - if (newinfo.symbol[newline] != - oldinfo.symbol[oldline]) - break; // not same - - newinfo.other[newline] = oldline; // record a match - oldinfo.other[oldline] = newline; - } - } - } - } - - /** - * scanbefore - * As scanafter, except scans towards file fronts. - * Assumes the off-end lines have been marked as a match. - */ - void scanbefore() - { - int oldline, newline; - - for (newline = newinfo.maxLine + 1; newline > 0; newline--) - { - oldline = newinfo.other[newline]; - if (oldline >= 0) - { /* unique in each */ - for (; ;) - { - if (--oldline <= 0) break; - if (oldinfo.other[oldline] >= 0) break; - if (--newline <= 0) break; - if (newinfo.other[newline] >= 0) break; - - /* oldline and newline exist, - and aren't marked yet */ - - if (newinfo.symbol[newline] != - oldinfo.symbol[oldline]) - break; // not same - - newinfo.other[newline] = oldline; // record a match - oldinfo.other[oldline] = newline; - } - } - } - } - - /** - * scanblocks - Finds the beginnings and lengths of blocks of matches. - * Sets the blocklen array (see definition). - * Expects oldinfo valid. - */ - void scanblocks() - { - int oldline, newline; - int oldfront = 0; // line# of front of a block in old, or 0 - int newlast = -1; // newline's value during prev. iteration - - for (oldline = 1; oldline <= oldinfo.maxLine; oldline++) - blocklen[oldline] = 0; - blocklen[oldinfo.maxLine + 1] = UNREAL; // starts a mythical blk - - for (oldline = 1; oldline <= oldinfo.maxLine; oldline++) - { - newline = oldinfo.other[oldline]; - if (newline < 0) - oldfront = 0; /* no match: not in block */ - else - { /* match. */ - if (oldfront == 0) oldfront = oldline; - if (newline != (newlast + 1)) oldfront = oldline; - ++blocklen[oldfront]; - } - newlast = newline; - } - } - - /* The following are global to printout's subsidiary routines */ - // enum{ idle, delete, insert, movenew, moveold, - // same, change } printstatus; - public static final int - idle = 0, delete = 1, insert = 2, movenew = 3, moveold = 4, - same = 5, change = 6; - int printstatus; - boolean anyprinted; - int printoldline, printnewline; // line numbers in old & new file - - /** - * printout - Prints summary to stdout. - * Expects all data structures have been filled out. - */ - String printout() - { - printstatus = idle; - anyprinted = false; - PrintStream _sysout = System.out; - _sysout.flush(); - String ret; - try - { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - System.setOut(new PrintStream(bout)); - for (printoldline = printnewline = 1; ;) - { - if (printoldline > oldinfo.maxLine) - { - newconsume(); - break; - } - if (printnewline > newinfo.maxLine) - { - oldconsume(); - break; - } - if (newinfo.other[printnewline] < 0) - { - if (oldinfo.other[printoldline] < 0) - showchange(); - else - showinsert(); - } else if (oldinfo.other[printoldline] < 0) - showdelete(); - else if (blocklen[printoldline] < 0) - skipold(); - else if (oldinfo.other[printoldline] == printnewline) - showsame(); - else - showmove(); - } - - if (anyprinted) - ret = bout.toString(); - else - ret = null; - } - finally - { - System.setOut(_sysout); - } - - return ret; - } - - /* - * newconsume Part of printout. Have run out of old file. - * Print the rest of the new file, as inserts and/or moves. - */ - void newconsume() - { - for (; ;) - { - if (printnewline > newinfo.maxLine) - break; /* end of file */ - if (newinfo.other[printnewline] < 0) - showinsert(); - else - showmove(); - } - } - - /** - * oldconsume Part of printout. Have run out of new file. - * Process the rest of the old file, printing any - * parts which were deletes or moves. - */ - void oldconsume() - { - for (; ;) - { - if (printoldline > oldinfo.maxLine) - break; /* end of file */ - printnewline = oldinfo.other[printoldline]; - if (printnewline < 0) - showdelete(); - else if (blocklen[printoldline] < 0) - skipold(); - else - showmove(); - } - } - - /** - * showdelete Part of printout. - * Expects printoldline is at a deletion. - */ - void showdelete() - { - if (printstatus != delete) - println(">>>> DELETE AT " + printoldline); - printstatus = delete; - oldinfo.symbol[printoldline].showSymbol(); - anyprinted = true; - printoldline++; - } - - /* - * showinsert Part of printout. - * Expects printnewline is at an insertion. - */ - void showinsert() - { - if (printstatus == change) - println(">>>> CHANGED TO"); - else if (printstatus != insert) - println(">>>> INSERT BEFORE " + printoldline); - printstatus = insert; - newinfo.symbol[printnewline].showSymbol(); - anyprinted = true; - printnewline++; - } - - /** - * showchange Part of printout. - * Expects printnewline is an insertion. - * Expects printoldline is a deletion. - */ - void showchange() - { - if (printstatus != change) - println(">>>> " + printoldline + " CHANGED FROM"); - printstatus = change; - oldinfo.symbol[printoldline].showSymbol(); - anyprinted = true; - printoldline++; - } - - /** - * skipold Part of printout. - * Expects printoldline at start of an old block that has - * already been announced as a move. - * Skips over the old block. - */ - void skipold() - { - printstatus = idle; - for (; ;) - { - if (++printoldline > oldinfo.maxLine) - break; /* end of file */ - if (oldinfo.other[printoldline] < 0) - break; /* end of block */ - if (blocklen[printoldline] != 0) - break; /* start of another */ - } - } - - /** - * skipnew Part of printout. - * Expects printnewline is at start of a new block that has - * already been announced as a move. - * Skips over the new block. - */ - void skipnew() - { - int oldline; - printstatus = idle; - for (; ;) - { - if (++printnewline > newinfo.maxLine) - break; /* end of file */ - oldline = newinfo.other[printnewline]; - if (oldline < 0) - break; /* end of block */ - if (blocklen[oldline] != 0) - break; /* start of another */ - } - } - - /** - * showsame Part of printout. - * Expects printnewline and printoldline at start of - * two blocks that aren't to be displayed. - */ - void showsame() - { - int count; - printstatus = idle; - if (newinfo.other[printnewline] != printoldline) - { - System.err.println("BUG IN LINE REFERENCING"); - System.exit(1); - } - count = blocklen[printoldline]; - printoldline += count; - printnewline += count; - } - - /** - * showmove Part of printout. - * Expects printoldline, printnewline at start of - * two different blocks ( a move was done). - */ - void showmove() - { - int oldblock = blocklen[printoldline]; - int newother = newinfo.other[printnewline]; - int newblock = blocklen[newother]; - - if (newblock < 0) - skipnew(); // already printed. - else if (oldblock >= newblock) - { // assume new's blk moved. - blocklen[newother] = -1; // stamp block as "printed". - println(">>>> " + newother + - " THRU " + (newother + newblock - 1) + - " MOVED TO BEFORE " + printoldline); - for (; newblock > 0; newblock--, printnewline++) - newinfo.symbol[printnewline].showSymbol(); - anyprinted = true; - printstatus = idle; - - } else /* assume old's block moved */ - skipold(); /* target line# not known, display later */ - } - - /** - * Convenience wrapper for println - */ - public void println(String s) - { - System.out.println(s); - } -} - -; // end of main class! - -/** - * Class "node". The symbol table routines in this class all - * understand the symbol table format, which is a binary tree. - * The methods are: addSymbol, symbolIsUnique, showSymbol. - */ -class node -{ /* the tree is made up of these nodes */ - node pleft, pright; - int linenum; - - static final int freshnode = 0, - oldonce = 1, newonce = 2, bothonce = 3, other = 4; - - int /* enum linestates */ linestate; - String line; - - static node panchor = null; /* symtab is a tree hung from this */ - - /** - * Construct a new symbol table node and fill in its fields. - * - * @param string A line of the text file - */ - node(String pline) - { - pleft = pright = null; - linestate = freshnode; - /* linenum field is not always valid */ - line = pline; - } - - /** - * matchsymbol Searches tree for a match to the line. - * - * @param String pline, a line of text - * If node's linestate == freshnode, then created the node. - */ - static node matchsymbol(String pline) - { - int comparison; - node pnode = panchor; - if (panchor == null) return panchor = new node(pline); - for (; ;) - { - comparison = pnode.line.compareTo(pline); - if (comparison == 0) return pnode; /* found */ - - if (comparison < 0) - { - if (pnode.pleft == null) - { - pnode.pleft = new node(pline); - return pnode.pleft; - } - pnode = pnode.pleft; - } - if (comparison > 0) - { - if (pnode.pright == null) - { - pnode.pright = new node(pline); - return pnode.pright; - } - pnode = pnode.pright; - } - } - /* NOTE: There are return stmts, so control does not get here. */ - } - - /** - * addSymbol(String pline) - Saves line into the symbol table. - * Returns a handle to the symtab entry for that unique line. - * If inoldfile nonzero, then linenum is remembered. - */ - static node addSymbol(String pline, boolean inoldfile, int linenum) - { - node pnode; - pnode = matchsymbol(pline); /* find the node in the tree */ - if (pnode.linestate == freshnode) - { - pnode.linestate = inoldfile ? oldonce : newonce; - } else - { - if ((pnode.linestate == oldonce && !inoldfile) || - (pnode.linestate == newonce && inoldfile)) - pnode.linestate = bothonce; - else - pnode.linestate = other; - } - if (inoldfile) pnode.linenum = linenum; - return pnode; - } - - /** - * symbolIsUnique Arg is a ptr previously returned by addSymbol. - * -------------- Returns true if the line was added to the - * symbol table exactly once with inoldfile true, - * and exactly once with inoldfile false. - */ - boolean symbolIsUnique() - { - return (linestate == bothonce); - } - - /** - * showSymbol Prints the line to stdout. - */ - void showSymbol() - { - System.out.println(line); - } -} - diff --git a/test/tools/src/tools/util/JarUtil.java b/test/tools/src/tools/util/JarUtil.java deleted file mode 100755 index 79a93e2..0000000 --- a/test/tools/src/tools/util/JarUtil.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.BufferedReader; -import java.io.*; -import java.net.JarURLConnection; -import java.net.URL; -import java.util.jar.JarFile; -import java.util.jar.JarEntry; - -/** - * A utility class for getting data from jar files - */ -public class JarUtil { - - final static String EOL = System.getProperty("line.separator"); - - /** - * returns an File Object within the given jarFile as a String. jarFile must exist in classpath - * pre: jar containing resource is in the classpath - * - * @param pathToResource - * @return File - */ - public static File getResourceFromJarasFile(String pathToResource) - throws IOException { - - String[] tokens = pathToResource.split("/"); - String fileName = tokens[tokens.length - 1]; - tokens = fileName.split("\\."); - String extension= (tokens.length < 2) ? null:"." + tokens[1]; - String prefix= ( tokens[0].length()<3 ) ? tokens[0]+"abc":tokens[0]; - File temp = File.createTempFile(prefix,extension ); - temp.deleteOnExit(); - PrintWriter pr = null; - try { - pr = new PrintWriter(new FileWriter(temp)); - String content = getResourceFromJar(pathToResource); - pr.write(content); - } - finally { - if (pr != null) pr.close(); - } - return temp; - } - - - /** - * returns an item within the given jarFile as a String. jarFile must exist in classpath - * - * @param pathToResource - * @return String - */ - - public static String getResourceFromJar(String pathToResource) - throws IOException { - - URL url = ClassLoader.getSystemClassLoader().getResource( - pathToResource); - if (url == null) { - throw new FileNotFoundException( - "Resource: " + pathToResource + " was not found "); - } - JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); - JarFile jar = jarConnection.getJarFile(); - if (jar.getJarEntry(pathToResource) == null) { - throw new FileNotFoundException( - "Resource: " + pathToResource + " was not found "); - } - - JarEntry item = jar.getJarEntry(pathToResource); - BufferedReader in = new BufferedReader( - new InputStreamReader(jar.getInputStream(item))); - - StringBuffer stb = new StringBuffer(); - String buffer; - - while (!((buffer = in.readLine()) == null)) { - stb.append(buffer + EOL); - } - return stb.toString(); - } - - /** - * returns an item within the given jarFile as a Stream - * - * @param pathToResource - * @return String - */ - - public static InputStream getResourceFromJarasStream(String pathToResource) - throws IOException { - InputStream resource=ClassLoader.getSystemClassLoader().getResourceAsStream( - pathToResource); - if ( resource==null ){ - throw new IOException(" Resource "+pathToResource+" was not found. " + - "Make sure Jar w/ resource is on classpath"); - } - return resource; - } - - /** - * Returns the classpath entry of a given item on the classpath. The item should be a jarFile reference - * - * @param jarFile - * @return String - * @throws FileNotFoundException - */ - - public static String getFilePath(String jarFile) - throws FileNotFoundException { - String sClassPath = System.getProperty("java.class.path"); - int jarIndex = sClassPath.indexOf(jarFile); - if (jarIndex <= 0) { - throw new FileNotFoundException( - "File: " + jarFile + " was not found on the classpath"); - } - - String P = File.pathSeparator; - String[] pathList = sClassPath.split(P); - for (int i = 0; i < pathList.length; i++) { - if (pathList[i].toLowerCase().endsWith(jarFile.toLowerCase())) { - return pathList[i]; - } - } - throw new FileNotFoundException( - "File: " + jarFile + " was not found when iterating classpath"); - } -} - diff --git a/test/tools/src/tools/util/Log.java b/test/tools/src/tools/util/Log.java deleted file mode 100755 index 1755cdc..0000000 --- a/test/tools/src/tools/util/Log.java +++ /dev/null @@ -1,255 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; - -/** - * Provides some logging utilities. I don't like how log4j is a cascading - * logger so I implemented a simple bitmask logger instead. It wouldn't be - * hard to switch to log4j if we wanted since all the method names are the - * same. - */ -public class Log -{ - /** Turn off all logging. */ - public static final int LEVEL_OFF = 0; - - /** Log {@link #debug(String)} messages. */ - public static final int LEVEL_DEBUG = 2; - - /** Log {@link #info(String)} messages. */ - public static final int LEVEL_INFO = 4; - - /** Log {@link #warn(String)} messages. */ - public static final int LEVEL_WARN = 8; - - /** Log {@link #error(String)} messages. */ - public static final int LEVEL_ERROR = 16; - - /** Log {@link #fatal(String)} messages. */ - public static final int LEVEL_FATAL = 32; - - /** Log all messages regardless of the level. */ - public static final int LEVEL_ALL = 0xffff; - - /** Set to "fatal", "error", and "info" by default. */ - public static final int DEFAULT_LEVEL = - LEVEL_FATAL | LEVEL_ERROR | LEVEL_INFO; - - /** Determines the current logging level. */ - private static int _level = DEFAULT_LEVEL; - - /** Destination of logging. */ - private static PrintStream out = System.out; - - /** Set destination of logging to a file. */ - public static void setOut(String file) - throws java.io.FileNotFoundException - { - if ("-".equals(file)) - setOut(System.out); - else - setOut(new PrintStream(new FileOutputStream(file))); - } - - /** Set destination of logging to a file. */ - public static void setOut(File file) - throws java.io.FileNotFoundException - { - setOut(new PrintStream(new FileOutputStream(file))); - } - - /** Set destination of logging to a stream. */ - public static void setOut(PrintStream out) - { - Log.out = out; - } - - /** Get the output stream. */ - public static PrintStream getOut() - { - return out; - } - - /** - * Set the debugging level. - */ - public static void setLevel(int level) { - _level = level; - } - - /** - * Set the debugging level. - */ - public static void onLevel(int level) { - _level |= level; - } - - /** - * Set the debugging level. - */ - public static void offLevel(int level) { - _level &= ~level; - } - - /** - * Flip the debugging level. - */ - public static void flipLevel(int level) { - _level ^= level; - } - - /** - * Set the debugging level. - */ - public static void setLevel(String level) { - level = level.toLowerCase(); - - if ("fatal".equals(level)) { - _level = LEVEL_FATAL; - } - else if ("error".equals(level)) { - _level = LEVEL_ERROR; - } - else if ("warn".equals(level)) { - _level = LEVEL_WARN; - } - else if ("info".equals(level)) { - _level = LEVEL_INFO; - } - else if ("debug".equals(level)) { - _level = LEVEL_DEBUG; - } - else if ("all".equals(level)) { - _level = LEVEL_ALL; - } - else if ("off".equals(level)) { - _level = LEVEL_OFF; - } - } - - /** - * Set the debugging level. - */ - public static void onLevel(String level) { - level = level.toLowerCase(); - - if ("fatal".equals(level)) { - onLevel(LEVEL_FATAL); - } - else if ("error".equals(level)) { - onLevel(LEVEL_ERROR); - } - else if ("warn".equals(level)) { - onLevel(LEVEL_WARN); - } - else if ("info".equals(level)) { - onLevel(LEVEL_INFO); - } - else if ("debug".equals(level)) { - onLevel(LEVEL_DEBUG); - } - else if ("all".equals(level)) { - _level = LEVEL_ALL; - } - else if ("off".equals(level)) { - _level = LEVEL_OFF; - } - } - - /** - * Set the debugging level. - */ - public static void offLevel(String level) { - level = level.toLowerCase(); - - if ("fatal".equals(level)) { - offLevel(LEVEL_FATAL); - } - else if ("error".equals(level)) { - offLevel(LEVEL_ERROR); - } - else if ("warn".equals(level)) { - offLevel(LEVEL_WARN); - } - else if ("info".equals(level)) { - offLevel(LEVEL_INFO); - } - else if ("debug".equals(level)) { - offLevel(LEVEL_DEBUG); - } - else if ("all".equals(level)) { - _level = LEVEL_OFF; - } - else if ("off".equals(level)) { - _level = LEVEL_ALL; - } - } - - /** - * Get the debugging level. - */ - public static int getLevel() { - return _level; - } - - /** - * Print a message if the level has the {@link #LEVEL_FATAL} bit set. - */ - public static void fatal(String message) - { - if ((LEVEL_FATAL & _level) != 0) - Log.out.println(message); - } - - /** - * Print a message if the level has the {@link #LEVEL_ERROR} bit set. - */ - public static void error(String message) - { - if ((LEVEL_ERROR & _level) != 0) - Log.out.println(message); - } - - /** - * Print a message if the level has the {@link #LEVEL_WARN} bit set. - */ - public static void warn(String message) - { - if ((LEVEL_WARN & _level) != 0) - Log.out.println(message); - } - - /** - * Print a message if the level has the {@link #LEVEL_INFO} bit set. - */ - public static void info(String message) - { - if ((LEVEL_INFO & _level) != 0) - Log.out.println(message); - } - - /** - * Print a message if the level has the {@link #LEVEL_DEBUG} bit set. - */ - public static void debug(String message) - { - if ((LEVEL_DEBUG & _level) != 0) - Log.out.println(message); - } -} diff --git a/test/tools/src/tools/util/ResourceClass.java b/test/tools/src/tools/util/ResourceClass.java deleted file mode 100755 index 6e3c369..0000000 --- a/test/tools/src/tools/util/ResourceClass.java +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.InputStream; -import java.io.IOException; - -/** - * Utility for obtaining a class tail name and last name. These - * are terms I invented and aren't very good: - *

          - *
          Last Name:
          The class name minus the package name part. - *
          Tail Name:
          The class name minus the first package. - *
          - * For example, if a class name is foo.bar.Blee, the last name - * would be Blee, while the tail name would be - * bar.Blee. - */ -public class ResourceClass -{ - Class clazz; - String lastName; - String tailName; - - public ResourceClass(Class clazz) - { - setResourceClass(clazz); - } - - public void setResourceClass(Class clazz) - { - this.clazz = clazz; - - setLastName(); - setTailName(); - } - - private void setTailName() - { - tailName = ResourceUtil.getTailName(clazz); - } - - private void setLastName() - { - lastName = ResourceUtil.getLastName(clazz); - } - - /** - * Get the class name minus the first package name; for the class name - * "foo.bar.Blee", the method returns "bar.Blee". If the class is missing - * any package, the whole class name is returned. - * - * @see ResourceUtil#getTailName(Class) - */ - public String getTailName() - { - return tailName; - } - - /** - * Get the trailing part of the classname; for the class name - * "foo.bar.Blee", the method returns "Blee" - * - * @see ResourceUtil#getLastName(Class) - */ - public String getLastName() - { - return lastName; - } - - public Class getResourceClass() - { - return clazz; - } - - /** - * Get resource from the class directory into a String. Example: - *
          -     * ResourceClass resClass = new ResourceClass(foo.bar.Blee.class);
          -     * String msg = resClass.getResource("file.txt");
          -     * 
          - * will obtain the contents of "foo/bar/Blee/file.txt". - * - * @param resourceName The name of the resource to obtain. - * @return The contents of the named resource. - * @see SoapUtil#getResource(Class clazz, String lastName, - * String resourceName) - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - */ - public String getResource(String resourceName) - throws NullPointerException, IOException - { - if (clazz == null) - throw new NullPointerException(); - - java.io.InputStream is = - this.getResourceAsStream(resourceName); - return Util.read(is); - } - - /** - * Get resource from the class message directory. Example: - *
          -     * ResourceClass resClass = new ResourceClass(foo.bar.Blee.class);
          -     * InputStream is = resClass.getResourceAsStream("file.txt");
          -     * 
          - * will obtain an InputStream to the file named - * "foo/bar/Blee/file.txt". - * - * @param resourceName The name of the resource to obtain. - * @return The InputStream to the named resource. - * @see SoapUtil#getResource(Class clazz, String lastName, - * String resourceName) - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - */ - public InputStream getResourceAsStream(String resourceName) - { - return ResourceUtil.getStream(clazz, lastName, resourceName); - } - -} diff --git a/test/tools/src/tools/util/ResourceUtil.java b/test/tools/src/tools/util/ResourceUtil.java deleted file mode 100755 index 2d9ad7b..0000000 --- a/test/tools/src/tools/util/ResourceUtil.java +++ /dev/null @@ -1,248 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.File; -import java.io.InputStream; - -import java.net.URL; - -/** - * Get a resource as InputStream, File, or URL from the classpath. - */ -public class ResourceUtil -{ - /** - * Get the class name minus the first package name; for the class name - * "foo.bar.Blee", the method returns "bar.Blee". If the class is missing - * any package, the whole class name is returned. - */ - public static String getTailName(Class c) - { - String name = c.getName(); - return name.substring(name.indexOf('.')+1); - } - - /** - * Get the trailing part of the classname; for the class name - * "foo.bar.Blee", the method returns "Blee". - */ - public static String getLastName(Class c) - { - String name = c.getName(); - int i = name.lastIndexOf('.'); - return name.substring(i+1, name.length()); - } - - /** - * Get a URL to a resource on the system classpath. For example: - *
          -     * getURL("xbean/xmlobject/simple/dumb/dumb.xml")
          -     * 
          - * NOTE: This is intended to be used from a junit test since it will throw - * an exception on failure which will be caught by the junit runner. - * - * @throws RuntimeException If no resource is found. - */ - public static URL getURL(String name) - { - URL url = ClassLoader.getSystemResource(name); - if (url == null) - throw new RuntimeException("Resource doesn't exist: " + name); - - return url; - } - - /** - * Get a File to a resource on the system classpath. - * NOTE: This is intended to be used from a junit test since it will throw - * an exception on failure which will be caught by the junit runner. - * - * @throws RuntimeException If no resource is found. - */ - public static File getFile(String name) - { - return new File(ResourceUtil.getURL(name).getFile()); - } - - /** - * Get a InputStream to a resource on the system classpath. - * NOTE: This is intended to be used from a junit test since it will throw - * an exception on failure which will be caught by the junit runner. - * - * @throws RuntimeException If no resource is found. - */ - public static InputStream getStream(String name) - { - InputStream is = ClassLoader.getSystemResourceAsStream(name); - if (is == null) - throw new RuntimeException("Resource doesn't exist: " + name); - - return is; - } - - /** - * Find a resource with the given name. For example, - *
          -     * getURL(foo.bar.Blee.class, "file.txt");
          -     * 
          - * will obtain an URL to the file named - * "foo/bar/Blee/file.txt". Note that the - * {@link Class#getResource()} method would return the resource - * for "foo/bar/file.txt" instead. - * - * @param clazz The resource class. - * @param name The name of the resource to obtain. - * @return The InputStream to the named resource. - * @see java.lang.Class#getResource(java.lang.String name) - * @throws RuntimeException If no resource is found. - */ - public static URL getURL(Class c, String name) - { - return ResourceUtil.getURL(c, ResourceUtil.getLastName(c), name); - } - - /** - * Find a resource with the given name. For example, - *
          -     * getURL(foo.bar.Blee.class, "Blee", "file.txt");
          -     * 
          - * will obtain an URL to the file named - * "foo/bar/Blee/file.txt". Note that the - * {@link Class#getResource()} method would return the resource - * for "foo/bar/file.txt" instead. - * - * @param clazz The resource class. - * @param lastName The name of the class itself, eg. for class - * "foo.bar.Blee", the lastName is "Blee". - * @param name The name of the resource to obtain. - * @return The URL to the named resource. - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - * @throws RuntimeException If no resource is found. - */ - public static URL getURL(Class c, String lastName, String name) - { - // get the contents of the resouce - URL url = c.getResource(lastName + "/" + name); - if (url == null) { - throw new RuntimeException("Can't find resource: " + - lastName + - File.separator + - File.separator + name); - } - return url; - } - - - /** - * Find a resource with the given name. For example, - *
          -     * getStream(foo.bar.Blee.class, "file.txt");
          -     * 
          - * will obtain an InputStream to the file named - * "foo/bar/Blee/file.txt". Note that the - * {@link Class#getResourceAsStream()} method would return the resource - * for "foo/bar/file.txt" instead. - * - * @param clazz The resource class. - * @param name The name of the resource to obtain. - * @return The URL to the named resource. - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - * @throws RuntimeException If no resource is found. - */ - public static InputStream getStream(Class clazz, String name) - { - return ResourceUtil.getStream(clazz, - ResourceUtil.getLastName(clazz), name); - } - - /** - * Find a resource with the given name. For example, - *
          -     * getStream(foo.bar.Blee.class, "Blee", "file.txt");
          -     * 
          - * will obtain an InputStream to the file named - * "foo/bar/Blee/file.txt". Note that the - * {@link Class#getResourceAsStream()} method would return the resource - * for "foo/bar/file.txt" instead. - * - * @param clazz The resource class. - * @param lastName The name of the class itself, eg. for class - * "foo.bar.Blee", the lastName is "Blee". - * @param name The name of the resource to obtain. - * @return The InputStream to the named resource. - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - * @throws RuntimeException If no resource is found. - */ - public static InputStream getStream(Class c, String lastName, String name) - { - // get the contents of the resouce - InputStream is = c.getResourceAsStream(lastName + "/" + name); - if (is == null) { - throw new RuntimeException("Can't find resource: " + - lastName + - File.separator + - File.separator + name); - } - return is; - } - - /** - * Find a resource with the given name. For example, - *
          -     * getFile(foo.bar.Blee.class, "file.txt");
          -     * 
          - * will obtain an File to the file named - * "foo/bar/Blee/file.txt". Note that the - * {@link Class#getResource()} method would return the resource - * for "foo/bar/file.txt" instead. - * - * @param clazz The resource class. - * @param lastName The name of the class itself, eg. for class - * "foo.bar.Blee", the lastName is "Blee". - * @param name The name of the resource to obtain. - * @return The File to the named resource. - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - * @throws RuntimeException If no resource is found. - */ - public static File getFile(Class c, String name) - { - return new File(getURL(c, name).getFile()); - } - - /** - * Find a resource with the given name. For example, - *
          -     * getFile(foo.bar.Blee.class, "Blee", "file.txt");
          -     * 
          - * will obtain an File to the file named - * "foo/bar/Blee/file.txt". Note that the - * {@link Class#getResource()} method would return the resource - * for "foo/bar/file.txt" instead. - * - * @param clazz The resource class. - * @param lastName The name of the class itself, eg. for class - * "foo.bar.Blee", the lastName is "Blee". - * @param name The name of the resource to obtain. - * @return The File to the named resource. - * @see java.lang.Class#getResourceAsStream(java.lang.String name) - * @throws RuntimeException If no resource is found. - */ - public static File getFile(Class c, String lastName, String name) - { - return new File(getURL(c, lastName, name).getFile()); - } - -} diff --git a/test/tools/src/tools/util/SchemaFilenameFilter.java b/test/tools/src/tools/util/SchemaFilenameFilter.java deleted file mode 100755 index 7a82436..0000000 --- a/test/tools/src/tools/util/SchemaFilenameFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.FilenameFilter; -import java.io.File; - -/** - * A filter for files ending in xsd - */ -public class SchemaFilenameFilter implements FilenameFilter{ - public boolean accept(File file, String s) { - if (s.endsWith("xsd")) - return true; - else - return false; - } -} diff --git a/test/tools/src/tools/util/SchemaValidator.java b/test/tools/src/tools/util/SchemaValidator.java deleted file mode 100755 index e4f1cf6..0000000 --- a/test/tools/src/tools/util/SchemaValidator.java +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import org.apache.xmlbeans.*; - -import java.util.ArrayList; -import java.util.Collection; -import java.io.File; -import java.io.IOException; - - -public class SchemaValidator -{ - - /* Some tests - public static void main(String args[]) - { - //String schema = "cases/qatest/files/xbean/java2schema/daily/j2s/cases/inheritance/schema.xsd"; - String schema = "build/AntTests/META-INF/schemas/schema-0.xsd"; - Collection errors = new ArrayList(); - - if (!isValidSchema(schema, errors)) - { - System.out.println(schema + " is not valid:"); - Iterator i = errors.iterator(); - while (i.hasNext()) - { - XmlError err = (XmlError) i.next(); - System.out.println(XmlError.severityAsString(err.getSeverity()) - + ": " + err.getMessage() - + " at line " + err.getLine() - + ", column " + err.getColumn()); - - } - } - - } - */ - - /** - * Validates a schema file. Errors if any are returned in the collection - * object that is passed in - * @param schemaFile - * @param errors - * @return true if schema is valid, false otherwise. - * @throws IllegalArgumentException - */ - public static boolean isSchemaValid(String schemaFile, Collection errors) - throws IllegalArgumentException - { - if (errors == null) - { - String msg = "Collection parameter cannot be null"; - throw new IllegalArgumentException(msg); - } - XmlOptions options = new XmlOptions(); - options.setErrorListener(errors); - options.setLoadLineNumbers(); - - Exception ex = null; - Exception ioex = null; - XmlObject[] schema = new XmlObject[1]; - SchemaTypeSystem system = null; - try - { - schema[0] = XmlObject.Factory.parse(new File(schemaFile)); - system = XmlBeans.compileXsd(schema, - XmlBeans.getBuiltinTypeSystem(), - options); - } catch (XmlException e) - { - // Parse Exception - ex = e; - } catch (IOException ioe) - { - // Error while trying to read file - ioex = ioe; - } - - if (ioex != null) - { - errors.add(XmlError.forMessage("EXCEPTION: " + ioex.toString(), - XmlError.SEVERITY_ERROR)); - return false; - } - if (ex != null) - { - errors.add(XmlError.forMessage("EXCEPTION: " + ex.toString(), - XmlError.SEVERITY_ERROR)); - return false; - } - - return (system == null)? false : true; - } - - /** - * Validates the given schema file. Errors if any are not available - * - * @param schemaFile - * @return true if schema is valid, false otherwise - * @throws IllegalArgumentException - */ - - public static boolean isSchemaValid(String schemaFile) - throws IllegalArgumentException - { - Collection errors = new ArrayList(); - return isSchemaValid(schemaFile, errors); - } - - -} diff --git a/test/tools/src/tools/util/TestRunUtil.java b/test/tools/src/tools/util/TestRunUtil.java deleted file mode 100755 index d4ef949..0000000 --- a/test/tools/src/tools/util/TestRunUtil.java +++ /dev/null @@ -1,87 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.File; -import java.net.URLClassLoader; -import java.net.URL; -import java.net.MalformedURLException; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; - -public class TestRunUtil -{ - /** - * Runs method that must be declared "static void test()" on the given - * class, with the given additional jars or directories on the classpath. - */ - public static void run(String classname, File[] classpath) throws Throwable - { - // System.err.println("Running " + classname + " with classpath:"); - for (int i = 0; i < classpath.length; i++) - { - // System.err.println(classpath[i]); - if (!classpath[i].exists()) - throw new IllegalArgumentException("Classpath component " + classpath + " cannot be found!"); - } - - URL[] extracp = new URL[classpath.length]; - for (int i = 0; i < classpath.length; i++) - { - try - { - extracp[i] = classpath[i].toURL(); - } - catch (MalformedURLException e) - { - throw new IllegalArgumentException("Malformed classpath filename"); - } - } - - ClassLoader curcl = Thread.currentThread().getContextClassLoader(); - - try - { - ClassLoader childcl = new URLClassLoader(extracp); - Class javaClass = childcl.loadClass(classname); - Class testClass = childcl.loadClass("org.openuri.mytest.CustomerDocument"); - if (testClass == null) - throw new IllegalStateException(); - Method meth = javaClass.getMethod("test", new Class[0]); // should be static - Thread.currentThread().setContextClassLoader(childcl); - meth.invoke(null, new Object[0]); - } - catch (ClassNotFoundException e) - { - throw new IllegalArgumentException("class not found"); - } - catch (NoSuchMethodException e) - { - throw new IllegalArgumentException("no test() method found"); - } - catch (IllegalAccessException e) - { - throw new IllegalArgumentException("could not invoke static public test method"); - } - catch (InvocationTargetException e) - { - throw e.getCause(); - } - finally - { - Thread.currentThread().setContextClassLoader(curcl); - } - } -} diff --git a/test/tools/src/tools/util/Util.java b/test/tools/src/tools/util/Util.java deleted file mode 100755 index 34c4639..0000000 --- a/test/tools/src/tools/util/Util.java +++ /dev/null @@ -1,1230 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.URL; -import java.net.URLConnection; -import java.net.JarURLConnection; -import java.security.MessageDigest; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.DriverManager; -import java.sql.Connection; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.Vector; -import java.util.Iterator; - -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import java.util.zip.ZipFile; -import java.util.zip.ZipEntry; - -/** - * Utilities to copy files, directories, etc. - */ -public class Util -{ - private static byte[] _byteBuffer = new byte[32768]; - private static char[] _charBuffer = new char[32768]; - private static boolean filteredStackTrace = true; - - /** - * Read the contents of the given file into a String. - */ - public static String read(File file) - throws IOException - { - FileInputStream fis = new FileInputStream(file); - return read(new InputStreamReader(fis, "UTF8")); - } - - /** - * Read the contents of the given input stream into a String. This will - * also close the stream. - */ - public static String read(InputStream in) - throws IOException - { - return read(new InputStreamReader(in, "UTF8")); - } - - /** - * Read the contents in the given Reader into a String. This - * will also close the reader. - */ - public static String read(Reader in) - throws IOException - { - try - { - StringBuffer sb = new StringBuffer(_charBuffer.length); - int amount = 0; - - while (true) - { - synchronized (_charBuffer) - { - amount = in.read(_charBuffer); - - if (amount != -1) - sb.append(_charBuffer, 0, amount); - else - break; - } - } - return sb.toString(); - } - finally - { - close(in); - } - } - - public static String read(Reader in, int length) - throws IOException - { - BufferedReader bin = null; - - try - { - bin = new BufferedReader(in, length); - char[] s = new char[length]; - bin.read(s, 0, length); - - return new String(s); - } - finally - { - close(bin); - } - } - - /** - * Read the contents of the given file line by line into a String array - * - * If the second argument is true, then all whitespace lines at the end will - * be removed from the array - */ - public static String[] readIntoArray(File file, boolean trimLines) - throws IOException - { - BufferedReader reader = new BufferedReader(new FileReader(file)); - Vector v = new Vector(); - - while (true) - { - String s = reader.readLine(); - if (s == null) break; - v.addElement(s); - } - reader.close(); - // Discard all trailing lines that are only whitespaces.. - if (trimLines) - { - int i = v.size(); - while (--i >= 0) - if (isWhiteSpace((String) v.get(i))) - v.removeElementAt(i); - } - - String[] strArray = new String[v.size()]; - v.copyInto(strArray); - return strArray; - } - - public static void copy(InputStream in, OutputStream out) - throws IOException - { - try - { - int amount = 0; - - while (true) - { - synchronized (_byteBuffer) - { - amount = in.read(_byteBuffer); - if (amount == -1) - break; - out.write(_byteBuffer, 0, amount); - } - } - } - finally - { - close(in); - close(out); - } - } - - /** - * Copy a stream to a file. - */ - public static void copyToFile(InputStream in, File toFile, - boolean overwrite) - throws IOException - { - if (toFile.exists() && !overwrite) - return; - - // create any parent directories - File parent = toFile.getParentFile(); - if (parent != null) - parent.mkdirs(); - - // creates a new file only if it doesn't exist - toFile.createNewFile(); - - copy(in, new FileOutputStream(toFile)); - } - - /** - * Copy URL to file. - */ - public static void copyToFile(URL url, File toFile, - boolean replaceNewer) - throws IOException - { - Log.debug("copyToFile(url=" + url + ",\n toFile=" + toFile + ")"); - - URLConnection conn = url.openConnection(); - if (toFile.exists() && - toFile.lastModified() > conn.getLastModified() && - !replaceNewer) - return; - - copyToFile(conn.getInputStream(), toFile, true); - } - - /** - * Copy file to file. - */ - public static void copyToFile(File fromFile, File toFile, - boolean replaceNewer) - throws IOException - { - Log.debug("copyToFile(fromFile=" + fromFile + ",\n toFile=" + toFile + - ")"); - - // don't replace newer files unless flag is set - if (toFile.exists() && - toFile.lastModified() > fromFile.lastModified() && - !replaceNewer) - return; - - copyToFile(new FileInputStream(fromFile), - toFile, true); - } - - /** - * Copy file to a dir. - */ - public static void copyToDir(File fromFile, File toDir, - boolean replaceNewer) - throws IOException - { - //System.out.println("copyToDir(fromFile=" + fromFile + - //",\n toDir=" + toDir + ")"); - - toDir.mkdirs(); - - copyToFile(fromFile, new File(toDir, fromFile.getName()), - replaceNewer); - } - - /** - * Copy URL to a dir. - */ - public static void copyToDir(URL url, File toDir, - boolean replaceNewer) - throws IOException - { - //System.out.println("copyToDir(url=" + url + - //",\n toDir=" + toDir + ")"); - - toDir.mkdirs(); - - copyToFile(url, new File(toDir, url.getFile()), - replaceNewer); - } - - /** - * Recursively copy a dir to a new dir. Creates target tree if needed. - */ - public static void copyDirToDir(File fromDir, File toDir, - boolean replaceNewer, final String[] exclude) - throws IOException - { - //System.out.println("copyDirToDir(fromDir=" + fromDir + - //",\n toDir=" + toDir + ")"); - - File[] fs = fromDir.listFiles(); - COPY_FILE_LOOP: - for (int i = 0; i < fs.length; i++) - { - // exclude based only on last part of file name - String name = fs[i].getName(); - - if (exclude != null) - { - for (int j = 0; j < exclude.length; ++j) - { - if (name.equals(exclude[j])) - continue COPY_FILE_LOOP; - } - } - - if (fs[i].isFile()) - { - copyToDir(fs[i], toDir, replaceNewer); - } else - { - copyDirToDir(fs[i], new File(toDir, fs[i].getName()), - replaceNewer, exclude); - } - } - } - - /** - * Recursively copy a jar dir entry to a new dir. This is expensive since - * we have to iterate over all the entries in the .zip/.jar file. - * The fromDir parameter must end in '/'. - */ - public static void copyDirToDir(ZipFile zip, String fromDir, - File toDir, boolean replaceNewer, final String[] exclude) - throws IOException - { - //System.out.println("copyDirToDir(zip=" + zip + - //", fromDir=" + fromDir + - //", toDir=" + toDir + ")"); - - if (!fromDir.endsWith("/")) - return; - - Enumeration _enum = zip.entries(); - COPY_JAR_LOOP: - while (_enum.hasMoreElements()) - { - ZipEntry entry = (ZipEntry) _enum.nextElement(); - //System.out.println(" entry = " + entry.getName()); - - // skip directories - if (entry.isDirectory()) - continue; - - if (!entry.getName().startsWith(fromDir)) - continue; - - String entryFile = entry.getName().substring(fromDir.length()); - - // FIXME: exclude files matching any pattern in exclude array - - // use this class' loader to obtain the resource - URL url = Util.class.getResource("/" + entry.getName()); - if (url == null) - { - throw new java.io.IOException("Resource not found: " + - entry.toString()); - } - copyToFile(url, new File(toDir, entryFile), replaceNewer); - } - } - - /** - * Copy a dir url to a new dir. - */ - public static void copyDirToDir(URL url, File toDir, - boolean replaceNewer, String[] exclude) - throws IOException - { - Log.debug("copyDirToDir(url=" + url + ", toDir=" + toDir + ")"); - - // url must end in '/' - if (!url.getFile().endsWith("/")) - return; - - if ("file".equals(url.getProtocol())) - { - copyDirToDir(new File(url.getPath()), toDir, - replaceNewer, exclude); - } else if ("jar".equals(url.getProtocol())) - { - JarURLConnection conn = (JarURLConnection) url.openConnection(); - copyDirToDir(conn.getJarFile(), conn.getEntryName(), - toDir, replaceNewer, exclude); - } else if ("zip".equals(url.getProtocol())) - { - URL newUrl = new URL("jar:file:" + url.getPath()); - Log.debug("changed zip url to = " + newUrl); - - copyDirToDir(newUrl, toDir, replaceNewer, exclude); - } else - { - throw new IOException("Protocol not supported yet: " + - url.getProtocol()); - } - } - - /** - * Copy a dir to a new dir. - */ - public static void copyDirToDir(File fromDir, File toDir, - boolean replaceNewer) - throws IOException - { - copyDirToDir(fromDir, toDir, replaceNewer, null); - } - - /** - * Recursively remove a directory and it's contents. - */ - public static void remove(String file) - { - remove(new File(file)); - } - - /** - * Recursively remove a directory and it's contents. - */ - public static void remove(File file) - { - if (file == null || !file.exists()) - return; - - if (file.isFile()) - removeFile(file); - else if (file.isDirectory()) - removeDir(file); - } - - /** - * Remove a directory's contents. - */ - private static void removeDir(File dir) - { - File[] entries = dir.listFiles(); - - if (entries == null) - { - Log.fatal("IO Error or dir doesn't exist: " + dir); - return; - } - - for (int i = 0; i < entries.length; ++i) - remove(entries[i]); - - Log.debug("removing dir: " + dir.toString()); - dir.delete(); - } - - /** - * Remote a file. - */ - private static void removeFile(File file) - { - Log.debug("removing file: " + file.toString()); - file.delete(); - } - - /** - * @deprecated This is really overkill. - * - * Parses command-line arguments into a Hashtable. - *
          -     *             command-line : ( arg-assignment )* the-rest
          -     *             arg-assignment : option-name option-value?
          -     *             option-name : "any string with a leading '-' "
          -     *             option-value : "any string without a leading '-' "
          -     *             the-rest : "any args after options ended"
          -     *
          -     *             The following rules are used:
          -     *             - If an option appears multiple times, then its value is OVERWRITTEN!
          -     *             - If no value is given for an option, then the Hashtable entry contains a Boolean object TRUE
          -     *             - the rest of the arguments are stored as an array under the special key @REST
          -     *             - @REST value is always filled, at least with an EMPTY ARRAY (and not a null!!!)
          -     *             - An option of "-" ends option parsing.  Use this when a value-less option is followed by the-rest
          -     *
          -     *             Examples: (1) "-foo bar -goo zabba -boo -hoo" is parsed as
          -     *                           {foo -> bar, goo -> zabba, -boo -> TRUE, -hoo -> TRUE}
          -     *                       (2) "-foo bar -foo bar2 aaa bbb ccc" is parsed as { foo -> bar2, @REST -> [aaa,bbb,ccc] }
          -     *
          -     *             Rationale:
          -     *               The above grammar and rules are less powerful than those given by gnu.getopt, but
          -     *               are easier to use for our purposes
          -     *             
          - */ - public static HashMap parseArgs(String args[]) - { - HashMap ht = new HashMap(); - int k; - int n = args.length; - - for (k = 0; k < n; k++) - { - // Stop option processing if not an option or is the single character '-' - if (args[k].startsWith("-")) - { - // eat the '-' and end option processing if it's just a '-' - if (args[k].length() == 1) - { - k++; - break; - } - - String opt = args[k].substring(1); // skip - - String optarg = null; - if ((k < n - 1) && !args[k + 1].startsWith("-")) - { - // got an option value - optarg = args[k + 1]; - k++; - } - - ht.put(opt, - (null != optarg) ? - (Object) optarg : - (Object) Boolean.TRUE); - } else - { - break; - } - } - - // either we have run out of options or - // we have hit the first non-option argument - // - int n_rest = n - k; - String rest[] = new String[n_rest]; - int j; - - for (j = 0; k < n; j++, k++) - { - rest[j] = args[k]; - } - - ht.put("@REST", rest); - - return ht; - } - - /** - * @deprecated This is really overkill. - * - * This is a subset of the above parser. It assumes only boolean options, but - * allows arguments to be interspersed with options. - * - * Parses command-line arguments into a Hashtable using the following grammar: - * command-line : ( option-name | argument )* - * option-name : "any string with a leading '-' " - * argument : "any string without a leading '-' " - * - * The following rules are used: - * - If an option appears multiple times, then its value is OVERWRITTEN! - * - The Hashtable entry for any option contains a Boolean object TRUE - * - the rest of the arguments are stored as an array under the special key @REST - * - @REST value is always filled, at least with an EMPTY ARRAY (and not a null!!!) - * - An option of "-" ends option parsing. Use this before an argument that must begin with a '-' - * - * Examples: (1) "-foo bar -goo zabba -boo -hoo" is parsed as - * {foo -> TRUE, goo -> TRUE, -boo -> TRUE, -hoo -> TRUE, @REST -> [bar,zabba]} - * (2) "-foo bar -foo bar2 aaa - -bbb -ccc" - * is parsed as { foo -> TRUE, @REST -> [bar,bar2,aaa,-bbb,-ccc] } - * - * Rationale: - * parseArgs does not have a way of specifying a trailing boolean option followed by an - * argument except through the '-' hack. It is unable to implement, for example, the argument scanning of - * SystemSchemaBooter without forcing a change in the command-line syntax - */ - public static HashMap parseOptions(String args[]) - { - HashMap ht = new HashMap(); - int k; - int n = args.length; - int nOptions = 0; - - for (k = 0; k < n; k++) - { - // Stop option processing if not an option or is the single character '-' - if (args[k].startsWith("-")) - { - nOptions++; - // eat the '-' and end option processing if it's just a '-' - if (args[k].length() == 1) - { - k++; - break; - } - - String opt = args[k].substring(1); // skip - - ht.put(opt, (Object) Boolean.TRUE); - } - } - - // either we have run out of options or - // we have hit a single '-' - // - int n_rest = n - nOptions; - String rest[] = new String[n_rest]; - boolean bIgnoreOptions = false; - int j = 0; - // Rescan the args and put non-options in the rest array - for (k = 0; k < n; k++) - { - if (bIgnoreOptions || !args[k].startsWith("-")) - { - rest[j++] = args[k]; - } else if (args[k].length() == 1) - { - bIgnoreOptions = true; - } - } - - ht.put("@REST", rest); - - return ht; - } - - - /** - * Close a possibly null output stream. Ignore any exceptions. - */ - static public void close(OutputStream stream) - { - if (stream == null) - return; - - try - { - stream.close(); - } - catch (Exception ignore) - { - } - } - - /** - * Close a possibly null input stream. Ignore any exceptions. - */ - static public void close(InputStream stream) - { - if (stream == null) - return; - - try - { - stream.close(); - } - catch (Exception ignore) - { - } - } - - - /** - * Close a possibly null reader. Ignore any exceptions. - */ - static public void close(Reader reader) - { - if (reader == null) - return; - - try - { - reader.close(); - } - catch (Exception ignore) - { - } - } - - /** - * Close a possibly null writer. Ignore any exceptions. - */ - static public void close(Writer writer) - { - if (writer == null) - return; - - try - { - writer.close(); - } - catch (Exception ignore) - { - } - } - - /** - * Close a possibly null server socket. Ignore any exceptions. - */ - static public void close(ServerSocket socket) - { - if (socket == null) - return; - - try - { - socket.close(); - } - catch (Exception ignore) - { - } - } - - /** - * Close a possibly null socket. Ignore any exceptions. - */ - static public void close(Socket socket) - { - if (socket == null) - return; - - try - { - socket.close(); - } - catch (Exception ignore) - { - } - } - - /** - * Copy from an output stream to an input stream. - */ - - static public int - copyStream(InputStream in, OutputStream out, byte[] buffer) - throws IOException - { - int c; - int length = 0; - - if (buffer == null) - buffer = new byte[4096]; - - while ((c = in.read(buffer)) > 0) - { - length += c; - out.write(buffer, 0, c); - } - - return length; - } - - public static String - hexStringFromBytes(byte[] bytes) - { - String hex = "0123456789abcdef"; - StringBuffer buf = new StringBuffer(2 * bytes.length); - - for (int i = 0; i < bytes.length; i++) - { - int b = bytes[i]; - buf.append(hex.charAt((b >> 4) & 0xf)); - buf.append(hex.charAt(b & 0xf)); - } - - return buf.toString(); - } - - /** - * Convert a nibble to a hex character - * - * @param nibble the nibble to convert. - */ - public static char toHex(int nibble) - { - return hexDigit[(nibble & 0xF)]; - } - - /** - * A table of hex digits - */ - private static final char[] hexDigit = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' - }; - - public static String gobbleUpReader(Reader in) - throws Exception - { - StringBuffer buf = new StringBuffer(); - int c; - - while (-1 != (c = in.read())) - { - buf.append(c); - } - - return buf.toString(); - } - - public static String createHashedPassword(String user, String password) - { - MessageDigest md = null; - try - { - md = MessageDigest.getInstance("SHA1", "SUN"); - } - catch (Exception e) - { - throw new RuntimeException(e.getMessage()); - } - - md.update(user.getBytes()); - md.update(password.getBytes()); - - return hexStringFromBytes(md.digest()); - } - - static public String makeHtmlStringNoNewLine(String sIn) - { - if (null == sIn) - return null; - - int lenIn = sIn.length(); - int iIn; - - StringBuffer outBuf = new StringBuffer(lenIn + lenIn / 4); // Plenty of room for extra characters - char c; - - for (iIn = 0; iIn < lenIn; ++iIn) - { - c = sIn.charAt(iIn); - switch (c) - { - case '&': - outBuf.append("&"); - break; - case '"': - outBuf.append("""); - break; - case '<': - outBuf.append("<"); - break; - case '>': - outBuf.append(">"); - break; - default: - outBuf.append(c); - break; - } - } - - return outBuf.toString(); - } - - /** - * Helper function to split a String into an array of Strings somewhat - * like the JDK 1.4.1 {@link java.lang.String#split(String)} method does. - */ - public static java.util.List splitList(String s, String match) - { - java.util.List strings = new java.util.ArrayList(); - s.trim(); - - while (!s.equals("")) - { - if (s.indexOf(match) != -1) - { - strings.add(s.substring(0, s.indexOf(match))); - s = s.substring(s.indexOf(match) + 1, s.length()); - } else - { - strings.add(s); - s = ""; - } - s.trim(); - } - - return strings; - } - - /** - * Helper function to split a String into an array of Strings somewhat - * like the JDK 1.4.1 {@link java.lang.String#split(String)} method does. - */ - public static String[] split(String s, String match) - { - java.util.List strings = splitList(s, match); - return (String[]) strings.toArray((Object[]) (new String[0])); - } - - /** - * Programtically turn on/off the stack trace filter. - */ - public static void setFilteredStackTrace(boolean filter) - { - Util.filteredStackTrace = filter; - } - - /** - * State of the stack trace filter. - */ - public static boolean isFilteredStackTrace() - { - return Util.filteredStackTrace; - } - - /** - * Helper to get the stack trace of an Exception as a String. - * - * @param t Use the stack trace of this exception. - * @return The stack trace as a String. - */ - public static String getStackTrace(Throwable t) - { - if (t == null) - return null; - - StringWriter sw = new StringWriter(); - t.printStackTrace(new PrintWriter(sw)); - return sw.toString(); - } - - /** - * Filter a stack trace by removing any lines matching the set. A default - * set will always be applied, but a custom set can also be provided. - * - * @param t Use the stack trace of this exception. - * @return The filtered stack trace as a String. - */ - public static String getFilteredStackTrace(Throwable t) - { - return getFilteredStackTrace(t, null); - } - - /** - * Filter a stack trace by removing any lines matching the set. A default - * set will always be applied, but a custom set can also be provided. - * - * @param t Use the stack trace of this exception. - * @param filters Set of custom filters where each filter is - * the beginning of a class name. - * @return The filtered stack trace as a String. - */ - public static String getFilteredStackTrace(Throwable t, String[] filters) - { - return filterStack(getStackTrace(t), filters); - } - - /** - * Helper for the {@link #getFilteredStackTrace(java.lang.Throwable)} - * method. - * - * @param stack A stack trace as a String. - * @param filters Set of custom filters where each filter is - * the beginning of a class name. - * @return The filtered stack trace as a String. - */ - public static String filterStack(String stack, String[] filters) - { - if (!isFilteredStackTrace()) - return stack; - - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - BufferedReader br = new BufferedReader(new StringReader(stack)); - - String line; - - try - { - while ((line = br.readLine()) != null) - { - if (!isFiltered(line, filters)) - { - pw.println(line); - } - } - } - catch (Exception e) - { - return stack; - } - - return sw.toString(); - } - - /** - * Helper for the {@link #getFilteredStackTrace(java.lang.Throwable)} - * method. - * - * @param line A single line from the stack trace. - * @param filters Set of custom filters where each filter is - * the beginning of a class name. - * @return true if the line should be filtered; false otherwise. - */ - static boolean isFiltered(String line, String[] filters) - { - final String[] defaultFilters = new String[]{ - "org.apache.xmlbeansbeans.test.tools.moosehead", - "org.apache.xmlbeansbeans.test.tools.harness.Main", - "junit.framework.TestCase", - "junit.framework.TestResult", - "junit.framework.TestSuite", - "junit.framework.Assert.", // don't filter AssertException - "java.lang.reflect.Method.invoke(", - "org.apache.tools.ant" - }; - - for (int i = 0; i < defaultFilters.length; ++i) - { - if (line.indexOf(defaultFilters[i]) > 0) - { - return true; - } - } - - if (filters != null) - for (int i = 0; i < filters.length; ++i) - { - if (line.indexOf(filters[i]) > 0) - return true; - } - - return false; - } - - /** - * @deprecated - */ - public static URL getURL(String name) - { - return ResourceUtil.getURL(name); - } - - /** - * @deprecated - */ - public static InputStream getStream(String name) - { - return ResourceUtil.getStream(name); - } - - /** - * @deprecated - */ - public static File getFile(String name) - { - return ResourceUtil.getFile(name); - } - - /** - * /** - * Expand key/value pairs in a String. - * Replaces patterns in the string of the form ${key} where - * the keys and values are taken from the hash map. I'm sure someone - * could write this more efficiently if they wanted to. Replacement is - * recursive. Eg, if the map contains the key "foo" with value "bar", the - * string "My dog has ${foo}." will become "My dog has bar." - * - * @param str String to be expanded. - * @param map Map of key value pairs. - * @return The string after replacement. - * - * @deprecated See expand(). - */ - public static String _expand(String str, HashMap map) - { - if (str == null) - return null; - - if (map == null) - return str; - - StringBuffer result = new StringBuffer(); - - int pos = 0; - int open = -1; - - //System.out.println("expand("+str+")"); - - while (-1 != (open = str.indexOf("${", pos))) - { - //System.out.println("open: " + open + " = " + str.charAt(open)); - //System.out.println("appending: " + str.substring(pos, open) + "<"); - - // replace everything we've passed so far. - result.append(str.substring(pos, open)); - pos = open + 1; - - int close = str.indexOf("}", open); - if (close == -1) - continue; - //System.out.println("close: " + close + " = " + str.charAt(close)); - //System.out.println("whole region: " + str.substring(open, close+1)); - //System.out.println("match region: " + str.substring(open+2, close)); - - String key = str.substring(open + 2, close); - if (map.containsKey(key)) - { - String value = expand((String) map.get(key), map); - result.append(value); - - // non-recursive implementation below: - //result.append(map.get(key)); - - pos = close + 1; - continue; - } - - // we've passed the start character (pos = open+1) and didn't find - // a match, so copy the '$' to the result string - result.append('$'); - - } - - result.append(str.substring(pos)); - - //System.out.println("## expanded: " + result.toString()); - return result.toString(); - } - - /** - * Expand key/value pairs in a String. - * Replaces patterns in the string of the form ${key} where - * the keys and values are taken from the hash map. I'm sure someone - * could write this more efficiently if they wanted to. Replacement is - * recursive. Eg, if the map contains the key "foo" with value "bar", the - * string "My dog has ${foo}." will become "My dog has bar." This version - * uses the JDK 1.4 regex classes. - * - * @param str String to be expanded. - * @param map Map of key value pairs. - * @return The string after replacement. - */ - public static String expand(String str, HashMap map) - { - final Pattern p = Pattern.compile("\\$\\{.+?\\}"); - - if (str == null) - return null; - - if (map == null) - return str; - - int last = 0; - StringBuffer buf = new StringBuffer(); - Matcher m = p.matcher(str); - - while (m.find()) - { - - // guarenteed to return ${key} where key is at least one character - // in length. match will never be null. - String match = m.group(); - int start = m.start(); - int end = m.end(); - - // remove the ${ and } from the match - String key = match.substring("${".length(), - match.length() - "}".length()); - - if (map.containsKey(key)) - { - String value = expand((String) map.get(key), map); - - buf.append(str.substring(last, start)); - buf.append(value); - - last = end; - } - } - - buf.append(str.substring(last, str.length())); - - return buf.toString(); - } - - /** - * Escape a string for writing to a property file. - * This is a simplistic version of the Properties.store() escaping. - */ - public static String escapeProperty(String s) - { - int len = s.length(); - StringBuffer buf = new StringBuffer(len * 2); - - for (int i = 0; i < len; ++i) - { - char c = s.charAt(i); - - switch (c) - { - case '\t': - buf.append('\\').append('t'); - break; - case '\n': - buf.append('\\').append('n'); - break; - case '\r': - buf.append('\\').append('r'); - break; - case '\f': - buf.append('\\').append('f'); - break; - - case '\\': - case ' ': - case '=': - case ':': - case '#': - case '!': - buf.append('\\').append(c); - break; - - default: - if ((c < 0x0020) || (c > 0x007e)) - { - buf.append('\\'); - buf.append('u'); - buf.append(toHex((c >> 12) & 0xF)); - buf.append(toHex((c >> 8) & 0xF)); - buf.append(toHex((c >> 4) & 0xF)); - buf.append(toHex(c & 0xF)); - } else - { - buf.append(c); - } - } - } - - return buf.toString(); - } - - /** - * Checks if a string is entirely whitespace - */ - public static boolean isWhiteSpace(String s) - { - for (int i = 0; i < s.length(); i++) - if (!Character.isWhitespace(s.charAt(i))) - return false; - - return true; - } - -} - - diff --git a/test/tools/src/tools/util/XMLFilenameFilter.java b/test/tools/src/tools/util/XMLFilenameFilter.java deleted file mode 100755 index e5e4b13..0000000 --- a/test/tools/src/tools/util/XMLFilenameFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package tools.util; - -import java.io.FilenameFilter; -import java.io.File; - -/** - * A filter for files ending in xml - */ -public class XMLFilenameFilter implements FilenameFilter{ - public boolean accept(File file, String s) { - if (s.endsWith("xml")) - return true; - else - return false; - } -} diff --git a/testbuild.xml b/testbuild.xml deleted file mode 100755 index 977dc04..0000000 --- a/testbuild.xml +++ /dev/null @@ -1,1127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/xkit/README.txt b/xkit/README.txt index 619c15f..4273293 100644 --- a/xkit/README.txt +++ b/xkit/README.txt @@ -13,7 +13,7 @@ * limitations under the License. */ -XMLBeans Development Kit Version 2.5.0 +XMLBeans Development Kit Version 3.1.0 Welcome to XMLBeans! @@ -22,53 +22,29 @@ Welcome to XMLBeans! Kit contents: (1) One copy of xbean.jar, which contains XMLBeans. - Should work on any JDK 1.4.x or 1.5.x. + Should work on any JDK 1.6.x or newer. ./lib/xbean.jar -(2) One copy of jsr173_1.0_api.jar, which contains classes - needed to parse XML files for use with XMLBeans. - ./lib/jsr173_1.0_api.jar - -(3) One copy of resolver.jar from Apache xml-commons. See scomp +(2) One copy of resolver.jar from Apache xml-commons. See scomp documentation for when it is needed. ./lib/resolver.jar -(4) One copy of xbean_xpath jar. Contains the XPath and XQuery - "glue" code, only needed if XPath-XQuery functionality is - required. - ./lib/xbean_xpath.jar - -(5) One copy of xmlpublic.jar, containing all the public interfaces of - XMLBeans. (Classes included here are a subset of those included - in xbean.jar.) - ./lib/xmlpublic.jar - -(6) One copy of xmlbeans-qname.jar, contains javax.xml.namespace - QName.class and NamespaceContext.class. These classes were - introduced in the jdk since 1.5. This jar is necesary on classpath - only if using jdk 1.4. - ./lib/xmlbeans-qname.jar - -(7) License information for XML Beans and included libraries +(3) License information for XML Beans and included libraries ./LICENSE.txt ./NOTICE.txt -(8) One folder full of command-line scripts, pointing to the +(4) One folder full of command-line scripts, pointing to the useful main() functions in the JAR. ./bin -(9) A copy of the plain javadoc tree for org.apache.xmlbeans.* - ./docs/reference +(5) A copy of the plain javadoc tree for org.apache.xmlbeans.* + ./docs/javadocs -(10) A preliminary collection of nicely formatted user-level - documentation HTML (includes reformatted and nicely - organized javadoc as well) +(6) A preliminary collection of nicely formatted user-level + documentation HTML ./docs/guide -(11) A few sample schemas - ./schemas - -(12) Samples that show the use of the XMLBeans API. (You'll +(7) Samples that show the use of the XMLBeans API. (You'll also find more samples at the XMLBeans web site.) ./samples @@ -76,7 +52,7 @@ Where to start? (1) Setup. - 1. Make sure you have a JDK 1.4.x installed (or 1.5.x); that + 1. Make sure you have a JDK 1.6.x or later installed; that java[.exe] is on your path and that JAVA_HOME/bin contains java[.exe], javac[.exe], and jar[.exe]. diff --git a/xkit/doap_XMLBeans.rdf b/xkit/doap_XMLBeans.rdf index 304f740..e4bfa33 100644 --- a/xkit/doap_XMLBeans.rdf +++ b/xkit/doap_XMLBeans.rdf @@ -45,6 +45,20 @@ All of this was built with performance in mind. Informal benchmarks and user fee Java + + + XMLBeans v3.1.0 + 2019-03-22 + 3.1.0 + + + + + XMLBeans v3.0.2 + 2018-10-28 + 3.0.2 + + XMLBeans v3.0.1